Skip to content

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

Go

feat(dingtalk): add DingTalk bot integration (MUL-3958) (#4829)

YYClawc3577cb04bcf
diff --git a/.env.example b/.env.example
index 4014558fc4..deaa15c41d 100644
--- a/.env.example
+++ b/.env.example
@@ -324,6 +324,12 @@ MULTICA_LARK_CALLBACK_BASE_URL=
# environment handling.
MULTICA_LARK_WS_PROXY_URL=
+# DingTalk bot integration (Settings → Integrations "Bind to DingTalk")
+# Off until MULTICA_DINGTALK_SECRET_KEY is set — a base64-encoded 32-byte key
+# that encrypts each Bot's AppSecret at rest. Leave empty to disable.
+# Generate one with: openssl rand -base64 32
+MULTICA_DINGTALK_SECRET_KEY=
+
# Frontend
# Leave empty — auto-derived from page origin in browser, set by Makefile for local dev.
# NEXT_PUBLIC_API_URL also feeds the Next.js SSR proxy when explicitly set.
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdx
index b0f1d6d331..1134863cf1 100644
--- a/apps/docs/content/docs/channels.ja.mdx
+++ b/apps/docs/content/docs/channels.ja.mdx
@@ -1,23 +1,23 @@
---
title: チャット連携
-description: Multica のエージェントを Feishu、Lark、Slack に接続し、チームが普段使っているチャットツールから利用する方法を説明します。
+description: Multica のエージェントを Feishu、Lark、Slack、DingTalk に接続し、チームが普段使っているチャットツールから利用する方法を説明します。
---
import { Callout } from "fumadocs-ui/components/callout";
チャット連携を使うと、Multica を開かなくても、エージェントへの質問、グループチャットでの @メンション、チャット画面からのイシュー作成ができます。
-現在は Feishu/Lark と Slack に対応しています。どちらもセッション、ユーザー識別、実行の仕組みは共通ですが、インストール方法が異なります。
+現在は Feishu/Lark、Slack、DingTalk に対応しています。セッション、ユーザー識別、実行の仕組みは共通ですが、インストール方法が異なります。
## プラットフォームを選ぶ
-| | Feishu / Lark | Slack |
-|---|---|---|
-| インストール | Multica で QR コードを生成し、Feishu でスキャンして認証 | Slack でアプリを作成し、2 つのトークンを Multica に入力 |
-| エージェントとの DM | 対応 | 対応 |
-| グループまたはチャンネル | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー |
-| イシューの作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` スラッシュコマンド。エージェントが説明を整理してから作成 |
-| 接続方式 | プラットフォームの常時接続 | Socket Mode |
+| | Feishu / Lark | Slack | DingTalk |
+|---|---|---|---|
+| インストール | Multica で QR コードを生成し、Feishu でスキャンして認証 | Slack でアプリを作成し、2 つのトークンを Multica に入力 | 社内アプリと Stream モードのロボットを作成し、AppKey と AppSecret を Multica に入力 |
+| エージェントとの DM | 対応 | 対応 | 対応 |
+| グループまたはチャンネル | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー |
+| イシューの作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` スラッシュコマンド。エージェントが説明を整理してから作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 |
+| 接続方式 | プラットフォームの常時接続 | Socket Mode | Stream モード |
新規接続は現在、中国本土版の Feishu でのみ利用できます。既存の国際版 Lark 接続は、引き続き利用および管理できます。
@@ -27,6 +27,7 @@ import { Callout } from "fumadocs-ui/components/callout";
- [Feishu / Lark Bot 連携](/lark-bot-integration)
- [Slack Bot 連携](/slack-bot-integration)
+- [DingTalk Bot 連携](/dingtalk-bot-integration)
## メッセージが処理される流れ
@@ -42,6 +43,7 @@ Bot を @メンションしていないチャンネルメッセージは、エ
- Feishu/Lark はチャットごとにセッションを分けます。同じチャットの後続メッセージは同じセッションを継続します。
- Slack は DM をチャンネルごとに分けます。チャンネル内では、スレッドごとに独立したセッションが保持されます。
+- DingTalk は conversation ごとにセッションを分けます。DM とグループはそれぞれのセッションを継続します。
チャンネルで追加の依頼を送る場合も、Bot を再度 @メンションする必要があります。エージェントが受け取るのは自分宛てのメッセージだけで、チャンネルの履歴全体を自動的に読み取ることはありません。
@@ -68,6 +70,7 @@ Multica がエージェントを実行するのは、アカウント連携が完
```dotenv
MULTICA_LARK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
```
これらのキーは、保存された Bot の認証情報を暗号化します。生成、保管、ローテーションの方法は[環境変数](/environment-variables)を参照してください。Multica Cloud ではすでに設定済みです。
@@ -76,4 +79,5 @@ MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
- [Feishu / Lark Bot 連携](/lark-bot-integration)
- [Slack Bot 連携](/slack-bot-integration)
+- [DingTalk Bot 連携](/dingtalk-bot-integration)
- [エージェントとチャットする](/chat)
diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdx
index 90d469f36a..2044357ab7 100644
--- a/apps/docs/content/docs/channels.ko.mdx
+++ b/apps/docs/content/docs/channels.ko.mdx
@@ -1,23 +1,23 @@
---
title: 채팅 연동
-description: Multica 에이전트를 Feishu, Lark 또는 Slack에 연결해 팀이 이미 사용하는 채팅 도구에서 활용합니다.
+description: Multica 에이전트를 Feishu, Lark, Slack 또는 DingTalk에 연결해 팀이 이미 사용하는 채팅 도구에서 활용합니다.
---
import { Callout } from "fumadocs-ui/components/callout";
채팅 연동을 사용하면 팀이 Multica를 열지 않고도 에이전트에게 바로 질문하고, 그룹 채팅에서 @멘션하거나, 채팅 창에서 이슈를 만들 수 있습니다.
-현재 Feishu/Lark와 Slack을 지원합니다. 두 연동은 같은 대화, 신원, 실행 메커니즘을 사용하지만 설치 방법은 다릅니다.
+현재 Feishu/Lark, Slack, DingTalk를 지원합니다. 같은 대화, 신원, 실행 메커니즘을 사용하지만 설치 방법은 다릅니다.
## 플랫폼 선택
-| | Feishu / Lark | Slack |
-|---|---|---|
-| 설치 방법 | Multica에서 QR 코드를 만든 뒤 Feishu로 스캔해 승인 | Slack에서 app을 만든 뒤 두 token을 Multica에 입력 |
-| 에이전트와 DM | 지원 | 지원 |
-| 그룹 채팅 또는 채널 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 |
-| 이슈 만들기 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` slash 명령으로 에이전트가 설명을 정리한 뒤 생성 |
-| 연결 방식 | 플랫폼 장기 연결 | Socket Mode |
+| | Feishu / Lark | Slack | DingTalk |
+|---|---|---|---|
+| 설치 방법 | Multica에서 QR 코드를 만든 뒤 Feishu로 스캔해 승인 | Slack에서 app을 만든 뒤 두 token을 Multica에 입력 | 사내 app과 Stream 모드 로봇을 만든 뒤 AppKey와 AppSecret을 Multica에 입력 |
+| 에이전트와 DM | 지원 | 지원 | 지원 |
+| 그룹 채팅 또는 채널 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 |
+| 이슈 만들기 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` slash 명령으로 에이전트가 설명을 정리한 뒤 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 |
+| 연결 방식 | 플랫폼 장기 연결 | Socket Mode | Stream 모드 |
새 연결은 현재 중국 본토 버전 Feishu에서만 만들 수 있습니다. 기존 국제 버전 Lark 연결은 계속 사용하고 관리할 수 있습니다.
@@ -27,6 +27,7 @@ Bot 하나는 Multica 에이전트 하나에 연결됩니다. 같은 채팅 플
- [Feishu / Lark Bot 연결](/lark-bot-integration)
- [Slack Bot 연결](/slack-bot-integration)
+- [DingTalk Bot 연결](/dingtalk-bot-integration)
## 메시지 실행 과정
@@ -42,6 +43,7 @@ Bot을 @멘션하지 않은 채널 메시지는 에이전트를 트리거하지
- Feishu/Lark는 채팅별로 대화를 구분하며 같은 채팅의 후속 메시지는 기존 대화를 이어갑니다.
- Slack DM은 채널별로 구분하고, 채널 안에서는 각 thread가 별도 대화를 저장합니다.
+- DingTalk는 conversation별로 대화를 구분하며 각 DM 또는 그룹이 자체 대화를 이어갑니다.
채널에서 후속 질문을 할 때도 Bot을 다시 @멘션해야 합니다. 에이전트는 자신에게 보낸 메시지만 받으며 전체 채널 기록을 자동으로 읽지 않습니다.
@@ -68,6 +70,7 @@ Bot을 @멘션하지 않은 채널 메시지는 에이전트를 트리거하지
```dotenv
MULTICA_LARK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
MULTICA_SLACK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
+MULTICA_DINGTALK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
```
이 키는 Bot 자격 증명을 암호화해 저장하는 데 사용됩니다. 생성, 보관, 교체 방법은 [환경 변수](/environment-variables)를 참고하세요. Multica Cloud에는 이미 설정되어 있습니다.
@@ -76,4 +79,5 @@ MULTICA_SLACK_SECRET_KEY=<base64로 인코딩한 32바이트 키>
- [Feishu / Lark Bot 연결](/lark-bot-integration)
- [Slack Bot 연결](/slack-bot-integration)
+- [DingTalk Bot 연결](/dingtalk-bot-integration)
- [에이전트와 대화](/chat)
diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdx
index e8cebe7e19..a4df423ddb 100644
--- a/apps/docs/content/docs/channels.mdx
+++ b/apps/docs/content/docs/channels.mdx
@@ -1,23 +1,23 @@
---
title: Chat integrations
-description: Connect Multica agents to Feishu, Lark, or Slack and use them from the chat tools your team already uses.
+description: Connect Multica agents to Feishu, Lark, Slack, or DingTalk and use them from the chat tools your team already uses.
---
import { Callout } from "fumadocs-ui/components/callout";
Chat integrations let the team ask an agent questions, @-mention it in a group chat, or create issues from the chat window — without opening Multica.
-Feishu/Lark and Slack are supported today. Both integrations share the same session, identity, and execution mechanics but install differently.
+Feishu/Lark, Slack, and DingTalk are supported today. They share the same session, identity, and execution mechanics but install differently.
## Choose a platform
-| | Feishu / Lark | Slack |
-|---|---|---|
-| Installation | Generate a QR code in Multica and authorize by scanning it with Feishu | Create an app in Slack, then paste two tokens into Multica |
-| DM the agent | Supported | Supported |
-| Groups or channels | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot |
-| Create issues | `/issue` message command; creates the issue from your input as-is | `/issue` slash command; the agent writes up the description before creating |
-| Connection | Platform long connection | Socket Mode |
+| | Feishu / Lark | Slack | DingTalk |
+|---|---|---|---|
+| Installation | Generate a QR code in Multica and authorize by scanning it with Feishu | Create an app in Slack, then paste two tokens into Multica | Create an internal app and Stream-mode robot, then paste its AppKey and AppSecret into Multica |
+| DM the agent | Supported | Supported | Supported |
+| Groups or channels | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot |
+| Create issues | `/issue` message command; creates the issue from your input as-is | `/issue` slash command; the agent writes up the description before creating | `/issue` message command; creates the issue from your input as-is |
+| Connection | Platform long connection | Socket Mode | Stream mode |
New connections are currently open only for mainland-China Feishu; existing international Lark connections keep working and can still be managed.
@@ -27,6 +27,7 @@ Step-by-step guides:
- [Feishu / Lark Bot integration](/lark-bot-integration)
- [Slack Bot integration](/slack-bot-integration)
+- [DingTalk Bot integration](/dingtalk-bot-integration)
## How a message is processed
@@ -42,6 +43,7 @@ Channel messages that don't @-mention the Bot never trigger the agent and are no
- Feishu/Lark separates sessions by chat; later messages in the same chat continue the same session.
- Slack separates DMs by channel; in a channel, each thread holds its own session.
+- DingTalk separates sessions by conversation; each DM or group continues its own session.
Follow-ups in a channel still need a fresh @-mention. The agent only receives messages addressed to it — it never reads the whole channel history automatically.
@@ -68,6 +70,7 @@ A self-hosted deployment must configure a 32-byte encryption key for each platfo
```dotenv
MULTICA_LARK_SECRET_KEY=<base64-encoded 32-byte key>
MULTICA_SLACK_SECRET_KEY=<base64-encoded 32-byte key>
+MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
```
These keys encrypt stored Bot credentials. See [Environment variables](/environment-variables) for how to generate, store, and rotate them. Multica Cloud already has this configured.
@@ -76,4 +79,5 @@ These keys encrypt stored Bot credentials. See [Environment variables](/environm
- [Feishu / Lark Bot integration](/lark-bot-integration) — connect an agent by scanning a QR code.
- [Slack Bot integration](/slack-bot-integration) — create a Slack app and paste its tokens into Multica.
+- [DingTalk Bot integration](/dingtalk-bot-integration) — create a Stream-mode robot and paste its credentials into Multica.
- [Chat](/chat) — the conversation and execution model behind every Bot.
diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdx
index 1ed8966c48..524cdb18af 100644
--- a/apps/docs/content/docs/channels.zh.mdx
+++ b/apps/docs/content/docs/channels.zh.mdx
@@ -1,23 +1,23 @@
---
title: 聊天集成
-description: 把 Multica 智能体接入飞书、Lark 或 Slack,在团队已有的聊天工具中使用。
+description: 把 Multica 智能体接入飞书、Lark、Slack 或钉钉,在团队已有的聊天工具中使用。
---
import { Callout } from "fumadocs-ui/components/callout";
聊天集成让团队不用打开 Multica,也能直接向智能体提问、在群聊中 @它,或从聊天窗口创建 issue。
-目前支持飞书/Lark 和 Slack。两种集成使用相同的会话、身份和执行机制,但安装方式不同。
+目前支持飞书/Lark、Slack 和钉钉。它们使用相同的会话、身份和执行机制,但安装方式不同。
## 选择平台
-| | 飞书 / Lark | Slack |
-|---|---|---|
-| 安装方式 | 在 Multica 中生成二维码,用飞书扫码授权 | 在 Slack 创建 app,再把两个 token 填入 Multica |
-| 私聊智能体 | 支持 | 支持 |
-| 群聊或频道 | @ Bot 后触发 | @ Bot 后触发 |
-| 创建 issue | `/issue` 消息命令,按输入直接创建 | `/issue` slash 命令,智能体整理描述后创建 |
-| 连接方式 | 平台长连接 | Socket Mode |
+| | 飞书 / Lark | Slack | 钉钉 |
+|---|---|---|---|
+| 安装方式 | 在 Multica 中生成二维码,用飞书扫码授权 | 在 Slack 创建 app,再把两个 token 填入 Multica | 创建企业内部应用和 Stream 模式机器人,再把 AppKey 与 AppSecret 填入 Multica |
+| 私聊智能体 | 支持 | 支持 | 支持 |
+| 群聊或频道 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 |
+| 创建 issue | `/issue` 消息命令,按输入直接创建 | `/issue` slash 命令,智能体整理描述后创建 | `/issue` 消息命令,按输入直接创建 |
+| 连接方式 | 平台长连接 | Socket Mode | Stream 模式 |
新连接目前只开放中国大陆版飞书;已有的国际版 Lark 连接仍可继续使用和管理。
@@ -27,6 +27,7 @@ import { Callout } from "fumadocs-ui/components/callout";
- [飞书 / Lark Bot 接入](/lark-bot-integration)
- [Slack Bot 接入](/slack-bot-integration)
+- [钉钉 Bot 接入](/dingtalk-bot-integration)
## 消息的执行流程
@@ -42,6 +43,7 @@ import { Callout } from "fumadocs-ui/components/callout";
- 飞书/Lark 按聊天区分会话;同一个聊天中的后续消息会继续原会话。
- Slack 私聊按频道区分;频道中的每个 thread 分别保存一段会话。
+- 钉钉按 conversation 区分会话;每个单聊或群聊分别延续自己的会话。
在频道中继续追问时仍需再次 @ Bot。智能体只收到发给自己的消息,不会自动读取整个频道的历史。
@@ -68,6 +70,7 @@ import { Callout } from "fumadocs-ui/components/callout";
```dotenv
MULTICA_LARK_SECRET_KEY=<base64 编码的 32 字节密钥>
MULTICA_SLACK_SECRET_KEY=<base64 编码的 32 字节密钥>
+MULTICA_DINGTALK_SECRET_KEY=<base64 编码的 32 字节密钥>
```
这些密钥用于加密保存 Bot 凭据。生成、保存和轮换方法见[环境变量](/environment-variables)。Multica Cloud 已完成这项配置。
@@ -76,4 +79,5 @@ MULTICA_SLACK_SECRET_KEY=<base64 编码的 32 字节密钥>
- [飞书 / Lark Bot 接入](/lark-bot-integration)
- [Slack Bot 接入](/slack-bot-integration)
+- [钉钉 Bot 接入](/dingtalk-bot-integration)
- [与智能体对话](/chat)
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
new file mode 100644
index 0000000000..83a87b1d03
--- /dev/null
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
@@ -0,0 +1,134 @@
+---
+title: DingTalk Bot 連携
+description: Multica エージェントをあなた自身の DingTalk アプリに接続します——DingTalk オープンプラットフォームで Stream モードのロボットを作成し、その AppKey と AppSecret をコピーして Multica に貼り付ければ、DingTalk の中から DM したり、グループで @ メンションしたり、/issue と入力したりできます。
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+任意の[エージェント](/agents)を DingTalk Bot に接続すれば、チームは DingTalk の中から直接それを使えます——Bot に DM したり、グループで @ メンションしたり、スクリーンショットを送ったり、`/issue` と入力してアプリを開かずに [Multica イシュー](/issues)を起票したりできます。
+
+DingTalk は**自分のアプリを持ち込む(BYO: bring-your-own-app)**モデルを採用しています。ワークスペースの admin が DingTalk アプリを作成し、それに Stream モードのロボットを追加して、その認証情報を Multica に貼り付けます。エージェントごとに**専用の** DingTalk アプリを持つため、同じ組織内で複数のエージェントがそれぞれ別個に @ メンションできる異なる Bot を持てます。(これは紐づけがスキャンしてインストールするフローである [Lark](/lark-bot-integration) とは異なります。)
+
+セットアップ全体は以下のとおりで、所要時間は約 5 分です。最終的に、Multica に貼り付ける 2 つの認証情報が得られます。
+
+- **AppKey** —— アプリの client id
+- **AppSecret** —— アプリの client secret
+
+## DingTalk アプリをセットアップする
+
+### 1. アプリを作成し、Stream モードのロボットを追加する
+
+1. [DingTalk オープンプラットフォーム](https://open-dev.dingtalk.com)を開き、**企業内部アプリ**(企业内部应用)を作成します。
+2. そのアプリを開き、**ロボット**(机器人)機能を追加します。
+3. ロボット設定で、**メッセージ受信モード**を **Stream モード**(推送模式)に設定します。これにより、Bot は webhook を受け取るのではなく、長時間維持される push 接続を通じて外向きに接続するようになります。
+
+これがプラットフォーム層で Multica が必要とするすべてです——Bot は Stream モードで外向きに接続するので、公開アドレスを設定する必要はありません。
+
+| 設定 | なぜそこにあるか |
+|---|---|
+| **企業内部アプリ** | ロボットを保持し、AppKey / AppSecret 認証情報を発行するアプリのコンテナです。 |
+| **ロボット機能** | @ メンションされ、返信を投稿する Bot のアイデンティティを作成します。 |
+| **Stream モード** | Bot は長時間維持される Stream 接続を通じて外向きに接続します——**公開 webhook/URL は不要**です。 |
+| **ロボット送信権限** | Bot が DingTalk にメッセージを送り返せるようにします(エージェントの返信や能動的なメッセージ)。 |
+| **メッセージ読み取り権限** | Bot が 1:1 メッセージと、自分を @ メンションしたグループメッセージを受け取れるようにします。 |
+
+**webhook URL も OAuth リダイレクト URL もありません**。ロボットは Stream モードで動作し、BYO は OAuth を使わないからです。
+
+<Callout type="info">
+DingTalk にはネイティブの入力中/リアクションのインジケーターがないため——Slack とは異なり——Bot は処理を始めると短い「処理中」の合図を先に返し、完全な返信はエージェントの処理が終わってから届きます。短時間に連投したメッセージは 1 つの合図にまとめられます。
+</Callout>
+
+### 2. ロボットに権限を付与する
+
+ロボットに、**メッセージを受信**し、**メッセージを送り返す**ために必要なスコープ(ロボットのメッセージ送信権限)を付与します。送信権限がないと、エージェントは動作しても返信を配信できません。
+
+### 3. AppKey と AppSecret をコピーする
+
+アプリの **凭证与基础信息**(認証情報と基本情報)を開き、以下をコピーします。
+
+- **AppKey** —— これがアプリの **client id** です
+- **AppSecret** —— これがアプリの **client secret** です
+
+### 4. Multica で接続する
+
+1. **Agents → _あなたのエージェント_** からそのエージェントを開き、**Integrations** タブ(または左サイドバーの **Integrations** 区画)を開きます。
+2. **Connect DingTalk** をクリックします。
+3. **AppKey** と **AppSecret** を貼り付け、**Connect** をクリックします。
+4. エージェントに **Connected to DingTalk** と表示されます。Bot はこれで、自身の Stream 接続を通じて待ち受けています。
+
+<Callout type="warning">
+2 つの認証情報は**同じ** DingTalk アプリのものでなければならず、そのアプリはちょうど **1 つ**のエージェントに対応します。すでに別のエージェントやワークスペースに接続されているアプリを接続しようとすると拒否されます。アプリを別のエージェントへ移すには、まず切断してください。**新しい**アプリでエージェントを再接続すると、そのエージェントの Bot がその場で更新されます。
+</Callout>
+
+<Callout type="info">
+**複数のエージェント**でこれを設定しますか? フロー全体をエージェントごとに 1 回ずつ繰り返してください——各エージェントが専用の DingTalk アプリと専用の AppKey / AppSecret を持ち、組織内で別々の Bot として表示されます。
+</Callout>
+
+## この連携でできること
+
+| 場所 | 動作 |
+|---|---|
+| **エージェント → Integrations** | owner と admin には **Connect DingTalk** が表示され、接続すると **Connected to DingTalk** バッジと **Disconnect** コントロールに切り替わります。 |
+| **Bot に DM** | ワークスペースメンバーが 1:1 チャットで Bot に直接メッセージを送ります。会話はそのエージェントとの Multica [chat](/chat) セッションになり、すべてのメッセージが読み取られます。 |
+| **グループで @ メンション** | Bot をグループに追加し、@ メンションします。読み取られるのはメンションしたメッセージだけで、Bot はグループ全体を聞いているわけではありません。 |
+| **画像を送る** | DM の画像も、グループで @ メンションと一緒に送った画像も、会話に入りエージェントが見られるようになります——PNG・JPEG・GIF・WebP・BMP に対応し、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。各画像は Multica のストレージにコピーされるため、DingTalk の一時リンクが失効した後も会話の中に表示され続けます。ファイルと音声には対応していません。 |
+| **`/issue` コマンド** | `/issue <タイトル>` で始めると、入力内容からあなた名義の Multica イシューを直接かつ同期的に作成し、同じ会話へ ID とタイトルを返します。続く行は説明になります。同じ DingTalk メッセージの画像はチャット側にのみ添付され、直接作成したイシューにはコピーされません。 |
+| **`/new` コマンド** | `/new <あなたのメッセージ>` で始めると、そのメッセージを過去の文脈なしで実行します。`/new` だけを送ると、同じ fresh-start の意図が次の空でないメッセージに適用され、空の turn は作られません。既存の会話履歴はそのまま残ります。 |
+| **返信** | エージェントの回答は、同じ 1:1 チャットまたはグループに投稿し返されます。 |
+
+## Bot を使う(メンバー)
+
+### 最初のメッセージ:アカウントを紐づける
+
+初めて Bot を @ メンションするか DM すると、Bot は **アカウントを紐づける** プロンプトで返信し、それはプロダクト内の **/dingtalk/bind** ページを指しています。リンクをタップして Multica にサインインすると、あなたの DingTalk アイデンティティがあなたの Multica メンバーシップに紐づきます——これによって、エージェントがあなたとして振る舞えるようになります(たとえば `/issue` はあなたの名義でイシューを起票します)。このリンクは使い切りで、約 15 分で失効します。新しいものが必要なら、もう一度 Bot にメッセージを送るだけです。
+
+<Callout type="warning">
+Bot を使えるのは **ワークスペースのメンバー** だけです。メンバーでない場合や、アイデンティティの紐づけをスキップした場合、Bot は実行されません——あなたのメッセージは破棄されます(内容は保存せず、監査のために記録されます)。
+</Callout>
+
+### 対話とコマンド
+
+- **グループで** —— 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 を次の空でないメッセージに適用できます。どちらも既存の会話履歴は削除しません。
+
+## 管理と切断
+
+ワークスペース全体の管理は **Settings → Integrations** にあります。
+
+- **Connected bots** は、ワークスペース内のすべての Bot と、それぞれが紐づくエージェントを一覧表示します(すべてのメンバーから見えます)。
+- **Disconnect** は **owner / admin 専用** です。切断すると Bot は DingTalk メッセージの受信を停止し、その接続が破棄されます。インストール記録は監査のために保持され、あとで再接続できます。
+
+## 権限
+
+- **接続 / 切断** にはワークスペースの **owner** または **admin** が必要です。
+- **Bot との対話** には、DingTalk アイデンティティを紐づけたワークスペースメンバーであることが必要です。それ以外の人は一律に破棄されます。
+- 破棄されたメッセージの本文が保存されることはありません——監査のために破棄理由だけが記録されます。
+
+## セルフホストのセットアップ
+
+Multica Cloud では連携はすでに利用可能です——このセクションは飛ばしてください。
+
+セルフホストの場合、DingTalk は**保存時の暗号化キーを設定するまでオフ**です。このキーは各アプリの AppSecret をデータベース保存前に暗号化します。AppKey は機密情報ではないインストールのルーティング識別子として平文で保存されます。BYO にはデプロイレベルの OAuth の client id/secret は**不要**です——各インストールは admin が貼り付けた認証情報を使います。
+
+1. 32 バイトのキーを生成し、API サーバーに設定します。
+
+ ```dotenv
+ MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
+ ```
+
+ たとえば: `openssl rand -base64 32`。
+
+2. API を再起動します。キーを設定するまで、**Settings → Integrations** には「DingTalk integration not enabled」という通知が表示され、**Connect DingTalk** のエントリポイントは非表示のままになります。
+
+<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) — セルフホスト構成の完全なリファレンス
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
new file mode 100644
index 0000000000..a4a88795df
--- /dev/null
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
@@ -0,0 +1,134 @@
+---
+title: DingTalk Bot 연동
+description: Multica 에이전트를 자체 DingTalk 앱에 연결하세요 — DingTalk 오픈 플랫폼에서 Stream 모드 로봇을 만들고, AppKey + AppSecret을 복사해 Multica에 붙여넣은 다음, DingTalk 안에서 DM하거나 그룹에서 @로 멘션하거나 /issue를 입력하세요.
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+아무 [에이전트](/agents)나 DingTalk 봇에 연결하면, 팀이 DingTalk 안에서 바로 그 에이전트와 함께 일할 수 있습니다 — 봇에게 DM을 보내거나, 그룹에서 `@`로 멘션하거나, 스크린샷을 보내거나, `/issue`를 입력해 앱을 열지 않고도 [Multica 이슈](/issues)를 생성하세요.
+
+DingTalk은 **자체 앱 사용(BYO)** 모델을 따릅니다: 워크스페이스 admin이 DingTalk 앱을 만들고, 거기에 Stream 모드 로봇을 추가한 다음, 그 자격 증명을 Multica에 붙여넣습니다. 각 에이전트가 **자체** DingTalk 앱을 갖습니다 — 그래서 하나의 조직 안에서 여러 에이전트가 각각 별개로 `@`로 멘션할 수 있는 봇을 가질 수 있습니다. (바인딩이 스캔하여 설치하는 방식인 [Lark](/lark-bot-integration)와는 다릅니다.)
+
+전체 설정은 아래에 있으며 약 5분이 걸립니다. 마지막에는 Multica에 붙여넣을 두 개의 자격 증명을 얻게 됩니다:
+
+- **AppKey** — 앱의 client id
+- **AppSecret** — 앱의 client secret
+
+## DingTalk 앱 설정하기
+
+### 1. 앱을 만들고 Stream 모드 로봇 추가하기
+
+1. [DingTalk 오픈 플랫폼](https://open-dev.dingtalk.com)으로 이동해 **기업 내부 앱**(企业内部应用)을 만듭니다.
+2. 그 앱을 열고 **로봇**(机器人) 기능을 추가합니다.
+3. 로봇 설정에서 **메시지 수신 모드**를 **Stream 모드**(推送模式)로 설정합니다. 이것이 봇으로 하여금 webhook을 받는 대신, 오래 유지되는 push 연결을 통해 밖으로 연결하게 합니다.
+
+이것이 플랫폼 수준에서 Multica가 필요로 하는 전부입니다 — 봇이 Stream 모드로 밖으로 연결하므로, 공개 주소를 구성할 필요가 없습니다:
+
+| 설정 | 이유 |
+|---|---|
+| **기업 내부 앱** | 로봇을 담고 AppKey / AppSecret 자격 증명을 발급하는 앱 컨테이너입니다. |
+| **로봇 기능** | `@`로 멘션되고 답변을 게시하는 봇 신원을 생성합니다. |
+| **Stream 모드** | 봇이 오래 유지되는 Stream 연결로 밖으로 연결합니다 — **공개 webhook / URL이 필요 없습니다**. |
+| **로봇 전송 권한** | 봇이 DingTalk으로 메시지를 다시 보낼 수 있게 합니다(에이전트의 답변과 능동적 메시지). |
+| **메시지 읽기 권한** | 봇이 1:1 메시지와, 자신을 `@`로 멘션한 그룹 메시지를 받을 수 있게 합니다. |
+
+**webhook URL도 OAuth redirect URL도 없습니다.** 로봇이 Stream 모드로 동작하고, BYO는 OAuth를 사용하지 않기 때문입니다.
+
+<Callout type="info">
+DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과 달리 — 봇이 처리를 시작하면 짧은 "처리 중" 안내를 먼저 보내고, 전체 답변은 에이전트가 끝난 뒤에 도착합니다. 짧은 시간에 연달아 보낸 메시지는 하나의 안내로 합쳐집니다.
+</Callout>
+
+### 2. 로봇에 권한 부여하기
+
+로봇이 **메시지를 받고** **메시지를 다시 보낼** 수 있도록 필요한 스코프(로봇 메시지 전송 권한)를 부여하세요. 전송 권한이 없으면 에이전트는 실행되더라도 답변을 전달할 수 없습니다.
+
+### 3. AppKey와 AppSecret 복사하기
+
+앱의 **凭证与基础信息**(자격 증명 및 기본 정보)을 열고 복사합니다:
+
+- **AppKey** — 이것이 앱의 **client id**입니다
+- **AppSecret** — 이것이 앱의 **client secret**입니다
+
+### 4. Multica에서 연결하기
+
+1. **Agents → _당신의 에이전트_** → **Integrations** 탭(또는 왼쪽 사이드바의 **Integrations** 섹션)에서 에이전트를 엽니다.
+2. **Connect DingTalk**을 클릭합니다.
+3. **AppKey**와 **AppSecret**을 붙여넣은 다음 **Connect**를 클릭합니다.
+4. 에이전트에 **Connected to DingTalk**이 표시됩니다. 봇은 이제 자체 Stream 연결로 수신 대기합니다.
+
+<Callout type="warning">
+두 자격 증명은 **같은** DingTalk 앱에서 와야 하며, 그 앱은 정확히 **하나의** 에이전트에 매핑됩니다. 이미 다른 에이전트나 워크스페이스에 연결된 앱을 연결하는 것은 거부됩니다. 앱을 다른 에이전트로 옮기려면 먼저 연결을 해제하세요. **새** 앱으로 에이전트를 다시 연결하면 그 에이전트의 봇이 그 자리에서 갱신됩니다.
+</Callout>
+
+<Callout type="info">
+**여러 에이전트**에 설정하나요? 에이전트당 전체 과정을 한 번씩 반복하세요 — 각 에이전트가 자체 DingTalk 앱과 자체 AppKey / AppSecret을 가지며, 조직에 별개의 봇으로 나타납니다.
+</Callout>
+
+## 연동이 하는 일
+
+| 위치 | 동작 |
+|---|---|
+| **Agent → Integrations** | owner와 admin에게는 **Connect DingTalk**이 보이며, 연결되면 **Connected to DingTalk** 배지와 **Disconnect** 컨트롤로 바뀝니다. |
+| **봇에게 DM** | 워크스페이스 멤버가 1:1 채팅에서 봇에게 직접 메시지를 보냅니다. 그 대화는 에이전트와의 Multica [chat](/chat) 세션이 되며, 모든 메시지를 읽습니다. |
+| **그룹에서 `@`-멘션** | 봇을 그룹에 추가하고 `@`로 멘션하세요. 멘션한 메시지만 읽으며, 봇이 그룹 전체를 듣지는 않습니다. |
+| **이미지 보내기** | DM의 이미지, 또는 그룹에서 `@`-멘션과 함께 보낸 이미지는 대화에 들어가 에이전트가 볼 수 있습니다 — PNG, JPEG, GIF, WebP, BMP를 지원하며, 메시지당 최대 4장, 장당 10 MB까지입니다. 각 이미지는 Multica 스토리지로 복사되므로, DingTalk의 임시 링크가 만료된 뒤에도 대화에서 계속 보입니다. 파일과 음성은 지원하지 않습니다. |
+| **`/issue` 명령** | `/issue <제목>`으로 시작하면 입력 내용에서 당신 이름의 Multica 이슈를 직접 동기적으로 만들고 같은 대화에 ID와 제목을 돌려줍니다. 다음 줄은 설명이 됩니다. 같은 DingTalk 메시지의 이미지는 채팅 메시지에만 첨부되고, 직접 만든 이슈에는 복사되지 않습니다. |
+| **`/new` 명령** | `/new <당신의 메시지>`로 시작하면 그 메시지를 이전 대화 맥락 없이 실행합니다. `/new`만 보내면 같은 fresh-start 의도가 다음 비어 있지 않은 메시지에 적용되며 빈 turn은 만들어지지 않습니다. 기존 대화 기록은 그대로 유지됩니다. |
+| **답변** | 에이전트의 답변은 같은 1:1 채팅 또는 그룹으로 다시 게시됩니다. |
+
+## 봇 사용하기 (멤버)
+
+### 첫 메시지: 계정 연결하기
+
+봇을 처음 `@`로 멘션하거나 DM하면, **계정을 연결하라**는 안내로 답하며, 이는 제품 내 **/dingtalk/bind** 페이지를 가리킵니다. 링크를 탭하고 Multica에 로그인하면, 당신의 DingTalk 신원이 Multica 멤버십에 바인딩됩니다 — 바로 이 단계가 에이전트로 하여금 당신을 대신해 행동하게 합니다(예: `/issue`는 당신 이름으로 이슈를 생성합니다). 이 링크는 일회용이며 약 15분 후에 만료됩니다. 새 링크가 필요하면 봇에게 다시 메시지를 보내세요.
+
+<Callout type="warning">
+**워크스페이스 멤버**만 봇을 사용할 수 있습니다. 멤버가 아니거나 신원 연결을 건너뛰면 봇은 실행되지 않으며, 메시지는 폐기됩니다(감사 목적으로 기록되며, 내용은 저장하지 않습니다).
+</Callout>
+
+### 대화와 명령
+
+- **그룹에서** — 봇을 그룹에 추가한 다음 `@your-bot <당신의 메시지>`로 보내세요. 후속 메시지마다 다시 멘션하세요(봇은 자신을 멘션한 메시지만 읽습니다).
+- **1:1 채팅에서** — 봇을 열고 직접 메시지를 보내세요. 멘션이 필요 없으며, 모든 메시지를 읽습니다.
+- **이미지 보내기** — 텍스트가 있든 없든 스크린샷이나 사진을 보내세요. 대화에 들어가 에이전트가 참고할 수 있습니다. PNG, JPEG, GIF, WebP, BMP를 지원하며, 메시지당 최대 4장, 장당 10 MB까지입니다.
+- **이슈 생성** — `/issue Safari에서 로그인 리다이렉트가 깨졌어요`를 보내고 필요하면 다음 줄에 설명을 추가하세요. Multica가 이슈를 동기적으로 만들고 ID와 제목을 채팅에 돌려줍니다. 같은 메시지의 이미지는 채팅에 남고 이슈에는 첨부되지 않습니다.
+- **새로 시작하기** — `/new <당신의 메시지>`를 보내 그 메시지를 이전 맥락 없이 실행하거나, `/new`만 보내 fresh-start를 다음 비어 있지 않은 메시지에 적용하세요. 어느 방식도 기존 대화 기록을 삭제하지 않습니다.
+
+## 관리 및 연결 해제
+
+워크스페이스 전체 관리는 **Settings → Integrations**에 있습니다:
+
+- **Connected bots**는 워크스페이스 내 모든 봇과 각 봇이 바인딩된 에이전트를 나열합니다(모든 멤버에게 보입니다).
+- **Disconnect**는 **owner / admin 전용**입니다. 봇이 DingTalk 메시지 수신을 멈추고 연결이 해체됩니다. 설치 기록은 감사용으로 유지되며, 이후 다시 연결할 수 있습니다.
+
+## 권한
+
+- **연결 / 연결 해제**에는 워크스페이스 **owner** 또는 **admin**이 필요합니다.
+- **봇과 대화하기**에는 DingTalk 신원이 연결된 워크스페이스 멤버여야 합니다. 그 외의 사람은 모두 폐기됩니다.
+- 폐기된 메시지의 본문은 절대 저장되지 않으며 — 감사용 폐기 사유만 기록됩니다.
+
+## 자체 호스팅 설정
+
+Multica Cloud에서는 연동이 이미 사용 가능합니다 — 이 섹션은 건너뛰세요.
+
+자체 호스팅의 경우, DingTalk은 **at-rest 암호화 키를 설정하기 전까지 꺼져 있습니다**. 이 키는 각 앱의 AppSecret을 데이터베이스에 저장하기 전에 암호화합니다. AppKey는 비밀이 아닌 installation 라우팅 식별자로 평문 저장됩니다. BYO에는 배포 수준의 OAuth client id/secret이 **필요 없습니다** — 각 installation은 admin이 붙여넣은 자격 증명을 사용합니다.
+
+1. 32바이트 키를 생성해 API 서버에 설정합니다:
+
+ ```dotenv
+ MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
+ ```
+
+ 예를 들면: `openssl rand -base64 32`.
+
+2. API를 재시작하세요. 키가 설정되기 전까지 **Settings → Integrations**에는 "DingTalk integration not enabled" 안내가 표시되고, **Connect DingTalk** 진입점은 숨겨진 채로 유지됩니다.
+
+<Callout type="info">
+키는 정확히 32바이트로 디코딩되어야 하며 — `openssl rand -base64 32`가 이를 충족합니다. 오래 유지되는 시크릿으로 다루세요: 키를 회전하거나 잃으면 이미 저장된 자격 증명을 복호화할 수 없게 되어, 모든 봇이 다시 연결해야 합니다. "계정을 연결하세요" 링크는 웹 앱 URL(`MULTICA_APP_URL`, 없으면 `FRONTEND_ORIGIN`으로 폴백)에서 만들어집니다. 일반적인 배포에서는 이미 설정되어 있으므로 추가로 구성할 것은 없습니다.
+</Callout>
+
+## 다음
+
+- [Chat 연동](/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.mdx
new file mode 100644
index 0000000000..477dd580f7
--- /dev/null
+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx
@@ -0,0 +1,134 @@
+---
+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.
+---
+
+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.
+
+DingTalk uses a **bring-your-own-app (BYO)** model: a workspace admin creates a DingTalk app, adds a Stream-mode robot to it, and pastes its credentials into Multica. Each agent gets **its own** DingTalk app — so several agents can each have a distinct, separately @-mentionable bot in the same organization. (This differs from [Lark](/lark-bot-integration), where binding is a scan-to-install flow.)
+
+The whole setup is below and takes about five minutes. You'll end up with two credentials to paste into Multica:
+
+- an **AppKey** — the app's client id
+- an **AppSecret** — the app's client secret
+
+## Set up your DingTalk app
+
+### 1. Create the app and add a Stream-mode robot
+
+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.
+
+This is everything Multica needs at the platform level — it connects out over Stream mode, so you don't configure any public address:
+
+| 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. |
+
+There is **no webhook URL and no OAuth redirect URL**, because the robot runs over Stream mode and BYO doesn't use OAuth.
+
+<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>
+
+### 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
+
+Open the app's **凭证与基础信息** (Credentials & Basic Information) and copy:
+
+- the **AppKey** — this is your app's **client id**
+- the **AppSecret** — this is your app's **client secret**
+
+### 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.
+
+<Callout type="warning">
+Both credentials must be from the **same** DingTalk app, and that app maps to exactly **one** agent. Connecting an app that's already connected to a different agent or workspace is refused. To move an app to another agent, disconnect it first; re-connecting an agent with a **new** app updates that agent's bot in place.
+</Callout>
+
+<Callout type="info">
+Setting this up for **multiple agents**? Repeat the whole flow once per agent — each agent gets its own DingTalk app and its own AppKey / AppSecret, and they show up as separate bots in your organization.
+</Callout>
+
+## What the integration does
+
+| 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. Only the mentioning message is 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. 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 remain attached to the chat turn; they are not copied onto the directly created issue. |
+| **`/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. The conversation history remains intact. |
+| **Reply** | The agent's answer is posted back into the same 1:1 chat or group. |
+
+## Use the bot (members)
+
+### First message: link your account
+
+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.
+
+<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>
+
+### Chat and commands
+
+- **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 and posts its ID and title back into the chat. Images in that message stay on the chat turn and are not attached to the issue.
+- **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. Neither form removes the existing conversation history.
+
+## Manage and disconnect
+
+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).
+- **Disconnect** is **owner / admin only**. It stops the bot from receiving DingTalk messages and tears down its connection; the installation record is kept for audit, and you can re-connect later.
+
+## Permissions
+
+- **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
+
+On Multica Cloud the integration is already available — skip this section.
+
+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.
+
+1. Generate a 32-byte key and set it on the API server:
+
+ ```dotenv
+ MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
+ ```
+
+ For example: `openssl rand -base64 32`.
+
+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.
+
+<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
+- [Agents](/agents) · [Chat](/chat) · [Issues](/issues)
+- [Environment variables](/environment-variables) — full self-host configuration reference
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
new file mode 100644
index 0000000000..cf52abff2d
--- /dev/null
+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
@@ -0,0 +1,134 @@
+---
+title: 钉钉 Bot 接入
+description: 把 Multica 智能体接入你自己的钉钉 app——在钉钉开放平台创建一个 Stream 模式的机器人、复制它的 AppKey 与 AppSecret、粘贴进 Multica,然后就能在钉钉里私聊它、在群里 @ 它,或输入 /issue。
+---
+
+import { Callout } from "fumadocs-ui/components/callout";
+
+把任意[智能体](/agents)接入一个钉钉 Bot,团队就能在钉钉里直接使用它——私聊 Bot、在群里 @ 它、发截图给它,或者输入 `/issue` 直接创建一个 [Multica issue](/issues),不用打开应用。
+
+钉钉走的是**自带应用(bring-your-own-app,BYO)**模式:workspace 管理员创建一个钉钉 app,给它加一个 Stream 模式的机器人,再把它的凭证粘贴进 Multica。每个智能体都有**它自己的**钉钉 app——所以多个智能体可以在同一个组织里各自拥有一个独立、可单独 @ 的 Bot。(这一点和 [Lark](/lark-bot-integration) 不同,Lark 的绑定是扫码安装流程。)
+
+整个设置流程在下面,大约五分钟。最后你会得到两个凭证粘贴进 Multica:
+
+- 一个 **AppKey** —— app 的 client id
+- 一个 **AppSecret** —— app 的 client secret
+
+## 设置你的钉钉 app
+
+### 1. 创建 app 并添加一个 Stream 模式的机器人
+
+1. 打开[钉钉开放平台](https://open-dev.dingtalk.com),创建一个**企业内部应用**。
+2. 进入该应用,添加**机器人**能力。
+3. 在机器人设置里,把**消息接收模式**设为 **Stream 模式**(推送模式)。正是这一项让 Bot 通过一条长连接向外推送接收消息,而不是去接收一个 webhook。
+
+这就是 Multica 在平台层所需的一切——它通过 Stream 模式向外连接,所以你不用配置任何公网地址:
+
+| 配置项 | 为什么需要它 |
+|---|---|
+| **企业内部应用** | 承载机器人、并签发 AppKey / AppSecret 凭证的那个 app 容器。 |
+| **机器人能力** | 创建被 @ 和发回复用的那个 Bot 身份。 |
+| **Stream 模式** | Bot 通过一条长连接的 Stream 向外连接——**无需任何公网 webhook / URL**。 |
+| **机器人发送权限** | 让 Bot 能把消息发回钉钉(智能体的回复以及主动消息)。 |
+| **消息读取权限** | 让 Bot 能接收单聊消息,以及群里 @ 了它的消息。 |
+
+这里**既没有 webhook URL,也没有 OAuth 重定向 URL**,因为机器人跑在 Stream 模式上,而 BYO 不使用 OAuth。
+
+<Callout type="info">
+钉钉没有原生的「正在输入」/ 表情回应指示器,所以——和 Slack 不同——Bot 会在开始处理时先回一条简短的「正在处理」提示,完整回复在智能体处理完后送达。短时间内连发的多条消息会合并为一条提示。
+</Callout>
+
+### 2. 给机器人授权
+
+给机器人授予它需要的权限,让它既能**接收消息**又能**把消息发回去**(机器人消息发送权限)。没有发送权限,智能体能跑,但它的回复发不出来。
+
+### 3. 复制 AppKey 和 AppSecret
+
+打开该应用的 **凭证与基础信息**,复制:
+
+- **AppKey** —— 这就是你 app 的 **client id**
+- **AppSecret** —— 这就是你 app 的 **client secret**
+
+### 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 恰好对应**一个**智能体。连接一个已经连到别的智能体或 workspace 的 app 会被拒绝。要把一个 app 挪到另一个智能体,先断开它;用一个**新的** app 重新连接某个智能体,会就地更新那个智能体的 Bot。
+</Callout>
+
+<Callout type="info">
+要给**多个智能体**做这套设置?每个智能体都把整套流程走一遍——每个智能体都有自己的钉钉 app 和自己的一对 AppKey / AppSecret,它们会在你的组织里显示成各自独立的 Bot。
+</Callout>
+
+## 这个集成能做什么
+
+| 入口 | 行为 |
+|---|---|
+| **智能体 → 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 <标题>` 开头,会按输入直接、同步地以你的身份创建 Multica issue,并在原对话中返回 issue 编号和标题;后续行会作为描述。同一条钉钉消息中的图片只附在聊天消息上,不会复制到直接创建的 issue。 |
+| **`/new` 命令** | 以 `/new <你的消息>` 开头,会让这条消息在不带旧上下文的情况下运行。单独发送 `/new` 会把同样的 fresh 意图留给下一条非空消息,不会创建空 turn;已有对话记录保持不变。 |
+| **回复** | 智能体的答复会被发回同一个单聊或群里。 |
+
+## 使用 Bot(成员)
+
+### 第一条消息:绑定你的账号
+
+第一次 @ 或私聊 Bot 时,它会回一条 **绑定你的账号** 提示,指向产品内的 **/dingtalk/bind** 页面。点开链接、登录 Multica,你的钉钉身份就会绑定到你的 Multica 成员身份——正是这一步让智能体能以你的身份行事(比如 `/issue` 会把 issue 记在你名下)。这个链接是一次性的,大约 15 分钟后过期;再给 Bot 发条消息就能拿到一个新的。
+
+<Callout type="warning">
+只有**工作区成员**才能使用 Bot。如果你不是成员,或者跳过了身份绑定,Bot 不会运行——你的消息会被丢弃(仅出于审计目的记录,不保存消息内容)。
+</Callout>
+
+### 对话与命令
+
+- **在群里** —— 把 Bot 加进群,然后 `@your-bot <你的消息>`。每次追问都要重新 @ 它一下(Bot 只读取 @ 了它的消息)。
+- **在单聊里** —— 打开 Bot 并直接给它发消息;不用 @,每一条消息都会被读取。
+- **发图片** —— 直接发截图或照片,带不带文字都行;它们会进入对话,供智能体查看。支持 PNG、JPEG、GIF、WebP、BMP;每条消息最多 4 张,每张不超过 10 MB。
+- **创建 issue** —— 发送 `/issue Safari 上登录跳转坏了`,需要时可在后续行补充描述。Multica 会同步创建 issue,并在聊天中返回编号和标题。同一条消息中的图片只保留在聊天消息上,不会附到 issue。
+- **重新开始** —— 发送 `/new <你的消息>`,让这条消息不带旧上下文运行;也可以单独发送 `/new`,把 fresh 意图应用到下一条非空消息。两种方式都不会删除已有对话记录。
+
+## 管理与断开
+
+工作区级别的管理在 **Settings → Integrations**:
+
+- **Connected bots** 列出工作区里每个 Bot 以及它各自绑定的智能体(所有成员都能看到)。
+- **Disconnect** 仅限 **所有者 / 管理员**。它会让 Bot 停止接收钉钉消息并拆掉它的连接;安装记录会保留以便审计,之后你可以重新连接。
+
+## 权限
+
+- **连接 / 断开** 需要工作区**所有者**或**管理员**。
+- **和 Bot 对话** 需要你是工作区成员且已绑定钉钉身份。其余的人一律被丢弃。
+- 对于被丢弃的消息,绝不保存消息内容——只记录一个丢弃原因,用于审计。
+
+## 自部署配置
+
+在 Multica Cloud 上这个集成已经可用——可跳过本节。
+
+自部署时,**在你设置好静态加密密钥之前,钉钉是关闭的**。这个密钥会在每个 app 的 AppSecret 落库前对其加密;AppKey 作为非敏感的安装路由标识明文保存。BYO 在部署层面**不需要** OAuth client id/secret——每个安装用的都是管理员粘贴进来的那对凭证。
+
+1. 生成一个 32 字节的密钥并设置到 API 服务器:
+
+ ```dotenv
+ MULTICA_DINGTALK_SECRET_KEY=<base64-encoded 32-byte key>
+ ```
+
+ 例如:`openssl rand -base64 32`。
+
+2. 重启 API。在密钥设置好之前,**Settings → Integrations** 会显示一条「DingTalk integration not enabled」提示,**Connect DingTalk** 入口也会保持隐藏。
+
+<Callout type="info">
+这个密钥必须正好解码出 32 字节——`openssl rand -base64 32` 就能做到。把它当成一个长期有效的密钥:轮换或丢失它会让已存储的凭证无法解密,迫使每个 Bot 重新连接。「绑定你的账号」链接是用你的 Web 应用地址(`MULTICA_APP_URL`,未设置时回退到 `FRONTEND_ORIGIN`)拼出来的——正常部署里这个值本来就有,不需要额外配置。
+</Callout>
+
+## 下一步
+
+- [聊天集成](/channels) —— channel 引擎、会话与授权是怎么运作的
+- [智能体](/agents) · [Chat](/chat) · [Issues](/issues)
+- [环境变量](/environment-variables) —— 完整的自部署配置参考
diff --git a/apps/docs/content/docs/meta.ja.json b/apps/docs/content/docs/meta.ja.json
index 75265939d7..839b1e4a6b 100644
--- a/apps/docs/content/docs/meta.ja.json
+++ b/apps/docs/content/docs/meta.ja.json
@@ -38,6 +38,7 @@
"channels",
"lark-bot-integration",
"slack-bot-integration",
+ "dingtalk-bot-integration",
"github-integration",
"vcs-integration",
"---アプリ---",
diff --git a/apps/docs/content/docs/meta.json b/apps/docs/content/docs/meta.json
index 39afc1645b..3aae89fe15 100644
--- a/apps/docs/content/docs/meta.json
+++ b/apps/docs/content/docs/meta.json
@@ -38,6 +38,7 @@
"channels",
"lark-bot-integration",
"slack-bot-integration",
+ "dingtalk-bot-integration",
"github-integration",
"vcs-integration",
"---Apps---",
diff --git a/apps/docs/content/docs/meta.ko.json b/apps/docs/content/docs/meta.ko.json
index 2da39a5ba0..3926622e47 100644
--- a/apps/docs/content/docs/meta.ko.json
+++ b/apps/docs/content/docs/meta.ko.json
@@ -38,6 +38,7 @@
"channels",
"lark-bot-integration",
"slack-bot-integration",
+ "dingtalk-bot-integration",
"github-integration",
"vcs-integration",
"---앱---",
diff --git a/apps/docs/content/docs/meta.zh.json b/apps/docs/content/docs/meta.zh.json
index 3bc352a701..1669f6456b 100644
--- a/apps/docs/content/docs/meta.zh.json
+++ b/apps/docs/content/docs/meta.zh.json
@@ -38,6 +38,7 @@
"channels",
"lark-bot-integration",
"slack-bot-integration",
+ "dingtalk-bot-integration",
"github-integration",
"vcs-integration",
"---客户端---",
diff --git a/apps/web/app/dingtalk/bind/page.tsx b/apps/web/app/dingtalk/bind/page.tsx
new file mode 100644
index 0000000000..c1f08cdb7c
--- /dev/null
+++ b/apps/web/app/dingtalk/bind/page.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { Suspense } from "react";
+import { useSearchParams } from "next/navigation";
+import { DingTalkBindPage } from "@multica/views/dingtalk";
+
+// /dingtalk/bind?token=<raw> is the bot's "link your account" destination.
+// Suspense wraps useSearchParams per Next.js 15's CSR-bailout rule; the loading
+// text never paints in practice because the redemption page itself renders the
+// "redeeming…" state immediately.
+function DingTalkBindPageContent() {
+ const searchParams = useSearchParams();
+ const token = searchParams.get("token");
+ return <DingTalkBindPage token={token} />;
+}
+
+export default function Page() {
+ return (
+ <Suspense fallback={null}>
+ <DingTalkBindPageContent />
+ </Suspense>
+ );
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d70f1f318d..a01df4008b 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -161,6 +161,10 @@ import type {
ListSlackInstallationsResponse,
RegisterSlackBYORequest,
RedeemSlackBindingTokenResponse,
+ DingTalkInstallation,
+ ListDingTalkInstallationsResponse,
+ RegisterDingTalkBYORequest,
+ RedeemDingTalkBindingTokenResponse,
Squad,
SquadMember,
SquadMemberStatusListResponse,
@@ -276,6 +280,12 @@ import {
CreateBillingCheckoutSessionResponseSchema,
BillingCheckoutSessionStatusSchema,
CreateBillingPortalSessionResponseSchema,
+ DingTalkInstallationSchema,
+ ListDingTalkInstallationsResponseSchema,
+ RedeemDingTalkBindingTokenResponseSchema,
+ EMPTY_DINGTALK_INSTALLATION,
+ EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE,
+ EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE,
EMPTY_BILLING_BALANCE,
EMPTY_BILLING_TRANSACTIONS_PAGE,
EMPTY_BILLING_BATCHES_PAGE,
@@ -3456,4 +3466,60 @@ export class ApiClient {
body: JSON.stringify({ token }),
});
}
+
+ // DingTalk integration
+ async listDingTalkInstallations(
+ workspaceId: string,
+ ): Promise<ListDingTalkInstallationsResponse> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/dingtalk/installations`);
+ return parseWithFallback(
+ raw,
+ ListDingTalkInstallationsResponseSchema,
+ EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE,
+ { endpoint: "GET /api/workspaces/:id/dingtalk/installations" },
+ );
+ }
+
+ // 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.
+ async registerDingTalkBYO(
+ workspaceId: string,
+ agentId: string,
+ body: RegisterDingTalkBYORequest,
+ ): Promise<DingTalkInstallation> {
+ const search = new URLSearchParams({ agent_id: agentId });
+ const raw = await this.fetch<unknown>(
+ `/api/workspaces/${workspaceId}/dingtalk/install/byo?${search.toString()}`,
+ {
+ method: "POST",
+ body: JSON.stringify(body),
+ },
+ );
+ return parseWithFallback(raw, DingTalkInstallationSchema, EMPTY_DINGTALK_INSTALLATION, {
+ endpoint: "POST /api/workspaces/:id/dingtalk/install/byo",
+ });
+ }
+
+ async deleteDingTalkInstallation(workspaceId: string, installationId: string): Promise<void> {
+ await this.fetch(`/api/workspaces/${workspaceId}/dingtalk/installations/${installationId}`, {
+ method: "DELETE",
+ });
+ }
+
+ async redeemDingTalkBindingToken(
+ token: string,
+ ): Promise<RedeemDingTalkBindingTokenResponse> {
+ const raw = await this.fetch<unknown>(`/api/dingtalk/binding/redeem`, {
+ method: "POST",
+ body: JSON.stringify({ token }),
+ });
+ return parseWithFallback(
+ raw,
+ RedeemDingTalkBindingTokenResponseSchema,
+ EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE,
+ { endpoint: "POST /api/dingtalk/binding/redeem" },
+ );
+ }
}
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index f475aafe90..15e1283c23 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -293,6 +293,31 @@ describe("ApiClient schema fallback", () => {
});
});
+ describe("listDingTalkInstallations", () => {
+ it("falls back to a safe empty shape when the response is malformed", async () => {
+ // `installations` with the wrong type triggers the fallback; the panel
+ // must not white-screen on `configured`/`install_supported`.
+ stubFetchJson({ installations: "not-an-array", configured: true });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listDingTalkInstallations("ws-1");
+ expect(res).toEqual({ installations: [], configured: false });
+ });
+
+ it("tolerates an old-server row and a missing install_supported flag", async () => {
+ stubFetchJson({
+ installations: [{ id: "dt-1", status: "active" }],
+ configured: true,
+ // install_supported omitted (predates the flag) -> undefined, not a crash
+ future_field: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listDingTalkInstallations("ws-1");
+ expect(res.installations).toHaveLength(1);
+ expect(res.configured).toBe(true);
+ expect(res.install_supported).toBeUndefined();
+ });
+ });
+
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.ts
index 89845298c7..b198a8b890 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -25,6 +25,9 @@ import type {
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
CronPreviewResponse,
+ DingTalkInstallation,
+ ListDingTalkInstallationsResponse,
+ RedeemDingTalkBindingTokenResponse,
GroupedIssuesResponse,
GitHubConnectResponse,
GitHubPullRequest,
@@ -2140,3 +2143,48 @@ export const MALFORMED_RUNTIME_MODEL_LIST_REQUEST: RuntimeModelListRequest = {
created_at: "",
updated_at: "",
};
+
+export const DingTalkInstallationSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ installer_user_id: z.string().default(""),
+ status: z.string().default("revoked"),
+ installed_at: z.string().default(""),
+ created_at: z.string().default(""),
+ updated_at: z.string().default(""),
+}).loose();
+
+export const EMPTY_DINGTALK_INSTALLATION: DingTalkInstallation = {
+ id: "",
+ workspace_id: "",
+ agent_id: "",
+ installer_user_id: "",
+ status: "revoked",
+ installed_at: "",
+ created_at: "",
+ updated_at: "",
+};
+
+export const ListDingTalkInstallationsResponseSchema = z.object({
+ installations: z.array(DingTalkInstallationSchema).default([]),
+ configured: z.boolean().default(false),
+ install_supported: z.boolean().optional(),
+}).loose();
+
+export const EMPTY_LIST_DINGTALK_INSTALLATIONS_RESPONSE: ListDingTalkInstallationsResponse = {
+ installations: [],
+ configured: false,
+};
+
+export const RedeemDingTalkBindingTokenResponseSchema = z.object({
+ workspace_id: z.string().default(""),
+ installation_id: z.string().default(""),
+ dingtalk_user_id: z.string().default(""),
+}).loose();
+
+export const EMPTY_REDEEM_DINGTALK_BINDING_TOKEN_RESPONSE: RedeemDingTalkBindingTokenResponse = {
+ workspace_id: "",
+ installation_id: "",
+ dingtalk_user_id: "",
+};
diff --git a/packages/core/dingtalk/index.ts b/packages/core/dingtalk/index.ts
new file mode 100644
index 0000000000..0df1bec842
--- /dev/null
+++ b/packages/core/dingtalk/index.ts
@@ -0,0 +1 @@
+export { dingtalkKeys, dingtalkInstallationsOptions } from "./queries";
diff --git a/packages/core/dingtalk/queries.ts b/packages/core/dingtalk/queries.ts
new file mode 100644
index 0000000000..ddec906cf1
--- /dev/null
+++ b/packages/core/dingtalk/queries.ts
@@ -0,0 +1,18 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+/** Query key namespace for everything DingTalk-installation-related. Realtime
+ * sync invalidates `installations(wsId)` on `dingtalk_installation:*` events so
+ * the Settings panel updates without a manual refetch (e.g. after a binding
+ * lands the install in another tab). */
+export const dingtalkKeys = {
+ all: (wsId: string) => ["dingtalk", wsId] as const,
+ installations: (wsId: string) => [...dingtalkKeys.all(wsId), "installations"] as const,
+};
+
+export const dingtalkInstallationsOptions = (wsId: string) =>
+ queryOptions({
+ queryKey: dingtalkKeys.installations(wsId),
+ queryFn: () => api.listDingTalkInstallations(wsId),
+ enabled: !!wsId,
+ });
diff --git a/packages/core/package.json b/packages/core/package.json
index 2a9fcfdad3..029e751686 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -105,6 +105,8 @@
"./composio/queries": "./composio/queries.ts",
"./slack": "./slack/index.ts",
"./slack/queries": "./slack/queries.ts",
+ "./dingtalk": "./dingtalk/index.ts",
+ "./dingtalk/queries": "./dingtalk/queries.ts",
"./feedback": "./feedback/index.ts",
"./feedback/mutations": "./feedback/mutations.ts",
"./realtime": "./realtime/index.ts",
diff --git a/packages/core/paths/reserved-slugs.ts b/packages/core/paths/reserved-slugs.ts
index efafda502b..50bf803db1 100644
--- a/packages/core/paths/reserved-slugs.ts
+++ b/packages/core/paths/reserved-slugs.ts
@@ -103,6 +103,11 @@ export const RESERVED_SLUGS: ReadonlySet<string> = new Set([
"tokens",
"cli",
+ // DingTalk account-bind route
+ // `/dingtalk/bind` is a global pre-workspace route where a member links their
+ // DingTalk identity. Reserve the prefix so a workspace slug cannot shadow it.
+ "dingtalk",
+
// Backend ops / observability
// `/health`, `/readyz`, `/healthz`, and `/ws` exist on the backend host;
// reserving them on the workspace slug space prevents naming confusion if/when
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index bc3517cb1c..a134b246c3 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -26,6 +26,7 @@ import {
import { githubKeys } from "../github/queries";
import { larkKeys } from "../lark/queries";
import { slackKeys } from "../slack/queries";
+import { dingtalkKeys } from "../dingtalk/queries";
import {
onIssueCreated,
onIssueUpdated,
@@ -796,6 +797,10 @@ export function useRealtimeSync(
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });
},
+ dingtalk_installation: () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
+ },
vcs_connection: () => {
const wsId = getCurrentWsId();
if (wsId) qc.invalidateQueries({ queryKey: ["vcs", wsId] });
diff --git a/packages/core/types/dingtalk.ts b/packages/core/types/dingtalk.ts
new file mode 100644
index 0000000000..984d8d3952
--- /dev/null
+++ b/packages/core/types/dingtalk.ts
@@ -0,0 +1,47 @@
+/** 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
+ * future MUST default to optional so older desktop builds keep parsing the
+ * response — see CLAUDE.md → API Compatibility. */
+export interface DingTalkInstallation {
+ id: string;
+ workspace_id: string;
+ agent_id: string;
+ installer_user_id: string;
+ status: "active" | "revoked" | string;
+ installed_at: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface ListDingTalkInstallationsResponse {
+ installations: DingTalkInstallation[];
+ /** Whether the deployment has the at-rest secret key configured. When false
+ * the connect entry points are hidden and the panel renders an "ask the
+ * operator to enable DingTalk" state. */
+ configured: boolean;
+ /** Whether the install path is available (true whenever DingTalk is
+ * configured, i.e. the at-rest key is set — a bring-your-own-app install
+ * needs no hosted credentials). Kept as a separate flag for forward/backward
+ * compat; optional so an older desktop build that predates it treats it as
+ * off. */
+ install_supported?: boolean;
+}
+
+/** 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. */
+export interface RegisterDingTalkBYORequest {
+ client_id: string;
+ client_secret: string;
+}
+
+/** Post-redemption echo: the DingTalk user id the token carried is now bound to
+ * the logged-in Multica user in this workspace/installation. */
+export interface RedeemDingTalkBindingTokenResponse {
+ workspace_id: string;
+ installation_id: string;
+ dingtalk_user_id: string;
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 7aa7823071..80214a6f44 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -191,6 +191,12 @@ export type {
RegisterSlackBYORequest,
RedeemSlackBindingTokenResponse,
} from "./slack";
+export type {
+ DingTalkInstallation,
+ ListDingTalkInstallationsResponse,
+ RegisterDingTalkBYORequest,
+ RedeemDingTalkBindingTokenResponse,
+} from "./dingtalk";
export type {
Autopilot,
AutopilotStatus,
diff --git a/packages/views/agents/components/agent-overview-pane.tsx b/packages/views/agents/components/agent-overview-pane.tsx
index 1bb283da35..9da7b0a46f 100644
--- a/packages/views/agents/components/agent-overview-pane.tsx
+++ b/packages/views/agents/components/agent-overview-pane.tsx
@@ -13,6 +13,7 @@ import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
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 {
AlertDialog,
AlertDialogAction,
@@ -171,9 +172,14 @@ export function AgentOverviewPane({
...slackInstallationsOptions(wsId),
enabled: !!wsId,
});
+ const { data: dingtalkListing } = useQuery({
+ ...dingtalkInstallationsOptions(wsId),
+ });
const integrationsConfigured =
- larkListing?.configured === true || slackListing?.configured === true;
+ larkListing?.configured === true ||
+ slackListing?.configured === true ||
+ dingtalkListing?.configured === true;
const visibleCapabilityTabs = useMemo(() => {
const showMcp = runtime
diff --git a/packages/views/agents/components/tabs/integrations-tab.test.tsx b/packages/views/agents/components/tabs/integrations-tab.test.tsx
index fa8556e0d4..d84d97e920 100644
--- a/packages/views/agents/components/tabs/integrations-tab.test.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.test.tsx
@@ -1,8 +1,8 @@
// @vitest-environment jsdom
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { ReactNode } from "react";
-import { render, screen } from "@testing-library/react";
+import { cleanup, render, screen } from "@testing-library/react";
import type { Agent } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../../locales/en/common.json";
@@ -100,6 +100,8 @@ const TEST_RESOURCES = {
en: { common: enCommon, agents: enAgents, settings: enSettings },
};
+afterEach(cleanup);
+
const agent: Agent = {
id: "agent-1",
workspace_id: "ws-1",
@@ -191,18 +193,18 @@ describe("IntegrationsTab", () => {
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's routes stay admin-only, so it
- // shows the read-only note instead of a CTA (MUL-4213).
+ // renders and receives owner_id; Slack's and DingTalk's routes stay
+ // admin-only, so each shows the read-only note instead of a CTA (MUL-4213).
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.queryByTestId("slack-bind-button")).toBeNull();
- // The Slack section falls back to the shared members note.
+ // The Slack and DingTalk sections each fall back to the shared members note.
expect(
- screen.getByText(/Only workspace owners and admins can connect an agent/i),
- ).toBeTruthy();
+ screen.getAllByText(/Only workspace owners and admins can connect an agent/i),
+ ).toHaveLength(2);
});
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.tsx
index 3aa4ce120c..af849fe8ed 100644
--- a/packages/views/agents/components/tabs/integrations-tab.tsx
+++ b/packages/views/agents/components/tabs/integrations-tab.tsx
@@ -7,9 +7,11 @@ 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 { memberListOptions } from "@multica/core/workspace/queries";
import { LarkAgentBindButton } from "../../../settings/components/lark-tab";
import { SlackAgentBindButton } from "../../../settings/components/slack-tab";
+import { DingTalkAgentBindButton } from "../../../settings/components/dingtalk-tab";
import { useT } from "../../../i18n";
/**
@@ -43,6 +45,9 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
...slackInstallationsOptions(wsId),
enabled: !!wsId,
});
+ const { data: dingtalkListing } = useQuery({
+ ...dingtalkInstallationsOptions(wsId),
+ });
const { data: members = [] } = useQuery({
...memberListOptions(wsId),
enabled: !!wsId,
@@ -74,11 +79,16 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
(inst) => inst.agent_id === agent.id && inst.status === "active",
) ?? false;
- // A member who can manage neither platform (not a workspace admin and not
- // this agent's owner) gets the read-only note instead of the sections.
+ 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;
+
+ // 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.
- if (!canManageLark && !canManageSlack) {
+ if (!canManageLark && !canManageSlack && !canManageDingtalk) {
return (
<div className="space-y-6">
<p className="text-caption text-muted-foreground">
@@ -183,6 +193,36 @@ export function IntegrationsTab({ agent }: { agent: Agent }) {
)}
</div>
</section>
+
+ <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">
+ <MessagesSquare className="h-4 w-4" />
+ </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.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>
+ ) : !dingtalkConfigured ? (
+ <p className="text-caption text-muted-foreground">
+ {ts(($) => $.dingtalk.not_enabled_title)}
+ </p>
+ ) : (
+ <DingTalkAgentBindButton agentId={agent.id} agentName={agent.name} />
+ )}
+ </div>
+ </section>
</div>
);
}
diff --git a/packages/views/dingtalk/bind-page.tsx b/packages/views/dingtalk/bind-page.tsx
new file mode 100644
index 0000000000..455a85b52a
--- /dev/null
+++ b/packages/views/dingtalk/bind-page.tsx
@@ -0,0 +1,145 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Card, CardContent } from "@multica/ui/components/ui/card";
+import { Button } from "@multica/ui/components/ui/button";
+import { api, ApiError } from "@multica/core/api";
+import { useAuthStore } from "@multica/core/auth";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+
+type RedeemState =
+ | { kind: "idle" }
+ | { kind: "redeeming" }
+ | { kind: "done"; workspaceId: string; installationId: string }
+ | { kind: "needs-auth" }
+ | { kind: "error"; reason: string };
+
+// DingTalkBindPage is the destination the bot's "link your account" prompt
+// points at. The user lands here logged out OR logged in; we require auth
+// before redeeming because the redeemer's Multica identity is taken from the
+// session (the token alone never proves who is binding).
+//
+// The token comes in via `?token=<raw>`. We POST it to
+// /api/dingtalk/binding/redeem; the backend returns 410 (invalid/expired),
+// 409 (already bound to another user), 403 (not a workspace member) or 200 with
+// the bound installation. Each maps to distinct copy via dingtalk_bind in
+// common.json.
+export function DingTalkBindPage({ token }: { token: string | null }) {
+ const { t } = useT("common");
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+ const navigation = useNavigation();
+ const [state, setState] = useState<RedeemState>({ kind: "idle" });
+ const redeemingToken = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (!token) {
+ setState({ kind: "error", reason: "missing_token" });
+ return;
+ }
+ if (isAuthLoading) return;
+ if (!user) {
+ setState({ kind: "needs-auth" });
+ return;
+ }
+ if (state.kind !== "idle" && state.kind !== "needs-auth") return;
+ if (redeemingToken.current === token) return;
+ redeemingToken.current = token;
+ setState({ kind: "redeeming" });
+ (async () => {
+ try {
+ const resp = await api.redeemDingTalkBindingToken(token);
+ setState({
+ kind: "done",
+ workspaceId: resp.workspace_id,
+ installationId: resp.installation_id,
+ });
+ } catch (e) {
+ setState({
+ kind: "error",
+ reason: redemptionFailureReason(e),
+ });
+ }
+ })();
+ }, [token, user, isAuthLoading, state.kind]);
+
+ return (
+ <div className="mx-auto flex min-h-screen max-w-md flex-col items-center justify-center p-6">
+ <Card className="w-full">
+ <CardContent className="space-y-4">
+ <h1 className="text-title font-semibold">{t(($) => $.dingtalk_bind.page_title)}</h1>
+ {state.kind === "idle" || state.kind === "redeeming" ? (
+ <p className="text-body text-muted-foreground">{t(($) => $.dingtalk_bind.redeeming)}</p>
+ ) : state.kind === "needs-auth" ? (
+ <>
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.dingtalk_bind.needs_auth_description)}
+ </p>
+ <Button
+ size="sm"
+ onClick={() =>
+ navigation.push(
+ `/login?next=${encodeURIComponent(
+ `/dingtalk/bind?token=${encodeURIComponent(token ?? "")}`,
+ )}`,
+ )
+ }
+ >
+ {t(($) => $.dingtalk_bind.sign_in)}
+ </Button>
+ </>
+ ) : state.kind === "done" ? (
+ <>
+ <p className="text-body font-medium">{t(($) => $.dingtalk_bind.done_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk_bind.done_description)}
+ </p>
+ </>
+ ) : (
+ <>
+ <p className="text-body font-medium">{t(($) => $.dingtalk_bind.error_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {(() => {
+ switch (state.reason) {
+ case "missing_token":
+ return t(($) => $.dingtalk_bind.error_missing_token);
+ case "expired":
+ return t(($) => $.dingtalk_bind.error_expired);
+ case "already_bound":
+ return t(($) => $.dingtalk_bind.error_already_bound);
+ case "not_member":
+ return t(($) => $.dingtalk_bind.error_not_member);
+ default:
+ return t(($) => $.dingtalk_bind.error_unknown);
+ }
+ })()}
+ </p>
+ <p className="text-micro text-muted-foreground">
+ {t(($) => $.dingtalk_bind.error_admin_hint)}
+ </p>
+ </>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+// Classify a redeem failure by the server's HTTP status, not the error text:
+// the backend returns 410 (invalid/expired), 409 (already bound to another
+// user) or 403 (not a workspace member). Matching ApiError.status keeps the
+// branch copy decoupled from the exact server wording.
+function redemptionFailureReason(err: unknown): string {
+ if (!(err instanceof ApiError)) return "unknown";
+ switch (err.status) {
+ case 410:
+ return "expired";
+ case 409:
+ return "already_bound";
+ case 403:
+ return "not_member";
+ default:
+ return "unknown";
+ }
+}
diff --git a/packages/views/dingtalk/index.ts b/packages/views/dingtalk/index.ts
new file mode 100644
index 0000000000..246dc00599
--- /dev/null
+++ b/packages/views/dingtalk/index.ts
@@ -0,0 +1 @@
+export { DingTalkBindPage } from "./bind-page";
diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.json
index 6d83fe0711..9bce79f512 100644
--- a/packages/views/locales/en/common.json
+++ b/packages/views/locales/en/common.json
@@ -72,6 +72,21 @@
"error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
"error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
},
+ "dingtalk_bind": {
+ "page_title": "Link your DingTalk account",
+ "redeeming": "Linking your account…",
+ "needs_auth_description": "Sign in to Multica to complete the link. The token in the link binds your DingTalk account to this Multica user, so you must be logged in first.",
+ "sign_in": "Sign in",
+ "done_title": "You're linked.",
+ "done_description": "Your next message to the bot in DingTalk will go straight to the agent. You can close this tab.",
+ "error_title": "Couldn't complete the link",
+ "error_admin_hint": "If this keeps happening, message the bot again in DingTalk to get a fresh link.",
+ "error_missing_token": "The link is missing its token. Message the bot again in DingTalk to get a new one.",
+ "error_expired": "This link is invalid or expired (links are valid for 15 minutes). Message the bot again to get a new one.",
+ "error_already_bound": "This DingTalk account is already linked to a different Multica user. Account transfers must go through an explicit unbind first.",
+ "error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
+ "error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
+ },
"expandable_description": {
"expand": "Show more",
"collapse": "Show less"
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index a7d5bdce39..0d4c8b74de 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -689,6 +689,42 @@
"byo_success_toast": "Slack bot connected",
"byo_failed_toast": "Could not connect the Slack bot"
},
+ "dingtalk": {
+ "section_title": "DingTalk",
+ "page_description": "Connect each Multica Agent to its own DingTalk robot. Members can DM the bot, @mention it in a group, and type /issue to spin up a new Multica issue.",
+ "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",
+ "loading": "Loading…",
+ "empty_title": "No bots connected yet",
+ "empty_description_prefix": "Open an Agent in this workspace and click",
+ "empty_description_cta": "Connect DingTalk",
+ "empty_description_suffix": "to install a robot for it.",
+ "revoked_badge": "revoked",
+ "installed_at_label": "Installed {{when}}",
+ "disconnect": "Disconnect",
+ "disconnecting": "Disconnecting…",
+ "disconnect_confirm_title": "Disconnect this DingTalk bot?",
+ "disconnect_confirm_description": "The bot will stop receiving DingTalk messages for this workspace. The installation row is kept for audit; you can reconnect the bot later.",
+ "disconnect_confirm_cancel": "Cancel",
+ "toast_disconnected": "Disconnected DingTalk bot",
+ "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_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",
+ "byo_appkey_label": "AppKey (client id)",
+ "byo_appsecret_label": "AppSecret (client secret)",
+ "byo_submit": "Connect",
+ "byo_submitting": "Connecting…",
+ "byo_cancel": "Cancel",
+ "byo_success_toast": "DingTalk bot connected",
+ "byo_failed_toast": "Could not connect the DingTalk bot"
+ },
"repositories": {
"section_title": "Repositories",
"description": "Git repositories associated with this workspace. Agents use these to clone and work on code.",
diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.json
index bbda344b44..eaaa57d0d5 100644
--- a/packages/views/locales/ja/common.json
+++ b/packages/views/locales/ja/common.json
@@ -72,6 +72,21 @@
"error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
"error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
},
+ "dingtalk_bind": {
+ "page_title": "DingTalk アカウントを連携",
+ "redeeming": "アカウントを連携しています…",
+ "needs_auth_description": "連携を完了するには Multica にサインインしてください。リンク内のトークンが、あなたの DingTalk アカウントをこの Multica ユーザーに紐付けるため、先にログインが必要です。",
+ "sign_in": "サインイン",
+ "done_title": "連携が完了しました。",
+ "done_description": "次に DingTalk でボットへ送るメッセージは、そのままエージェントに届きます。このタブは閉じて構いません。",
+ "error_title": "連携を完了できませんでした",
+ "error_admin_hint": "繰り返し発生する場合は、DingTalk でボットにもう一度メッセージを送って新しいリンクを取得してください。",
+ "error_missing_token": "リンクにトークンがありません。DingTalk でボットにもう一度メッセージを送って新しいリンクを取得してください。",
+ "error_expired": "このリンクは無効か期限切れです(有効期限は 15 分)。ボットにもう一度メッセージを送って新しいリンクを取得してください。",
+ "error_already_bound": "この DingTalk アカウントは別の Multica ユーザーに連携済みです。移行するにはまず明示的に解除する必要があります。",
+ "error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
+ "error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
+ },
"expandable_description": {
"expand": "詳細を表示",
"collapse": "折りたたむ"
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 3ee7a07c83..e20015c106 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -688,6 +688,42 @@
"byo_success_toast": "Slack ボットを接続しました",
"byo_failed_toast": "Slack ボットを接続できませんでした"
},
+ "dingtalk": {
+ "section_title": "DingTalk",
+ "page_description": "各 Multica エージェントを専用の DingTalk ロボットに接続します。メンバーはボットに DM したり、グループで @メンションしたり、/issue と入力して新しい Multica イシューを起こすことができます。",
+ "not_enabled_title": "DingTalk 連携が有効になっていません",
+ "not_enabled_description_prefix": "サーバーで",
+ "not_enabled_description_suffix": "を設定すると DingTalk ロボットのインストールが有効になります。",
+ "not_enabled_self_host_hint": "セルフホストの場合: 詳細はプロジェクトの README を参照してください。",
+ "connected_bots": "接続済みのボット",
+ "loading": "読み込み中…",
+ "empty_title": "まだボットが接続されていません",
+ "empty_description_prefix": "このワークスペースのエージェントを開き、",
+ "empty_description_cta": "DingTalk を接続",
+ "empty_description_suffix": "をクリックしてロボットをインストールします。",
+ "revoked_badge": "取り消し済み",
+ "installed_at_label": "{{when}} にインストール",
+ "disconnect": "切断",
+ "disconnecting": "切断中…",
+ "disconnect_confirm_title": "この DingTalk ボットを切断しますか?",
+ "disconnect_confirm_description": "このボットはこのワークスペースの DingTalk メッセージを受信しなくなります。インストール記録は監査のため保持され、あとでボットを再接続できます。",
+ "disconnect_confirm_cancel": "キャンセル",
+ "toast_disconnected": "DingTalk ボットを切断しました",
+ "toast_disconnect_failed": "切断に失敗しました",
+ "bind_button": "DingTalk を接続",
+ "bind_button_title": "{{agent}} を DingTalk ボットに接続",
+ "agent_bot_connected_label": "DingTalk に接続済み",
+ "agent_bot_disconnect_tooltip": "この DingTalk ボットをエージェントから解除します。ボットは DingTalk メッセージを受信しなくなります。",
+ "byo_dialog_title": "DingTalk ボットを接続",
+ "byo_docs_link": "Step-by-step:Multica エージェントを DingTalk に接続する",
+ "byo_appkey_label": "AppKey(client id)",
+ "byo_appsecret_label": "AppSecret(client secret)",
+ "byo_submit": "接続",
+ "byo_submitting": "接続中…",
+ "byo_cancel": "キャンセル",
+ "byo_success_toast": "DingTalk ボットを接続しました",
+ "byo_failed_toast": "DingTalk ボットを接続できませんでした"
+ },
"repositories": {
"section_title": "リポジトリ",
"description": "このワークスペースに関連付けられた Git リポジトリです。エージェントはこれらをクローンしてコードを作業します。",
diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.json
index d07cda7975..5d6c52fc8c 100644
--- a/packages/views/locales/ko/common.json
+++ b/packages/views/locales/ko/common.json
@@ -72,6 +72,21 @@
"error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
"error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
},
+ "dingtalk_bind": {
+ "page_title": "DingTalk 계정 연결",
+ "redeeming": "계정을 연결하는 중…",
+ "needs_auth_description": "연결을 완료하려면 Multica에 로그인하세요. 링크의 토큰이 DingTalk 계정을 이 Multica 사용자와 연결하므로 먼저 로그인해야 해요.",
+ "sign_in": "로그인",
+ "done_title": "연결되었어요.",
+ "done_description": "이제 DingTalk에서 봇에게 보내는 다음 메시지는 바로 에이전트로 전달돼요. 이 탭은 닫아도 됩니다.",
+ "error_title": "연결을 완료하지 못했어요",
+ "error_admin_hint": "계속 발생하면 DingTalk에서 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_missing_token": "링크에 토큰이 없어요. DingTalk에서 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_expired": "이 링크는 유효하지 않거나 만료됐어요(유효 기간 15분). 봇에게 다시 메시지를 보내 새 링크를 받으세요.",
+ "error_already_bound": "이 DingTalk 계정은 이미 다른 Multica 사용자에 연결되어 있어요. 이전하려면 먼저 명시적으로 연결을 해제해야 합니다.",
+ "error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
+ "error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
+ },
"expandable_description": {
"expand": "자세히 보기",
"collapse": "접기"
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 24d7158bd9..e2e1121733 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -792,5 +792,41 @@
"byo_cancel": "취소",
"byo_success_toast": "Slack 봇을 연결했어요",
"byo_failed_toast": "Slack 봇을 연결하지 못했어요"
+ },
+ "dingtalk": {
+ "section_title": "DingTalk",
+ "page_description": "각 Multica 에이전트를 전용 DingTalk 로봇에 연결하세요. 멤버는 봇과 1:1로 대화하거나, 그룹에서 @ 멘션하거나, /issue 를 입력해 새 Multica 이슈를 만들 수 있습니다.",
+ "not_enabled_title": "DingTalk 연동이 활성화되지 않았어요",
+ "not_enabled_description_prefix": "서버에서",
+ "not_enabled_description_suffix": "를 설정하면 DingTalk 로봇 설치가 활성화됩니다.",
+ "not_enabled_self_host_hint": "셀프 호스팅: 자세한 내용은 프로젝트 README를 참고하세요.",
+ "connected_bots": "연결된 봇",
+ "loading": "불러오는 중…",
+ "empty_title": "아직 연결된 봇이 없어요",
+ "empty_description_prefix": "이 워크스페이스의 에이전트를 열고",
+ "empty_description_cta": "DingTalk 연결",
+ "empty_description_suffix": "을(를) 클릭해 로봇을 설치하세요.",
+ "revoked_badge": "해제됨",
+ "installed_at_label": "{{when}}에 설치됨",
+ "disconnect": "연결 해제",
+ "disconnecting": "연결 해제 중…",
+ "disconnect_confirm_title": "이 DingTalk 봇을 연결 해제할까요?",
+ "disconnect_confirm_description": "봇이 이 워크스페이스의 DingTalk 메시지를 더 이상 받지 않습니다. 설치 기록은 감사를 위해 보관되며, 나중에 봇을 다시 연결할 수 있어요.",
+ "disconnect_confirm_cancel": "취소",
+ "toast_disconnected": "DingTalk 봇을 연결 해제했어요",
+ "toast_disconnect_failed": "연결 해제에 실패했어요",
+ "bind_button": "DingTalk 연결",
+ "bind_button_title": "{{agent}}을(를) DingTalk 봇에 연결",
+ "agent_bot_connected_label": "DingTalk에 연결됨",
+ "agent_bot_disconnect_tooltip": "이 DingTalk 봇을 에이전트에서 연결 해제합니다. 봇이 DingTalk 메시지를 받지 않게 됩니다.",
+ "byo_dialog_title": "DingTalk 봇 연결",
+ "byo_docs_link": "Step-by-step: Multica 에이전트를 DingTalk에 연결하기",
+ "byo_appkey_label": "AppKey(client id)",
+ "byo_appsecret_label": "AppSecret(client secret)",
+ "byo_submit": "연결",
+ "byo_submitting": "연결 중…",
+ "byo_cancel": "취소",
+ "byo_success_toast": "DingTalk 봇을 연결했어요",
+ "byo_failed_toast": "DingTalk 봇을 연결하지 못했어요"
}
}
diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.json
index 77fdf90240..deff351afb 100644
--- a/packages/views/locales/zh-Hans/common.json
+++ b/packages/views/locales/zh-Hans/common.json
@@ -72,6 +72,21 @@
"error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
"error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
},
+ "dingtalk_bind": {
+ "page_title": "关联钉钉账号",
+ "redeeming": "正在关联账号…",
+ "needs_auth_description": "需要登录 Multica 才能完成关联。链接中的 token 会将你的钉钉账号绑定到当前登录的 Multica 用户。",
+ "sign_in": "登录",
+ "done_title": "已关联。",
+ "done_description": "下次在钉钉向机器人发送消息时,会直接送达绑定的智能体。可以关闭此页面。",
+ "error_title": "关联未完成",
+ "error_admin_hint": "如果反复失败,请在钉钉重新向机器人发消息以获取新的链接。",
+ "error_missing_token": "链接缺少 token。请在钉钉重新向机器人发消息以获取新的链接。",
+ "error_expired": "链接无效或已过期(有效期 15 分钟)。请重新向机器人发消息获取新的链接。",
+ "error_already_bound": "该钉钉账号已关联到其他 Multica 用户。账户转移需要先显式解绑。",
+ "error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
+ "error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
+ },
"expandable_description": {
"expand": "查看详情",
"collapse": "收起"
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 32f79bb834..cdca6cc959 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -688,6 +688,42 @@
"byo_success_toast": "Slack 机器人已连接",
"byo_failed_toast": "无法连接 Slack 机器人"
},
+ "dingtalk": {
+ "section_title": "钉钉",
+ "page_description": "将每个 Multica 智能体连接到专属的钉钉机器人。成员可私聊机器人、在群里 @ 它,或输入 /issue 直接创建 Multica issue。",
+ "not_enabled_title": "钉钉集成未启用",
+ "not_enabled_description_prefix": "在服务器上设置",
+ "not_enabled_description_suffix": "以启用钉钉机器人安装。",
+ "not_enabled_self_host_hint": "自部署用户:详见项目 README。",
+ "connected_bots": "已连接的机器人",
+ "loading": "加载中…",
+ "empty_title": "尚未连接机器人",
+ "empty_description_prefix": "在本工作区打开一个 Agent,点击",
+ "empty_description_cta": "连接钉钉",
+ "empty_description_suffix": "为其安装机器人。",
+ "revoked_badge": "已撤销",
+ "installed_at_label": "安装于 {{when}}",
+ "disconnect": "断开连接",
+ "disconnecting": "正在断开…",
+ "disconnect_confirm_title": "断开此钉钉机器人?",
+ "disconnect_confirm_description": "该机器人将停止接收此工作区的钉钉消息。安装记录会保留以备审计;你之后可以重新连接该机器人。",
+ "disconnect_confirm_cancel": "取消",
+ "toast_disconnected": "已断开钉钉机器人",
+ "toast_disconnect_failed": "断开失败",
+ "bind_button": "连接钉钉",
+ "bind_button_title": "把 {{agent}} 连接到钉钉机器人",
+ "agent_bot_connected_label": "已连接到钉钉",
+ "agent_bot_disconnect_tooltip": "将此钉钉机器人从 Agent 解绑。机器人将停止接收钉钉消息。",
+ "byo_dialog_title": "连接钉钉机器人",
+ "byo_docs_link": "Step-by-step:把你的 Multica 智能体连接到钉钉",
+ "byo_appkey_label": "AppKey(client id)",
+ "byo_appsecret_label": "AppSecret(client secret)",
+ "byo_submit": "连接",
+ "byo_submitting": "连接中…",
+ "byo_cancel": "取消",
+ "byo_success_toast": "钉钉机器人已连接",
+ "byo_failed_toast": "无法连接钉钉机器人"
+ },
"repositories": {
"section_title": "代码仓库",
"description": "与该工作区关联的 Git 仓库。智能体会从这里 clone 代码并完成工作。",
diff --git a/packages/views/package.json b/packages/views/package.json
index b1fa32f173..70239cb30e 100644
--- a/packages/views/package.json
+++ b/packages/views/package.json
@@ -44,6 +44,7 @@
"./settings/lark-tab": "./settings/components/lark-tab.tsx",
"./lark": "./lark/index.ts",
"./slack": "./slack/index.ts",
+ "./dingtalk": "./dingtalk/index.ts",
"./invite": "./invite/index.ts",
"./invitations": "./invitations/index.ts",
"./onboarding": "./onboarding/index.ts",
diff --git a/packages/views/settings/components/dingtalk-tab.test.tsx b/packages/views/settings/components/dingtalk-tab.test.tsx
new file mode 100644
index 0000000000..5a2568b4b7
--- /dev/null
+++ b/packages/views/settings/components/dingtalk-tab.test.tsx
@@ -0,0 +1,204 @@
+// @vitest-environment jsdom
+
+import { type ReactNode } from "react";
+import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+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";
+
+const membersRef = vi.hoisted(() => ({
+ current: [{ user_id: "user-1", role: "owner" as MemberRole }],
+}));
+const installationsRef = vi.hoisted(() => ({
+ current: {
+ installations: [] as unknown[],
+ configured: true,
+ install_supported: true,
+ },
+}));
+const mockRegisterBYO = vi.hoisted(() => vi.fn());
+const mockDeleteInstallation = vi.hoisted(() => vi.fn());
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+const mockInvalidate = 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("installations")) return { data: installationsRef.current, isLoading: false };
+ return { data: undefined, isLoading: false };
+ },
+ useQueryClient: () => ({ invalidateQueries: mockInvalidate }),
+ queryOptions: <T,>(opts: T) => opts,
+}));
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ memberListOptions: () => ({ queryKey: ["members"], queryFn: vi.fn() }),
+}));
+
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({
+ getAgentName: (agentId: string) => `Agent ${agentId}`,
+ getMemberName: () => "Unknown",
+ getSquadName: () => "Unknown Squad",
+ getActorName: () => "Unknown",
+ getActorInitials: () => "??",
+ getActorAvatarUrl: () => null,
+ }),
+}));
+
+vi.mock("../../common/actor-avatar", () => ({
+ ActorAvatar: ({ actorId }: { actorId: string }) => (
+ <span data-testid="actor-avatar" data-actor-id={actorId} />
+ ),
+}));
+
+vi.mock("@multica/core/dingtalk", () => ({
+ dingtalkInstallationsOptions: () => ({
+ queryKey: ["dingtalk", "installations"],
+ queryFn: vi.fn(),
+ }),
+ dingtalkKeys: { installations: (wsId: string) => ["dingtalk", "installations", wsId] },
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: {
+ registerDingTalkBYO: mockRegisterBYO,
+ deleteDingTalkInstallation: mockDeleteInstallation,
+ },
+}));
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (sel?: (s: { user: { id: string } }) => unknown) =>
+ sel ? sel({ user: { id: "user-1" } }) : { user: { id: "user-1" } },
+ { getState: () => ({ user: { id: "user-1" } }) },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn(), message: vi.fn() },
+}));
+
+vi.mock("../../platform", () => ({ openExternal: mockOpenExternal }));
+
+import { DingTalkAgentBindButton, DingTalkTab } from "./dingtalk-tab";
+
+const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
+
+afterEach(cleanup);
+
+function renderUI(children: ReactNode) {
+ return render(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ {children}
+ </I18nProvider>,
+ );
+}
+
+function resetFixtures() {
+ vi.clearAllMocks();
+ membersRef.current = [{ user_id: "user-1", role: "owner" }];
+ installationsRef.current = { installations: [], configured: true, install_supported: true };
+}
+
+describe("DingTalkAgentBindButton", () => {
+ beforeEach(resetFixtures);
+
+ it("opens the BYO dialog and submits the pasted AppKey + AppSecret", async () => {
+ mockRegisterBYO.mockResolvedValue({ id: "i1", agent_id: "agent-1", status: "active" });
+ renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("dingtalk-agent-connect"));
+ const idInput = await screen.findByTestId("dingtalk-byo-client-id");
+ await userEvent.type(idInput, "ding-appkey");
+ await userEvent.type(screen.getByTestId("dingtalk-byo-client-secret"), "ding-appsecret");
+ await userEvent.click(screen.getByTestId("dingtalk-byo-submit"));
+ await waitFor(() =>
+ expect(mockRegisterBYO).toHaveBeenCalledWith("workspace-1", "agent-1", {
+ client_id: "ding-appkey",
+ client_secret: "ding-appsecret",
+ }),
+ );
+ expect(mockOpenExternal).not.toHaveBeenCalled();
+ });
+
+ it("masks both credential inputs as password fields", async () => {
+ renderUI(<DingTalkAgentBindButton agentId="agent-1" agentName="Bot" />);
+ await userEvent.click(screen.getByTestId("dingtalk-agent-connect"));
+ const idInput = await screen.findByTestId("dingtalk-byo-client-id");
+ const secretInput = screen.getByTestId("dingtalk-byo-client-secret");
+ expect(idInput.getAttribute("type")).toBe("password");
+ expect(secretInput.getAttribute("type")).toBe("password");
+ });
+
+ it("shows the connected badge (not the CTA) when the agent already has an active install", () => {
+ installationsRef.current = {
+ installations: [{ id: "i1", agent_id: "agent-1", status: "active" }],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
+ expect(screen.getByTestId("dingtalk-agent-bot-connected")).toBeTruthy();
+ expect(screen.getByTestId("dingtalk-agent-bot-disconnect")).toBeTruthy();
+ 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("renders nothing when install is unavailable and the agent is unbound", () => {
+ installationsRef.current = { installations: [], configured: true, install_supported: false };
+ const { container } = renderUI(<DingTalkAgentBindButton agentId="agent-1" />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
+describe("DingTalkTab", () => {
+ beforeEach(resetFixtures);
+
+ it("surfaces the not-enabled notice when the deployment has no DingTalk key", () => {
+ installationsRef.current = { installations: [], configured: false, install_supported: false };
+ renderUI(<DingTalkTab />);
+ expect(screen.getByText(/DingTalk integration not enabled/i)).toBeTruthy();
+ });
+
+ it("shows the empty state when configured but nothing is connected", () => {
+ renderUI(<DingTalkTab />);
+ expect(screen.getByText(/No bots connected yet/i)).toBeTruthy();
+ });
+
+ it("lists a connected installation with its agent name and a disconnect control", () => {
+ installationsRef.current = {
+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
+ configured: true,
+ install_supported: true,
+ };
+ renderUI(<DingTalkTab />);
+ expect(screen.getByText("Agent agent-7")).toBeTruthy();
+ expect(screen.getByText(/Disconnect/i)).toBeTruthy();
+ });
+
+ 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.tsx
new file mode 100644
index 0000000000..b7dde88287
--- /dev/null
+++ b/packages/views/settings/components/dingtalk-tab.tsx
@@ -0,0 +1,572 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { ChevronRight, ExternalLink, MessagesSquare, 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";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label } from "@multica/ui/components/ui/label";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { dingtalkInstallationsOptions, dingtalkKeys } from "@multica/core/dingtalk";
+import { api } from "@multica/core/api";
+import type { DingTalkInstallation } from "@multica/core/types";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { openExternal } from "../../platform";
+import { useT } from "../../i18n";
+
+// 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 {
+ const t = Date.parse(value);
+ if (!value || Number.isNaN(t) || t <= 0) return "—";
+ return new Date(t).toLocaleString();
+}
+
+// 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).
+//
+// Adding a new installation flows through the Agent detail page: the install
+// path is per-agent (each Multica agent gets exactly one robot — the
+// (workspace_id, agent_id, channel_type) UNIQUE in channel_installation), so
+// asking the user to pick an agent here would re-create that page's picker.
+export function DingTalkTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const user = useAuthStore((s) => s.user);
+
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
+ const canManage =
+ currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ const { data, isLoading } = useQuery({
+ ...dingtalkInstallationsOptions(wsId),
+ });
+ const installations = data?.installations ?? [];
+ const configured = data?.configured === true;
+
+ const [disconnectTarget, setDisconnectTarget] = useState<string | null>(null);
+ const [disconnecting, setDisconnecting] = useState(false);
+
+ async function handleDisconnect() {
+ if (!disconnectTarget || disconnecting) return;
+ setDisconnecting(true);
+ try {
+ await api.deleteDingTalkInstallation(wsId, disconnectTarget);
+ await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
+ toast.success(t(($) => $.dingtalk.toast_disconnected));
+ setDisconnectTarget(null);
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.dingtalk.toast_disconnect_failed),
+ );
+ } finally {
+ setDisconnecting(false);
+ }
+ }
+
+ return (
+ <div className="space-y-8">
+ <section className="space-y-1">
+ <p className="text-body text-muted-foreground">
+ {t(($) => $.dingtalk.page_description)}
+ </p>
+ </section>
+
+ {!configured ? (
+ <Card>
+ <CardContent className="space-y-2">
+ <p className="text-body font-medium">{t(($) => $.dingtalk.not_enabled_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.not_enabled_description_prefix)}{" "}
+ <code className="rounded bg-muted px-1 py-0.5 text-micro">
+ MULTICA_DINGTALK_SECRET_KEY
+ </code>{" "}
+ {t(($) => $.dingtalk.not_enabled_description_suffix)}{" "}
+ {t(($) => $.dingtalk.not_enabled_self_host_hint)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <section className="space-y-3">
+ <h2 className="text-body font-semibold">{t(($) => $.dingtalk.connected_bots)}</h2>
+ {isLoading ? (
+ <Card>
+ <CardContent>
+ <p className="text-body text-muted-foreground">{t(($) => $.dingtalk.loading)}</p>
+ </CardContent>
+ </Card>
+ ) : installations.length === 0 ? (
+ <Card>
+ <CardContent className="space-y-2">
+ <p className="text-body font-medium">{t(($) => $.dingtalk.empty_title)}</p>
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.dingtalk.empty_description_prefix)}{" "}
+ <strong>{t(($) => $.dingtalk.empty_description_cta)}</strong>{" "}
+ {t(($) => $.dingtalk.empty_description_suffix)}
+ </p>
+ </CardContent>
+ </Card>
+ ) : (
+ <Card>
+ <CardContent className="divide-y">
+ {installations.map((inst) => (
+ <InstallationRow
+ key={inst.id}
+ installation={inst}
+ canManage={canManage}
+ onDisconnect={() => setDisconnectTarget(inst.id)}
+ />
+ ))}
+ </CardContent>
+ </Card>
+ )}
+ </section>
+ )}
+
+ <AlertDialog
+ open={!!disconnectTarget}
+ onOpenChange={(v) => {
+ if (!v && !disconnecting) setDisconnectTarget(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.dingtalk.disconnect_confirm_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.dingtalk.disconnect_confirm_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnecting}>
+ {t(($) => $.dingtalk.disconnect_confirm_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
+ {disconnecting
+ ? t(($) => $.dingtalk.disconnecting)
+ : t(($) => $.dingtalk.disconnect)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+function InstallationRow({
+ installation,
+ canManage,
+ onDisconnect,
+}: {
+ installation: DingTalkInstallation;
+ canManage: boolean;
+ onDisconnect: () => void;
+}) {
+ const { t } = useT("settings");
+ const { getAgentName } = useActorName();
+ const isActive = installation.status === "active";
+ const agentName = getAgentName(installation.agent_id);
+ return (
+ <div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
+ <div className="flex items-start gap-3">
+ <ActorAvatar
+ actorType="agent"
+ actorId={installation.agent_id}
+ size="lg"
+ enableHoverCard
+ profileLink
+ />
+ <div className="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="text-micro text-muted-foreground">
+ {t(($) => $.dingtalk.installed_at_label, {
+ when: formatInstalledAt(installation.installed_at),
+ })}
+ </p>
+ </div>
+ </div>
+ {canManage && isActive && (
+ <Button variant="outline" size="sm" onClick={onDisconnect}>
+ <Trash2 className="h-3 w-3" />
+ {t(($) => $.dingtalk.disconnect)}
+ </Button>
+ )}
+ </div>
+ );
+}
+
+// dingtalkDocsUrl points at the DingTalk integration guide on the docs site,
+// localized to the viewer's language. The docs site uses /<lang>/ path
+// prefixes (English has none), matching the convention used elsewhere in the
+// app for doc links.
+function dingtalkDocsUrl(lang: string | undefined): string {
+ const prefix = lang?.startsWith("zh")
+ ? "/zh"
+ : lang?.startsWith("ja")
+ ? "/ja"
+ : lang?.startsWith("ko")
+ ? "/ko"
+ : "";
+ return `https://multica.ai/docs${prefix}/dingtalk-bot-integration`;
+}
+
+// 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).
+// 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,
+ className,
+ onShowConnectedDetails,
+}: {
+ agentId: string;
+ agentName?: string;
+ className?: string;
+ /**
+ * When set, the connected state renders as a compact read-only status row
+ * that invokes this callback on click instead of the full badge with inline
+ * actions — the agent inspector passes a "jump to the Integrations tab"
+ * handler so management actions live in one place.
+ */
+ onShowConnectedDetails?: () => void;
+}) {
+ const { t, i18n } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+ const user = useAuthStore((s) => s.user);
+
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [clientId, setClientId] = useState("");
+ const [clientSecret, setClientSecret] = useState("");
+ const [submitting, setSubmitting] = useState(false);
+
+ const { data: listing } = useQuery({
+ ...dingtalkInstallationsOptions(wsId),
+ });
+ const installSupported = listing?.install_supported === true;
+
+ const { data: members = [] } = useQuery({
+ ...memberListOptions(wsId),
+ enabled: !!wsId,
+ });
+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
+ const canManage =
+ currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ if (!canManage) return null;
+
+ const existing = listing?.installations?.find(
+ (inst) => inst.agent_id === agentId && inst.status === "active",
+ );
+ if (existing) {
+ return onShowConnectedDetails ? (
+ <DingTalkAgentBotStatusRow
+ onClick={onShowConnectedDetails}
+ className={className}
+ />
+ ) : (
+ <DingTalkAgentBotConnectedBadge installation={existing} className={className} />
+ );
+ }
+
+ if (!installSupported) return null;
+
+ function closeDialog() {
+ if (submitting) return;
+ setDialogOpen(false);
+ setClientId("");
+ setClientSecret("");
+ }
+
+ async function handleSubmit() {
+ const client_id = clientId.trim();
+ const client_secret = clientSecret.trim();
+ if (submitting || !agentId || !client_id || !client_secret) return;
+ setSubmitting(true);
+ try {
+ await api.registerDingTalkBYO(wsId, agentId, { client_id, client_secret });
+ // The dingtalk_installation realtime event also refreshes this list, but
+ // invalidate explicitly so the connected badge appears immediately.
+ await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
+ toast.success(t(($) => $.dingtalk.byo_success_toast));
+ setDialogOpen(false);
+ setClientId("");
+ setClientSecret("");
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.dingtalk.byo_failed_toast),
+ );
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ const canSubmit =
+ clientId.trim() !== "" && clientSecret.trim() !== "" && !submitting;
+
+ return (
+ <div
+ className={cn("flex flex-wrap items-center gap-2", className)}
+ data-testid="dingtalk-agent-bind-buttons"
+ >
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setDialogOpen(true)}
+ disabled={!agentId}
+ title={
+ agentName
+ ? t(($) => $.dingtalk.bind_button_title, { agent: agentName })
+ : undefined
+ }
+ data-testid="dingtalk-agent-connect"
+ >
+ <MessagesSquare className="h-3 w-3" />
+ {t(($) => $.dingtalk.bind_button)}
+ </Button>
+
+ <Dialog
+ open={dialogOpen}
+ onOpenChange={(v) => (v ? setDialogOpen(true) : closeDialog())}
+ >
+ <DialogContent
+ className="gap-0 overflow-hidden p-0 sm:max-w-lg"
+ data-testid="dingtalk-byo-dialog"
+ >
+ <DialogHeader className="gap-1 border-b px-5 py-3">
+ <DialogTitle className="text-title-sm font-semibold">
+ {t(($) => $.dingtalk.byo_dialog_title)}
+ </DialogTitle>
+
+ <button
+ type="button"
+ onClick={() => openExternal(dingtalkDocsUrl(i18n.language))}
+ 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" />
+ {t(($) => $.dingtalk.byo_docs_link)}
+ </button>
+ </DialogHeader>
+
+ <div className="space-y-4 p-5">
+ <div className="space-y-1.5">
+ <Label
+ htmlFor="dingtalk-byo-client-id"
+ className="text-caption text-muted-foreground"
+ >
+ {t(($) => $.dingtalk.byo_appkey_label)}
+ </Label>
+ <Input
+ id="dingtalk-byo-client-id"
+ data-testid="dingtalk-byo-client-id"
+ type="password"
+ value={clientId}
+ onChange={(e) => setClientId(e.target.value)}
+ autoComplete="off"
+ spellCheck={false}
+ disabled={submitting}
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <Label
+ htmlFor="dingtalk-byo-client-secret"
+ className="text-caption text-muted-foreground"
+ >
+ {t(($) => $.dingtalk.byo_appsecret_label)}
+ </Label>
+ <Input
+ id="dingtalk-byo-client-secret"
+ data-testid="dingtalk-byo-client-secret"
+ type="password"
+ value={clientSecret}
+ onChange={(e) => setClientSecret(e.target.value)}
+ autoComplete="off"
+ spellCheck={false}
+ disabled={submitting}
+ />
+ </div>
+ </div>
+
+ {/* Inline footer instead of <DialogFooter>: its -mx-4/-mb-4 offsets
+ assume the default p-4 DialogContent; with p-0 they push the bar
+ outside the dialog (same workaround as CreateAgentDialog). */}
+ <div className="flex items-center justify-end gap-2 border-t bg-background px-5 py-3">
+ <Button variant="ghost" onClick={closeDialog} disabled={submitting}>
+ {t(($) => $.dingtalk.byo_cancel)}
+ </Button>
+ <Button
+ onClick={handleSubmit}
+ disabled={!canSubmit}
+ data-testid="dingtalk-byo-submit"
+ >
+ {submitting
+ ? t(($) => $.dingtalk.byo_submitting)
+ : t(($) => $.dingtalk.byo_submit)}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
+// DingTalkAgentBotStatusRow is the compact, read-only connected affordance the
+// agent inspector renders instead of the full badge; it deep-links into the
+// Integrations tab where Manage / Disconnect live.
+function DingTalkAgentBotStatusRow({
+ onClick,
+ className,
+}: {
+ onClick: () => void;
+ className?: string;
+}) {
+ const { t } = useT("settings");
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ className={cn(
+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-caption text-muted-foreground transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
+ className,
+ )}
+ 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" />
+ </button>
+ );
+}
+
+// DingTalkAgentBotConnectedBadge is the full "already connected" affordance the
+// Integrations tab renders in place of the Connect button: a status row plus a
+// soft-destructive Disconnect. Only owners/admins ever reach this component.
+function DingTalkAgentBotConnectedBadge({
+ installation,
+ className,
+}: {
+ installation: DingTalkInstallation;
+ className?: string;
+}) {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const qc = useQueryClient();
+
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ const [disconnecting, setDisconnecting] = useState(false);
+
+ async function handleDisconnect() {
+ if (disconnecting) return;
+ setDisconnecting(true);
+ try {
+ await api.deleteDingTalkInstallation(wsId, installation.id);
+ await qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
+ toast.success(t(($) => $.dingtalk.toast_disconnected));
+ setConfirmOpen(false);
+ } catch (e) {
+ toast.error(
+ e instanceof Error ? e.message : t(($) => $.dingtalk.toast_disconnect_failed),
+ );
+ } finally {
+ setDisconnecting(false);
+ }
+ }
+
+ return (
+ <div
+ className={cn("space-y-2", className)}
+ 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>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => setConfirmOpen(true)}
+ disabled={disconnecting}
+ title={t(($) => $.dingtalk.agent_bot_disconnect_tooltip)}
+ aria-label={t(($) => $.dingtalk.disconnect)}
+ data-testid="dingtalk-agent-bot-disconnect"
+ >
+ <Trash2 className="h-3 w-3" />
+ {disconnecting
+ ? t(($) => $.dingtalk.disconnecting)
+ : t(($) => $.dingtalk.disconnect)}
+ </Button>
+ </div>
+
+ <AlertDialog
+ open={confirmOpen}
+ onOpenChange={(v) => {
+ if (!v && !disconnecting) setConfirmOpen(false);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $.dingtalk.disconnect_confirm_title)}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.dingtalk.disconnect_confirm_description)}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={disconnecting}>
+ {t(($) => $.dingtalk.disconnect_confirm_cancel)}
+ </AlertDialogCancel>
+ <AlertDialogAction onClick={handleDisconnect} disabled={disconnecting}>
+ {disconnecting
+ ? t(($) => $.dingtalk.disconnecting)
+ : t(($) => $.dingtalk.disconnect)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/packages/views/settings/components/integrations-tab.test.tsx b/packages/views/settings/components/integrations-tab.test.tsx
index 7db6ab51fc..2e4c25d9a1 100644
--- a/packages/views/settings/components/integrations-tab.test.tsx
+++ b/packages/views/settings/components/integrations-tab.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
-import { beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
import { ApiError } from "@multica/core/api";
import { configStore } from "@multica/core/config";
import { COMPOSIO_MCP_APPS_FLAG } from "@multica/core/feature-flags";
@@ -44,12 +44,18 @@ vi.mock("./slack-tab", () => ({
SlackTab: () => <div data-testid="slack-tab" />,
}));
+vi.mock("./dingtalk-tab", () => ({
+ DingTalkTab: () => <div data-testid="dingtalk-tab" />,
+}));
+
vi.mock("./vcs-tab", () => ({
VCSTab: () => <div data-testid="vcs-tab" />,
}));
import { IntegrationsTab } from "./integrations-tab";
+afterEach(cleanup);
+
function renderTab() {
return render(
<I18nProvider locale="en" resources={{ en: { common: enCommon, settings: enSettings } }}>
diff --git a/packages/views/settings/components/integrations-tab.tsx b/packages/views/settings/components/integrations-tab.tsx
index 03d8025f35..2b4984c566 100644
--- a/packages/views/settings/components/integrations-tab.tsx
+++ b/packages/views/settings/components/integrations-tab.tsx
@@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query";
import { LarkTab } from "./lark-tab";
import { ComposioTab } from "./composio-tab";
import { SlackTab } from "./slack-tab";
+import { DingTalkTab } from "./dingtalk-tab";
import { VCSTab } from "./vcs-tab";
import { ApiError } from "@multica/core/api";
import { composioToolkitsOptions } from "@multica/core/composio";
@@ -51,6 +52,9 @@ export function IntegrationsTab() {
<SettingsSection title={t(($) => $.slack.section_title)}>
<SlackTab />
</SettingsSection>
+ <SettingsSection title={t(($) => $.dingtalk.section_title)}>
+ <DingTalkTab />
+ </SettingsSection>
{vcsAvailable && (
<SettingsSection title={t(($) => $.vcs.section_title)}>
<VCSTab />
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 87ae6963e6..9bd503a936 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -27,6 +27,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
composiointeg "github.com/multica-ai/multica/server/internal/integrations/composio"
+ "github.com/multica-ai/multica/server/internal/integrations/dingtalk"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
@@ -585,6 +586,54 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
slog.Info("slack integration disabled (MULTICA_SLACK_SECRET_KEY not set)")
}
+ // DingTalk uses one outbound Stream connection per BYO installation. The
+ // AppSecret is encrypted at rest and the integration is inert unless its
+ // dedicated deployment key is configured.
+ if dingtalkKey, err := secretbox.LoadKey("MULTICA_DINGTALK_SECRET_KEY"); err == nil {
+ box, err := secretbox.New(dingtalkKey)
+ if err != nil {
+ slog.Error("dingtalk: secretbox.New failed; integration disabled", "error", err)
+ } else {
+ dingtalkClient := dingtalk.NewClient(nil, "")
+ bindingSvc := dingtalk.NewBindingTokenService(queries, pool)
+ h.DingTalkBindingTokens = bindingSvc
+ replier := dingtalk.NewOutboundReplier(dingtalk.OutboundReplierConfig{
+ Binding: bindingSvc,
+ Decrypt: box.Open,
+ Client: dingtalkClient,
+ AppURL: appURLFromEnv(),
+ Logger: slog.Default(),
+ })
+ ack := dingtalk.NewAckNotifier(dingtalkClient, box.Open, slog.Default())
+ var media engine.MediaResolver
+ if store != nil {
+ media = dingtalk.NewMediaResolver(
+ dingtalkClient,
+ box.Open,
+ store,
+ engine.NewDBMediaIntentLedger(queries),
+ slog.Default(),
+ )
+ }
+ channelRouter.Register(dingtalk.TypeDingTalk, dingtalk.NewDingTalkResolverSet(queries, pool, replier, ack, media))
+ dingtalk.NewOutbound(queries, box.Open, dingtalkClient, slog.Default()).Register(bus)
+ dingtalk.RegisterDingTalk(channelRegistry, dingtalk.ChannelDeps{
+ Decrypt: box.Open,
+ Client: dingtalkClient,
+ Logger: slog.Default(),
+ })
+ installSvc, installErr := dingtalk.NewInstallService(queries, pool, box, slog.Default())
+ if installErr != nil {
+ slog.Error("dingtalk: InstallService init failed; install disabled", "error", installErr)
+ } else {
+ h.DingTalkInstall = installSvc
+ }
+ slog.Info("dingtalk integration enabled (BYO per-installation stream mode)")
+ }
+ } else {
+ slog.Info("dingtalk integration disabled (MULTICA_DINGTALK_SECRET_KEY not set)")
+ }
+
// Composio integration (MUL-3720). Gated by COMPOSIO_API_KEY plus the
// composio_mcp_apps feature flag. The env var is the project-scoped key the
// standalone SDK authenticates Composio with (sent as x-api-key; the project
@@ -1031,6 +1080,16 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Delete("/slack/installations/{installationId}", h.RevokeSlackInstallation)
r.Post("/slack/install/byo", h.RegisterSlackBYO)
})
+
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMemberFromURL(queries, "id"))
+ r.Get("/dingtalk/installations", h.ListDingTalkInstallations)
+ })
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceRoleFromURL(queries, "id", "owner", "admin"))
+ r.Delete("/dingtalk/installations/{installationId}", h.RevokeDingTalkInstallation)
+ r.Post("/dingtalk/install/byo", h.RegisterDingTalkBYO)
+ })
})
})
@@ -1047,6 +1106,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// logged-in user (from the session) is bound to the Slack id the token
// carries.
r.Post("/api/slack/binding/redeem", h.RedeemSlackBindingToken)
+ // DingTalk binding redemption is user-scoped for the same reason as
+ // Slack: the token is redeemed before workspace context is selected.
+ r.Post("/api/dingtalk/binding/redeem", h.RedeemDingTalkBindingToken)
// Composio integration (MUL-3720). User-scoped (no workspace context):
// a connection belongs to a user. These four require a logged-in
diff --git a/server/internal/handler/dingtalk.go b/server/internal/handler/dingtalk.go
new file mode 100644
index 0000000000..a6f1c82991
--- /dev/null
+++ b/server/internal/handler/dingtalk.go
@@ -0,0 +1,281 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+
+ "github.com/multica-ai/multica/server/internal/integrations/dingtalk"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// DingTalkInstallationResponse is the wire shape for a DingTalk installation
+// row. The encrypted AppSecret in config is INTENTIONALLY absent — it is
+// server-internal (only the outbound sender decrypts it). WS lease columns are
+// runtime state, not API surface, so they are omitted too.
+type DingTalkInstallationResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+ InstalledAt string `json:"installed_at"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func dingtalkInstallationToResponse(row db.ChannelInstallation) DingTalkInstallationResponse {
+ return DingTalkInstallationResponse{
+ ID: uuidToString(row.ID),
+ WorkspaceID: uuidToString(row.WorkspaceID),
+ AgentID: uuidToString(row.AgentID),
+ InstallerUserID: uuidToString(row.InstallerUserID),
+ Status: row.Status,
+ InstalledAt: row.InstalledAt.Time.UTC().Format(time.RFC3339),
+ CreatedAt: row.CreatedAt.Time.UTC().Format(time.RFC3339),
+ UpdatedAt: row.UpdatedAt.Time.UTC().Format(time.RFC3339),
+ }
+}
+
+// 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{
+ "installations": []DingTalkInstallationResponse{},
+ "configured": false,
+ "install_supported": false,
+ })
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ rows, err := h.DingTalkInstall.ListByWorkspace(r.Context(), wsUUID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk installations")
+ return
+ }
+ out := make([]DingTalkInstallationResponse, 0, len(rows))
+ for _, row := range rows {
+ out = append(out, dingtalkInstallationToResponse(row))
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "installations": out,
+ "configured": true,
+ "install_supported": true,
+ })
+}
+
+// RegisterDingTalkBYORequest is the body for a bring-your-own-app install: the
+// two credentials the user pasted from their own DingTalk Stream-mode robot.
+type RegisterDingTalkBYORequest struct {
+ ClientID string `json:"client_id"` // AppKey
+ ClientSecret string `json:"client_secret"` // AppSecret
+}
+
+// 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).
+func (h *Handler) RegisterDingTalkBYO(w http.ResponseWriter, r *http.Request) {
+ if h.DingTalkInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "dingtalk integration not enabled")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ agentIDStr := strings.TrimSpace(r.URL.Query().Get("agent_id"))
+ if agentIDStr == "" {
+ writeError(w, http.StatusBadRequest, "agent_id is required")
+ return
+ }
+ agentUUID, ok := parseUUIDOrBadRequest(w, agentIDStr, "agent_id")
+ 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{
+ ID: agentUUID,
+ WorkspaceID: wsUUID,
+ }); err != nil {
+ writeError(w, http.StatusNotFound, "agent not found in this workspace")
+ return
+ }
+ initiatorUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ var body RegisterDingTalkBYORequest
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ row, err := h.DingTalkInstall.RegisterBYO(r.Context(), dingtalk.RegisterBYOParams{
+ WorkspaceID: wsUUID,
+ AgentID: agentUUID,
+ InitiatorID: initiatorUUID,
+ AppKey: body.ClientID,
+ AppSecret: body.ClientSecret,
+ })
+ if err != nil {
+ switch {
+ case errors.Is(err, dingtalk.ErrInvalidAppKey), errors.Is(err, dingtalk.ErrInvalidAppSecret):
+ writeError(w, http.StatusBadRequest, err.Error())
+ case errors.Is(err, dingtalk.ErrRobotOwnedBySameWorkspace):
+ writeError(w, http.StatusConflict, "this DingTalk robot is already connected to another agent in this workspace — disconnect it there first, then connect it here")
+ case errors.Is(err, dingtalk.ErrRobotOwnedByArchivedAgent):
+ writeError(w, http.StatusConflict, "this DingTalk robot is connected to an archived agent in this workspace — restore that agent, or disconnect its robot, before connecting it here")
+ case errors.Is(err, dingtalk.ErrRobotOwnedByAnotherWorkspace):
+ writeError(w, http.StatusConflict, "this DingTalk robot is already connected to a different Multica workspace — disconnect it there before connecting it here")
+ case errors.Is(err, dingtalk.ErrCredentialValidation):
+ // The access-token mint rejected the pasted credentials (a user error),
+ // so guide the user to recheck them.
+ writeError(w, http.StatusBadRequest, "could not verify the DingTalk credentials — check the AppKey (client id) and AppSecret (client secret), and that the robot is a Stream-mode robot in your organization")
+ default:
+ // Encrypt / persist / unexpected failures are server-side, not the
+ // user's credentials — surface a 500 instead of misreporting them as bad
+ // credentials.
+ writeError(w, http.StatusInternalServerError, "could not connect the DingTalk robot")
+ }
+ return
+ }
+ // Broadcast so every open client (Settings, Agent Integrations, other tabs)
+ // invalidates its installations query and shows the new bot — matching the
+ // revoke event and Slack's install semantics.
+ h.publishDingTalkInstallationCreated(row, userID)
+ writeJSON(w, http.StatusOK, dingtalkInstallationToResponse(row))
+}
+
+// publishDingTalkInstallationCreated emits dingtalk_installation:created for a
+// newly connected bot. The realtime layer fans it out to the workspace; the web
+// app listens on dingtalk_installation:* to invalidate the installations query.
+func (h *Handler) publishDingTalkInstallationCreated(row db.ChannelInstallation, actorID string) {
+ h.publish(protocol.EventDingTalkInstallationCreated, uuidToString(row.WorkspaceID), "user", actorID, map[string]any{
+ "id": uuidToString(row.ID),
+ })
+}
+
+// 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'.
+func (h *Handler) RevokeDingTalkInstallation(w http.ResponseWriter, r *http.Request) {
+ if h.DingTalkInstall == nil {
+ writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace id")
+ if !ok {
+ return
+ }
+ instUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation id")
+ if !ok {
+ return
+ }
+ // 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 {
+ if errors.Is(err, dingtalk.ErrInstallationNotFound) {
+ writeError(w, http.StatusNotFound, "dingtalk installation not found")
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load installation")
+ return
+ }
+ if err := h.DingTalkInstall.Revoke(r.Context(), instUUID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to revoke installation")
+ return
+ }
+ h.publish(protocol.EventDingTalkInstallationRevoked, uuidToString(wsUUID), "user", userID, map[string]any{
+ "id": uuidToString(instUUID),
+ })
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// RedeemDingTalkBindingTokenRequest carries the raw token the user clicked
+// through from the bot's "link your account" prompt.
+type RedeemDingTalkBindingTokenRequest struct {
+ Token string `json:"token"`
+}
+
+// RedeemDingTalkBindingTokenResponse echoes the bound workspace/installation/user
+// so the frontend can confirm without a second fetch.
+type RedeemDingTalkBindingTokenResponse struct {
+ WorkspaceID string `json:"workspace_id"`
+ InstallationID string `json:"installation_id"`
+ DingTalkUserID string `json:"dingtalk_user_id"`
+}
+
+// RedeemDingTalkBindingToken (POST /api/dingtalk/binding/redeem) binds the
+// DingTalk user id carried by the bearer token to the logged-in Multica user.
+// The redeemer's identity comes from the session, while token possession proves
+// control of the link delivered to that DingTalk account. Failure modes map to
+// distinct status codes:
+// - 410 Gone: token unknown / consumed / expired
+// - 409 Conflict: this DingTalk id is already bound to a different user
+// - 403 Forbidden: redeemer is not a workspace member
+func (h *Handler) RedeemDingTalkBindingToken(w http.ResponseWriter, r *http.Request) {
+ if h.DingTalkBindingTokens == nil {
+ writeError(w, http.StatusServiceUnavailable, "dingtalk integration not configured")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ var req RedeemDingTalkBindingTokenRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.Token == "" {
+ writeError(w, http.StatusBadRequest, "token is required")
+ return
+ }
+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+
+ redeemed, err := h.DingTalkBindingTokens.RedeemAndBind(r.Context(), req.Token, userUUID)
+ if err != nil {
+ switch {
+ case errors.Is(err, dingtalk.ErrBindingTokenInvalid):
+ writeError(w, http.StatusGone, "binding token invalid or expired")
+ case errors.Is(err, dingtalk.ErrBindingAlreadyAssigned):
+ writeError(w, http.StatusConflict, "this DingTalk account is already bound to a different Multica user")
+ case errors.Is(err, dingtalk.ErrBindingNotWorkspaceMember):
+ writeError(w, http.StatusForbidden, "binding refused (are you a workspace member?)")
+ default:
+ writeError(w, http.StatusInternalServerError, "failed to redeem token")
+ }
+ return
+ }
+ writeJSON(w, http.StatusOK, RedeemDingTalkBindingTokenResponse{
+ WorkspaceID: uuidToString(redeemed.WorkspaceID),
+ InstallationID: uuidToString(redeemed.InstallationID),
+ DingTalkUserID: redeemed.DingTalkUserID,
+ })
+}
diff --git a/server/internal/handler/dingtalk_test.go b/server/internal/handler/dingtalk_test.go
new file mode 100644
index 0000000000..df53209023
--- /dev/null
+++ b/server/internal/handler/dingtalk_test.go
@@ -0,0 +1,42 @@
+package handler
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestPublishDingTalkInstallationCreated(t *testing.T) {
+ bus := events.New()
+ h := &Handler{Bus: bus}
+
+ const (
+ wsID = "11111111-1111-1111-1111-111111111111"
+ instID = "22222222-2222-2222-2222-222222222222"
+ )
+
+ var got events.Event
+ fired := 0
+ bus.Subscribe(protocol.EventDingTalkInstallationCreated, func(e events.Event) {
+ got = e
+ fired++
+ })
+
+ h.publishDingTalkInstallationCreated(db.ChannelInstallation{
+ ID: parseUUID(instID),
+ WorkspaceID: parseUUID(wsID),
+ }, "user-1")
+
+ if fired != 1 {
+ t.Fatalf("expected dingtalk_installation:created published once, got %d", fired)
+ }
+ if got.WorkspaceID != wsID || got.ActorType != "user" || got.ActorID != "user-1" {
+ t.Errorf("event envelope = %+v", got)
+ }
+ payload, ok := got.Payload.(map[string]any)
+ if !ok || payload["id"] != instID {
+ t.Errorf("payload = %v, want installation id %s", got.Payload, instID)
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index ca5a27e141..761e212a27 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -25,6 +25,7 @@ import (
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
composio "github.com/multica-ai/multica/server/internal/integrations/composio"
+ "github.com/multica-ai/multica/server/internal/integrations/dingtalk"
"github.com/multica-ai/multica/server/internal/integrations/ghsnapshot"
"github.com/multica-ai/multica/server/internal/integrations/lark"
"github.com/multica-ai/multica/server/internal/integrations/slack"
@@ -254,6 +255,11 @@ type Handler struct {
// "link your Slack account" prompt (MUL-3666). Nil unless Slack is
// configured (MULTICA_SLACK_SECRET_KEY set).
SlackBindingTokens *slack.BindingTokenService
+ // DingTalkInstall owns the bring-your-own-app DingTalk lifecycle. It is nil
+ // unless MULTICA_DINGTALK_SECRET_KEY is configured.
+ DingTalkInstall *dingtalk.InstallService
+ // DingTalkBindingTokens mints and redeems the single-use account-link tokens.
+ DingTalkBindingTokens *dingtalk.BindingTokenService
// SlackHistory backs the agent-facing `multica chat history` command: it
// reads a chat session's bound Slack conversation on demand (MUL-3871). Nil
// unless Slack is configured; GetChatChannelHistory then reports "no channel
diff --git a/server/internal/handler/reserved_slugs.json b/server/internal/handler/reserved_slugs.json
index f2f6d01511..80c688bc57 100644
--- a/server/internal/handler/reserved_slugs.json
+++ b/server/internal/handler/reserved_slugs.json
@@ -96,6 +96,13 @@
"cli"
]
},
+ {
+ "label": "DingTalk account-bind route",
+ "description": "`/dingtalk/bind` is a global pre-workspace route where a member links their DingTalk identity. Reserve the prefix so a workspace slug cannot shadow it.",
+ "slugs": [
+ "dingtalk"
+ ]
+ },
{
"label": "Backend ops / observability",
"description": "`/health`, `/readyz`, `/healthz`, and `/ws` exist on the backend host; reserving them on the workspace slug space prevents naming confusion if/when these paths are ever proxied through the web origin.",
diff --git a/server/internal/integrations/dingtalk/ack.go b/server/internal/integrations/dingtalk/ack.go
new file mode 100644
index 0000000000..de0be3cb9b
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ack.go
@@ -0,0 +1,136 @@
+package dingtalk
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// The classic robot API we send through (oToMessages/batchSend) exposes no
+// per-message reaction, so a long-running agent turn leaves a mobile user
+// staring at silence until the reply lands. (DingTalk's AI-assistant stack does
+// offer a reaction capability via ackReactionScope, but the v0.9.1 stream SDK
+// does not surface it.) The ack notifier stands in for a typing indicator: on
+// ingest it posts a lightweight "working on it" message so the user sees their
+// message was received.
+//
+// It implements engine.TypingNotifier. The engine calls OnIngested after an
+// accepted turn has been persisted and scheduled for an agent run. Terminal
+// commands such as /issue return their synchronous result without posting this
+// non-retractable processing acknowledgement.
+
+// ackProcessingText is the stand-in "typing" message. Kept short: it is a real,
+// non-retractable chat message, not an ephemeral indicator.
+const ackProcessingText = "👀 On it — I'll reply here when it's ready."
+
+// ackCoalesceWindow suppresses duplicate acks for the same session. It sits just
+// above the run debounce window so a burst of messages that flush into one run
+// yields a single ack, while a genuinely later turn re-acks.
+const ackCoalesceWindow = 5 * time.Second
+
+// ackNotifier posts the processing ack and coalesces bursts per session.
+type ackNotifier struct {
+ client *Client
+ decrypt Decrypter
+ logger *slog.Logger
+ window time.Duration
+ now func() time.Time
+
+ mu sync.Mutex
+ lastAck map[string]time.Time
+
+ // sendText delivers text into the installation's conversation. Nil uses the
+ // real Open-API send; tests inject a recorder.
+ sendText func(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error
+}
+
+var _ engine.TypingNotifier = (*ackNotifier)(nil)
+
+// NewAckNotifier builds the ack notifier over the shared outbound client and the
+// credential decrypter.
+func NewAckNotifier(client *Client, decrypt Decrypter, logger *slog.Logger) *ackNotifier {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &ackNotifier{
+ client: client,
+ decrypt: decrypt,
+ logger: logger,
+ window: ackCoalesceWindow,
+ lastAck: make(map[string]time.Time),
+ }
+}
+
+// OnIngested posts the processing ack unless a recent ack for the same session
+// is still within the coalesce window.
+func (n *ackNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {
+ if n.suppress(sessionID) {
+ return
+ }
+ send := n.sendText
+ if send == nil {
+ send = n.realSend
+ }
+ if err := send(ctx, inst, msg, ackProcessingText); err != nil {
+ n.logger.WarnContext(ctx, "dingtalk ack: send failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+}
+
+// OnSettled clears the session's dedup entry so its next turn acks immediately.
+func (n *ackNotifier) OnSettled(_ context.Context, sessionID pgtype.UUID) {
+ key := util.UUIDToString(sessionID)
+ if key == "" {
+ return
+ }
+ n.mu.Lock()
+ delete(n.lastAck, key)
+ n.mu.Unlock()
+}
+
+// suppress reports whether an ack for sessionID should be skipped, and otherwise
+// records this ack. The check-and-set is atomic so concurrent ingests of one
+// burst yield a single ack.
+func (n *ackNotifier) suppress(sessionID pgtype.UUID) bool {
+ key := util.UUIDToString(sessionID)
+ if key == "" {
+ return false
+ }
+ now := n.clock()
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ if last, ok := n.lastAck[key]; ok && now.Sub(last) < n.window {
+ return true
+ }
+ // Prune entries past the window before inserting. OnSettled only fires for
+ // runs that enqueue no task, so task-spawning sessions would otherwise leak
+ // their entry forever. Stale entries are dead (any later turn re-acks), and
+ // this runs only on a cache miss, keeping the map bounded by the sessions
+ // seen within one window.
+ for k, last := range n.lastAck {
+ if now.Sub(last) >= n.window {
+ delete(n.lastAck, k)
+ }
+ }
+ n.lastAck[key] = now
+ return false
+}
+
+func (n *ackNotifier) clock() time.Time {
+ if n.now != nil {
+ return n.now()
+ }
+ return time.Now()
+}
+
+func (n *ackNotifier) realSend(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
+ _, err := sendInstallationText(ctx, n.client, n.decrypt, inst, targetFromMessage(msg), text)
+ return err
+}
diff --git a/server/internal/integrations/dingtalk/ack_test.go b/server/internal/integrations/dingtalk/ack_test.go
new file mode 100644
index 0000000000..7dfd8b3f6f
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ack_test.go
@@ -0,0 +1,85 @@
+package dingtalk
+
+import (
+ "context"
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+func sessionUUID(b byte) pgtype.UUID {
+ var u pgtype.UUID
+ u.Valid = true
+ u.Bytes[0] = b
+ return u
+}
+
+func newTestAck(now func() time.Time) (*ackNotifier, *[]string) {
+ var sent []string
+ n := &ackNotifier{
+ logger: slog.Default(),
+ window: 5 * time.Second,
+ now: now,
+ lastAck: map[string]time.Time{},
+ sendText: func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, text string) error {
+ sent = append(sent, text)
+ return nil
+ },
+ }
+ return n, &sent
+}
+
+func TestAckNotifier_CoalescesBurstThenReacksAfterWindow(t *testing.T) {
+ base := time.Unix(1700000000, 0)
+ cur := base
+ n, sent := newTestAck(func() time.Time { return cur })
+ sid := sessionUUID(1)
+ ctx := context.Background()
+
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)
+ if len(*sent) != 1 {
+ t.Fatalf("a burst within the window must coalesce to one ack, got %d", len(*sent))
+ }
+ if (*sent)[0] != ackProcessingText {
+ t.Errorf("ack text = %q, want %q", (*sent)[0], ackProcessingText)
+ }
+
+ cur = base.Add(6 * time.Second)
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)
+ if len(*sent) != 2 {
+ t.Fatalf("a message after the window must re-ack, got %d", len(*sent))
+ }
+}
+
+func TestAckNotifier_SettleResetsDedup(t *testing.T) {
+ cur := time.Unix(1700000000, 0)
+ n, sent := newTestAck(func() time.Time { return cur })
+ sid := sessionUUID(2)
+ ctx := context.Background()
+
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)
+ n.OnSettled(ctx, sid)
+ // Even within the window, a settled session acks its next turn immediately.
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)
+ if len(*sent) != 2 {
+ t.Fatalf("OnSettled must reset dedup so the next turn re-acks, got %d", len(*sent))
+ }
+}
+
+func TestAckNotifier_DistinctSessionsAckIndependently(t *testing.T) {
+ cur := time.Unix(1700000000, 0)
+ n, sent := newTestAck(func() time.Time { return cur })
+ ctx := context.Background()
+
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sessionUUID(3))
+ n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sessionUUID(4))
+ if len(*sent) != 2 {
+ t.Fatalf("distinct sessions must each ack, got %d", len(*sent))
+ }
+}
diff --git a/server/internal/integrations/dingtalk/binding.go b/server/internal/integrations/dingtalk/binding.go
new file mode 100644
index 0000000000..412bc21d52
--- /dev/null
+++ b/server/internal/integrations/dingtalk/binding.go
@@ -0,0 +1,178 @@
+package dingtalk
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// This file is the DingTalk user-binding token flow: an unbound DingTalk user
+// who messages the bot gets a "link your account" prompt (minted here, delivered
+// by the OutboundReplier), clicks through to the in-product redeem page, and
+// their DingTalk staff id is bound to their Multica account. It mirrors
+// slack.BindingTokenService but runs on the generic channel_* queries with
+// channel_type='dingtalk'.
+
+// BindingTokenTTL bounds a token's life. The channel_binding_token CHECK
+// enforces the same 15-minute cap so a misconfigured caller cannot mint longer.
+const BindingTokenTTL = 15 * time.Minute
+
+var (
+ // ErrBindingTokenInvalid: token unknown / already consumed / expired. One
+ // opaque error for all three avoids a replay timing oracle.
+ ErrBindingTokenInvalid = errors.New("dingtalk: binding token invalid or expired")
+ // ErrBindingAlreadyAssigned: this DingTalk user id is already bound to a
+ // different Multica user (account transfer must go through explicit unbind).
+ ErrBindingAlreadyAssigned = errors.New("dingtalk: user id is already bound to a different user")
+ // ErrBindingNotWorkspaceMember: the redeemer is not a member of the token's
+ // workspace. Translated to 403 at the HTTP boundary.
+ ErrBindingNotWorkspaceMember = errors.New("dingtalk: redeemer is not a workspace member")
+)
+
+// BindingToken is a freshly minted token. The raw value is returned exactly
+// once (embedded in the binding URL); only its hash is persisted.
+type BindingToken struct {
+ Raw string
+ ExpiresAt time.Time
+}
+
+// RedeemedBindingToken is returned after a successful redemption.
+type RedeemedBindingToken struct {
+ WorkspaceID pgtype.UUID
+ InstallationID pgtype.UUID
+ DingTalkUserID string
+}
+
+// BindingTokenService mints and redeems DingTalk binding tokens. Redemption is
+// transactional: consuming the token and inserting the channel_user_binding row
+// commit together, so a failed bind never burns a token.
+type BindingTokenService struct {
+ q *db.Queries
+ tx engine.TxStarter
+ now func() time.Time
+}
+
+// NewBindingTokenService constructs the service. tx (a *pgxpool.Pool) is needed
+// for the transactional redeem path.
+func NewBindingTokenService(q *db.Queries, tx engine.TxStarter) *BindingTokenService {
+ return &BindingTokenService{q: q, tx: tx, now: time.Now}
+}
+
+// Mint creates a single-use binding token for (installation, dingtalkUserID) and
+// returns the raw secret + expiry. The raw value must be delivered over DingTalk
+// (encrypted in transit by the platform) and never logged.
+func (s *BindingTokenService) Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, dingtalkUserID string) (BindingToken, error) {
+ raw, err := randomBindingToken(32)
+ if err != nil {
+ return BindingToken{}, fmt.Errorf("generate token: %w", err)
+ }
+ expiresAt := s.now().Add(BindingTokenTTL)
+ if _, err := s.q.CreateChannelBindingToken(ctx, db.CreateChannelBindingTokenParams{
+ TokenHash: hashBindingToken(raw),
+ WorkspaceID: workspaceID,
+ InstallationID: installationID,
+ ChannelType: string(TypeDingTalk),
+ ChannelUserID: dingtalkUserID,
+ ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},
+ }); err != nil {
+ return BindingToken{}, fmt.Errorf("persist token: %w", err)
+ }
+ return BindingToken{Raw: raw, ExpiresAt: expiresAt}, nil
+}
+
+// RedeemAndBind atomically consumes a raw token and binds the DingTalk user id
+// to multicaUserID (taken from the session, never from the token). Returns
+// ErrBindingTokenInvalid / ErrBindingAlreadyAssigned / ErrBindingNotWorkspaceMember.
+func (s *BindingTokenService) RedeemAndBind(ctx context.Context, raw string, multicaUserID pgtype.UUID) (RedeemedBindingToken, error) {
+ if s.tx == nil {
+ return RedeemedBindingToken{}, errors.New("dingtalk: BindingTokenService missing TxStarter")
+ }
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("begin tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.q.WithTx(tx)
+
+ row, err := qtx.ConsumeChannelBindingToken(ctx, hashBindingToken(raw))
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingTokenInvalid
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("consume token: %w", err)
+ }
+ if err := validateBindingTokenChannel(row); err != nil {
+ // Consume and bind share this transaction, so returning here rolls the
+ // consume back. A token from another adapter must never create a DingTalk
+ // binding against that adapter's installation.
+ return RedeemedBindingToken{}, err
+ }
+
+ // Explicit membership gate (no member FK): returning before Commit rolls the
+ // consume back, so a non-member's attempt does not burn the token.
+ if _, err := qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: multicaUserID,
+ WorkspaceID: row.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingNotWorkspaceMember
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("check membership: %w", err)
+ }
+
+ if _, err := qtx.CreateChannelUserBinding(ctx, db.CreateChannelUserBindingParams{
+ WorkspaceID: row.WorkspaceID,
+ MulticaUserID: multicaUserID,
+ InstallationID: row.InstallationID,
+ ChannelType: string(TypeDingTalk),
+ ChannelUserID: row.ChannelUserID,
+ Config: []byte(`{}`),
+ }); err != nil {
+ // pgx.ErrNoRows means the existing binding points at a different user —
+ // the ON CONFLICT DO UPDATE WHERE multica_user_id=… gating rejected it.
+ if errors.Is(err, pgx.ErrNoRows) {
+ return RedeemedBindingToken{}, ErrBindingAlreadyAssigned
+ }
+ return RedeemedBindingToken{}, fmt.Errorf("create binding: %w", err)
+ }
+
+ if err := tx.Commit(ctx); err != nil {
+ return RedeemedBindingToken{}, fmt.Errorf("commit: %w", err)
+ }
+ return RedeemedBindingToken{
+ WorkspaceID: row.WorkspaceID,
+ InstallationID: row.InstallationID,
+ DingTalkUserID: row.ChannelUserID,
+ }, nil
+}
+
+func validateBindingTokenChannel(row db.ChannelBindingToken) error {
+ if row.ChannelType != string(TypeDingTalk) {
+ return ErrBindingTokenInvalid
+ }
+ return nil
+}
+
+func randomBindingToken(n int) (string, error) {
+ buf := make([]byte, n)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(buf), nil
+}
+
+func hashBindingToken(raw string) string {
+ sum := sha256.Sum256([]byte(raw))
+ return hex.EncodeToString(sum[:])
+}
diff --git a/server/internal/integrations/dingtalk/binding_test.go b/server/internal/integrations/dingtalk/binding_test.go
new file mode 100644
index 0000000000..4a9936d5de
--- /dev/null
+++ b/server/internal/integrations/dingtalk/binding_test.go
@@ -0,0 +1,17 @@
+package dingtalk
+
+import (
+ "errors"
+ "testing"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestValidateBindingTokenChannel(t *testing.T) {
+ if err := validateBindingTokenChannel(db.ChannelBindingToken{ChannelType: string(TypeDingTalk)}); err != nil {
+ t.Fatalf("DingTalk token rejected: %v", err)
+ }
+ if err := validateBindingTokenChannel(db.ChannelBindingToken{ChannelType: "slack"}); !errors.Is(err, ErrBindingTokenInvalid) {
+ t.Fatalf("cross-channel token error = %v, want ErrBindingTokenInvalid", err)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/byo_install.go b/server/internal/integrations/dingtalk/byo_install.go
new file mode 100644
index 0000000000..266cb0a40a
--- /dev/null
+++ b/server/internal/integrations/dingtalk/byo_install.go
@@ -0,0 +1,100 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ErrInvalidAppKey / ErrInvalidAppSecret are returned by RegisterBYO when a
+// pasted credential is empty. The handler maps them to 400 so the dialog can
+// show a precise hint instead of a generic failure.
+var (
+ ErrInvalidAppKey = errors.New("dingtalk: AppKey (client id) is required")
+ ErrInvalidAppSecret = errors.New("dingtalk: AppSecret (client secret) is required")
+ // ErrCredentialValidation wraps a live access-token mint that rejected the
+ // pasted AppKey/AppSecret. It is a user error (bad credentials), so the
+ // handler maps it to 400 — unlike an internal encrypt/persist failure, which
+ // must surface as 500.
+ ErrCredentialValidation = errors.New("dingtalk: could not validate credentials")
+)
+
+// RegisterBYOParams are the inputs for a bring-your-own-app install: the agent
+// this bot represents, who is installing, and the two credentials the user
+// pasted from their own DingTalk Stream-mode robot.
+type RegisterBYOParams struct {
+ WorkspaceID pgtype.UUID
+ AgentID pgtype.UUID
+ InitiatorID pgtype.UUID
+ AppKey string // client id — robotCode + access-token mint
+ AppSecret string // client secret — access-token mint (encrypted at rest)
+}
+
+// RegisterBYO installs a user-supplied ("bring your own") DingTalk robot for an
+// agent. The user creates their own DingTalk Stream-mode robot and pastes its
+// 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
+// persist the installation.
+//
+// Because each BYO robot is a distinct DingTalk app — a distinct bot identity —
+// the SAME DingTalk organization can host several of them, one per agent. The
+// stored config carries the AppKey as the routing key (config->>'app_id', equal
+// to the inbound event's robotCode for a Stream-mode robot); persistInstall keys
+// the row by (workspace, agent), reclaims a DEAD prior owner of that AppKey
+// (a revoked placeholder, or an orphan whose workspace/agent was deleted) so the
+// robot can move to this agent, and refuses a LIVE owner with an accurate
+// conflict sentinel. The dedicated Stream connection that consumes the stored
+// credentials lives in dingtalk_channel.go; this method only persists the
+// installation.
+func (s *InstallService) RegisterBYO(ctx context.Context, p RegisterBYOParams) (db.ChannelInstallation, error) {
+ appKey := strings.TrimSpace(p.AppKey)
+ appSecret := strings.TrimSpace(p.AppSecret)
+ if appKey == "" {
+ return db.ChannelInstallation{}, ErrInvalidAppKey
+ }
+ if appSecret == "" {
+ return db.ChannelInstallation{}, ErrInvalidAppSecret
+ }
+
+ // Validate the credentials live: a successful access_token mint proves the
+ // AppKey/AppSecret pair is real and installed. The robotCode of a Stream-mode
+ // robot equals the AppKey, so no separate identity lookup is needed.
+ validationCtx, cancel := context.WithTimeout(ctx, s.validationTimeout)
+ defer cancel()
+ if _, _, err := fetchAccessToken(validationCtx, s.httpClient, s.apiBase, appKey, appSecret); err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("%w: %v", ErrCredentialValidation, err)
+ }
+
+ sealedSecret, err := s.box.Seal([]byte(appSecret))
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("encrypt dingtalk app secret: %w", err)
+ }
+ cfgJSON, err := json.Marshal(installConfig{
+ AppID: appKey,
+ RobotCode: appKey,
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealedSecret),
+ })
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("encode dingtalk installation config: %w", err)
+ }
+
+ // 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.
+ return s.persistInstall(ctx, installPersist{
+ wsID: p.WorkspaceID,
+ agentID: p.AgentID,
+ installerID: p.InitiatorID,
+ appIDKey: appKey,
+ configJSON: cfgJSON,
+ })
+}
diff --git a/server/internal/integrations/dingtalk/byo_install_db_test.go b/server/internal/integrations/dingtalk/byo_install_db_test.go
new file mode 100644
index 0000000000..db8a40bb71
--- /dev/null
+++ b/server/internal/integrations/dingtalk/byo_install_db_test.go
@@ -0,0 +1,174 @@
+package dingtalk
+
+import (
+ "context"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "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"
+)
+
+func dingtalkInstallTestDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dsn := os.Getenv("DATABASE_URL")
+ if dsn == "" {
+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Skipf("no database: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ var migrated bool
+ if err := pool.QueryRow(ctx, `
+SELECT to_regclass('public.channel_installation') IS NOT NULL
+ AND to_regclass('public.channel_media_pending_object') IS NOT NULL
+`).Scan(&migrated); err != nil || !migrated {
+ pool.Close()
+ t.Skip("channel installation tables not present (database not migrated)")
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+// A DingTalk senderStaffId is only unique inside one organization. Swapping an
+// agent from one AppKey to another must therefore produce a new installation
+// identity, require the colliding staff id to bind again, and make the old chat
+// session unavailable to the new robot.
+func TestRegisterBYO_DifferentAppKey_IsolatesIdentityStateDB(t *testing.T) {
+ pool := dingtalkInstallTestDB(t)
+ ctx := context.Background()
+ const (
+ workspaceID = "d1470000-0000-4000-8000-000000000001"
+ agentID = "d1470000-0000-4000-8000-000000000002"
+ installerID = "d1470000-0000-4000-8000-000000000003"
+ multicaUserID = "d1470000-0000-4000-8000-000000000004"
+ oldInstallID = "d1470000-0000-4000-8000-000000000010"
+ chatSessionID = "d1470000-0000-4000-8000-000000000020"
+ mediaMessageID = "d1470000-0000-4000-8000-000000000030"
+ oldAppKey = "dingtalk_identity_old_app"
+ newAppKey = "dingtalk_identity_new_app"
+ staffID = "staff-id-collision"
+ chatID = "cid-old-organization-chat"
+ tokenHash = "dingtalk_identity_old_token"
+ auditEventID = "dingtalk_identity_old_audit"
+ storageKey = "test/dingtalk/identity-old-image"
+ )
+
+ clean := func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_outbound_card_message WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_binding_token WHERE token_hash = $1`, tokenHash)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_user_binding WHERE workspace_id = $1 AND channel_user_id = $2`, workspaceID, staffID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE message_id = 'dingtalk-identity-old-message'`)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_inbound_audit WHERE channel_event_id = $1`, auditEventID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_media_pending_object WHERE storage_key = $1`, storageKey)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE workspace_id = $1 AND agent_id = $2 AND channel_type = 'dingtalk'`, workspaceID, agentID)
+ }
+ clean()
+ t.Cleanup(clean)
+
+ exec := func(query string, args ...any) {
+ t.Helper()
+ if _, err := pool.Exec(ctx, query, args...); err != nil {
+ t.Fatalf("seed replacement fixture: %v", err)
+ }
+ }
+ 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)
+`, oldInstallID, workspaceID, agentID, oldAppKey, installerID)
+ 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, multicaUserID, oldInstallID, staffID)
+ exec(`
+INSERT INTO channel_chat_session_binding (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+VALUES ($1, $2, 'dingtalk', $3, 'p2p')
+`, chatSessionID, oldInstallID, chatID)
+ exec(`
+INSERT INTO channel_binding_token (token_hash, workspace_id, installation_id, channel_type, channel_user_id, expires_at)
+VALUES ($1, $2, $3, 'dingtalk', $4, now() + interval '10 minutes')
+`, tokenHash, workspaceID, oldInstallID, staffID)
+ exec(`
+INSERT INTO channel_outbound_card_message (chat_session_id, channel_type, channel_chat_id, channel_card_message_id)
+VALUES ($1, 'dingtalk', $2, 'old-outbound-message')
+`, chatSessionID, chatID)
+ exec(`
+INSERT INTO channel_inbound_message_dedup (installation_id, message_id)
+VALUES ($1, 'dingtalk-identity-old-message')
+`, oldInstallID)
+ exec(`
+INSERT INTO channel_inbound_audit (installation_id, channel_type, event_type, channel_event_id, drop_reason)
+VALUES ($1, 'dingtalk', 'chatbot-message', $2, 'test')
+`, oldInstallID, auditEventID)
+ exec(`
+INSERT INTO channel_media_pending_object (storage_key, workspace_id, chat_message_id, storage_url, installation_id)
+VALUES ($1, $2, $3, 'https://storage.example.test/old-image', $4)
+`, storageKey, workspaceID, mediaMessageID, oldInstallID)
+
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ svc, err := NewInstallService(db.New(pool), pool, testBox(t), nil)
+ if err != nil {
+ t.Fatalf("NewInstallService: %v", err)
+ }
+ svc.apiBase = srv.URL
+ params := byoParams(workspaceID, agentID)
+ params.AppKey = newAppKey
+ row, err := svc.RegisterBYO(ctx, params)
+ if err != nil {
+ t.Fatalf("RegisterBYO replacement: %v", err)
+ }
+ oldUUID := util.MustParseUUID(oldInstallID)
+ if row.ID == oldUUID {
+ t.Fatalf("different AppKey reused installation id %s", oldInstallID)
+ }
+
+ resolver := identityResolver{q: db.New(pool)}
+ _, err = resolver.ResolveSender(ctx, engine.ResolvedInstallation{
+ ID: row.ID,
+ WorkspaceID: util.MustParseUUID(workspaceID),
+ }, channel.InboundMessage{Source: channel.Source{SenderID: staffID}})
+ if !errors.Is(err, engine.ErrSenderUnbound) {
+ t.Fatalf("colliding staff id resolved after AppKey swap: %v, want ErrSenderUnbound", err)
+ }
+
+ queries := db.New(pool)
+ if _, err := queries.GetChannelChatSessionBinding(ctx, db.GetChannelChatSessionBindingParams{
+ InstallationID: row.ID,
+ ChannelChatID: chatID,
+ }); !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("old chat session reused by replacement: %v, want pgx.ErrNoRows", err)
+ }
+
+ assertCount := func(name, query string, want int, args ...any) {
+ t.Helper()
+ var got int
+ if err := pool.QueryRow(ctx, query, args...).Scan(&got); err != nil {
+ t.Fatalf("count %s: %v", name, err)
+ }
+ if got != want {
+ t.Fatalf("%s rows = %d, want %d", name, got, want)
+ }
+ }
+ assertCount("old installation", `SELECT count(*) FROM channel_installation WHERE id = $1`, 0, oldInstallID)
+ assertCount("old user binding", `SELECT count(*) FROM channel_user_binding WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("old chat binding", `SELECT count(*) FROM channel_chat_session_binding WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("old binding token", `SELECT count(*) FROM channel_binding_token WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("old outbound state", `SELECT count(*) FROM channel_outbound_card_message WHERE chat_session_id = $1`, 0, chatSessionID)
+ assertCount("old dedup state", `SELECT count(*) FROM channel_inbound_message_dedup WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("detached audit", `SELECT count(*) FROM channel_inbound_audit WHERE channel_event_id = $1 AND installation_id IS NULL`, 1, auditEventID)
+ assertCount("detached media intent", `SELECT count(*) FROM channel_media_pending_object WHERE storage_key = $1 AND installation_id IS NULL`, 1, storageKey)
+}
diff --git a/server/internal/integrations/dingtalk/byo_install_test.go b/server/internal/integrations/dingtalk/byo_install_test.go
new file mode 100644
index 0000000000..d27d647072
--- /dev/null
+++ b/server/internal/integrations/dingtalk/byo_install_test.go
@@ -0,0 +1,366 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+// dingtalkMockServer stubs the single Open-API call RegisterBYO makes:
+// /v1.0/oauth2/accessToken (mint a token from AppKey/AppSecret). tokenOK=false
+// makes it reject the credentials with a 400, as DingTalk does for a bad pair.
+func dingtalkMockServer(t *testing.T, tokenOK bool) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path != accessTokenPath {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"code":"unknownPath","message":"unknown"}`))
+ return
+ }
+ if !tokenOK {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"code":"InvalidAuthentication","message":"appKey or appSecret is invalid"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"accessToken":"tok-abc","expireIn":7200}`))
+ }))
+}
+
+func byoParams(ws, agent string) RegisterBYOParams {
+ return RegisterBYOParams{
+ WorkspaceID: pgtypeUUID(ws),
+ AgentID: pgtypeUUID(agent),
+ InitiatorID: pgtypeUUID("33333333-3333-3333-3333-333333333333"),
+ AppKey: "ding-app-key-xyz",
+ AppSecret: "ding-app-secret-xyz",
+ }
+}
+
+// pgtypeUUID is a test-local UUID parse that panics on bad input (test data is
+// always valid), so byoParams stays a plain literal.
+func pgtypeUUID(s string) pgtype.UUID {
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ panic(err)
+ }
+ return u
+}
+
+func TestRegisterBYO_PersistsEncryptedSecretKeyedByAppID(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+
+ q := &fakeInstallQueries{rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444")}
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ row, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ ))
+ if err != nil {
+ t.Fatalf("RegisterBYO: %v", err)
+ }
+ if row.ID != q.rowID {
+ t.Errorf("row id = %v, want %v", row.ID, q.rowID)
+ }
+ if !q.upsertCalled || q.upsertParams.ChannelType != string(TypeDingTalk) {
+ t.Fatalf("upsert not called for dingtalk: %+v", q.upsertParams)
+ }
+
+ var cfg installConfig
+ if err := json.Unmarshal(q.upsertParams.Config, &cfg); err != nil {
+ t.Fatalf("decode upserted config: %v", err)
+ }
+ // Routing key is the AppKey (== robotCode for a Stream-mode robot).
+ if cfg.AppID != "ding-app-key-xyz" || cfg.RobotCode != "ding-app-key-xyz" {
+ t.Errorf("config app_id/robot_code = %q/%q, want ding-app-key-xyz", cfg.AppID, cfg.RobotCode)
+ }
+ // AppSecret stored encrypted (never plaintext) and decrypts back. AppKey is
+ // not a secret and lives in app_id in the clear (like Feishu's app_id).
+ if cfg.AppSecretEncrypted == "" {
+ t.Fatalf("app secret must be stored: %+v", cfg)
+ }
+ if strings.Contains(cfg.AppSecretEncrypted, "ding-app-secret-xyz") {
+ t.Error("app secret must be stored encrypted, not plaintext")
+ }
+ secret, err := decryptToken(cfg.AppSecretEncrypted, svc.box.Open)
+ if err != nil || secret != "ding-app-secret-xyz" {
+ t.Errorf("decrypted app secret = %q, %v", secret, err)
+ }
+}
+
+func TestRegisterBYO_MissingCredentials(t *testing.T) {
+ q := &fakeInstallQueries{}
+ svc := newTestInstallService(t, q)
+
+ // Empty AppKey — rejected before any network call or upsert.
+ p := byoParams("11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222")
+ p.AppKey = " "
+ if _, err := svc.RegisterBYO(context.Background(), p); err != ErrInvalidAppKey {
+ t.Errorf("empty app key = %v, want ErrInvalidAppKey", err)
+ }
+ // Empty AppSecret.
+ p = byoParams("11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222")
+ p.AppSecret = ""
+ if _, err := svc.RegisterBYO(context.Background(), p); err != ErrInvalidAppSecret {
+ t.Errorf("empty app secret = %v, want ErrInvalidAppSecret", err)
+ }
+ if q.upsertCalled {
+ t.Error("missing credentials must be rejected before the upsert")
+ }
+}
+
+func TestRegisterBYO_AccessTokenFailure(t *testing.T) {
+ srv := dingtalkMockServer(t, false) // DingTalk rejects the credentials
+ defer srv.Close()
+ q := &fakeInstallQueries{}
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ if _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )); err == nil {
+ t.Fatal("expected an error when the access-token mint rejects the credentials")
+ }
+ if q.upsertCalled {
+ t.Error("a failed credential validation must not persist an installation")
+ }
+}
+
+func TestRegisterBYO_CredentialValidationTimesOut(t *testing.T) {
+ q := &fakeInstallQueries{}
+ svc := newTestInstallService(t, q)
+ svc.validationTimeout = 10 * time.Millisecond
+ svc.httpClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ <-r.Context().Done()
+ return nil, r.Context().Err()
+ })}
+
+ _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ ))
+ if !errors.Is(err, ErrCredentialValidation) {
+ t.Fatalf("timeout error = %v, want ErrCredentialValidation", err)
+ }
+ if q.upsertCalled {
+ t.Fatal("timed-out credential validation persisted an installation")
+ }
+}
+
+func TestRegisterBYO_RobotConnectedToAnotherWorkspace_Rejected(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ // The pasted robot is live-owned by an agent in a DIFFERENT Multica
+ // workspace, so after the dead-owner reclaim the (channel_type, app_id)
+ // routing index still rejects the upsert. We must refuse, not steal it — and
+ // name the real case (another workspace), not a catch-all.
+ q := &fakeInstallQueries{
+ rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ appIDTaken: true,
+ ownerWorkspaceID: mustUUID(t, "99999999-9999-9999-9999-999999999999"),
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ if _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )); err != ErrRobotOwnedByAnotherWorkspace {
+ t.Fatalf("robot already connected = %v, want ErrRobotOwnedByAnotherWorkspace", err)
+ }
+ if !q.reclaimCalled {
+ t.Error("install must attempt a dead-owner reclaim before the upsert")
+ }
+}
+
+func TestRegisterBYO_RobotConnectedToAnotherAgentSameWorkspace_Rejected(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ // The pasted robot is live-owned by a DIFFERENT (non-archived) agent in the
+ // SAME workspace. This must surface the same-workspace sentinel so the UI
+ // points at the Disconnect the user can actually reach (#4810).
+ q := &fakeInstallQueries{
+ rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ appIDTaken: true,
+ ownerWorkspaceID: mustUUID(t, "11111111-1111-1111-1111-111111111111"),
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ if _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )); err != ErrRobotOwnedBySameWorkspace {
+ t.Fatalf("robot owned by another agent in this workspace = %v, want ErrRobotOwnedBySameWorkspace", err)
+ }
+}
+
+func TestRegisterBYO_RobotConnectedToArchivedAgent_Rejected(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ // The pasted robot's owning agent is archived — a live-but-reversible owner —
+ // so the reclaim leaves it in place and the upsert is refused. The user is
+ // told to restore the agent or disconnect its robot, not that it's gone.
+ q := &fakeInstallQueries{
+ rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ appIDTaken: true,
+ ownerWorkspaceID: mustUUID(t, "11111111-1111-1111-1111-111111111111"),
+ ownerArchived: true,
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ if _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )); err != ErrRobotOwnedByArchivedAgent {
+ t.Fatalf("robot owned by an archived agent = %v, want ErrRobotOwnedByArchivedAgent", err)
+ }
+}
+
+// A DEAD prior owner of the AppKey — a revoked placeholder, or an orphan whose
+// workspace/agent was deleted — is reclaimed by the shared
+// ReclaimDeadChannelInstallationByAppID gate, freeing the routing slot so the
+// upsert inserts a fresh row for the new agent (#4810).
+func TestRegisterBYO_ReclaimsDeadOwner(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ deadID := mustUUID(t, "99999999-9999-9999-9999-999999999999")
+ q := &fakeInstallQueries{
+ rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ reclaimedID: &deadID, // the reclaim cleared a dead prior owner
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ row, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ ))
+ if err != nil {
+ t.Fatalf("RegisterBYO after reclaim: %v", err)
+ }
+ if !q.reclaimCalled {
+ t.Error("install must run the dead-owner reclaim before the upsert")
+ }
+ if !q.upsertCalled {
+ t.Error("upsert must run after reclaiming the dead owner")
+ }
+ if row.ID != q.rowID {
+ t.Errorf("row id = %v, want %v", row.ID, q.rowID)
+ }
+}
+
+// Re-connecting the SAME (workspace, agent) is an in-place update: the reclaim
+// spares the caller's own row (the SQL guard excludes it), and the upsert's
+// (workspace, agent, channel) conflict target reactivates it with its
+// installation_id — and every binding hanging off it — preserved.
+func TestRegisterBYO_SameAgentReconnect_UpdatesRowInPlace(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ existing := &db.ChannelInstallation{
+ ID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ WorkspaceID: mustUUID(t, "11111111-1111-1111-1111-111111111111"),
+ AgentID: mustUUID(t, "22222222-2222-2222-2222-222222222222"),
+ }
+ q := &fakeInstallQueries{existing: existing, existingAppID: "ding-app-key-xyz"}
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ row, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ ))
+ if err != nil {
+ t.Fatalf("RegisterBYO same-agent reconnect: %v", err)
+ }
+ if row.ID != existing.ID {
+ t.Errorf("reconnect row id = %v, want in-place %v", row.ID, existing.ID)
+ }
+ if q.replaceCalled {
+ t.Fatal("same-AppKey reconnect retired the installation identity")
+ }
+}
+
+// Replacing an agent's robot with a DIFFERENT AppKey must establish a fresh
+// installation identity. Keeping the old installation_id would carry
+// organization-scoped senderStaffId bindings and chat sessions into the new
+// DingTalk organization.
+func TestRegisterBYO_DifferentAppKey_ReplacesInstallationIdentity(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ oldID := mustUUID(t, "44444444-4444-4444-4444-444444444444")
+ newID := mustUUID(t, "55555555-5555-5555-5555-555555555555")
+ existing := &db.ChannelInstallation{
+ ID: oldID,
+ WorkspaceID: mustUUID(t, "11111111-1111-1111-1111-111111111111"),
+ AgentID: mustUUID(t, "22222222-2222-2222-2222-222222222222"),
+ }
+ q := &fakeInstallQueries{
+ existing: existing,
+ existingAppID: "ding-old-app-key",
+ rowID: newID,
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ row, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ ))
+ if err != nil {
+ t.Fatalf("RegisterBYO different-AppKey replacement: %v", err)
+ }
+ if !q.lockCalled {
+ t.Fatal("replacement decision was not serialized")
+ }
+ if !q.replaceCalled || q.replaceParams.InstallationID != oldID {
+ t.Fatalf("retired installation = (%v, %+v), want old id %v", q.replaceCalled, q.replaceParams, oldID)
+ }
+ if row.ID != newID || row.ID == oldID {
+ t.Fatalf("replacement row id = %v, want fresh %v (old %v)", row.ID, newID, oldID)
+ }
+}
+
+// A concurrent disconnect can free the slot between the failed upsert and the
+// live-owner lookup; the lookup's ErrNoRows then falls back to the generic
+// cross-workspace sentinel (HTTP 409, a retry succeeds) instead of surfacing an
+// opaque 500.
+func TestRegisterBYO_OwnerLookupMiss_FallsBackToConflict(t *testing.T) {
+ srv := dingtalkMockServer(t, true)
+ defer srv.Close()
+ q := &fakeInstallQueries{
+ rowID: mustUUID(t, "44444444-4444-4444-4444-444444444444"),
+ appIDTaken: true,
+ ownerMissing: true,
+ }
+ svc := newTestInstallService(t, q)
+ svc.apiBase = srv.URL
+
+ if _, err := svc.RegisterBYO(context.Background(), byoParams(
+ "11111111-1111-1111-1111-111111111111",
+ "22222222-2222-2222-2222-222222222222",
+ )); err != ErrRobotOwnedByAnotherWorkspace {
+ t.Fatalf("owner lookup miss = %v, want fallback ErrRobotOwnedByAnotherWorkspace", err)
+ }
+ if !q.upsertCalled {
+ t.Error("the upsert must run and trip the routing unique index")
+ }
+}
diff --git a/server/internal/integrations/dingtalk/client.go b/server/internal/integrations/dingtalk/client.go
new file mode 100644
index 0000000000..1eab4ff516
--- /dev/null
+++ b/server/internal/integrations/dingtalk/client.go
@@ -0,0 +1,109 @@
+package dingtalk
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// errUnauthorized is returned by postJSON on an HTTP 401 so the outbound sender
+// can drop the cached access_token and retry once with a fresh one.
+var errUnauthorized = errors.New("dingtalk: unauthorized (access token expired or invalid)")
+
+// This file is the thin DingTalk Open-API REST seam the install + outbound
+// paths share: minting an access_token from AppKey/AppSecret. It is deliberately
+// hand-rolled over net/http (not the Stream SDK) because the only REST call the
+// server makes outside the Stream connection is the token mint plus the message
+// send; keeping it here makes both trivially testable against an httptest
+// server via the apiBase override.
+
+// defaultAPIBase is the DingTalk Open-API host. The mainland cloud is the only
+// region DingTalk exposes for these endpoints, so unlike Feishu there is no
+// per-installation region split.
+const defaultAPIBase = "https://api.dingtalk.com"
+
+// accessTokenPath mints an enterprise-internal-app access_token from the app's
+// AppKey/AppSecret. The response carries the token and its lifetime in seconds.
+const accessTokenPath = "/v1.0/oauth2/accessToken"
+
+// accessTokenResponse is the success shape of accessTokenPath.
+type accessTokenResponse struct {
+ AccessToken string `json:"accessToken"`
+ ExpireIn int64 `json:"expireIn"`
+}
+
+// apiError is the DingTalk Open-API error envelope (non-2xx responses).
+type apiError struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+// 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 never
+// persist or log either value.
+const messageFilesDownloadPath = "/v1.0/robot/messageFiles/download"
+
+// messageFileDownloadResponse is the success shape of messageFilesDownloadPath.
+type messageFileDownloadResponse struct {
+ DownloadUrl string `json:"downloadUrl"`
+}
+
+// fetchAccessToken mints an access_token for (appKey, appSecret). baseURL
+// defaults to the DingTalk Open-API host; tests point it at an httptest server.
+// httpClient defaults to http.DefaultClient. It returns the token and its
+// lifetime in seconds. A non-2xx response or a missing token is an error — the
+// install path uses a failure here as "these credentials are wrong".
+func fetchAccessToken(ctx context.Context, httpClient *http.Client, baseURL, appKey, appSecret string) (string, int64, error) {
+ if httpClient == nil {
+ httpClient = http.DefaultClient
+ }
+ base := baseURL
+ if base == "" {
+ base = defaultAPIBase
+ }
+ base = strings.TrimRight(base, "/")
+
+ reqBody, err := json.Marshal(map[string]string{"appKey": appKey, "appSecret": appSecret})
+ if err != nil {
+ return "", 0, fmt.Errorf("dingtalk: marshal access token request: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+accessTokenPath, bytes.NewReader(reqBody))
+ if err != nil {
+ return "", 0, fmt.Errorf("dingtalk: build access token request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return "", 0, fmt.Errorf("dingtalk: access token request: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if err != nil {
+ return "", 0, fmt.Errorf("dingtalk: read access token response: %w", err)
+ }
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ var apiErr apiError
+ _ = json.Unmarshal(body, &apiErr)
+ if apiErr.Message != "" {
+ return "", 0, fmt.Errorf("dingtalk: access token: code=%q message=%q", apiErr.Code, apiErr.Message)
+ }
+ return "", 0, fmt.Errorf("dingtalk: access token: http %d", resp.StatusCode)
+ }
+
+ var tok accessTokenResponse
+ if err := json.Unmarshal(body, &tok); err != nil {
+ return "", 0, fmt.Errorf("dingtalk: decode access token response: %w", err)
+ }
+ if tok.AccessToken == "" {
+ return "", 0, fmt.Errorf("dingtalk: access token response missing accessToken")
+ }
+ return tok.AccessToken, tok.ExpireIn, nil
+}
diff --git a/server/internal/integrations/dingtalk/client_test.go b/server/internal/integrations/dingtalk/client_test.go
new file mode 100644
index 0000000000..6e803faff7
--- /dev/null
+++ b/server/internal/integrations/dingtalk/client_test.go
@@ -0,0 +1,148 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestFetchAccessToken_Success(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != accessTokenPath {
+ t.Errorf("unexpected path %q", r.URL.Path)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"accessToken":"tok-123","expireIn":7200}`))
+ }))
+ defer srv.Close()
+
+ tok, ttl, err := fetchAccessToken(context.Background(), nil, srv.URL, "k", "s")
+ if err != nil {
+ t.Fatalf("fetchAccessToken: %v", err)
+ }
+ if tok != "tok-123" || ttl != 7200 {
+ t.Errorf("got %q / %d, want tok-123 / 7200", tok, ttl)
+ }
+}
+
+func TestFetchAccessToken_ErrorStatus(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"code":"InvalidAuthentication","message":"bad creds"}`))
+ }))
+ defer srv.Close()
+
+ if _, _, err := fetchAccessToken(context.Background(), nil, srv.URL, "k", "s"); err == nil {
+ t.Fatal("expected an error on a 400 response")
+ }
+}
+
+func TestFetchAccessToken_MissingToken(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"expireIn":7200}`))
+ }))
+ defer srv.Close()
+
+ if _, _, err := fetchAccessToken(context.Background(), nil, srv.URL, "k", "s"); err == nil {
+ t.Fatal("expected an error when the response carries no accessToken")
+ }
+}
+
+// downloadTestServer fakes the token + messageFiles/download endpoints and
+// counts token mints so the 401-refresh path is observable.
+func downloadTestServer(t *testing.T, onDownload func(w http.ResponseWriter, r *http.Request), tokenMints *int) *httptest.Server {
+ t.Helper()
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case accessTokenPath:
+ *tokenMints++
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(fmt.Sprintf(`{"accessToken":"tok-%d","expireIn":7200}`, *tokenMints)))
+ case messageFilesDownloadPath:
+ onDownload(w, r)
+ default:
+ t.Errorf("unexpected path %q", r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+}
+
+func TestMessageFileDownloadURL(t *testing.T) {
+ mints := 0
+ srv := downloadTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("x-acs-dingtalk-access-token"); got != "tok-1" {
+ t.Errorf("access token header = %q, want tok-1", got)
+ }
+ var body map[string]string
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["robotCode"] != "robot-1" || body["downloadCode"] != "dl-code" {
+ t.Errorf("body = %v", body)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"downloadUrl":"http://files.example/one"}`))
+ }, &mints)
+ defer srv.Close()
+
+ c := NewClient(nil, srv.URL)
+ url, err := c.messageFileDownloadURL(context.Background(), "k", "s", "robot-1", "dl-code")
+ if err != nil {
+ t.Fatalf("messageFileDownloadURL: %v", err)
+ }
+ if url != "http://files.example/one" {
+ t.Errorf("url = %q", url)
+ }
+ if mints != 1 {
+ t.Errorf("token mints = %d, want 1", mints)
+ }
+}
+
+func TestMessageFileDownloadURL_RefreshOn401(t *testing.T) {
+ mints := 0
+ calls := 0
+ srv := downloadTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ if calls == 1 {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ if got := r.Header.Get("x-acs-dingtalk-access-token"); got != "tok-2" {
+ t.Errorf("retry should carry the refreshed token, got %q", got)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"downloadUrl":"http://files.example/two"}`))
+ }, &mints)
+ defer srv.Close()
+
+ c := NewClient(nil, srv.URL)
+ url, err := c.messageFileDownloadURL(context.Background(), "k", "s", "robot-1", "dl-code")
+ if err != nil {
+ t.Fatalf("messageFileDownloadURL: %v", err)
+ }
+ if url != "http://files.example/two" {
+ t.Errorf("url = %q", url)
+ }
+ if mints != 2 || calls != 2 {
+ t.Errorf("mints=%d calls=%d, want 2/2", mints, calls)
+ }
+}
+
+func TestMessageFileDownloadURL_EmptyURL(t *testing.T) {
+ mints := 0
+ srv := downloadTestServer(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{}`))
+ }, &mints)
+ defer srv.Close()
+
+ c := NewClient(nil, srv.URL)
+ if _, err := c.messageFileDownloadURL(context.Background(), "k", "s", "robot-1", "dl-code"); err == nil {
+ t.Fatal("expected an error on an empty downloadUrl")
+ }
+}
diff --git a/server/internal/integrations/dingtalk/config.go b/server/internal/integrations/dingtalk/config.go
new file mode 100644
index 0000000000..e3a0fcc58d
--- /dev/null
+++ b/server/internal/integrations/dingtalk/config.go
@@ -0,0 +1,141 @@
+// 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.
+//
+// Each installation's Stream connection only ever delivers events for its own
+// robot, so the per-installation connection stamps its AppKey into the inbound
+// envelope and the resolver routes on it (config->>'app_id'). Unlike Slack's
+// static bot token, DingTalk outbound needs a short-lived access_token minted
+// from AppKey/AppSecret, so the outbound path caches it like Feishu's
+// tenant_access_token (token.go).
+package dingtalk
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// TypeDingTalk is the channel discriminator for the DingTalk adapter. It is
+// defined here (not in the channel core package) on purpose: registering a new
+// platform must not require editing the core, so the Type value lives with its
+// adapter (mirroring slack.TypeSlack).
+const TypeDingTalk channel.Type = "dingtalk"
+
+// installConfig is the JSON shape stored in channel_installation.config for a
+// DingTalk installation. The cross-platform columns stay flat; everything
+// DingTalk-specific lives in this opaque blob (the documented config boundary).
+//
+// app_id holds the AppKey, which for a Stream-mode robot equals the inbound
+// event's robotCode. It is the per-installation routing key: the generic
+// GetChannelInstallationByAppID query (config->>'app_id') and the
+// (channel_type, app_id) unique index map an inbound event's robotCode to its
+// installation, so several robots — several agents — in one DingTalk org stay
+// distinct.
+//
+// robot_code is kept explicit for the outbound send APIs (oToMessages.batchSend
+// / groupMessages.send both require it); it equals app_id but is stored
+// separately so the outbound path never has to assume the equivalence.
+//
+// app_secret_encrypted is base64-encoded secretbox ciphertext, never plaintext
+// (mirroring Feishu's app_secret_encrypted and Slack's bot_token_encrypted).
+// The AppKey itself is not a secret and lives in app_id in the clear, exactly
+// like Feishu stores app_id in the clear next to app_secret_encrypted.
+type installConfig struct {
+ AppID string `json:"app_id"`
+ RobotCode string `json:"robot_code,omitempty"`
+ AppSecretEncrypted string `json:"app_secret_encrypted"`
+}
+
+// robotCodeOrAppID returns the explicit robot_code, falling back to app_id for
+// the Stream-mode robot where the two are equal (older configs stored only
+// app_id).
+func (c installConfig) robotCodeOrAppID() string {
+ if c.RobotCode != "" {
+ return c.RobotCode
+ }
+ return c.AppID
+}
+
+// credentials is the decoded, decrypted form the outbound sender and the
+// access-token cache run on. The installation IDENTITY (workspace / agent /
+// installer) is deliberately absent: it is resolved per message by the Router's
+// InstallationResolver, exactly as the Feishu and Slack adapters do.
+type credentials struct {
+ AppKey string
+ RobotCode string
+ AppSecret string
+}
+
+// Decrypter turns stored ciphertext into plaintext. The wiring injects a
+// secretbox-backed implementation; tests inject an identity decrypter (or nil,
+// which treats the stored bytes as plaintext).
+type Decrypter func(ciphertext []byte) (plaintext []byte, err error)
+
+// decodeCredentials parses the per-installation config blob and decrypts the
+// stored AppSecret. It is the single place the DingTalk config JSON is
+// interpreted for the outbound/token paths.
+func decodeCredentials(raw json.RawMessage, decrypt Decrypter) (credentials, error) {
+ if len(raw) == 0 {
+ return credentials{}, errors.New("dingtalk: empty installation config")
+ }
+ var cfg installConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return credentials{}, fmt.Errorf("decode dingtalk installation config: %w", err)
+ }
+ appSecret, err := decryptToken(cfg.AppSecretEncrypted, decrypt)
+ if err != nil {
+ return credentials{}, fmt.Errorf("decrypt app secret: %w", err)
+ }
+ return credentials{
+ AppKey: cfg.AppID,
+ RobotCode: cfg.robotCodeOrAppID(),
+ AppSecret: appSecret,
+ }, nil
+}
+
+// decryptToken base64-decodes the stored ciphertext (tolerating the MIME
+// newline wrapping PostgreSQL's encode(...,'base64') emits) and runs it through
+// the injected Decrypter. An empty stored value decodes to an empty secret; a
+// nil Decrypter treats the decoded bytes as plaintext (test convenience).
+func decryptToken(enc string, decrypt Decrypter) (string, error) {
+ if enc == "" {
+ return "", nil
+ }
+ ciphertext, err := base64.StdEncoding.DecodeString(stripWhitespace(enc))
+ if err != nil {
+ return "", fmt.Errorf("base64 decode: %w", err)
+ }
+ if decrypt == nil {
+ return string(ciphertext), nil
+ }
+ plaintext, err := decrypt(ciphertext)
+ if err != nil {
+ return "", err
+ }
+ return string(plaintext), nil
+}
+
+// stripWhitespace removes ASCII whitespace so a MIME-wrapped base64 string
+// (newlines every 64 chars) and an unwrapped one decode identically.
+func stripWhitespace(s string) string {
+ var b strings.Builder
+ b.Grow(len(s))
+ for _, r := range s {
+ switch r {
+ case ' ', '\t', '\n', '\r':
+ continue
+ default:
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
diff --git a/server/internal/integrations/dingtalk/config_test.go b/server/internal/integrations/dingtalk/config_test.go
new file mode 100644
index 0000000000..a8f6d301de
--- /dev/null
+++ b/server/internal/integrations/dingtalk/config_test.go
@@ -0,0 +1,50 @@
+package dingtalk
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "testing"
+)
+
+func TestDecodeCredentials_RoundTrip(t *testing.T) {
+ box := testBox(t)
+ sealed, err := box.Seal([]byte("the-app-secret"))
+ if err != nil {
+ t.Fatalf("seal: %v", err)
+ }
+ raw, _ := json.Marshal(installConfig{
+ AppID: "appkey-1",
+ RobotCode: "appkey-1",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealed),
+ })
+
+ creds, err := decodeCredentials(raw, box.Open)
+ if err != nil {
+ t.Fatalf("decodeCredentials: %v", err)
+ }
+ if creds.AppKey != "appkey-1" || creds.RobotCode != "appkey-1" || creds.AppSecret != "the-app-secret" {
+ t.Errorf("creds = %+v, want appkey-1 / the-app-secret", creds)
+ }
+}
+
+func TestDecodeCredentials_RobotCodeDefaultsToAppID(t *testing.T) {
+ box := testBox(t)
+ sealed, _ := box.Seal([]byte("s"))
+ raw, _ := json.Marshal(installConfig{
+ AppID: "appkey-2",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealed),
+ })
+ creds, err := decodeCredentials(raw, box.Open)
+ if err != nil {
+ t.Fatalf("decodeCredentials: %v", err)
+ }
+ if creds.RobotCode != "appkey-2" {
+ t.Errorf("robotCode = %q, want fallback to app_id appkey-2", creds.RobotCode)
+ }
+}
+
+func TestDecodeCredentials_EmptyConfig(t *testing.T) {
+ if _, err := decodeCredentials(nil, nil); err == nil {
+ t.Error("expected an error for empty config")
+ }
+}
diff --git a/server/internal/integrations/dingtalk/dingtalk_channel.go b/server/internal/integrations/dingtalk/dingtalk_channel.go
new file mode 100644
index 0000000000..a57da54513
--- /dev/null
+++ b/server/internal/integrations/dingtalk/dingtalk_channel.go
@@ -0,0 +1,267 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// dingtalkChannel is ONE installation's DingTalk Stream connection. Every
+// installation carries its own robot — its own AppKey plus encrypted AppSecret
+// in the installation config — so it gets its own connection, exactly
+// like the per-installation Slack and Feishu adapters. The engine.Supervisor
+// builds one dingtalkChannel per active installation (via the registered
+// Factory) and owns the lease / reconnect lifecycle; Connect blocks until the
+// run context is cancelled.
+//
+// Inbound events are translated by inbound.go, parameterized by THIS
+// installation's AppKey so the engine router can resolve the installation (the
+// DingTalk callback carries no robot code). Outbound replies flow through the
+// EventChatDone subscriber (outbound.go) and the OutboundReplier; Send satisfies
+// the Channel contract for a group reply.
+type dingtalkChannel struct {
+ appID string // AppKey — routing key stamped into each inbound envelope
+ robotCode string
+ appKey string
+ appSecret string // decrypted — opens the Stream connection + mints tokens
+ client *Client
+ handler channel.InboundHandler
+ logger *slog.Logger
+ // dispatch runs inbound jobs off the socket read loop on per-conversation
+ // serial queues (see dispatch.go). Built once per channel in the factory;
+ // it survives redials, and in-flight jobs deliberately outlive the socket.
+ dispatch *dispatcher
+ slot *dispatchSlot
+ // stopDispatch is set by Connect only when its run context was already
+ // cancelled when the transport returned (revoke, lease loss, rotation, or
+ // process shutdown). A normal gateway redial leaves it false so the queue
+ // survives and preserves per-conversation ordering across the reconnect.
+ stopDispatch atomic.Bool
+}
+
+func (c *dingtalkChannel) Type() channel.Type { return TypeDingTalk }
+
+func (c *dingtalkChannel) Capabilities() channel.Capability {
+ return channel.CapText | channel.CapAttachment
+}
+
+// Disconnect drains the dispatch queue only when Connect observed lifecycle
+// cancellation. Transport errors and gateway-requested redials intentionally
+// keep the queue alive for the next channel generation. The slot lock prevents
+// an older cancelled generation from closing a queue already adopted by its
+// replacement.
+func (c *dingtalkChannel) Disconnect(ctx context.Context) error {
+ if !c.stopDispatch.Load() || c.slot == nil || c.dispatch == nil {
+ return nil
+ }
+ c.slot.mu.Lock()
+ if c.slot.current.Load() != c {
+ c.slot.mu.Unlock()
+ return nil
+ }
+ // Keep current pointing at this generation while accepted jobs drain. The
+ // closed marker is published under slot.mu before a replacement can inspect
+ // the slot, so the factory will create a fresh queue instead of adopting it.
+ c.dispatch.startClose()
+ c.slot.mu.Unlock()
+ defer c.slot.current.CompareAndSwap(c, nil)
+ if !c.dispatch.waitClosed(ctx) {
+ return fmt.Errorf("dingtalk: dispatcher drain: %w", ctx.Err())
+ }
+ return nil
+}
+
+// Send posts a group reply into out.ChatID with this installation's robot. It
+// satisfies the Channel contract; the primary reply paths (EventChatDone
+// subscriber and OutboundReplier) build their own sender with a full target.
+func (c *dingtalkChannel) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ s := &sender{client: c.client, robotCode: c.robotCode, appKey: c.appKey, appSecret: c.appSecret}
+ key, err := s.send(ctx, sendTarget{ConversationType: convTypeGroup, ConversationID: out.ChatID}, out.Text)
+ if err != nil {
+ return channel.SendResult{}, err
+ }
+ return channel.SendResult{MessageID: key}, nil
+}
+
+// Connect opens this installation's Stream connection (authenticated with its
+// own AppKey/AppSecret) and blocks until ctx is cancelled. The connector owns a
+// single socket session and returns on ctx cancel, a gateway disconnect, or a
+// broken socket; the engine.Supervisor owns reconnect/backoff and the
+// per-installation lease, so an error here just triggers a supervised redial.
+func (c *dingtalkChannel) Connect(ctx context.Context) (err error) {
+ defer func() {
+ // Supervisor cancels its child context after every Connect return, so this
+ // verdict must be captured here, before control returns to Supervisor.
+ c.stopDispatch.Store(ctx.Err() != nil)
+ }()
+ if c.handler == nil {
+ return errors.New("dingtalk: inbound handler not configured")
+ }
+ if c.appSecret == "" {
+ return errors.New("dingtalk: app secret not configured")
+ }
+ conn := &wsConnector{
+ httpClient: c.client.httpClient,
+ apiBase: c.client.apiBase,
+ appKey: c.appKey,
+ appSecret: c.appSecret,
+ onMessage: c.onMessage,
+ logger: c.logger,
+ }
+ return conn.run(ctx)
+}
+
+// onMessage is the connector's bot-message callback. It translates the event
+// with THIS installation's AppKey and enqueues it on the per-conversation
+// dispatcher, so the socket read loop ACKs immediately and is never blocked
+// by pipeline work (media downloads can take tens of seconds). It always
+// returns nil: DingTalk never redelivers robot messages and the engine's
+// (installation, msgId) dedup guards any duplicate anyway.
+func (c *dingtalkChannel) onMessage(ctx context.Context, data *botCallbackData) error {
+ msg, ok := inboundFromCallback(data, c.appID)
+ if !ok {
+ // The message never reaches the engine (no sender staff id — a system
+ // or bot-authored event), so no channel_inbound_audit row is written
+ // for it. Log the drop so the report is diagnosable instead of
+ // vanishing silently. (Malformed/over-quota media now DOES reach the
+ // engine as an unavailable-image placeholder.)
+ if data != nil {
+ c.logger.InfoContext(ctx, "dingtalk: dropped unsupported inbound message",
+ "app_id", c.appID, "msg_type", data.Msgtype, "msg_id", data.MsgId,
+ "has_sender", data.SenderStaffId != "")
+ }
+ return nil
+ }
+ c.dispatch.enqueue(msg.Source.ChatID, msg)
+ return nil
+}
+
+// runInbound is the dispatcher's job body: hand the message to the engine and
+// surface pipeline errors the way the old inline path did.
+func (c *dingtalkChannel) runInbound(ctx context.Context, msg channel.InboundMessage) {
+ if err := c.handler(ctx, msg); err != nil {
+ c.logger.WarnContext(ctx, "dingtalk: inbound handler error", "error", err, "app_id", c.appID)
+ c.notifyIssueDispatchError(msg)
+ }
+}
+
+// issueErrorReplyTimeout bounds the detached dispatch-error reply send.
+const issueErrorReplyTimeout = 5 * time.Second
+
+const issueDispatchFailedText = "⚠️ I couldn't create that issue because an internal error occurred. Please try again."
+
+// notifyIssueDispatchError posts an internal-error notice when an addressed
+// /issue command failed inside the engine pipeline (a transient resolver / DB
+// error, before the shared issue-command path could report a Result).
+// The frame is already ACKed and never redelivered, so without this the
+// command would vanish silently. Detached so onMessage returns promptly.
+func (c *dingtalkChannel) notifyIssueDispatchError(msg channel.InboundMessage) {
+ if !isAddressedIssueCommand(msg) {
+ return
+ }
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), issueErrorReplyTimeout)
+ defer cancel()
+ s := &sender{client: c.client, robotCode: c.robotCode, appKey: c.appKey, appSecret: c.appSecret}
+ if _, err := s.send(ctx, targetFromMessage(msg), issueDispatchFailedText); err != nil {
+ c.logger.WarnContext(ctx, "dingtalk: issue dispatch-error reply failed",
+ "error", err, "app_id", c.appID)
+ }
+ }()
+}
+
+// ChannelDeps are the shared dependencies the DingTalk Factory closes over. The
+// engine inbound handler is supplied per-build via channel.Config.Handler; the
+// Decrypter turns the installation's stored ciphertext AppSecret into plaintext;
+// the Client owns the outbound token cache + transport.
+type ChannelDeps struct {
+ Decrypt Decrypter
+ Client *Client
+ Logger *slog.Logger
+}
+
+// dispatchSlot keeps one conversation dispatcher alive across the channel
+// objects the supervisor rebuilds for Stream reconnects. current is replaced
+// before each reconnect so queued jobs use the newest credentials and client.
+type dispatchSlot struct {
+ mu sync.Mutex
+ current atomic.Pointer[dingtalkChannel]
+ queue *dispatcher
+}
+
+// RegisterDingTalk registers the per-installation DingTalk Factory so the
+// engine.Supervisor builds + supervises one dingtalkChannel per active
+// installation.
+func RegisterDingTalk(reg *channel.Registry, deps ChannelDeps) {
+ reg.Register(TypeDingTalk, newDingTalkFactory(deps))
+}
+
+func newDingTalkFactory(deps ChannelDeps) channel.Factory {
+ logger := deps.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ dtClient := deps.Client
+ if dtClient == nil {
+ dtClient = NewClient(nil, "")
+ }
+ var dispatchMu sync.Mutex
+ dispatchByAppID := make(map[string]*dispatchSlot)
+ return func(cfg channel.Config) (channel.Channel, error) {
+ var ic installConfig
+ if err := json.Unmarshal(cfg.Raw, &ic); err != nil {
+ return nil, fmt.Errorf("dingtalk: decode installation config: %w", err)
+ }
+ appSecret, err := decryptToken(ic.AppSecretEncrypted, deps.Decrypt)
+ if err != nil {
+ return nil, fmt.Errorf("dingtalk: decrypt app secret: %w", err)
+ }
+ if appSecret == "" {
+ return nil, errors.New("dingtalk: installation has no app secret")
+ }
+ ch := &dingtalkChannel{
+ appID: ic.AppID,
+ robotCode: ic.robotCodeOrAppID(),
+ appKey: ic.AppID,
+ appSecret: appSecret,
+ client: dtClient,
+ handler: cfg.Handler,
+ logger: logger,
+ }
+
+ // Supervisor.Build runs once per reconnect. Reusing the queue by the
+ // installation's unique AppKey prevents an old in-flight turn and the
+ // next turn received after reconnect from running concurrently.
+ dispatchMu.Lock()
+ slot := dispatchByAppID[ch.appID]
+ if slot != nil {
+ slot.mu.Lock()
+ }
+ if slot == nil || slot.queue.isClosed() {
+ if slot != nil {
+ slot.mu.Unlock()
+ }
+ slot = &dispatchSlot{}
+ slot.mu.Lock()
+ slot.queue = newDispatcher(func(ctx context.Context, msg channel.InboundMessage) {
+ if current := slot.current.Load(); current != nil {
+ current.runInbound(ctx, msg)
+ }
+ }, logger)
+ dispatchByAppID[ch.appID] = slot
+ }
+ slot.current.Store(ch)
+ ch.dispatch = slot.queue
+ ch.slot = slot
+ slot.mu.Unlock()
+ dispatchMu.Unlock()
+ return ch, nil
+ }
+}
diff --git a/server/internal/integrations/dingtalk/dingtalk_channel_test.go b/server/internal/integrations/dingtalk/dingtalk_channel_test.go
new file mode 100644
index 0000000000..c64f8b04a6
--- /dev/null
+++ b/server/internal/integrations/dingtalk/dingtalk_channel_test.go
@@ -0,0 +1,315 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func noopHandler(_ context.Context, _ channel.InboundMessage) error { return nil }
+
+func TestNewDingTalkFactory_DecryptsAndBuilds(t *testing.T) {
+ box := testBox(t)
+ sealed, _ := box.Seal([]byte("plain-secret"))
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-1",
+ RobotCode: "appkey-1",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealed),
+ })
+
+ factory := newDingTalkFactory(ChannelDeps{Decrypt: box.Open})
+ built, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("factory: %v", err)
+ }
+ dc, ok := built.(*dingtalkChannel)
+ if !ok {
+ t.Fatalf("built channel is not a *dingtalkChannel: %T", built)
+ }
+ if dc.appKey != "appkey-1" || dc.appID != "appkey-1" || dc.robotCode != "appkey-1" {
+ t.Errorf("identity fields wrong: %+v", dc)
+ }
+ if dc.appSecret != "plain-secret" {
+ t.Errorf("app secret = %q, want decrypted plain-secret", dc.appSecret)
+ }
+ if dc.Type() != TypeDingTalk {
+ t.Errorf("Type() = %q", dc.Type())
+ }
+ if dc.Capabilities()&channel.CapText == 0 {
+ t.Error("channel must declare text capability")
+ }
+}
+
+func TestNewDingTalkFactory_ReusesDispatcherAcrossReconnects(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-reconnect",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ factory := newDingTalkFactory(ChannelDeps{})
+
+ firstBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("first build: %v", err)
+ }
+ secondBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("second build: %v", err)
+ }
+ first := firstBuilt.(*dingtalkChannel)
+ second := secondBuilt.(*dingtalkChannel)
+ if first.dispatch != second.dispatch {
+ t.Fatal("reconnect build replaced the per-installation dispatcher")
+ }
+}
+
+func TestDingTalkChannel_DisconnectDoesNotCloseDispatcherAfterNormalRedial(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-redial",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ factory := newDingTalkFactory(ChannelDeps{})
+ built, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ c := built.(*dingtalkChannel)
+ if err := c.Disconnect(context.Background()); err != nil {
+ t.Fatalf("disconnect: %v", err)
+ }
+ if c.dispatch.isClosed() {
+ t.Fatal("normal redial closed the reusable dispatcher")
+ }
+}
+
+func TestDingTalkChannel_DisconnectClosesOnlyCurrentCancelledGeneration(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-rotation",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ factory := newDingTalkFactory(ChannelDeps{})
+ firstBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("first build: %v", err)
+ }
+ secondBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("second build: %v", err)
+ }
+ first := firstBuilt.(*dingtalkChannel)
+ second := secondBuilt.(*dingtalkChannel)
+ first.stopDispatch.Store(true)
+ if err := first.Disconnect(context.Background()); err != nil {
+ t.Fatalf("old generation disconnect: %v", err)
+ }
+ if second.dispatch.isClosed() {
+ t.Fatal("old generation closed the replacement's dispatcher")
+ }
+
+ second.stopDispatch.Store(true)
+ if err := second.Disconnect(context.Background()); err != nil {
+ t.Fatalf("current generation disconnect: %v", err)
+ }
+ if !second.dispatch.isClosed() {
+ t.Fatal("current cancelled generation left its dispatcher open")
+ }
+
+ thirdBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("third build: %v", err)
+ }
+ third := thirdBuilt.(*dingtalkChannel)
+ if third.dispatch == second.dispatch {
+ t.Fatal("factory reused a closed dispatcher")
+ }
+}
+
+func TestDingTalkChannel_DisconnectDrainsQueuedMessagesBeforeReplacement(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-drain",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ started := make(chan struct{}, 1)
+ release := make(chan struct{})
+ handled := make(chan string, 2)
+ factory := newDingTalkFactory(ChannelDeps{})
+ built, err := factory(channel.Config{
+ Type: TypeDingTalk,
+ Raw: cfg,
+ Handler: func(_ context.Context, msg channel.InboundMessage) error {
+ started <- struct{}{}
+ <-release
+ handled <- msg.MessageID
+ return nil
+ },
+ })
+ if err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ first := built.(*dingtalkChannel)
+ first.dispatch.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ first.dispatch.enqueue("conv-A", dispatchMsg("conv-A", "second"))
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("first message did not start")
+ }
+
+ first.stopDispatch.Store(true)
+ disconnected := make(chan error, 1)
+ go func() { disconnected <- first.Disconnect(context.Background()) }()
+ deadline := time.Now().Add(time.Second)
+ for !first.dispatch.isClosed() && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if !first.dispatch.isClosed() {
+ t.Fatal("dispatcher did not start closing")
+ }
+
+ replacementBuilt, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("replacement build: %v", err)
+ }
+ if replacementBuilt.(*dingtalkChannel).dispatch == first.dispatch {
+ t.Fatal("replacement adopted a closing dispatcher")
+ }
+ close(release)
+
+ select {
+ case err := <-disconnected:
+ if err != nil {
+ t.Fatalf("disconnect: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("disconnect did not finish draining")
+ }
+ for _, want := range []string{"first", "second"} {
+ select {
+ case got := <-handled:
+ if got != want {
+ t.Fatalf("handled %q, want %q", got, want)
+ }
+ case <-time.After(time.Second):
+ t.Fatalf("queued message %q was dropped during drain", want)
+ }
+ }
+}
+
+// A handler (engine dispatch) error on an addressed /issue command must post
+// the internal-error notice: the frame is already ACKed and never redelivered,
+// so silence would lose the command with no signal to the user.
+func TestOnMessage_HandlerError_IssueCommandGetsErrorReply(t *testing.T) {
+ sent := make(chan string, 1)
+ 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
+ }
+ body, _ := io.ReadAll(r.Body)
+ select {
+ case sent <- string(body):
+ default:
+ }
+ _, _ = w.Write([]byte(`{"processQueryKey":"pqk-1"}`))
+ }))
+ defer srv.Close()
+
+ c := &dingtalkChannel{
+ appID: "appkey-1",
+ robotCode: "robot-1",
+ appKey: "ak",
+ appSecret: "as",
+ client: NewClient(nil, srv.URL),
+ handler: func(_ context.Context, _ channel.InboundMessage) error {
+ return errors.New("resolve sender: transient db error")
+ },
+ logger: slog.Default(),
+ }
+ c.dispatch = newDispatcher(c.runInbound, c.logger)
+ data := &botCallbackData{
+ ConversationId: "cid-1",
+ ConversationType: convTypeP2P,
+ SenderStaffId: "staff-1",
+ MsgId: "msg-1",
+ Msgtype: "text",
+ Text: botCallbackText{Content: "/issue login broken"},
+ }
+ if err := c.onMessage(context.Background(), data); err != nil {
+ t.Fatalf("onMessage: %v", err)
+ }
+ select {
+ case body := <-sent:
+ if !strings.Contains(body, issueDispatchFailedText) {
+ t.Fatalf("reply body = %q, want the internal-error notice", body)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("no error reply was sent for the failed /issue dispatch")
+ }
+}
+
+// onMessage must return immediately even when the pipeline is slow: the
+// socket read loop ACKs right after it, and a blocked loop would starve
+// ping/system frames and get the connection torn down.
+func TestOnMessage_ReturnsWithoutWaitingForHandler(t *testing.T) {
+ release := make(chan struct{})
+ started := make(chan struct{})
+ c := &dingtalkChannel{appID: "appkey-1", logger: slog.Default(), handler: func(_ context.Context, _ channel.InboundMessage) error {
+ close(started)
+ <-release
+ return nil
+ }}
+ c.dispatch = newDispatcher(c.runInbound, c.logger)
+ defer close(release)
+
+ data := &botCallbackData{
+ ConversationId: "cid-1",
+ ConversationType: convTypeP2P,
+ SenderStaffId: "staff-1",
+ MsgId: "msg-1",
+ Msgtype: "text",
+ Text: botCallbackText{Content: "hello"},
+ }
+ done := make(chan struct{})
+ go func() {
+ _ = c.onMessage(context.Background(), data)
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("onMessage blocked on the handler")
+ }
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("the queued job never ran")
+ }
+}
+
+// A handler error on a plain chat turn stays silent — only /issue commands
+// warrant the dispatch-error notice.
+func TestNotifyIssueDispatchError_GatesOnIssueCommand(t *testing.T) {
+ c := &dingtalkChannel{logger: slog.Default()}
+ // Non-issue text and unaddressed messages must return before spawning the
+ // send goroutine; a nil client would panic if they did not.
+ c.notifyIssueDispatchError(channel.InboundMessage{Text: "hello", AddressedToBot: true})
+ c.notifyIssueDispatchError(channel.InboundMessage{Text: "/issue x", AddressedToBot: false})
+}
+
+func TestNewDingTalkFactory_RejectsMissingSecret(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{AppID: "appkey-1"})
+ factory := newDingTalkFactory(ChannelDeps{Decrypt: testBox(t).Open})
+ if _, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg}); err == nil {
+ t.Error("an installation with no app secret must fail to build")
+ }
+}
diff --git a/server/internal/integrations/dingtalk/dispatch.go b/server/internal/integrations/dingtalk/dispatch.go
new file mode 100644
index 0000000000..4a6955d91c
--- /dev/null
+++ b/server/internal/integrations/dingtalk/dispatch.go
@@ -0,0 +1,204 @@
+package dingtalk
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// Tunables for the inbound dispatcher. Remote media resolution is detached by
+// the shared Router, so this timeout bounds only the synchronous ingest path.
+const (
+ dispatchJobTimeout = 120 * time.Second
+ maxDispatchWorkers = 8
+ // maxDispatchQueueDepth bounds one conversation's backlog purely as a
+ // memory-safety backstop. It is set far above any realistic human burst so
+ // the overflow drop is effectively unreachable in practice — a single
+ // conversation would need hundreds of un-drained turns to hit it. Overflow
+ // (should it ever happen) drops the newest message with a warn log; the
+ // caller (the socket read loop) must never block, so blocking backpressure
+ // is not an option here.
+ maxDispatchQueueDepth = 256
+ // A per-conversation limit alone still permits one waiting drain goroutine
+ // per distinct conversation. Bound all accepted-but-not-finished messages
+ // for one installation so both queued payloads and semaphore waiters have a
+ // deterministic ceiling.
+ maxDispatchPending = 2048
+)
+
+// dispatcher decouples inbound processing from the Stream read loop: frames
+// are ACKed immediately and jobs run on per-conversation serial queues, so a
+// slow media download can neither starve ping/system frames nor reorder a
+// conversation's transcript. Cross-conversation jobs run in parallel, bounded
+// by a global semaphore per installation. The per-conversation queue is bounded
+// only as a memory backstop (maxDispatchQueueDepth), set high enough that a
+// real human burst never reaches it; the engine's dedup makes any duplicate
+// delivery harmless.
+//
+// Jobs run on context.Background() with their own deadline, deliberately
+// detached from the socket's run context: a gateway redial must not cancel an
+// in-flight append.
+type dispatcher struct {
+ handle func(ctx context.Context, msg channel.InboundMessage)
+ logger *slog.Logger
+ sem chan struct{}
+ ctx context.Context
+ cancel context.CancelFunc
+
+ mu sync.Mutex
+ queues map[string][]channel.InboundMessage
+ active map[string]bool
+ closed bool
+ pending int
+ maxPending int
+ workers sync.WaitGroup
+ done chan struct{}
+}
+
+func newDispatcher(handle func(ctx context.Context, msg channel.InboundMessage), logger *slog.Logger) *dispatcher {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ return &dispatcher{
+ handle: handle,
+ logger: logger,
+ sem: make(chan struct{}, maxDispatchWorkers),
+ ctx: ctx,
+ cancel: cancel,
+ queues: make(map[string][]channel.InboundMessage),
+ active: make(map[string]bool),
+ maxPending: maxDispatchPending,
+ done: make(chan struct{}),
+ }
+}
+
+// enqueue appends msg to its conversation's queue and starts a drain worker
+// for the conversation when none is running. Never blocks the caller.
+func (d *dispatcher) enqueue(convID string, msg channel.InboundMessage) {
+ d.mu.Lock()
+ if d.closed {
+ d.mu.Unlock()
+ d.logger.Debug("dingtalk dispatch: dispatcher closed, dropping message",
+ "conversation_id", convID, "msg_id", msg.MessageID)
+ return
+ }
+ if d.pending >= d.maxPending {
+ d.mu.Unlock()
+ d.logger.Warn("dingtalk dispatch: installation queue full, dropping message",
+ "conversation_id", convID, "msg_id", msg.MessageID)
+ return
+ }
+ if len(d.queues[convID]) >= maxDispatchQueueDepth {
+ d.mu.Unlock()
+ d.logger.Warn("dingtalk dispatch: conversation queue full, dropping message",
+ "conversation_id", convID, "msg_id", msg.MessageID)
+ return
+ }
+ d.queues[convID] = append(d.queues[convID], msg)
+ d.pending++
+ start := !d.active[convID]
+ if start {
+ d.active[convID] = true
+ d.workers.Add(1)
+ }
+ d.mu.Unlock()
+ if start {
+ go d.drain(convID)
+ }
+}
+
+// drain runs the conversation's jobs strictly in order and exits when the
+// queue is empty (a later enqueue starts a fresh worker). The semaphore
+// bounds concurrently running jobs across all conversations; waiting on it
+// keeps this conversation's order intact.
+func (d *dispatcher) drain(convID string) {
+ defer d.workers.Done()
+ for {
+ d.mu.Lock()
+ if d.ctx.Err() != nil {
+ d.pending -= len(d.queues[convID])
+ delete(d.queues, convID)
+ delete(d.active, convID)
+ d.mu.Unlock()
+ return
+ }
+ q := d.queues[convID]
+ if len(q) == 0 {
+ delete(d.queues, convID)
+ delete(d.active, convID)
+ d.mu.Unlock()
+ return
+ }
+ msg := q[0]
+ d.queues[convID] = q[1:]
+ d.mu.Unlock()
+
+ select {
+ case d.sem <- struct{}{}:
+ case <-d.ctx.Done():
+ d.mu.Lock()
+ d.pending -= 1 + len(d.queues[convID])
+ delete(d.queues, convID)
+ delete(d.active, convID)
+ d.mu.Unlock()
+ return
+ }
+ ctx, cancel := context.WithTimeout(d.ctx, dispatchJobTimeout)
+ d.handle(ctx, msg)
+ cancel()
+ <-d.sem
+ d.mu.Lock()
+ d.pending--
+ d.mu.Unlock()
+ }
+}
+
+// drainAndClose stops accepting new jobs and waits for already-ACKed messages
+// to finish. If ctx expires, it cancels every active job and leaves the worker
+// joins to complete asynchronously; callers are never held past their shutdown
+// budget. It is idempotent.
+func (d *dispatcher) drainAndClose(ctx context.Context) bool {
+ d.startClose()
+ return d.waitClosed(ctx)
+}
+
+// startClose atomically stops new enqueues and starts the asynchronous worker
+// join. Splitting this from waitClosed lets the owning dispatchSlot publish the
+// closing state before a reconnect decides whether the queue can be reused.
+func (d *dispatcher) startClose() {
+ d.mu.Lock()
+ if !d.closed {
+ d.closed = true
+ go func() {
+ d.workers.Wait()
+ d.cancel()
+ close(d.done)
+ }()
+ }
+ d.mu.Unlock()
+}
+
+func (d *dispatcher) waitClosed(ctx context.Context) bool {
+ select {
+ case <-d.done:
+ return true
+ case <-ctx.Done():
+ d.cancel()
+ select {
+ case <-d.done:
+ return true
+ default:
+ return false
+ }
+ }
+}
+
+func (d *dispatcher) isClosed() bool {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.closed
+}
diff --git a/server/internal/integrations/dingtalk/dispatch_test.go b/server/internal/integrations/dingtalk/dispatch_test.go
new file mode 100644
index 0000000000..6dd9f5b1ea
--- /dev/null
+++ b/server/internal/integrations/dingtalk/dispatch_test.go
@@ -0,0 +1,280 @@
+package dingtalk
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func dispatchMsg(conv, id string) channel.InboundMessage {
+ return channel.InboundMessage{
+ MessageID: id,
+ Source: channel.Source{ChatID: conv},
+ }
+}
+
+func TestDispatcher_SerialPerConversation(t *testing.T) {
+ var mu sync.Mutex
+ var got []string
+ done := make(chan struct{}, 8)
+ d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ // Jitter so an ordering bug actually reorders.
+ time.Sleep(time.Duration(len(msg.MessageID)%3) * time.Millisecond)
+ mu.Lock()
+ got = append(got, msg.MessageID)
+ mu.Unlock()
+ done <- struct{}{}
+ }, nil)
+
+ want := make([]string, 0, 5)
+ for i := 0; i < 5; i++ {
+ id := fmt.Sprintf("m-%d", i)
+ want = append(want, id)
+ d.enqueue("conv-A", dispatchMsg("conv-A", id))
+ }
+ for i := 0; i < 5; i++ {
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("timed out waiting for jobs")
+ }
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("order broken: got %v, want %v", got, want)
+ }
+ }
+}
+
+func TestDispatcher_ParallelAcrossConversations(t *testing.T) {
+ blockA := make(chan struct{})
+ sawB := make(chan struct{})
+ d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ switch msg.Source.ChatID {
+ case "conv-A":
+ <-blockA
+ case "conv-B":
+ close(sawB)
+ }
+ }, nil)
+
+ d.enqueue("conv-A", dispatchMsg("conv-A", "a1"))
+ d.enqueue("conv-B", dispatchMsg("conv-B", "b1"))
+
+ select {
+ case <-sawB:
+ // conv-B ran while conv-A is still blocked — parallel across convs.
+ case <-time.After(2 * time.Second):
+ t.Fatal("conv-B was starved by conv-A's slow job")
+ }
+ close(blockA)
+}
+
+func TestDispatcher_OverflowDrops(t *testing.T) {
+ release := make(chan struct{})
+ var handled int
+ var mu sync.Mutex
+ d := newDispatcher(func(_ context.Context, _ channel.InboundMessage) {
+ <-release
+ mu.Lock()
+ handled++
+ mu.Unlock()
+ }, nil)
+
+ // One job occupies the worker; then fill the queue past its depth.
+ total := maxDispatchQueueDepth + 5
+ for i := 0; i < total+1; i++ {
+ d.enqueue("conv-A", dispatchMsg("conv-A", fmt.Sprintf("m-%d", i)))
+ }
+ close(release)
+
+ deadline := time.After(2 * time.Second)
+ for {
+ mu.Lock()
+ n := handled
+ mu.Unlock()
+ if n > maxDispatchQueueDepth+1 {
+ t.Fatalf("handled %d jobs, want at most %d (overflow must drop)", n, maxDispatchQueueDepth+1)
+ }
+ select {
+ case <-deadline:
+ if n == 0 {
+ t.Fatal("no jobs handled at all")
+ }
+ return
+ case <-time.After(50 * time.Millisecond):
+ }
+ }
+}
+
+func TestDispatcher_GlobalPendingLimitBoundsDistinctConversations(t *testing.T) {
+ release := make(chan struct{})
+ done := make(chan string, 3)
+ d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ <-release
+ done <- msg.MessageID
+ }, nil)
+ d.maxPending = 2
+
+ d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ d.enqueue("conv-B", dispatchMsg("conv-B", "second"))
+ d.enqueue("conv-C", dispatchMsg("conv-C", "dropped"))
+
+ d.mu.Lock()
+ if d.pending != 2 {
+ t.Fatalf("accepted pending messages = %d, want 2", d.pending)
+ }
+ d.mu.Unlock()
+ close(release)
+
+ got := map[string]bool{}
+ for i := 0; i < 2; i++ {
+ select {
+ case id := <-done:
+ got[id] = true
+ case <-time.After(time.Second):
+ t.Fatalf("accepted messages did not finish: %v", got)
+ }
+ }
+ if !got["first"] || !got["second"] || got["dropped"] {
+ t.Fatalf("handled messages = %v", got)
+ }
+ select {
+ case id := <-done:
+ t.Fatalf("global overflow message was handled: %q", id)
+ case <-time.After(20 * time.Millisecond):
+ }
+
+ deadline := time.Now().Add(time.Second)
+ for {
+ d.mu.Lock()
+ pending := d.pending
+ d.mu.Unlock()
+ if pending == 0 {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("pending count did not return to zero: %d", pending)
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
+
+func TestDispatcher_WorkerExitsAndRestarts(t *testing.T) {
+ done := make(chan string, 2)
+ d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ done <- msg.MessageID
+ }, nil)
+
+ d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ select {
+ case id := <-done:
+ if id != "first" {
+ t.Fatalf("got %q", id)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("first job never ran")
+ }
+ // Give the worker a moment to drain and exit, then enqueue again.
+ time.Sleep(20 * time.Millisecond)
+ d.enqueue("conv-A", dispatchMsg("conv-A", "second"))
+ select {
+ case id := <-done:
+ if id != "second" {
+ t.Fatalf("got %q", id)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("worker did not restart for a drained conversation")
+ }
+}
+
+func TestDispatcher_DrainAndCloseFinishesAcceptedJobsAndRejectsNewOnes(t *testing.T) {
+ release := make(chan struct{})
+ started := make(chan struct{}, 1)
+ done := make(chan string, 2)
+ d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ started <- struct{}{}
+ <-release
+ done <- msg.MessageID
+ }, nil)
+
+ d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ d.enqueue("conv-A", dispatchMsg("conv-A", "second"))
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("first accepted job did not start")
+ }
+
+ closed := make(chan bool, 1)
+ go func() {
+ closed <- d.drainAndClose(context.Background())
+ }()
+ deadline := time.Now().Add(time.Second)
+ for !d.isClosed() && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if !d.isClosed() {
+ t.Fatal("dispatcher did not enter closing state")
+ }
+ d.enqueue("conv-A", dispatchMsg("conv-A", "late"))
+ close(release)
+
+ select {
+ case ok := <-closed:
+ if !ok {
+ t.Fatal("dispatcher did not drain accepted jobs")
+ }
+ case <-time.After(time.Second):
+ t.Fatal("dispatcher close did not complete")
+ }
+
+ var got []string
+ for i := 0; i < 2; i++ {
+ select {
+ case id := <-done:
+ got = append(got, id)
+ case <-time.After(time.Second):
+ t.Fatalf("accepted jobs did not finish: %v", got)
+ }
+ }
+ if len(got) != 2 || got[0] != "first" || got[1] != "second" {
+ t.Fatalf("drained jobs = %v, want [first second]", got)
+ }
+ select {
+ case id := <-done:
+ t.Fatalf("closed dispatcher accepted late job %q", id)
+ default:
+ }
+}
+
+func TestDispatcher_CloseDeadlineCancelsInFlightJob(t *testing.T) {
+ started := make(chan struct{})
+ cancelled := make(chan struct{})
+ d := newDispatcher(func(ctx context.Context, _ channel.InboundMessage) {
+ close(started)
+ <-ctx.Done()
+ close(cancelled)
+ }, nil)
+ d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("job did not start")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ _ = d.drainAndClose(ctx)
+ select {
+ case <-cancelled:
+ case <-time.After(time.Second):
+ t.Fatal("close deadline did not cancel the in-flight job")
+ }
+}
diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.go
new file mode 100644
index 0000000000..f25be8b0be
--- /dev/null
+++ b/server/internal/integrations/dingtalk/inbound.go
@@ -0,0 +1,280 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// This file holds the translation from a DingTalk Stream callback
+// (botCallbackData) to the engine's normalized channel.InboundMessage. The
+// per-installation connection (dingtalk_channel.go) threads in its OWN
+// installation's AppKey so the resolver can route the event back to its
+// installation — DingTalk's callback payload does not carry the robot code
+// itself.
+
+// botCallbackData is the DingTalk bot-message callback payload — the JSON carried
+// in a CALLBACK frame's data field. It holds only the fields the translation
+// reads; DingTalk sends more, which we ignore. Replaces the vendor SDK's
+// chatbot.BotCallbackDataModel.
+type botCallbackData struct {
+ ConversationId string `json:"conversationId"`
+ ConversationType string `json:"conversationType"`
+ SenderStaffId string `json:"senderStaffId"`
+ MsgId string `json:"msgId"`
+ Msgtype string `json:"msgtype"`
+ IsInAtList bool `json:"isInAtList"`
+ Text botCallbackText `json:"text"`
+ // Content is the msgtype-discriminated payload of non-text messages
+ // (picture / richText). Decoded lazily per msgtype; absent on over-quota
+ // callbacks (errorCode 20001 strips text/content entirely).
+ Content json.RawMessage `json:"content"`
+}
+
+type botCallbackText struct {
+ Content string `json:"content"`
+}
+
+// pictureContent is the content shape of msgtype=picture. Real payloads carry
+// both codes (developerpedia); either resolves through messageFiles/download.
+type pictureContent struct {
+ DownloadCode string `json:"downloadCode"`
+ PictureDownloadCode string `json:"pictureDownloadCode"`
+}
+
+// richTextContent is the content shape of msgtype=richText: an ORDERED array
+// of heterogeneous items — text runs {"text":…} interleaved with picture items
+// {"type":"picture","downloadCode":…} in send order. Item kinds beyond
+// text/picture are undocumented today and skipped.
+type richTextContent struct {
+ RichText []richTextItem `json:"richText"`
+}
+
+type richTextItem struct {
+ Text string `json:"text"`
+ Type string `json:"type"`
+ DownloadCode string `json:"downloadCode"`
+ PictureDownloadCode string `json:"pictureDownloadCode"`
+}
+
+// refAlt orders a picture item's two download codes into (primary, fallback),
+// promoting the secondary code when the primary is missing.
+func refAlt(downloadCode, pictureDownloadCode string) (ref, alt string) {
+ if downloadCode != "" {
+ return downloadCode, pictureDownloadCode
+ }
+ return pictureDownloadCode, ""
+}
+
+// dingtalkRawEvent carries the DingTalk-specific fields the cross-platform
+// envelope does not. AppID is stamped by the receiving connection (it is the
+// installation's routing key) and read back only inside the resolvers.
+type dingtalkRawEvent struct {
+ AppID string `json:"app_id"`
+ Media []dingtalkMediaResource `json:"media,omitempty"`
+}
+
+type dingtalkMediaResource struct {
+ Ref string `json:"ref"`
+ Alt string `json:"alt,omitempty"`
+}
+
+// conversation type discriminators DingTalk sends in conversationType.
+const (
+ convTypeP2P = "1"
+ convTypeGroup = "2"
+)
+
+// inboundFromCallback normalizes a DingTalk bot callback. It returns ok=false
+// only for events that must not reach the core at all: messages with no sender
+// staff id (system / bot-authored). Text, picture and richText become
+// ingestable messages; a malformed/over-quota media payload (the 20001 shape
+// strips content) still reaches the core as an explicit unavailable-image
+// placeholder rather than the adapter dropping it silently;
+// audio/video/file/unknown kinds likewise pass through as text placeholders.
+// A direct (1:1) message is always addressed to the bot; a group
+// message reaches the bot only when it carries an @-mention of it, which
+// DingTalk reports via isInAtList.
+func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMessage, bool) {
+ if data == nil {
+ return channel.InboundMessage{}, false
+ }
+ if data.SenderStaffId == "" {
+ return channel.InboundMessage{}, false
+ }
+
+ chatType := dingtalkChatType(data.ConversationType)
+ rawEvent := dingtalkRawEvent{AppID: appID}
+ msg := channel.InboundMessage{
+ EventID: data.MsgId,
+ MessageID: data.MsgId,
+ AddressedToBot: chatType == channel.ChatTypeP2P || data.IsInAtList,
+ Source: channel.Source{
+ ChannelType: TypeDingTalk,
+ ChatID: data.ConversationId,
+ ChatType: chatType,
+ SenderID: data.SenderStaffId,
+ },
+ }
+
+ switch data.Msgtype {
+ case "text":
+ msg.Type = channel.MsgTypeText
+ msg.Text = strings.TrimSpace(data.Text.Content)
+ msg.CommandText = msg.Text
+ return withDingTalkRaw(msg, rawEvent), true
+
+ case "picture":
+ var pc pictureContent
+ if len(data.Content) == 0 || json.Unmarshal(data.Content, &pc) != nil {
+ // Over-quota (errorCode 20001 strips content) or malformed payload:
+ // the sender is a real user who sent an image the bot cannot read.
+ // Route it into the engine so it gets identity-gated feedback.
+ return mediaUnreadableMsg(msg, rawEvent), true
+ }
+ ref, alt := refAlt(pc.DownloadCode, pc.PictureDownloadCode)
+ if ref == "" {
+ return mediaUnreadableMsg(msg, rawEvent), true
+ }
+ msg.Type = channel.MsgTypeImage
+ msg.Text = "[Image]"
+ msg.CommandText = msg.Text
+ rawEvent.Media = []dingtalkMediaResource{{Ref: ref, Alt: alt}}
+ return withDingTalkRaw(msg, rawEvent), true
+
+ case "richText":
+ var rc richTextContent
+ if len(data.Content) == 0 || json.Unmarshal(data.Content, &rc) != nil {
+ // Over-quota / malformed richText: surface it to the engine for
+ // identity-gated feedback rather than a silent adapter drop.
+ return mediaUnreadableMsg(msg, rawEvent), true
+ }
+ var (
+ text strings.Builder
+ commandText strings.Builder
+ )
+ for _, item := range rc.RichText {
+ // A single item may in principle carry BOTH a text run and a picture
+ // code; handle each independently (not a switch) so neither is
+ // silently dropped. Text first, then image, matching send order.
+ // Items with neither (undocumented kinds) contribute nothing.
+ if item.Text != "" {
+ text.WriteString(item.Text)
+ commandText.WriteString(item.Text)
+ }
+ if item.Type == "picture" || item.DownloadCode != "" || item.PictureDownloadCode != "" {
+ ref, alt := refAlt(item.DownloadCode, item.PictureDownloadCode)
+ if ref == "" {
+ continue // a picture item with no usable code
+ }
+ appendImagePlaceholder(&text)
+ rawEvent.Media = append(rawEvent.Media, dingtalkMediaResource{Ref: ref, Alt: alt})
+ }
+ }
+ if len(rawEvent.Media) == 0 {
+ msg.Type = channel.MsgTypeText
+ } else {
+ msg.Type = channel.MsgTypeImage
+ }
+ msg.Text = strings.TrimSpace(text.String())
+ msg.CommandText = strings.TrimSpace(commandText.String())
+ normalizeDingTalkRichTextFreshLayout(&msg, rc.RichText, len(rawEvent.Media) > 0)
+ return withDingTalkRaw(msg, rawEvent), true
+
+ case "audio":
+ msg.Type = channel.MsgTypeAudio
+ msg.Text = "[Audio message]"
+ case "video":
+ msg.Type = channel.MsgTypeVideo
+ msg.Text = "[Video message]"
+ case "file":
+ msg.Type = channel.MsgTypeFile
+ msg.Text = "[File]"
+ default:
+ msg.Type = channel.MsgTypeUnknown
+ msg.Text = "[Unsupported DingTalk message]"
+ }
+ msg.CommandText = msg.Text
+ return withDingTalkRaw(msg, rawEvent), true
+}
+
+// normalizeDingTalkRichTextFreshLayout strips /new from the visible rich-text
+// body before the shared Router handles it, preserving interleaved image
+// placeholders that Router cannot reconstruct from CommandText. It deliberately
+// keeps the original command source, so `/new /issue ...` remains one /new
+// command just like it does on Lark and Slack; the adapter never reclassifies
+// the remainder as a second command.
+func normalizeDingTalkRichTextFreshLayout(msg *channel.InboundMessage, items []richTextItem, hasMedia bool) {
+ body, ok := engine.ParseFreshSessionCommand(msg.CommandText)
+ if !ok || (body == "" && !hasMedia) {
+ return
+ }
+
+ firstText := -1
+ for i := range items {
+ if strings.TrimSpace(items[i].Text) != "" {
+ firstText = i
+ break
+ }
+ }
+ if firstText < 0 {
+ return
+ }
+ firstBody, ok := engine.ParseFreshSessionCommand(items[firstText].Text)
+ if !ok {
+ return
+ }
+
+ msg.ForceFresh = true
+ items[firstText].Text = firstBody
+ var visible strings.Builder
+ for _, item := range items {
+ visible.WriteString(item.Text)
+ if item.Type == "picture" || item.DownloadCode != "" || item.PictureDownloadCode != "" {
+ ref, _ := refAlt(item.DownloadCode, item.PictureDownloadCode)
+ if ref != "" {
+ appendImagePlaceholder(&visible)
+ }
+ }
+ }
+ msg.Text = strings.TrimSpace(visible.String())
+ if body == "" {
+ // A media-bearing `/new` is a real turn, not the shared bare-command
+ // sentinel. ForceFresh carries the already-consumed directive.
+ msg.CommandText = msg.Text
+ }
+}
+
+func withDingTalkRaw(msg channel.InboundMessage, rawEvent dingtalkRawEvent) channel.InboundMessage {
+ msg.Raw, _ = json.Marshal(rawEvent)
+ return msg
+}
+
+// mediaUnreadableMsg turns media the adapter cannot resolve into an explicit
+// placeholder. With no downloadable reference, the shared media resolver stays
+// out of the path and the normal channel turn carries the degradation signal.
+func mediaUnreadableMsg(msg channel.InboundMessage, rawEvent dingtalkRawEvent) channel.InboundMessage {
+ msg.Type = channel.MsgTypeImage
+ msg.Text = "[Image unavailable]"
+ msg.CommandText = msg.Text
+ return withDingTalkRaw(msg, rawEvent)
+}
+
+func appendImagePlaceholder(b *strings.Builder) {
+ if b.Len() > 0 {
+ b.WriteByte('\n')
+ }
+ b.WriteString("[Image]\n")
+}
+
+// dingtalkChatType maps DingTalk's conversationType to the normalized ChatType.
+// "1" is a 1:1 direct chat; everything else (group "2") is a group, which routes
+// through the engine's "must address the bot" filter.
+func dingtalkChatType(conversationType string) channel.ChatType {
+ if conversationType == convTypeP2P {
+ return channel.ChatTypeP2P
+ }
+ return channel.ChatTypeGroup
+}
diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.go
new file mode 100644
index 0000000000..2078839e0e
--- /dev/null
+++ b/server/internal/integrations/dingtalk/inbound_test.go
@@ -0,0 +1,200 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func textCallback(convType string, inAtList bool) *botCallbackData {
+ return &botCallbackData{
+ MsgId: "msg-1",
+ Msgtype: "text",
+ ConversationId: "cid-123",
+ ConversationType: convType,
+ SenderStaffId: "staff-9",
+ IsInAtList: inAtList,
+ Text: botCallbackText{Content: " hello bot "},
+ }
+}
+
+func TestInboundFromCallback_P2PAddressedAndTrimmed(t *testing.T) {
+ msg, ok := inboundFromCallback(textCallback(convTypeP2P, false), "appkey-A")
+ if !ok {
+ t.Fatal("expected a 1:1 text message to be ingested")
+ }
+ if msg.Source.ChatType != channel.ChatTypeP2P || !msg.AddressedToBot {
+ t.Errorf("1:1 must be p2p + addressed: %+v", msg.Source)
+ }
+ if msg.Text != "hello bot" || msg.CommandText != msg.Text {
+ t.Errorf("text/command = %q/%q", msg.Text, msg.CommandText)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || raw.AppID != "appkey-A" {
+ t.Fatalf("raw app id = %q, err=%v", raw.AppID, err)
+ }
+}
+
+func TestInboundFromCallback_GroupAddressing(t *testing.T) {
+ if msg, ok := inboundFromCallback(textCallback(convTypeGroup, true), "a"); !ok || !msg.AddressedToBot {
+ t.Fatalf("group mention must be addressed: ok=%v msg=%+v", ok, msg)
+ }
+ msg, ok := inboundFromCallback(textCallback(convTypeGroup, false), "a")
+ if !ok || msg.AddressedToBot {
+ t.Fatalf("unmentioned group message must reach the shared filter unaddressed: ok=%v msg=%+v", ok, msg)
+ }
+}
+
+func TestInboundFromCallback_LeavesFreshCommandForSharedRouter(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Text.Content = " /new start over "
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok {
+ t.Fatal("expected /new message")
+ }
+ if msg.Text != "/new start over" || msg.CommandText != msg.Text || msg.ForceFresh {
+ t.Fatalf("DingTalk must leave /new classification to the shared Router: %+v", msg)
+ }
+}
+
+func TestInboundFromCallback_BareFreshStaysForSharedPendingPath(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Text.Content = " /new "
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.Text != "/new" || msg.CommandText != "/new" || msg.ForceFresh {
+ t.Fatalf("bare /new must remain visible to the shared Router: ok=%v msg=%+v", ok, msg)
+ }
+}
+
+func TestInboundFromCallback_DoesNotPrivatelyComposeFreshAndIssue(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Text.Content = "/new /issue calculate 1+2"
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.ForceFresh || msg.Text != "/new /issue calculate 1+2" || msg.CommandText != msg.Text {
+ t.Fatalf("combined commands must remain untouched for shared classification: ok=%v msg=%+v", ok, msg)
+ }
+}
+
+func TestInboundFromCallback_PictureCarriesResolverMetadata(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "picture"
+ cb.Content = json.RawMessage(`{"downloadCode":"dl-1","pictureDownloadCode":"pdl-1"}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.Type != channel.MsgTypeImage || msg.Text != "[Image]" {
+ t.Fatalf("picture message = %+v, ok=%v", msg, ok)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) != 1 || raw.Media[0].Ref != "dl-1" || raw.Media[0].Alt != "pdl-1" {
+ t.Fatalf("raw media = %+v, err=%v", raw.Media, err)
+ }
+}
+
+func TestInboundFromCallback_RichTextKeepsCommandSourceAndImagePositions(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"/issue fix login"},
+ {"type":"picture","downloadCode":"dl-2"},
+ {"text":"\nrepro steps"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok {
+ t.Fatal("expected richText message")
+ }
+ if msg.CommandText != "/issue fix login\nrepro steps" {
+ t.Fatalf("command text = %q", msg.CommandText)
+ }
+ if strings.Count(msg.Text, "[Image]") != 2 || !strings.Contains(msg.Text, "/issue fix login") {
+ t.Fatalf("rendered text lost ordering markers: %q", msg.Text)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) != 2 || raw.Media[0].Ref != "dl-1" || raw.Media[1].Ref != "dl-2" {
+ t.Fatalf("raw media = %+v, err=%v", raw.Media, err)
+ }
+}
+
+func TestInboundFromCallback_RichTextDoesNotPrivatelyComposeFreshAndIssue(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"/new /issue inspect image"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || !msg.ForceFresh || msg.CommandText != "/new /issue inspect image" {
+ t.Fatalf("rich-text combined commands must remain untouched: %+v, ok=%v", msg, ok)
+ }
+ if !strings.Contains(msg.Text, "[Image]") || strings.Contains(msg.Text, "/new") || !strings.Contains(msg.Text, "/issue inspect image") {
+ t.Fatalf("rich-text visible body lost media or /new layout stripping: %q", msg.Text)
+ }
+}
+
+func TestInboundFromCallback_RichTextBareFreshWithoutMediaStaysForSharedPendingPath(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[{"text":" /new "}]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.ForceFresh || msg.Text != "/new" || msg.CommandText != "/new" {
+ t.Fatalf("text-only bare fresh = %+v, ok=%v", msg, ok)
+ }
+}
+
+func TestInboundFromCallback_RichTextBareFreshWithMediaPreservesMediaTurn(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"text":"/new"},
+ {"type":"picture","downloadCode":"dl-1"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || !msg.ForceFresh || msg.CommandText != "[Image]" || msg.Text != "[Image]" {
+ t.Fatalf("media-bearing bare fresh = %+v, ok=%v", msg, ok)
+ }
+}
+
+func TestInboundFromCallback_RichTextRunsDoNotCreatePrivateCommandComposition(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"text":"/new"},
+ {"text":"/issue split title"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.ForceFresh || msg.Text != "/new/issue split title" || msg.CommandText != msg.Text {
+ t.Fatalf("split rich-text runs must remain ordinary text: %+v, ok=%v", msg, ok)
+ }
+}
+
+func TestInboundFromCallback_UnreadableMediaStillReachesEngine(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "picture"
+ cb.Content = json.RawMessage(`{}`)
+ msg, ok := inboundFromCallback(cb, "a")
+ if !ok || msg.Text != "[Image unavailable]" {
+ t.Fatalf("unreadable image = %+v, ok=%v", msg, ok)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) != 0 {
+ t.Fatalf("raw unreadable metadata = %+v, err=%v", raw, err)
+ }
+}
+
+func TestInboundFromCallback_DropsOnlySenderless(t *testing.T) {
+ msg := textCallback(convTypeP2P, false)
+ msg.SenderStaffId = ""
+ if _, ok := inboundFromCallback(msg, "a"); ok {
+ t.Fatal("senderless callback must be dropped")
+ }
+ if _, ok := inboundFromCallback(nil, "a"); ok {
+ t.Fatal("nil callback must be dropped")
+ }
+}
+
+func TestCapabilitiesIncludeAttachment(t *testing.T) {
+ if c := (&dingtalkChannel{}).Capabilities(); !c.Has(channel.CapText | channel.CapAttachment) {
+ t.Fatalf("capabilities = %v", c)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/install.go b/server/internal/integrations/dingtalk/install.go
new file mode 100644
index 0000000000..844f059ddf
--- /dev/null
+++ b/server/internal/integrations/dingtalk/install.go
@@ -0,0 +1,285 @@
+package dingtalk
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// 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
+// 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.
+
+var (
+ // ErrInstallationNotFound surfaces "no row matches in this workspace".
+ ErrInstallationNotFound = errors.New("dingtalk installation not found")
+ // ErrRobotOwnedByAnotherWorkspace is returned when the pasted DingTalk robot
+ // is already connected to a live owner in a DIFFERENT Multica workspace — it
+ // would collide with the (channel_type, app_id) routing index. A DingTalk
+ // robot is one bot identity and maps to one agent; reusing it here requires
+ // disconnecting it in the other workspace first.
+ 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
+ // the user at the Disconnect they can actually reach (#4810).
+ ErrRobotOwnedBySameWorkspace = errors.New("dingtalk: this DingTalk robot is already connected to another agent in this workspace")
+ // ErrRobotOwnedByArchivedAgent is returned when the robot's owning agent is
+ // archived (and so still holds the robot, since archiving is reversible). The
+ // user recovers by restoring that agent or disconnecting its robot.
+ ErrRobotOwnedByArchivedAgent = errors.New("dingtalk: this DingTalk robot is connected to an archived agent in this workspace")
+)
+
+// installQueries is the slice of generated queries InstallService needs. WithTx
+// returns the same interface bound to a transaction so persistInstall runs its
+// upsert atomically (and so tests can inject a fake without a real DB).
+type installQueries interface {
+ WithTx(tx pgx.Tx) installQueries
+ LockDingTalkInstallationOwner(ctx context.Context, arg db.LockDingTalkInstallationOwnerParams) error
+ GetDingTalkInstallationOwnerForUpdate(ctx context.Context, arg db.GetDingTalkInstallationOwnerForUpdateParams) (db.GetDingTalkInstallationOwnerForUpdateRow, error)
+ DeleteDingTalkInstallationForReplacement(ctx context.Context, arg db.DeleteDingTalkInstallationForReplacementParams) (pgtype.UUID, error)
+ UpsertChannelInstallation(ctx context.Context, arg db.UpsertChannelInstallationParams) (db.ChannelInstallation, error)
+ ReclaimDeadChannelInstallationByAppID(ctx context.Context, arg db.ReclaimDeadChannelInstallationByAppIDParams) (pgtype.UUID, error)
+ GetChannelInstallationOwnerByAppID(ctx context.Context, arg db.GetChannelInstallationOwnerByAppIDParams) (db.GetChannelInstallationOwnerByAppIDRow, error)
+ ListChannelInstallationsByWorkspace(ctx context.Context, arg db.ListChannelInstallationsByWorkspaceParams) ([]db.ChannelInstallation, error)
+ GetChannelInstallationInWorkspace(ctx context.Context, arg db.GetChannelInstallationInWorkspaceParams) (db.ChannelInstallation, error)
+ SetChannelInstallationStatus(ctx context.Context, arg db.SetChannelInstallationStatusParams) error
+}
+
+// dbInstallQueries adapts *db.Queries to installQueries — the generated WithTx
+// returns *db.Queries, so we wrap it to return the interface (the same adapter
+// pattern slack.InstallService uses).
+type dbInstallQueries struct{ *db.Queries }
+
+func (q dbInstallQueries) WithTx(tx pgx.Tx) installQueries {
+ return dbInstallQueries{q.Queries.WithTx(tx)}
+}
+
+// InstallService owns the at-rest encryption of the AppSecret (so no caller can
+// write a channel_installation with a plaintext secret) and the shared install
+// transaction. The box MUST be non-nil (we refuse plaintext storage even in
+// dev).
+type InstallService struct {
+ box *secretbox.Box
+ q installQueries
+ tx engine.TxStarter
+ httpClient *http.Client
+ logger *slog.Logger
+ validationTimeout time.Duration
+
+ // apiBase overrides the DingTalk Open-API base for the BYO access-token
+ // validation call (tests point it at an httptest server). Empty uses the real
+ // DingTalk API.
+ apiBase string
+}
+
+// NewInstallService binds the service to queries, a tx starter (*pgxpool.Pool),
+// and an encryption box. Listing / revoking and BYO register all require only
+// the box (the at-rest key); there is no hosted OAuth credential.
+func NewInstallService(q *db.Queries, tx engine.TxStarter, box *secretbox.Box, logger *slog.Logger) (*InstallService, error) {
+ if q == nil {
+ return nil, errors.New("dingtalk: InstallService requires queries")
+ }
+ return newInstallService(dbInstallQueries{q}, tx, box, logger)
+}
+
+// newInstallService is the testable core: it takes the installQueries interface
+// so tests can inject a fake (with a fake TxStarter) without a real DB.
+func newInstallService(q installQueries, tx engine.TxStarter, box *secretbox.Box, logger *slog.Logger) (*InstallService, error) {
+ if box == nil {
+ return nil, errors.New("dingtalk: InstallService requires a non-nil secretbox.Box")
+ }
+ if q == nil {
+ return nil, errors.New("dingtalk: InstallService requires queries")
+ }
+ if tx == nil {
+ return nil, errors.New("dingtalk: InstallService requires a tx starter")
+ }
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &InstallService{
+ box: box,
+ q: q,
+ tx: tx,
+ httpClient: http.DefaultClient,
+ logger: logger,
+ validationTimeout: 10 * time.Second,
+ }, nil
+}
+
+// installPersist carries the resolved fields persistInstall writes. configJSON
+// holds the AppKey (config->>'app_id') used for inbound routing; the ROW itself
+// is keyed by (workspace, agent) — one bot per agent.
+type installPersist struct {
+ wsID pgtype.UUID
+ agentID pgtype.UUID
+ installerID pgtype.UUID
+ // appIDKey is the AppKey stored at config->>'app_id'; it MUST equal the
+ // app_id inside configJSON. It keys the dead-owner reclaim and the live-owner
+ // lookup that drives the accurate conflict message.
+ appIDKey string
+ configJSON []byte
+}
+
+// pgUniqueViolation is the Postgres SQLSTATE for a unique-constraint violation.
+const pgUniqueViolation = "23505"
+
+// 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 user
+// and session bindings must never cross from one robot identity to another.
+//
+// The (channel_type, app_id) routing index is the only OTHER unique constraint.
+// It is NOT this upsert's conflict target, so binding the robot to a DIFFERENT
+// agent would trip it. Before upserting we therefore reclaim a DEAD prior owner
+// of the AppKey (a revoked placeholder, or an orphan whose workspace/agent was
+// deleted) so the robot can move to the new agent; a LIVE owner trips the unique
+// index and is refused with an accurate conflict sentinel.
+func (s *InstallService) persistInstall(ctx context.Context, p installPersist) (db.ChannelInstallation, error) {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("begin install tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ qtx := s.q.WithTx(tx)
+
+ // A replacement deletes and recreates the unique (workspace, agent,
+ // channel) row. Serialize the logical slot across that gap so concurrent
+ // installs cannot update the newly-created identity in place.
+ if err := qtx.LockDingTalkInstallationOwner(ctx, db.LockDingTalkInstallationOwnerParams{
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ }); err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("lock dingtalk installation owner: %w", err)
+ }
+
+ // Free the (dingtalk, app_id) routing slot from any DEAD prior owner — a
+ // revoked placeholder, or an orphan whose owning workspace/agent was deleted
+ // (#4810) — before the upsert, so a robot whose old owner is gone can be
+ // rebound. A live owner (active agent, including an archived one) is left in
+ // place and trips the unique index below, which we turn into an accurate
+ // conflict.
+ if _, err := qtx.ReclaimDeadChannelInstallationByAppID(ctx, db.ReclaimDeadChannelInstallationByAppIDParams{
+ ChannelType: string(TypeDingTalk),
+ AppID: p.appIDKey,
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ }); err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ // pgx.ErrNoRows just means nothing was dead — a no-op, not a failure.
+ return db.ChannelInstallation{}, fmt.Errorf("reclaim dead dingtalk installation: %w", err)
+ }
+
+ current, err := qtx.GetDingTalkInstallationOwnerForUpdate(ctx, db.GetDingTalkInstallationOwnerForUpdateParams{
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ })
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return db.ChannelInstallation{}, fmt.Errorf("load current dingtalk installation: %w", err)
+ }
+ if err == nil && current.AppID != p.appIDKey {
+ if _, err := qtx.DeleteDingTalkInstallationForReplacement(ctx, db.DeleteDingTalkInstallationForReplacementParams{
+ InstallationID: current.ID,
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ }); err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("retire replaced dingtalk installation: %w", err)
+ }
+ }
+
+ inst, err := qtx.UpsertChannelInstallation(ctx, db.UpsertChannelInstallationParams{
+ WorkspaceID: p.wsID,
+ AgentID: p.agentID,
+ ChannelType: string(TypeDingTalk),
+ Config: p.configJSON,
+ InstallerUserID: p.installerID,
+ })
+ if err != nil {
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation {
+ return db.ChannelInstallation{}, s.liveOwnerConflictErr(ctx, p.wsID, p.appIDKey)
+ }
+ return db.ChannelInstallation{}, fmt.Errorf("upsert dingtalk installation: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.ChannelInstallation{}, fmt.Errorf("commit dingtalk install: %w", err)
+ }
+ return inst, nil
+}
+
+// liveOwnerConflictErr classifies who holds the (dingtalk, app_id) routing slot
+// after the dead-owner reclaim ran, so persistInstall returns a sentinel the
+// handler renders as an accurate message rather than a catch-all that always
+// blames "another workspace" (#4810). Read on the base pool (s.q), since the
+// failed upsert has aborted the tx. A now-free slot (concurrent disconnect) or
+// lookup error falls back to the generic cross-workspace sentinel — a retry
+// then succeeds.
+func (s *InstallService) liveOwnerConflictErr(ctx context.Context, requestingWorkspaceID pgtype.UUID, appID string) error {
+ owner, err := s.q.GetChannelInstallationOwnerByAppID(ctx, db.GetChannelInstallationOwnerByAppIDParams{
+ ChannelType: string(TypeDingTalk),
+ AppID: appID,
+ })
+ if err != nil {
+ return ErrRobotOwnedByAnotherWorkspace
+ }
+ switch {
+ case owner.WorkspaceID != requestingWorkspaceID:
+ return ErrRobotOwnedByAnotherWorkspace
+ case owner.AgentArchivedAt.Valid:
+ return ErrRobotOwnedByArchivedAgent
+ default:
+ return ErrRobotOwnedBySameWorkspace
+ }
+}
+
+// ListByWorkspace returns every DingTalk installation in the workspace (active
+// and revoked), for the management surface.
+func (s *InstallService) ListByWorkspace(ctx context.Context, wsID pgtype.UUID) ([]db.ChannelInstallation, error) {
+ return s.q.ListChannelInstallationsByWorkspace(ctx, db.ListChannelInstallationsByWorkspaceParams{
+ WorkspaceID: wsID,
+ ChannelType: string(TypeDingTalk),
+ })
+}
+
+// GetInWorkspace is the workspace-scoped lookup so a forged installation id from
+// another workspace returns NotFound instead of leaking existence.
+func (s *InstallService) GetInWorkspace(ctx context.Context, id, wsID pgtype.UUID) (db.ChannelInstallation, error) {
+ inst, err := s.q.GetChannelInstallationInWorkspace(ctx, db.GetChannelInstallationInWorkspaceParams{
+ ID: id,
+ WorkspaceID: wsID,
+ ChannelType: string(TypeDingTalk),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return db.ChannelInstallation{}, ErrInstallationNotFound
+ }
+ return db.ChannelInstallation{}, err
+ }
+ return inst, nil
+}
+
+// Revoke flips status to 'revoked'. The row is preserved for audit; a re-install
+// flips it back to 'active'. The Supervisor stops supervising the installation
+// (ListActiveInstallations filters to active), so its Stream connection winds
+// down, and outbound drops too.
+func (s *InstallService) Revoke(ctx context.Context, id pgtype.UUID) error {
+ return s.q.SetChannelInstallationStatus(ctx, db.SetChannelInstallationStatusParams{
+ ID: id,
+ Status: "revoked",
+ })
+}
diff --git a/server/internal/integrations/dingtalk/install_test.go b/server/internal/integrations/dingtalk/install_test.go
new file mode 100644
index 0000000000..68df5c5390
--- /dev/null
+++ b/server/internal/integrations/dingtalk/install_test.go
@@ -0,0 +1,164 @@
+package dingtalk
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/util"
+ "github.com/multica-ai/multica/server/internal/util/secretbox"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func testBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ key := make([]byte, secretbox.KeySize)
+ for i := range key {
+ key[i] = byte(i + 1)
+ }
+ box, err := secretbox.New(key)
+ if err != nil {
+ t.Fatalf("secretbox.New: %v", err)
+ }
+ return box
+}
+
+func mustUUID(t *testing.T, s string) pgtype.UUID {
+ t.Helper()
+ u, err := util.ParseUUID(s)
+ if err != nil {
+ t.Fatalf("parse uuid %q: %v", s, err)
+ }
+ return u
+}
+
+type fakeInstallQueries struct {
+ // existing, when set, is the agent's current row; UpsertChannelInstallation
+ // returns it (an UPDATE) so a reconnect reuses the same row id.
+ existing *db.ChannelInstallation
+ // existingAppID is the current row's platform identity returned under lock.
+ // It distinguishes a same-robot reconnect from a different-robot replacement.
+ existingAppID string
+ lockCalled bool
+ replaceCalled bool
+ replaceParams db.DeleteDingTalkInstallationForReplacementParams
+ // appIDTaken makes UpsertChannelInstallation report a unique-constraint
+ // violation on the (channel_type, app_id) routing index — i.e. the pasted
+ // robot is already connected to a LIVE owner (the reclaim has run by then).
+ appIDTaken bool
+ upsertParams db.UpsertChannelInstallationParams
+ upsertCalled bool
+ rowID pgtype.UUID
+
+ // reclaimedID, when set, is returned by ReclaimDeadChannelInstallationByAppID
+ // to model a dead prior owner having been cleared; otherwise it reports
+ // pgx.ErrNoRows (nothing was dead). reclaimCalled records that the install
+ // path ran the reclaim before upserting.
+ reclaimedID *pgtype.UUID
+ reclaimCalled bool
+ // ownerWorkspaceID / ownerArchived / ownerMissing drive the live-owner lookup
+ // that classifies an appIDTaken conflict into the right sentinel.
+ ownerWorkspaceID pgtype.UUID
+ ownerArchived bool
+ ownerMissing bool
+}
+
+// WithTx returns the same fake — the fake tx is a no-op token.
+func (f *fakeInstallQueries) WithTx(_ pgx.Tx) installQueries { return f }
+
+func (f *fakeInstallQueries) LockDingTalkInstallationOwner(_ context.Context, _ db.LockDingTalkInstallationOwnerParams) error {
+ f.lockCalled = true
+ return nil
+}
+
+func (f *fakeInstallQueries) GetDingTalkInstallationOwnerForUpdate(_ context.Context, _ db.GetDingTalkInstallationOwnerForUpdateParams) (db.GetDingTalkInstallationOwnerForUpdateRow, error) {
+ if f.existing == nil {
+ return db.GetDingTalkInstallationOwnerForUpdateRow{}, pgx.ErrNoRows
+ }
+ return db.GetDingTalkInstallationOwnerForUpdateRow{ID: f.existing.ID, AppID: f.existingAppID}, nil
+}
+
+func (f *fakeInstallQueries) DeleteDingTalkInstallationForReplacement(_ context.Context, arg db.DeleteDingTalkInstallationForReplacementParams) (pgtype.UUID, error) {
+ f.replaceCalled = true
+ f.replaceParams = arg
+ id := f.existing.ID
+ f.existing = nil
+ return id, nil
+}
+
+func (f *fakeInstallQueries) ReclaimDeadChannelInstallationByAppID(_ context.Context, _ db.ReclaimDeadChannelInstallationByAppIDParams) (pgtype.UUID, error) {
+ f.reclaimCalled = true
+ if f.reclaimedID != nil {
+ return *f.reclaimedID, nil
+ }
+ return pgtype.UUID{}, pgx.ErrNoRows
+}
+
+func (f *fakeInstallQueries) GetChannelInstallationOwnerByAppID(_ context.Context, _ db.GetChannelInstallationOwnerByAppIDParams) (db.GetChannelInstallationOwnerByAppIDRow, error) {
+ if f.ownerMissing {
+ return db.GetChannelInstallationOwnerByAppIDRow{}, pgx.ErrNoRows
+ }
+ return db.GetChannelInstallationOwnerByAppIDRow{
+ WorkspaceID: f.ownerWorkspaceID,
+ AgentArchivedAt: pgtype.Timestamptz{Valid: f.ownerArchived},
+ }, nil
+}
+
+func (f *fakeInstallQueries) UpsertChannelInstallation(_ context.Context, arg db.UpsertChannelInstallationParams) (db.ChannelInstallation, error) {
+ f.upsertCalled = true
+ f.upsertParams = arg
+ if f.appIDTaken {
+ return db.ChannelInstallation{}, &pgconn.PgError{Code: "23505"}
+ }
+ id := f.rowID
+ if f.existing != nil {
+ id = f.existing.ID // reconnect updates the agent's existing row in place
+ }
+ return db.ChannelInstallation{
+ ID: id,
+ WorkspaceID: arg.WorkspaceID,
+ AgentID: arg.AgentID,
+ ChannelType: arg.ChannelType,
+ Config: arg.Config,
+ InstallerUserID: arg.InstallerUserID,
+ Status: "active",
+ }, nil
+}
+
+func (f *fakeInstallQueries) ListChannelInstallationsByWorkspace(_ context.Context, _ db.ListChannelInstallationsByWorkspaceParams) ([]db.ChannelInstallation, error) {
+ return nil, nil
+}
+
+func (f *fakeInstallQueries) GetChannelInstallationInWorkspace(_ context.Context, _ db.GetChannelInstallationInWorkspaceParams) (db.ChannelInstallation, error) {
+ return db.ChannelInstallation{}, nil
+}
+
+func (f *fakeInstallQueries) SetChannelInstallationStatus(_ context.Context, _ db.SetChannelInstallationStatusParams) error {
+ return nil
+}
+
+// fakeTx is a no-op pgx.Tx: embedding the interface satisfies it, and the
+// install paths only ever call Commit / Rollback.
+type fakeTx struct {
+ pgx.Tx
+ committed bool
+}
+
+func (t *fakeTx) Commit(context.Context) error { t.committed = true; return nil }
+func (t *fakeTx) Rollback(context.Context) error { return nil }
+
+type fakeTxStarter struct{ tx *fakeTx }
+
+func (f *fakeTxStarter) Begin(context.Context) (pgx.Tx, error) { return f.tx, nil }
+
+func newTestInstallService(t *testing.T, q installQueries) *InstallService {
+ t.Helper()
+ svc, err := newInstallService(q, &fakeTxStarter{tx: &fakeTx{}}, testBox(t), nil)
+ if err != nil {
+ t.Fatalf("newInstallService: %v", err)
+ }
+ return svc
+}
diff --git a/server/internal/integrations/dingtalk/markdown.go b/server/internal/integrations/dingtalk/markdown.go
new file mode 100644
index 0000000000..67dc35d7f6
--- /dev/null
+++ b/server/internal/integrations/dingtalk/markdown.go
@@ -0,0 +1,190 @@
+package dingtalk
+
+import (
+ "strings"
+ "unicode/utf8"
+)
+
+// DingTalk's robot send APIs (oToMessages.batchSend / groupMessages.send) hard-
+// reject a sampleMarkdown body over ~20000 bytes and drop the whole message, so
+// we chunk well under that. The budget is measured in UTF-8 BYTES, not runes,
+// because the limit is on the encoded payload. A code fence open at a chunk
+// boundary is closed at the end of the chunk and reopened at the start of the
+// next, so neither half renders as broken markdown.
+
+const (
+ // markdownByteBudget bounds one chunk's body in UTF-8 bytes.
+ markdownByteBudget = 16000
+ // A split inside a code block appends "\n```" to make the emitted chunk
+ // self-contained. Keep this space out of the content budget so the final
+ // wire body, not just the pre-rendered slice, stays under the hard limit.
+ markdownSyntheticFenceCloseBytes = len("\n```")
+ markdownContentByteBudget = markdownByteBudget - markdownSyntheticFenceCloseBytes
+ // A continuation repeats the opening fence line. Bound that synthetic
+ // prefix so an adversarially long info string cannot consume the entire
+ // piece budget (or make it negative) when the next code line is split.
+ maxMarkdownFenceInfoBytes = 256
+ // defaultMarkdownTitle is the chat-list notification preview used when the
+ // body carries no leading heading. DingTalk shows the title only in the push
+ // preview, not in the message body.
+ defaultMarkdownTitle = "Multica has replied."
+)
+
+// markdownTitle derives the sampleMarkdown title (the notification preview) from
+// the body's first ATX heading, falling back to a default. The heading is left
+// in the body; only its leading hashes are stripped for the preview.
+func markdownTitle(body string) string {
+ for _, line := range strings.Split(body, "\n") {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, "#") {
+ heading := strings.TrimSpace(strings.TrimLeft(trimmed, "#"))
+ if heading != "" {
+ return heading
+ }
+ }
+ if trimmed != "" {
+ break
+ }
+ }
+ return defaultMarkdownTitle
+}
+
+// chunkMarkdown splits body into pieces each at most markdownByteBudget bytes,
+// preferring line boundaries. A code fence (```) left open at a boundary is
+// closed at the end of the chunk and reopened at the start of the next so each
+// chunk is self-contained markdown. A single line longer than the budget is
+// hard-split on a byte boundary that respects UTF-8 rune edges.
+func chunkMarkdown(body string) []string {
+ if len(body) <= markdownByteBudget {
+ return []string{body}
+ }
+
+ var (
+ chunks []string
+ cur strings.Builder
+ fenceOpen bool
+ // fenceInfo is the opening fence line (e.g. "```go") of the currently open
+ // block, so a continuation chunk can reopen with the SAME info string.
+ // DingTalk highlights by that language tag; a bare "```" reopen renders the
+ // continuation unhighlighted.
+ fenceInfo string
+ )
+ flush := func(reopen bool) {
+ if cur.Len() == 0 {
+ return
+ }
+ text := cur.String()
+ if fenceOpen {
+ text += "\n```"
+ }
+ // Drop a chunk that carries only fence/blank lines — e.g. an opening fence
+ // stranded right before an oversized line, or a reopened fence with nothing
+ // after it — so it never renders as an empty code block.
+ if !isBlankChunk(text) {
+ chunks = append(chunks, text)
+ }
+ cur.Reset()
+ if reopen && fenceOpen {
+ cur.WriteString(fenceInfo + "\n")
+ }
+ }
+
+ for _, line := range splitKeepNewline(body) {
+ // A single oversized line cannot fit a chunk; hard-split it.
+ if len(line) > markdownContentByteBudget {
+ flush(true)
+ pieceBudget := markdownContentByteBudget
+ if fenceOpen {
+ pieceBudget = markdownByteBudget - len(fenceInfo) - len("\n") - len("\n```")
+ }
+ for _, piece := range hardSplit(line, pieceBudget) {
+ // A piece split out of an oversized line inside a code block must
+ // carry its own fences, or it would render as plain text.
+ if fenceOpen {
+ piece = fenceInfo + "\n" + piece + "\n```"
+ }
+ chunks = append(chunks, piece)
+ }
+ continue
+ }
+ if cur.Len()+len(line) > markdownContentByteBudget {
+ flush(true)
+ }
+ if isFenceLine(line) {
+ if fenceOpen {
+ fenceOpen = false
+ fenceInfo = ""
+ } else {
+ fenceOpen = true
+ fenceInfo = continuationFence(line)
+ }
+ }
+ cur.WriteString(line)
+ }
+ flush(false)
+ return chunks
+}
+
+func continuationFence(line string) string {
+ fence := strings.TrimRight(line, "\r\n")
+ if len(fence) > maxMarkdownFenceInfoBytes {
+ return "```"
+ }
+ return fence
+}
+
+// splitKeepNewline splits s into lines, keeping the trailing "\n" on each line
+// so reassembly (strings.Join) is exact. SplitAfter yields a trailing "" when s
+// ends in "\n"; drop it so an exact-newline body does not gain a blank line.
+func splitKeepNewline(s string) []string {
+ lines := strings.SplitAfter(s, "\n")
+ if n := len(lines); n > 0 && lines[n-1] == "" {
+ lines = lines[:n-1]
+ }
+ return lines
+}
+
+// isFenceLine reports whether a line opens or closes a fenced code block (its
+// first non-space content is ```).
+func isFenceLine(line string) bool {
+ return strings.HasPrefix(strings.TrimLeft(line, " \t"), "```")
+}
+
+// isBlankChunk reports whether text carries no renderable content — every line
+// is blank or a fence marker. Such a chunk would render as an empty code block,
+// so the chunker drops it instead of sending it.
+func isBlankChunk(text string) bool {
+ for _, line := range strings.Split(text, "\n") {
+ t := strings.TrimSpace(line)
+ if t != "" && !strings.HasPrefix(t, "```") {
+ return false
+ }
+ }
+ return true
+}
+
+// hardSplit breaks s into byte-budget pieces without cutting a UTF-8 rune.
+func hardSplit(s string, budget int) []string {
+ // All production callers provide a much larger budget. Keep this helper
+ // total anyway: a future synthetic prefix change must not turn a malformed
+ // budget into an infinite loop, negative slice, or split UTF-8 rune.
+ if budget < utf8.UTFMax {
+ budget = utf8.UTFMax
+ }
+ var pieces []string
+ for len(s) > budget {
+ cut := budget
+ for cut > 0 && !utf8.RuneStart(s[cut]) {
+ cut--
+ }
+ if cut == 0 {
+ cut = budget
+ }
+ pieces = append(pieces, s[:cut])
+ s = s[cut:]
+ }
+ if s != "" {
+ pieces = append(pieces, s)
+ }
+ return pieces
+}
diff --git a/server/internal/integrations/dingtalk/markdown_test.go b/server/internal/integrations/dingtalk/markdown_test.go
new file mode 100644
index 0000000000..2030781446
--- /dev/null
+++ b/server/internal/integrations/dingtalk/markdown_test.go
@@ -0,0 +1,155 @@
+package dingtalk
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf8"
+)
+
+func TestMarkdownTitle(t *testing.T) {
+ cases := map[string]string{
+ "# Heading one\nbody": "Heading one",
+ "\n\n## Second\nmore": "Second",
+ "no heading here": defaultMarkdownTitle,
+ "plain line\n# late": defaultMarkdownTitle, // first non-empty line is not a heading
+ "### spaced \nbody": "spaced",
+ }
+ for body, want := range cases {
+ if got := markdownTitle(body); got != want {
+ t.Errorf("markdownTitle(%q) = %q, want %q", body, got, want)
+ }
+ }
+}
+
+func TestChunkMarkdown_ShortPassthrough(t *testing.T) {
+ body := "a short body"
+ got := chunkMarkdown(body)
+ if len(got) != 1 || got[0] != body {
+ t.Errorf("short body must pass through unchunked: %v", got)
+ }
+}
+
+func TestChunkMarkdown_SplitsUnderByteBudget(t *testing.T) {
+ line := strings.Repeat("x", 1000) + "\n"
+ body := strings.Repeat(line, 40) // ~40k bytes
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("expected multiple chunks, got %d", len(chunks))
+ }
+ for i, c := range chunks {
+ if len(c) > markdownByteBudget {
+ t.Errorf("chunk %d exceeds budget: %d bytes", i, len(c))
+ }
+ }
+ // Reassembling the chunks recovers the original text.
+ if strings.Join(chunks, "") != body {
+ t.Error("rejoined chunks must equal the original body")
+ }
+}
+
+func TestChunkMarkdown_ReopensCodeFence(t *testing.T) {
+ // A code block that straddles the byte budget must be closed at the split and
+ // reopened in the next chunk so neither half renders broken.
+ codeLine := strings.Repeat("y", 500) + "\n"
+ body := "```\n" + strings.Repeat(codeLine, 40) + "```\n"
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("expected the long code block to split, got %d chunks", len(chunks))
+ }
+ for i, c := range chunks {
+ if len(c) > markdownByteBudget {
+ t.Errorf("chunk %d exceeds budget: %d bytes", i, len(c))
+ }
+ fences := strings.Count(c, "```")
+ if fences%2 != 0 {
+ t.Errorf("chunk %d has unbalanced code fences (%d): not self-contained", i, fences)
+ }
+ }
+}
+
+func TestChunkMarkdown_ReopenPreservesLanguage(t *testing.T) {
+ // DingTalk highlights a code block by its language info string (```go). When a
+ // block straddles the budget, the reopened chunk must carry the SAME info
+ // string, or the continuation renders unhighlighted.
+ codeLine := strings.Repeat("y", 500) + "\n"
+ body := "```go\n" + strings.Repeat(codeLine, 40) + "```\n"
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("expected the long code block to split, got %d chunks", len(chunks))
+ }
+ if !strings.HasPrefix(chunks[1], "```go\n") {
+ t.Errorf("continuation chunk must reopen the go fence, got prefix %q", chunks[1][:min(6, len(chunks[1]))])
+ }
+}
+
+func TestChunkMarkdown_HardSplitsOversizedLine(t *testing.T) {
+ body := strings.Repeat("z", markdownByteBudget*2+50) // single line, no newlines
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("oversized single line must hard-split, got %d", len(chunks))
+ }
+ for i, c := range chunks {
+ if len(c) > markdownByteBudget {
+ t.Errorf("hard-split chunk %d exceeds budget: %d", i, len(c))
+ }
+ }
+ if strings.Join(chunks, "") != body {
+ t.Error("hard-split chunks must rejoin to the original")
+ }
+}
+
+func TestChunkMarkdown_OversizedLineInsideCodeFence(t *testing.T) {
+ // An oversized line inside an open code fence must be split into self-contained
+ // code blocks (no plain-text leak, no stray empty code-block messages).
+ oversized := strings.Repeat("a", markdownByteBudget*2+50)
+ body := "```\n" + oversized + "\n```\n"
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("oversized fenced line must split, got %d chunks", len(chunks))
+ }
+ for i, c := range chunks {
+ if len(c) > markdownByteBudget {
+ t.Errorf("chunk %d exceeds budget: %d bytes", i, len(c))
+ }
+ if fences := strings.Count(c, "```"); fences%2 != 0 {
+ t.Errorf("chunk %d has unbalanced code fences (%d): not self-contained", i, fences)
+ }
+ if isBlankChunk(c) {
+ t.Errorf("chunk %d is an empty code block", i)
+ }
+ }
+}
+
+func TestChunkMarkdown_LongFenceInfoCannotExhaustPieceBudget(t *testing.T) {
+ // Keep the opening line just inside the normal-line budget, then force the
+ // following code line through hardSplit. Before the continuation fence was
+ // bounded, this made pieceBudget negative and panicked.
+ fence := "```" + strings.Repeat("x", markdownContentByteBudget-5)
+ body := fence + "\n" + strings.Repeat("界", markdownByteBudget) + "\n```\n"
+ chunks := chunkMarkdown(body)
+ if len(chunks) < 2 {
+ t.Fatalf("pathological fenced body must split, got %d chunks", len(chunks))
+ }
+ for i, chunk := range chunks {
+ if len(chunk) > markdownByteBudget {
+ t.Errorf("chunk %d exceeds budget: %d bytes", i, len(chunk))
+ }
+ if fences := strings.Count(chunk, "```"); fences%2 != 0 {
+ t.Errorf("chunk %d has unbalanced fences: %d", i, fences)
+ }
+ }
+}
+
+func TestHardSplitDefendsAgainstInvalidBudget(t *testing.T) {
+ for _, budget := range []int{-1, 0, 1} {
+ pieces := hardSplit("界界", budget)
+ if got := strings.Join(pieces, ""); got != "界界" {
+ t.Fatalf("hardSplit budget %d rejoined to %q", budget, got)
+ }
+ for _, piece := range pieces {
+ if !utf8.ValidString(piece) {
+ t.Fatalf("hardSplit budget %d produced invalid UTF-8 %q", budget, piece)
+ }
+ }
+ }
+}
diff --git a/server/internal/integrations/dingtalk/media.go b/server/internal/integrations/dingtalk/media.go
new file mode 100644
index 0000000000..962959a0b9
--- /dev/null
+++ b/server/internal/integrations/dingtalk/media.go
@@ -0,0 +1,383 @@
+package dingtalk
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "path"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "golang.org/x/sync/errgroup"
+
+ "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/storage"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// DingTalk publishes no inbound image limits. Keep the adapter's memory and
+// remote-I/O budget deliberately below the shared Router's 45-second media
+// deadline: at most two 10 MiB downloads are buffered concurrently.
+const (
+ maxImagesPerMessage = 4
+ maxInboundImageBytes = 10 << 20
+ imageFetchTimeout = 30 * time.Second
+ mediaFetchConcurrency = 2
+ maxDownloadRedirects = 3
+)
+
+var allowedImageTypes = map[string]string{
+ "image/png": ".png",
+ "image/jpeg": ".jpg",
+ "image/gif": ".gif",
+ "image/webp": ".webp",
+ "image/bmp": ".bmp",
+}
+
+type mediaResolver struct {
+ client *Client
+ decrypt Decrypter
+ store storage.Storage
+ ledger engine.MediaIntentLedger
+ logger *slog.Logger
+ fetch *http.Client
+}
+
+var _ engine.MediaResolver = (*mediaResolver)(nil)
+
+func NewMediaResolver(client *Client, decrypt Decrypter, store storage.Storage, ledger engine.MediaIntentLedger, logger *slog.Logger) engine.MediaResolver {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &mediaResolver{
+ client: client,
+ decrypt: decrypt,
+ store: store,
+ ledger: ledger,
+ logger: logger,
+ fetch: newMediaHTTPClient(),
+ }
+}
+
+// DingTalk's authenticated messageFiles/download API can return a public HTTP
+// URL as well as HTTPS. The adapter must honor that provider-issued URL without
+// rewriting its scheme, but the URL remains untrusted egress input: resolve the
+// host ourselves, reject every non-public answer, and dial the validated IP
+// directly so DNS rebinding cannot redirect the connection into the local
+// network. Proxy use is disabled because a proxy would resolve the target again
+// and bypass this guarantee.
+func newMediaHTTPClient() *http.Client {
+ transport := http.DefaultTransport.(*http.Transport).Clone()
+ transport.Proxy = nil
+ transport.DialContext = (&publicDownloadDialer{
+ resolver: net.DefaultResolver,
+ dialer: &net.Dialer{Timeout: imageFetchTimeout},
+ }).DialContext
+ return &http.Client{
+ Transport: transport,
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= maxDownloadRedirects {
+ return errors.New("too many redirects")
+ }
+ // net/http derives Referer from the previous URL. The query string
+ // is a short-lived bearer credential, so it must never cross into a
+ // redirect request, including an otherwise-allowed same-origin hop.
+ req.Header.Del("Referer")
+ if err := validateDownloadURL(req.URL); err != nil {
+ return err
+ }
+ previous := via[len(via)-1].URL
+ if strings.EqualFold(previous.Scheme, "https") && !strings.EqualFold(req.URL.Scheme, "https") {
+ return errors.New("disallowed HTTPS download redirect downgrade")
+ }
+ if strings.EqualFold(req.URL.Scheme, "http") && !sameDownloadOrigin(previous, req.URL) {
+ return errors.New("disallowed cross-origin HTTP download redirect")
+ }
+ return nil
+ },
+ }
+}
+
+type publicDownloadDialer struct {
+ resolver *net.Resolver
+ dialer *net.Dialer
+}
+
+func (d *publicDownloadDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
+ host, port, err := net.SplitHostPort(address)
+ if err != nil {
+ return nil, errors.New("invalid download target address")
+ }
+ addrs, err := d.lookup(ctx, host)
+ if err != nil || len(addrs) == 0 {
+ return nil, errors.New("resolve download target failed")
+ }
+ for _, addr := range addrs {
+ if !isPublicDownloadAddress(addr) {
+ return nil, errors.New("blocked non-public download target")
+ }
+ }
+ for _, addr := range addrs {
+ conn, err := d.dialer.DialContext(ctx, network, net.JoinHostPort(addr.String(), port))
+ if err == nil {
+ return conn, nil
+ }
+ }
+ return nil, errors.New("connect to download target failed")
+}
+
+func (d *publicDownloadDialer) lookup(ctx context.Context, host string) ([]netip.Addr, error) {
+ if addr, err := netip.ParseAddr(host); err == nil {
+ return []netip.Addr{addr.Unmap()}, nil
+ }
+ addrs, err := d.resolver.LookupNetIP(ctx, "ip", host)
+ if err != nil {
+ return nil, err
+ }
+ for i := range addrs {
+ addrs[i] = addrs[i].Unmap()
+ }
+ return addrs, nil
+}
+
+var nonPublicDownloadPrefixes = []netip.Prefix{
+ netip.MustParsePrefix("0.0.0.0/8"),
+ netip.MustParsePrefix("100.64.0.0/10"),
+ netip.MustParsePrefix("192.0.0.0/24"),
+ netip.MustParsePrefix("192.0.2.0/24"),
+ netip.MustParsePrefix("198.18.0.0/15"),
+ netip.MustParsePrefix("198.51.100.0/24"),
+ netip.MustParsePrefix("203.0.113.0/24"),
+ netip.MustParsePrefix("240.0.0.0/4"),
+ // IPv6 transition mechanisms can encapsulate an otherwise-blocked IPv4
+ // destination in an address that netip classifies as global unicast. The
+ // download client does not need these legacy/local transition ranges, so
+ // fail closed instead of attempting to decode every deployment-specific
+ // mapping and risking a route into loopback or RFC1918 space.
+ netip.MustParsePrefix("::/96"), // deprecated IPv4-compatible
+ netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64
+ netip.MustParsePrefix("100::/64"), // discard-only
+ netip.MustParsePrefix("2001::/32"), // Teredo
+ netip.MustParsePrefix("2001:2::/48"), // benchmarking
+ netip.MustParsePrefix("2001:db8::/32"),
+ netip.MustParsePrefix("2001:10::/28"), // deprecated ORCHID
+ netip.MustParsePrefix("2001:20::/28"), // ORCHIDv2
+ netip.MustParsePrefix("2002::/16"), // 6to4
+ netip.MustParsePrefix("3fff::/20"), // documentation
+}
+
+var wellKnownNAT64Prefix = netip.MustParsePrefix("64:ff9b::/96")
+
+func isPublicDownloadAddress(addr netip.Addr) bool {
+ addr = addr.Unmap()
+ if !addr.IsValid() || !addr.IsGlobalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsLinkLocalUnicast() {
+ return false
+ }
+ if wellKnownNAT64Prefix.Contains(addr) {
+ // The standard NAT64 prefix carries an IPv4 address in its low 32
+ // bits. Permit a synthesized public target, but apply the complete IPv4
+ // deny policy to prevent an attacker-controlled AAAA record from
+ // smuggling loopback or RFC1918 through an apparently global IPv6 value.
+ raw := addr.As16()
+ return isPublicDownloadAddress(netip.AddrFrom4([4]byte(raw[12:16])))
+ }
+ for _, prefix := range nonPublicDownloadPrefixes {
+ if prefix.Contains(addr) {
+ return false
+ }
+ }
+ return true
+}
+
+func sameDownloadOrigin(a, b *url.URL) bool {
+ return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host)
+}
+
+// HasMedia is a pure decode of the already-received callback metadata. Remote
+// work stays behind ResolveMedia, after dedup, identity and membership checks.
+func (m *mediaResolver) HasMedia(msg channel.InboundMessage) bool {
+ raw, err := decodeDingTalkRaw(msg)
+ return err == nil && len(raw.Media) > 0
+}
+
+func (m *mediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) == 0 {
+ return msg
+ }
+ if len(raw.Media) > maxImagesPerMessage {
+ m.logWarn(msg, fmt.Errorf("%d images exceed the limit of %d", len(raw.Media), maxImagesPerMessage))
+ return msg
+ }
+ if m.client == nil || m.store == nil || m.ledger == nil {
+ m.logWarn(msg, errors.New("media dependency missing"))
+ return msg
+ }
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ m.logWarn(msg, errors.New("installation platform row unavailable"))
+ return msg
+ }
+ creds, err := decodeCredentials(row.Config, m.decrypt)
+ if err != nil {
+ m.logWarn(msg, fmt.Errorf("decode credentials: %w", err))
+ return msg
+ }
+
+ refs := make([]channel.MediaRef, len(raw.Media))
+ valid := make([]bool, len(raw.Media))
+ g, gctx := errgroup.WithContext(ctx)
+ g.SetLimit(mediaFetchConcurrency)
+ for i, resource := range raw.Media {
+ g.Go(func() error {
+ key := dingtalkMediaObjectKey(inst, chatMessageID, resource, i)
+ link := m.store.ObjectURL(key)
+ owned, err := m.ledger.RecordPendingMediaObject(gctx, engine.RecordPendingMediaObjectParams{
+ StorageKey: key,
+ WorkspaceID: inst.WorkspaceID,
+ ChatMessageID: chatMessageID,
+ StorageURL: link,
+ InstallationID: inst.ID,
+ })
+ if err != nil {
+ m.logWarn(msg, fmt.Errorf("record media intent: %w", err))
+ return nil
+ }
+ if !owned {
+ m.logWarn(msg, errors.New("media key owned by reconciler"))
+ return nil
+ }
+ data, contentType, err := m.fetchResource(gctx, creds, resource)
+ if err != nil {
+ m.logWarn(msg, err)
+ return nil
+ }
+ ext := allowedImageTypes[contentType]
+ filename := fmt.Sprintf("dingtalk-image-%d%s", i+1, ext)
+ if _, err := m.store.Upload(gctx, key, data, contentType, filename); err != nil {
+ m.logWarn(msg, fmt.Errorf("upload image: %w", err))
+ return nil
+ }
+ refs[i] = channel.MediaRef{
+ Type: channel.MsgTypeImage,
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: int64(len(data)),
+ }
+ valid[i] = true
+ return nil
+ })
+ }
+ _ = g.Wait()
+ for i, ref := range refs {
+ if valid[i] {
+ msg.MediaRefs = append(msg.MediaRefs, ref)
+ }
+ }
+ return msg
+}
+
+func dingtalkMediaObjectKey(inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, resource dingtalkMediaResource, index int) string {
+ sum := sha256.Sum256([]byte(util.UUIDToString(chatMessageID) + "\x00" + resource.Ref + "\x00" + fmt.Sprint(index)))
+ return path.Join("workspaces", util.UUIDToString(inst.WorkspaceID), "dingtalk", util.UUIDToString(inst.ID), hex.EncodeToString(sum[:]))
+}
+
+func (m *mediaResolver) fetchResource(ctx context.Context, creds credentials, resource dingtalkMediaResource) ([]byte, string, error) {
+ data, contentType, primaryErr := m.fetchByCode(ctx, creds, resource.Ref)
+ if primaryErr == nil || resource.Alt == "" || resource.Alt == resource.Ref {
+ return data, contentType, primaryErr
+ }
+ data, contentType, fallbackErr := m.fetchByCode(ctx, creds, resource.Alt)
+ if fallbackErr == nil {
+ return data, contentType, nil
+ }
+ return nil, "", errors.Join(
+ fmt.Errorf("primary media reference: %w", primaryErr),
+ fmt.Errorf("fallback media reference: %w", fallbackErr),
+ )
+}
+
+func (m *mediaResolver) fetchByCode(ctx context.Context, creds credentials, code string) ([]byte, string, error) {
+ downloadURL, err := m.client.messageFileDownloadURL(ctx, creds.AppKey, creds.AppSecret, creds.RobotCode, code)
+ if err != nil {
+ return nil, "", fmt.Errorf("resolve download url: %w", err)
+ }
+ return m.fetchBytes(ctx, downloadURL)
+}
+
+func (m *mediaResolver) fetchBytes(ctx context.Context, rawURL string) ([]byte, string, error) {
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return nil, "", errors.New("invalid image download URL")
+ }
+ if err := validateDownloadURL(parsed); err != nil {
+ return nil, "", err
+ }
+ fetchCtx, cancel := context.WithTimeout(ctx, imageFetchTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(fetchCtx, http.MethodGet, parsed.String(), nil)
+ if err != nil {
+ return nil, "", errors.New("build image download request failed")
+ }
+ resp, err := m.fetch.Do(req)
+ if err != nil {
+ // net/http's *url.Error includes the full request URL. DingTalk download
+ // URLs are short-lived bearer credentials, so unwrap it before the caller
+ // logs the error and never persist the signed query string.
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) {
+ return nil, "", fmt.Errorf("download image request failed: %w", urlErr.Err)
+ }
+ return nil, "", errors.New("download image request failed")
+ }
+ defer func() { _ = resp.Body.Close() }()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, "", fmt.Errorf("download image: http %d", resp.StatusCode)
+ }
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxInboundImageBytes+1))
+ if err != nil {
+ return nil, "", fmt.Errorf("read image: %w", err)
+ }
+ if len(data) > maxInboundImageBytes {
+ return nil, "", fmt.Errorf("image exceeds the %d MB limit", maxInboundImageBytes>>20)
+ }
+ sniff := data
+ if len(sniff) > 512 {
+ sniff = sniff[:512]
+ }
+ contentType := http.DetectContentType(sniff)
+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {
+ contentType = strings.TrimSpace(contentType[:semi])
+ }
+ if _, ok := allowedImageTypes[contentType]; !ok {
+ return nil, "", fmt.Errorf("disallowed content type %q", contentType)
+ }
+ return data, contentType, nil
+}
+
+func validateDownloadURL(parsed *url.URL) error {
+ if parsed == nil || parsed.Host == "" || parsed.User != nil || parsed.Fragment != "" {
+ return errors.New("invalid image download URL shape")
+ }
+ if !strings.EqualFold(parsed.Scheme, "http") && !strings.EqualFold(parsed.Scheme, "https") {
+ return fmt.Errorf("invalid image download URL scheme %q", parsed.Scheme)
+ }
+ return nil
+}
+
+func (m *mediaResolver) logWarn(msg channel.InboundMessage, err error) {
+ m.logger.Warn("dingtalk media resolve skipped", "message_id", msg.MessageID, "error", err)
+}
diff --git a/server/internal/integrations/dingtalk/media_test.go b/server/internal/integrations/dingtalk/media_test.go
new file mode 100644
index 0000000000..58ac907fb7
--- /dev/null
+++ b/server/internal/integrations/dingtalk/media_test.go
@@ -0,0 +1,323 @@
+package dingtalk
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+var (
+ pngBytes = append([]byte{0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}, make([]byte, 64)...)
+ jpegBytes = append([]byte{0xFF, 0xD8, 0xFF, 0xE0}, make([]byte, 64)...)
+ svgBytes = []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`)
+)
+
+type fakeStorage struct {
+ mu sync.Mutex
+ uploads map[string][]byte
+}
+
+func newFakeStorage() *fakeStorage { return &fakeStorage{uploads: map[string][]byte{}} }
+
+func (f *fakeStorage) Upload(_ context.Context, key string, data []byte, _ string, _ string) (string, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.uploads[key] = append([]byte(nil), data...)
+ return f.ObjectURL(key), nil
+}
+func (f *fakeStorage) Delete(context.Context, string) {}
+func (f *fakeStorage) DeleteObject(context.Context, string) error { return nil }
+func (f *fakeStorage) DeleteKeys(context.Context, []string) {}
+func (f *fakeStorage) KeyFromURL(string) string { return "" }
+func (f *fakeStorage) ObjectURL(key string) string { return "https://cdn.example/" + key }
+func (f *fakeStorage) CdnDomain() string { return "" }
+func (f *fakeStorage) GetReader(context.Context, string) (io.ReadCloser, error) {
+ return nil, errors.New("not implemented")
+}
+
+type fakeLedger struct {
+ mu sync.Mutex
+ records []engine.RecordPendingMediaObjectParams
+}
+
+func (f *fakeLedger) RecordPendingMediaObject(_ context.Context, p engine.RecordPendingMediaObjectParams) (bool, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.records = append(f.records, p)
+ return true, nil
+}
+
+type mediaTestEnv struct {
+ resolver *mediaResolver
+ store *fakeStorage
+ ledger *fakeLedger
+ resolves *atomic.Int32
+}
+
+func newMediaTestEnv(t *testing.T, files map[string][]byte) *mediaTestEnv {
+ t.Helper()
+ var resolves atomic.Int32
+ fileHost := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ code := strings.TrimPrefix(r.URL.Path, "/f/")
+ data, ok := files[code]
+ if !ok {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ _, _ = w.Write(data)
+ }))
+ t.Cleanup(fileHost.Close)
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case accessTokenPath:
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ case messageFilesDownloadPath:
+ resolves.Add(1)
+ var body map[string]string
+ _ = json.NewDecoder(r.Body).Decode(&body)
+ code := body["downloadCode"]
+ if _, ok := files[code]; !ok {
+ w.WriteHeader(http.StatusBadRequest)
+ return
+ }
+ _, _ = fmt.Fprintf(w, `{"downloadUrl":%q}`, fileHost.URL+"/f/"+code)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(api.Close)
+ store := newFakeStorage()
+ ledger := &fakeLedger{}
+ resolver := NewMediaResolver(NewClient(nil, api.URL), nil, store, ledger, nil).(*mediaResolver)
+ resolver.fetch.Transport = fileHost.Client().Transport
+ return &mediaTestEnv{resolver: resolver, store: store, ledger: ledger, resolves: &resolves}
+}
+
+func mediaFixture(resources ...dingtalkMediaResource) (engine.ResolvedInstallation, pgtype.UUID, channel.InboundMessage) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "app-key",
+ RobotCode: "robot-1",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ var ws, instID, messageID pgtype.UUID
+ ws.Bytes[0], instID.Bytes[0], messageID.Bytes[0] = 0xAB, 0xCD, 0xEF
+ ws.Valid, instID.Valid, messageID.Valid = true, true, true
+ raw, _ := json.Marshal(dingtalkRawEvent{AppID: "app-key", Media: resources})
+ inst := engine.ResolvedInstallation{
+ ID: instID, WorkspaceID: ws,
+ Platform: db.ChannelInstallation{Config: cfg},
+ }
+ return inst, messageID, channel.InboundMessage{MessageID: "dt-msg", Type: channel.MsgTypeImage, Text: "[Image]", Raw: raw}
+}
+
+func TestMediaResolver_HappyPathAndIntentLedger(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"c1": pngBytes, "c2": jpegBytes})
+ inst, messageID, msg := mediaFixture(dingtalkMediaResource{Ref: "c1"}, dingtalkMediaResource{Ref: "c2"})
+ if !env.resolver.HasMedia(msg) {
+ t.Fatal("HasMedia=false")
+ }
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 2 {
+ t.Fatalf("media refs = %+v", got.MediaRefs)
+ }
+ if got.MediaRefs[0].MimeType != "image/png" || got.MediaRefs[1].MimeType != "image/jpeg" {
+ t.Fatalf("mime types = %q/%q", got.MediaRefs[0].MimeType, got.MediaRefs[1].MimeType)
+ }
+ if len(env.ledger.records) != 2 || len(env.store.uploads) != 2 {
+ t.Fatalf("intents/uploads = %d/%d", len(env.ledger.records), len(env.store.uploads))
+ }
+ for _, ref := range got.MediaRefs {
+ if !strings.HasPrefix(ref.StorageKey, "workspaces/ab000000-0000-0000-0000-000000000000/dingtalk/") {
+ t.Fatalf("unexpected storage key %q", ref.StorageKey)
+ }
+ }
+}
+
+func TestMediaResolver_AltFallback(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"alt": pngBytes})
+ inst, messageID, msg := mediaFixture(dingtalkMediaResource{Ref: "expired", Alt: "alt"})
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 1 || env.resolves.Load() != 2 {
+ t.Fatalf("refs/resolves = %d/%d", len(got.MediaRefs), env.resolves.Load())
+ }
+}
+
+func TestMediaResolver_AltFailurePreservesPrimaryError(t *testing.T) {
+ env := newMediaTestEnv(t, nil)
+ _, _, err := env.resolver.fetchResource(context.Background(), credentials{
+ AppKey: "app-key", AppSecret: "secret", RobotCode: "robot-1",
+ }, dingtalkMediaResource{Ref: "primary", Alt: "fallback"})
+ if err == nil || !strings.Contains(err.Error(), "primary media reference") || !strings.Contains(err.Error(), "fallback media reference") {
+ t.Fatalf("combined media error = %v", err)
+ }
+ if env.resolves.Load() != 2 {
+ t.Fatalf("resolve calls = %d, want 2", env.resolves.Load())
+ }
+}
+
+func TestMediaResolver_RejectsSVGButLeavesIntentForReconciler(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"svg": svgBytes})
+ inst, messageID, msg := mediaFixture(dingtalkMediaResource{Ref: "svg"})
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 0 || len(env.store.uploads) != 0 || len(env.ledger.records) != 1 {
+ t.Fatalf("refs/uploads/intents = %d/%d/%d", len(got.MediaRefs), len(env.store.uploads), len(env.ledger.records))
+ }
+}
+
+func TestMediaResolver_TooManyImagesSkipsNetwork(t *testing.T) {
+ env := newMediaTestEnv(t, nil)
+ resources := make([]dingtalkMediaResource, maxImagesPerMessage+1)
+ for i := range resources {
+ resources[i].Ref = fmt.Sprintf("c%d", i)
+ }
+ inst, messageID, msg := mediaFixture(resources...)
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 0 || env.resolves.Load() != 0 || len(env.ledger.records) != 0 {
+ t.Fatalf("unexpected work: refs=%d resolves=%d intents=%d", len(got.MediaRefs), env.resolves.Load(), len(env.ledger.records))
+ }
+}
+
+func TestMediaResolver_DownloadErrorDoesNotExposeSignedURL(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
+ client := server.Client()
+ server.Close()
+ resolver := &mediaResolver{fetch: client}
+ _, _, err := resolver.fetchBytes(context.Background(), server.URL+"/image?token=supersecret")
+ if err == nil {
+ t.Fatal("expected the closed server download to fail")
+ }
+ if strings.Contains(err.Error(), "supersecret") || strings.Contains(err.Error(), server.URL) {
+ t.Fatalf("download error leaked signed URL: %v", err)
+ }
+}
+
+func TestMediaResolver_AcceptsProviderIssuedHTTPURL(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(pngBytes)
+ }))
+ defer server.Close()
+ resolver := NewMediaResolver(nil, nil, nil, nil, nil).(*mediaResolver)
+ // Bypass the production public-network dialer only for this loopback test;
+ // fetchBytes still exercises the real URL validation and response handling.
+ resolver.fetch.Transport = server.Client().Transport
+ data, contentType, err := resolver.fetchBytes(context.Background(), server.URL+"/image?token=supersecret")
+ if err != nil || contentType != "image/png" || !bytes.Equal(data, pngBytes) {
+ t.Fatalf("HTTP download: type=%q bytes=%d err=%v", contentType, len(data), err)
+ }
+}
+
+func TestMediaResolver_RejectsUnsupportedDownloadURLScheme(t *testing.T) {
+ resolver := &mediaResolver{fetch: http.DefaultClient}
+ _, _, err := resolver.fetchBytes(context.Background(), "ftp://files.example/image?token=supersecret")
+ if err == nil || strings.Contains(err.Error(), "supersecret") || strings.Contains(err.Error(), "files.example") {
+ t.Fatalf("unsupported URL error = %v", err)
+ }
+}
+
+func TestMediaResolver_ProductionDialerBlocksLoopback(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(pngBytes)
+ }))
+ defer server.Close()
+ resolver := NewMediaResolver(nil, nil, nil, nil, nil).(*mediaResolver)
+ _, _, err := resolver.fetchBytes(context.Background(), server.URL+"/image?token=supersecret")
+ if err == nil || !strings.Contains(err.Error(), "blocked non-public download target") || strings.Contains(err.Error(), "supersecret") {
+ t.Fatalf("loopback download error = %v", err)
+ }
+}
+
+func TestIsPublicDownloadAddress(t *testing.T) {
+ tests := []struct {
+ address string
+ want bool
+ }{
+ {address: "8.8.8.8", want: true},
+ {address: "2606:4700:4700::1111", want: true},
+ {address: "64:ff9b::808:808", want: true},
+ {address: "127.0.0.1"},
+ {address: "10.0.0.1"},
+ {address: "169.254.169.254"},
+ {address: "100.64.0.1"},
+ {address: "192.0.2.1"},
+ {address: "::1"},
+ {address: "fd00::1"},
+ {address: "fe80::1"},
+ {address: "64:ff9b::7f00:1"},
+ {address: "64:ff9b:1::7f00:1"},
+ {address: "2001::ffff:7f00:1"},
+ {address: "2001:db8::1"},
+ {address: "2002:7f00:1::"},
+ }
+ for _, tc := range tests {
+ if got := isPublicDownloadAddress(netip.MustParseAddr(tc.address)); got != tc.want {
+ t.Errorf("isPublicDownloadAddress(%s) = %v, want %v", tc.address, got, tc.want)
+ }
+ }
+}
+
+func TestMediaResolver_RejectsCrossOriginHTTPRedirect(t *testing.T) {
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(pngBytes)
+ }))
+ defer target.Close()
+ source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+"/image?token=supersecret", http.StatusFound)
+ }))
+ defer source.Close()
+ resolver := NewMediaResolver(nil, nil, nil, nil, nil).(*mediaResolver)
+ resolver.fetch.Transport = source.Client().Transport
+ _, _, err := resolver.fetchBytes(context.Background(), source.URL+"/image")
+ if err == nil || !strings.Contains(err.Error(), "cross-origin HTTP") || strings.Contains(err.Error(), "supersecret") {
+ t.Fatalf("cross-origin redirect error = %v", err)
+ }
+}
+
+func TestMediaResolver_AllowsSameOriginHTTPRedirectWithoutReferer(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/start" {
+ http.Redirect(w, r, "/image", http.StatusFound)
+ return
+ }
+ if got := r.Header.Get("Referer"); got != "" {
+ t.Errorf("redirect leaked signed URL through Referer: %q", got)
+ }
+ _, _ = w.Write(pngBytes)
+ }))
+ defer server.Close()
+ resolver := NewMediaResolver(nil, nil, nil, nil, nil).(*mediaResolver)
+ resolver.fetch.Transport = server.Client().Transport
+ data, contentType, err := resolver.fetchBytes(context.Background(), server.URL+"/start?token=supersecret")
+ if err != nil || contentType != "image/png" || !bytes.Equal(data, pngBytes) {
+ t.Fatalf("same-origin redirect: type=%q bytes=%d err=%v", contentType, len(data), err)
+ }
+}
+
+func TestMediaResolver_RejectsHTTPSDowngradeRedirect(t *testing.T) {
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, "http://files.example/image?token=supersecret", http.StatusFound)
+ }))
+ defer server.Close()
+ resolver := NewMediaResolver(nil, nil, nil, nil, nil).(*mediaResolver)
+ resolver.fetch.Transport = server.Client().Transport
+ _, _, err := resolver.fetchBytes(context.Background(), server.URL+"/image")
+ if err == nil || strings.Contains(err.Error(), "supersecret") {
+ t.Fatalf("downgrade redirect error = %v", err)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/outbound.go b/server/internal/integrations/dingtalk/outbound.go
new file mode 100644
index 0000000000..62123b3bc7
--- /dev/null
+++ b/server/internal/integrations/dingtalk/outbound.go
@@ -0,0 +1,179 @@
+package dingtalk
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// outboundQueries is the slice of generated queries the DingTalk outbound
+// subscriber needs. *db.Queries satisfies it.
+type outboundQueries interface {
+ GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
+ TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
+ GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
+ GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
+}
+
+// Outbound delivers an agent's chat reply back to DingTalk — the outbound half
+// of the round trip. On EventChatDone / EventTaskFailed
+// it finds the DingTalk chat binding for the task's session and posts the reply
+// (or failure notice) into the originating conversation. Sessions with no
+// DingTalk binding are ignored, so it coexists with the Feishu and Slack
+// subscribers on the shared event bus. Registered only when DingTalk is
+// configured.
+type Outbound struct {
+ q outboundQueries
+ decrypt Decrypter
+ client *Client
+ logger *slog.Logger
+}
+
+// NewOutbound builds the DingTalk outbound subscriber over the generated queries,
+// the AppSecret decrypter, and the shared token-caching Client.
+func NewOutbound(q outboundQueries, decrypt Decrypter, client *Client, logger *slog.Logger) *Outbound {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ if client == nil {
+ client = NewClient(nil, "")
+ }
+ return &Outbound{q: q, decrypt: decrypt, client: client, logger: logger}
+}
+
+// Register subscribes to chat-done and task-failed. Task-failed keeps the DingTalk
+// conversation consistent with the web transcript — without it a failed run
+// leaves the user staring at the "👀 On it" ack forever.
+func (o *Outbound) Register(bus *events.Bus) {
+ bus.Subscribe(protocol.EventChatDone, o.handleEvent)
+ bus.Subscribe(protocol.EventTaskFailed, o.handleEvent)
+}
+
+func (o *Outbound) handleEvent(e events.Event) {
+ // Bus delivery is synchronous, so a stuck DingTalk HTTP call must not wedge
+ // the publish call site: use a fresh ctx with a tight timeout.
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ if err := o.processEvent(ctx, e); err != nil {
+ o.logger.WarnContext(ctx, "dingtalk outbound: reply delivery failed",
+ "error", err, "chat_session_id", e.ChatSessionID)
+ }
+}
+
+func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
+ taskID, sessionID, ok := taskAndSessionFromEvent(e)
+ if !ok || !sessionID.Valid {
+ // Issue / autopilot tasks carry no chat_session.
+ return nil
+ }
+ content := eventContent(e)
+ if content == "" {
+ return nil // nothing to say (empty completion, or a retry-pending failure)
+ }
+ binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
+ ChatSessionID: sessionID,
+ ChannelType: string(TypeDingTalk),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil // not a DingTalk session (Feishu / Slack / web-only)
+ }
+ return fmt.Errorf("lookup dingtalk chat binding: %w", err)
+ }
+ task, err := o.q.GetAgentTask(ctx, taskID)
+ if err != nil {
+ return fmt.Errorf("load agent task: %w", err)
+ }
+ deliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, task)
+ if err != nil {
+ return fmt.Errorf("classify task input origin: %w", err)
+ }
+ if !deliver {
+ return nil
+ }
+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
+ ID: binding.InstallationID,
+ ChannelType: string(TypeDingTalk),
+ })
+ if err != nil {
+ return fmt.Errorf("load dingtalk installation: %w", err)
+ }
+ if inst.Status != "active" {
+ return nil // revoked between trigger and reply
+ }
+ creds, err := decodeCredentials(inst.Config, o.decrypt)
+ if err != nil {
+ return fmt.Errorf("decode dingtalk credentials: %w", err)
+ }
+ s := &sender{client: o.client, robotCode: creds.RobotCode, appKey: creds.AppKey, appSecret: creds.AppSecret}
+ if _, err := s.send(ctx, outboundTarget(binding), content); err != nil {
+ return fmt.Errorf("post dingtalk reply: %w", err)
+ }
+ return nil
+}
+
+// eventContent extracts the deliverable text from an EventChatDone payload
+// (typed, or its map form after a serialization round trip) or an
+// EventTaskFailed payload. Empty means stay silent.
+//
+// For task-failed the text mirrors the web transcript's failure chat_message:
+// the broadcast's `error` field carries the same redacted failure text and is
+// omitted while an auto-retry is pending (the retry attempt reports its own
+// outcome), so error-present means deliverable.
+func eventContent(e events.Event) string {
+ switch p := e.Payload.(type) {
+ case protocol.ChatDonePayload:
+ return p.Content
+ case map[string]any:
+ if e.Type == protocol.EventTaskFailed {
+ if s, _ := p["error"].(string); s != "" {
+ return "⚠️ " + s
+ }
+ return ""
+ }
+ if s, ok := p["content"].(string); ok {
+ return s
+ }
+ }
+ return ""
+}
+
+func taskAndSessionFromEvent(e events.Event) (taskID, sessionID pgtype.UUID, ok bool) {
+ if e.TaskID != "" {
+ _ = taskID.Scan(e.TaskID)
+ }
+ if e.ChatSessionID != "" {
+ _ = sessionID.Scan(e.ChatSessionID)
+ }
+ switch p := e.Payload.(type) {
+ case protocol.ChatDonePayload:
+ if !taskID.Valid {
+ _ = taskID.Scan(p.TaskID)
+ }
+ if !sessionID.Valid {
+ _ = sessionID.Scan(p.ChatSessionID)
+ }
+ case map[string]any:
+ if !taskID.Valid {
+ if raw, _ := p["task_id"].(string); raw != "" {
+ _ = taskID.Scan(raw)
+ }
+ }
+ if !sessionID.Valid {
+ if raw, _ := p["chat_session_id"].(string); raw != "" {
+ _ = sessionID.Scan(raw)
+ }
+ }
+ }
+ return taskID, sessionID, taskID.Valid
+}
diff --git a/server/internal/integrations/dingtalk/outbound_send.go b/server/internal/integrations/dingtalk/outbound_send.go
new file mode 100644
index 0000000000..6b53fd3bb7
--- /dev/null
+++ b/server/internal/integrations/dingtalk/outbound_send.go
@@ -0,0 +1,122 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+)
+
+// This file is the OUTBOUND send path shared by the EventChatDone subscriber
+// (outbound.go) and the OutboundReplier (replier.go). It turns a reply body into
+// one or more DingTalk sampleMarkdown messages and posts them with the
+// installation's access_token, routing 1:1 vs group to the right robot endpoint.
+
+const (
+ // msgKeyMarkdown renders a {title, text} sampleMarkdown card.
+ msgKeyMarkdown = "sampleMarkdown"
+
+ // p2p (1:1) proactive send; group send.
+ pathSendP2P = "/v1.0/robot/oToMessages/batchSend"
+ pathSendGroup = "/v1.0/robot/groupMessages/send"
+)
+
+// sendTarget is the resolved DingTalk destination for a reply. ConversationType
+// selects the endpoint; StaffID is the recipient for a 1:1 send; ConversationID
+// is the group's openConversationId for a group send.
+type sendTarget struct {
+ ConversationType string
+ ConversationID string
+ StaffID string
+}
+
+// sender posts replies for one installation. The robotCode + credentials come
+// from the installation; the shared Client owns the token cache and transport.
+type sender struct {
+ client *Client
+ robotCode string
+ appKey string
+ appSecret string
+}
+
+// markdownParam is the msgParam payload for a sampleMarkdown message.
+type markdownParam struct {
+ Title string `json:"title"`
+ Text string `json:"text"`
+}
+
+// send delivers text to target as one or more sampleMarkdown messages (chunked
+// under DingTalk's per-message byte cap). It returns the last message's send
+// key. A 401 triggers one token refresh + retry, covering a server-side token
+// revocation between cache fill and use.
+func (s *sender) send(ctx context.Context, target sendTarget, text string) (string, error) {
+ if text == "" {
+ return "", nil
+ }
+ title := markdownTitle(text)
+ var lastKey string
+ for _, chunk := range chunkMarkdown(text) {
+ param, err := json.Marshal(markdownParam{Title: title, Text: chunk})
+ if err != nil {
+ return "", fmt.Errorf("marshal msgParam: %w", err)
+ }
+ key, err := s.sendOne(ctx, target, string(param))
+ if err != nil {
+ return "", err
+ }
+ lastKey = key
+ }
+ return lastKey, nil
+}
+
+// sendOne posts a single rendered message, refreshing the token once on 401.
+func (s *sender) sendOne(ctx context.Context, target sendTarget, msgParam string) (string, error) {
+ path, body, err := s.request(target, msgParam)
+ if err != nil {
+ return "", err
+ }
+ var resp struct {
+ ProcessQueryKey string `json:"processQueryKey"`
+ }
+ for attempt := 0; attempt < 2; attempt++ {
+ token, err := s.client.accessToken(ctx, s.appKey, s.appSecret)
+ if err != nil {
+ return "", fmt.Errorf("access token: %w", err)
+ }
+ err = s.client.postJSON(ctx, path, token, body, &resp)
+ if err == nil {
+ return resp.ProcessQueryKey, nil
+ }
+ if errors.Is(err, errUnauthorized) && attempt == 0 {
+ s.client.invalidate(s.appKey)
+ continue
+ }
+ return "", err
+ }
+ return "", errUnauthorized
+}
+
+// request builds the endpoint + body for a target. A 1:1 send needs a recipient
+// staff id; a group send needs the group's openConversationId.
+func (s *sender) request(target sendTarget, msgParam string) (string, map[string]any, error) {
+ if target.ConversationType == convTypeP2P {
+ if target.StaffID == "" {
+ return "", nil, errors.New("dingtalk: 1:1 send missing recipient staff id")
+ }
+ return pathSendP2P, map[string]any{
+ "robotCode": s.robotCode,
+ "userIds": []string{target.StaffID},
+ "msgKey": msgKeyMarkdown,
+ "msgParam": msgParam,
+ }, nil
+ }
+ if target.ConversationID == "" {
+ return "", nil, errors.New("dingtalk: group send missing conversation id")
+ }
+ return pathSendGroup, map[string]any{
+ "robotCode": s.robotCode,
+ "openConversationId": target.ConversationID,
+ "msgKey": msgKeyMarkdown,
+ "msgParam": msgParam,
+ }, nil
+}
diff --git a/server/internal/integrations/dingtalk/outbound_send_test.go b/server/internal/integrations/dingtalk/outbound_send_test.go
new file mode 100644
index 0000000000..3a8cabc559
--- /dev/null
+++ b/server/internal/integrations/dingtalk/outbound_send_test.go
@@ -0,0 +1,266 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// dingtalkSendServer stubs the access-token mint plus the two robot send
+// endpoints, recording the last send it saw.
+type dingtalkSendServer struct {
+ srv *httptest.Server
+ tokenCalls int32
+ lastPath string
+ lastBody map[string]any
+ // failFirstSendAuth makes the first send return 401 so the token-refresh
+ // retry path is exercised.
+ failFirstSendAuth bool
+ sendCalls int32
+}
+
+func newDingtalkSendServer(t *testing.T) *dingtalkSendServer {
+ t.Helper()
+ d := &dingtalkSendServer{}
+ d.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:
+ atomic.AddInt32(&d.tokenCalls, 1)
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ case pathSendP2P, pathSendGroup:
+ n := atomic.AddInt32(&d.sendCalls, 1)
+ if d.failFirstSendAuth && n == 1 {
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"code":"unauthorized","message":"token expired"}`))
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ d.lastPath = r.URL.Path
+ d.lastBody = map[string]any{}
+ _ = json.Unmarshal(body, &d.lastBody)
+ _, _ = w.Write([]byte(`{"processQueryKey":"pqk-1"}`))
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(d.srv.Close)
+ return d
+}
+
+func newTestSender(client *Client) *sender {
+ return &sender{client: client, robotCode: "robot-1", appKey: "ak", appSecret: "as"}
+}
+
+func TestSender_P2PSendHitsBatchSend(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ s := newTestSender(NewClient(nil, d.srv.URL))
+
+ key, err := s.send(context.Background(), sendTarget{ConversationType: convTypeP2P, ConversationID: "cid", StaffID: "staff-1"}, "hi")
+ if err != nil {
+ t.Fatalf("send: %v", err)
+ }
+ if key != "pqk-1" {
+ t.Errorf("key = %q, want pqk-1", key)
+ }
+ if d.lastPath != pathSendP2P {
+ t.Errorf("path = %q, want batchSend", d.lastPath)
+ }
+ if d.lastBody["robotCode"] != "robot-1" {
+ t.Errorf("robotCode = %v", d.lastBody["robotCode"])
+ }
+ if ids, ok := d.lastBody["userIds"].([]any); !ok || len(ids) != 1 || ids[0] != "staff-1" {
+ t.Errorf("userIds = %v", d.lastBody["userIds"])
+ }
+}
+
+func TestSender_GroupSendHitsGroupMessages(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ s := newTestSender(NewClient(nil, d.srv.URL))
+
+ if _, err := s.send(context.Background(), sendTarget{ConversationType: convTypeGroup, ConversationID: "cid-g"}, "hi"); err != nil {
+ t.Fatalf("send: %v", err)
+ }
+ if d.lastPath != pathSendGroup {
+ t.Errorf("path = %q, want groupMessages/send", d.lastPath)
+ }
+ if d.lastBody["openConversationId"] != "cid-g" {
+ t.Errorf("openConversationId = %v", d.lastBody["openConversationId"])
+ }
+}
+
+func TestSender_P2PWithoutStaffIDFails(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ s := newTestSender(NewClient(nil, d.srv.URL))
+ if _, err := s.send(context.Background(), sendTarget{ConversationType: convTypeP2P, ConversationID: "cid"}, "hi"); err == nil {
+ t.Error("a 1:1 send without a recipient staff id must fail")
+ }
+}
+
+func TestSender_RefreshesTokenOn401(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ d.failFirstSendAuth = true
+ s := newTestSender(NewClient(nil, d.srv.URL))
+
+ if _, err := s.send(context.Background(), sendTarget{ConversationType: convTypeGroup, ConversationID: "cid-g"}, "hi"); err != nil {
+ t.Fatalf("send should succeed after a token refresh: %v", err)
+ }
+ if got := atomic.LoadInt32(&d.tokenCalls); got != 2 {
+ t.Errorf("token fetched %d times, want 2 (initial + refresh on 401)", got)
+ }
+ if got := atomic.LoadInt32(&d.sendCalls); got != 2 {
+ t.Errorf("send attempted %d times, want 2 (401 then retry)", got)
+ }
+}
+
+func TestClient_CachesAccessToken(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ c := NewClient(nil, d.srv.URL)
+
+ for i := 0; i < 3; i++ {
+ if _, err := c.accessToken(context.Background(), "ak", "as"); err != nil {
+ t.Fatalf("accessToken: %v", err)
+ }
+ }
+ if got := atomic.LoadInt32(&d.tokenCalls); got != 1 {
+ t.Errorf("token fetched %d times, want 1 (cached)", got)
+ }
+ // After invalidation the next call refetches.
+ c.invalidate("ak")
+ if _, err := c.accessToken(context.Background(), "ak", "as"); err != nil {
+ t.Fatalf("accessToken after invalidate: %v", err)
+ }
+ if got := atomic.LoadInt32(&d.tokenCalls); got != 2 {
+ t.Errorf("token fetched %d times after invalidate, want 2", got)
+ }
+}
+
+func TestClient_RefreshesExpiredToken(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ c := NewClient(nil, d.srv.URL)
+ // Freeze time so we can step past the cached token's expiry deterministically.
+ base := time.Unix(1_700_000_000, 0)
+ cur := base
+ c.now = func() time.Time { return cur }
+
+ if _, err := c.accessToken(context.Background(), "ak", "as"); err != nil {
+ t.Fatalf("accessToken: %v", err)
+ }
+ // expireIn=7200s, margin=5m → cached ~7200-300s. Jump past it.
+ cur = base.Add(2 * time.Hour)
+ if _, err := c.accessToken(context.Background(), "ak", "as"); err != nil {
+ t.Fatalf("accessToken: %v", err)
+ }
+ if got := atomic.LoadInt32(&d.tokenCalls); got != 2 {
+ t.Errorf("token fetched %d times, want 2 (cache expired)", got)
+ }
+}
+
+func TestClient_AccessToken_SingleflightOnConcurrentMiss(t *testing.T) {
+ var tokenCalls int32
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != accessTokenPath {
+ http.Error(w, "unexpected path", http.StatusNotFound)
+ return
+ }
+ atomic.AddInt32(&tokenCalls, 1)
+ <-release // hold the mint open so concurrent callers pile into the flight
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ }))
+ defer srv.Close()
+
+ c := NewClient(nil, srv.URL)
+ const n = 8
+ var wg sync.WaitGroup
+ errs := make(chan error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, err := c.accessToken(context.Background(), "ak", "as"); err != nil {
+ errs <- err
+ }
+ }()
+ }
+ // Let every goroutine reach the singleflight before the mint completes: a
+ // missing singleflight would let each concurrent miss fire its own request.
+ time.Sleep(50 * time.Millisecond)
+ close(release)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Fatalf("accessToken: %v", err)
+ }
+ if got := atomic.LoadInt32(&tokenCalls); got != 1 {
+ t.Fatalf("concurrent cache misses minted %d tokens, want 1 (singleflight)", got)
+ }
+}
+
+func TestClient_AccessToken_CancelledCallerDoesNotCancelSharedMint(t *testing.T) {
+ var tokenCalls int32
+ started := make(chan struct{})
+ release := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != accessTokenPath {
+ http.Error(w, "unexpected path", http.StatusNotFound)
+ return
+ }
+ if atomic.AddInt32(&tokenCalls, 1) == 1 {
+ close(started)
+ }
+ <-release
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ }))
+ defer srv.Close()
+
+ c := NewClient(nil, srv.URL)
+ firstCtx, cancelFirst := context.WithCancel(context.Background())
+ firstDone := make(chan error, 1)
+ go func() {
+ _, err := c.accessToken(firstCtx, "ak", "as")
+ firstDone <- err
+ }()
+
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("shared mint did not start")
+ }
+
+ secondDone := make(chan error, 1)
+ go func() {
+ _, err := c.accessToken(context.Background(), "ak", "as")
+ secondDone <- err
+ }()
+
+ cancelFirst()
+ select {
+ case err := <-firstDone:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("first caller error = %v, want context.Canceled", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("cancelled caller stayed blocked on the shared mint")
+ }
+
+ close(release)
+ select {
+ case err := <-secondDone:
+ if err != nil {
+ t.Fatalf("second caller lost the shared mint: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("second caller did not receive the shared mint result")
+ }
+ if got := atomic.LoadInt32(&tokenCalls); got != 1 {
+ t.Fatalf("cancelled first caller caused %d token mints, want 1", got)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/outbound_test.go b/server/internal/integrations/dingtalk/outbound_test.go
new file mode 100644
index 0000000000..bdf2d3ec53
--- /dev/null
+++ b/server/internal/integrations/dingtalk/outbound_test.go
@@ -0,0 +1,48 @@
+package dingtalk
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+func TestEventContent(t *testing.T) {
+ cases := []struct {
+ name string
+ event events.Event
+ want string
+ }{
+ {"chat done typed", events.Event{Type: protocol.EventChatDone, Payload: protocol.ChatDonePayload{Content: "reply"}}, "reply"},
+ {"map round trip", events.Event{Type: protocol.EventChatDone, Payload: map[string]any{"content": "from map"}}, "from map"},
+ {"empty map", events.Event{Type: protocol.EventChatDone, Payload: map[string]any{}}, ""},
+ {"nil", events.Event{Type: protocol.EventChatDone}, ""},
+ {
+ "task failed with error",
+ events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"error": "task timed out", "retry_pending": false}},
+ "⚠️ task timed out",
+ },
+ {
+ // Failure broadcasts without an error text (a retry-pending
+ // failure — the publisher omits `error` then — or the reaper
+ // sweep) write no transcript message either — stay silent.
+ "task failed without error",
+ events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"failure_reason": "timeout", "retry_pending": true}},
+ "",
+ },
+ {
+ // task:failed payloads never carry "content"; it must not leak
+ // through the chat-done branch.
+ "task failed ignores content key",
+ events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"content": "not for delivery"}},
+ "",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := eventContent(tc.event); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/dingtalk/replier.go b/server/internal/integrations/dingtalk/replier.go
new file mode 100644
index 0000000000..0c00fa61ad
--- /dev/null
+++ b/server/internal/integrations/dingtalk/replier.go
@@ -0,0 +1,270 @@
+package dingtalk
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "strings"
+
+ "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"
+)
+
+// This file is the DingTalk OutboundReplier — the engine seam that delivers a
+// verdict-driven reply back to the user. It posts through the same sender as the
+// EventChatDone subscriber.
+//
+// Outcomes handled:
+// - NeedsBinding: the sender is unbound. Mint a single-use binding token and
+// reply with a "link your account" prompt pointing at the in-product redeem
+// page. After they bind, their next message reaches the agent.
+// - AgentOffline / AgentArchived: a status notice so the user is not left
+// wondering why nothing happened.
+// - Ingested with a synchronously-created /issue: a confirmation carrying the
+// issue identifier and title. Plain chat turns stay silent.
+
+const (
+ agentOfflineText = "⚠️ The agent is offline, so this message won't be processed automatically."
+ agentArchivedText = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."
+ // Refusals for dropped /issue commands, carried over from the deleted
+ // 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."
+)
+
+// bindingMinter is the binding-token surface the replier needs.
+// *BindingTokenService satisfies it.
+type bindingMinter interface {
+ Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, dingtalkUserID string) (BindingToken, error)
+}
+
+// OutboundReplier implements engine.OutboundReplier for DingTalk.
+type OutboundReplier struct {
+ binding bindingMinter
+ decrypt Decrypter
+ client *Client
+ appURL string
+ bindingPath string
+ logger *slog.Logger
+}
+
+// OutboundReplierConfig configures the replier. Binding + AppURL are required for
+// the NeedsBinding prompt to work; without them the prompt is skipped (the
+// offline/archived/issue notices still fire).
+type OutboundReplierConfig struct {
+ Binding bindingMinter
+ Decrypt Decrypter
+ Client *Client
+ // AppURL is the Multica web app host the user clicks into to redeem the
+ // binding token (e.g. https://multica.example). The bind page (/dingtalk/bind)
+ // is served by the web app, so the link must point at the app host, not the
+ // API host. Mirrors the Slack replier's AppURL.
+ AppURL string
+ BindingPath string // default "/dingtalk/bind"
+ Logger *slog.Logger
+}
+
+var _ engine.OutboundReplier = (*OutboundReplier)(nil)
+
+// NewOutboundReplier builds the replier.
+func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {
+ logger := cfg.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+ client := cfg.Client
+ if client == nil {
+ client = NewClient(nil, "")
+ }
+ bindingPath := cfg.BindingPath
+ if bindingPath == "" {
+ bindingPath = "/dingtalk/bind"
+ }
+ if !strings.HasPrefix(bindingPath, "/") {
+ bindingPath = "/" + bindingPath
+ }
+ return &OutboundReplier{
+ binding: cfg.Binding,
+ decrypt: cfg.Decrypt,
+ client: client,
+ appURL: strings.TrimRight(cfg.AppURL, "/"),
+ bindingPath: bindingPath,
+ logger: logger,
+ }
+}
+
+// Reply routes each outcome to its user-visible message. Errors are logged, not
+// propagated: the replier runs detached from the inbound ACK path.
+func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {
+ switch res.Outcome {
+ case engine.OutcomeNeedsBinding:
+ if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: binding prompt failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentOffline:
+ if err := r.post(ctx, inst, msg, agentOfflineText); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: offline notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeAgentArchived:
+ if err := r.post(ctx, inst, msg, agentArchivedText); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: archived notice failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ case engine.OutcomeIngested:
+ if res.IssueID.Valid {
+ text := issueCreatedText(res)
+ if res.IssueDuplicate {
+ text = issueDuplicateText(res)
+ }
+ if err := r.post(ctx, inst, msg, text); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: issue outcome reply failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ }
+ case engine.OutcomeDropped:
+ // Dropped /issue commands get a refusal so the sender is not left
+ // waiting for an issue that will never be created; every other drop
+ // (duplicates, unaddressed group chatter) stays silent.
+ if text := droppedReplyText(res, msg); text != "" {
+ if err := r.post(ctx, inst, msg, text); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: drop refusal failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
+ }
+ }
+}
+
+func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) error {
+ sender := res.Sender
+ if sender == "" {
+ sender = msg.Source.SenderID
+ }
+ if sender == "" {
+ return errors.New("missing sender id")
+ }
+ if r.binding == nil {
+ return errors.New("binding service not configured")
+ }
+ if r.appURL == "" {
+ return errors.New("app url not configured")
+ }
+ token, err := r.binding.Mint(ctx, inst.WorkspaceID, inst.ID, sender)
+ if err != nil {
+ return fmt.Errorf("mint binding token: %w", err)
+ }
+ bindURL := r.appURL + r.bindingPath + "?token=" + url.QueryEscape(token.Raw)
+ text := "👋 To start chatting with me, link your DingTalk account to Multica: [link your account](" +
+ bindURL + ")\n\n(This link expires in 15 minutes.)"
+ // Deliver the single-use binding link privately (1:1) to the sender, never
+ // via targetFromMessage: in a group that would post the token into the whole
+ // chat, where any other workspace member could redeem it and bind the
+ // sender's DingTalk id to their own account (identity misbinding).
+ target := sendTarget{ConversationType: convTypeP2P, StaffID: sender}
+ if _, err := sendInstallationText(ctx, r.client, r.decrypt, inst, target, text); err != nil {
+ return fmt.Errorf("post dingtalk binding prompt: %w", err)
+ }
+ return nil
+}
+
+// post resolves the installation's credentials from the carried platform row and
+// sends text back into the originating conversation.
+func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
+ if _, err := sendInstallationText(ctx, r.client, r.decrypt, inst, targetFromMessage(msg), text); err != nil {
+ return fmt.Errorf("post dingtalk reply: %w", err)
+ }
+ return nil
+}
+
+// sendInstallationText resolves an installation's credentials from the carried
+// platform row and sends text into target. Shared by the OutboundReplier and the
+// ack notifier so both proactive-send paths decode credentials identically.
+func sendInstallationText(ctx context.Context, client *Client, decrypt Decrypter, inst engine.ResolvedInstallation, target sendTarget, text string) (string, error) {
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ return "", errors.New("installation platform row unavailable")
+ }
+ creds, err := decodeCredentials(row.Config, decrypt)
+ if err != nil {
+ return "", fmt.Errorf("decode credentials: %w", err)
+ }
+ s := &sender{client: client, robotCode: creds.RobotCode, appKey: creds.AppKey, appSecret: creds.AppSecret}
+ return s.send(ctx, target, text)
+}
+
+// targetFromMessage builds the reply target from the inbound message's own
+// routing identity (used for the immediate binding/status replies, before any
+// chat binding exists).
+func targetFromMessage(msg channel.InboundMessage) sendTarget {
+ t := sendTarget{ConversationType: convTypeGroup, ConversationID: msg.Source.ChatID}
+ if msg.Source.ChatType == channel.ChatTypeP2P {
+ t.ConversationType = convTypeP2P
+ t.StaffID = msg.Source.SenderID
+ }
+ return t
+}
+
+// isAddressedIssueCommand reports whether msg is an /issue command explicitly
+// addressed to the bot — the gating the deleted pre-engine divert used. Only
+// such messages warrant an error/refusal reply: the sender asked for an
+// action, so silence would read as acceptance.
+func isAddressedIssueCommand(msg channel.InboundMessage) bool {
+ if !msg.AddressedToBot {
+ return false
+ }
+ source := msg.CommandText
+ if source == "" {
+ source = msg.Text
+ }
+ _, ok := engine.ParseIssueCommand(source)
+ return ok
+}
+
+// droppedReplyText maps an OutcomeDropped result to a user-facing refusal.
+func droppedReplyText(res engine.Result, msg channel.InboundMessage) string {
+ if !isAddressedIssueCommand(msg) {
+ return ""
+ }
+ switch res.DropReason {
+ case engine.DropReasonNonWorkspaceMember:
+ return issueNotMemberText
+ case engine.DropReasonRevokedInstallation:
+ return issueDisabledText
+ default:
+ return ""
+ }
+}
+
+func issueCreatedText(res engine.Result) string {
+ identifier := issueResultIdentifier(res)
+ if res.IssueTitle == "" {
+ return "✅ Created " + identifier
+ }
+ return "✅ Created " + identifier + " — " + res.IssueTitle
+}
+
+func issueDuplicateText(res engine.Result) string {
+ identifier := issueResultIdentifier(res)
+ if res.IssueTitle == "" {
+ return "⚠️ Not created — active issue " + identifier + " already exists."
+ }
+ return "⚠️ Not created — active issue " + identifier + " already exists: " + res.IssueTitle
+}
+
+func issueResultIdentifier(res engine.Result) string {
+ if res.IssueIdentifier != "" {
+ return res.IssueIdentifier
+ }
+ if res.IssueNumber > 0 {
+ return fmt.Sprintf("#%d", res.IssueNumber)
+ }
+ return util.UUIDToString(res.IssueID)
+}
diff --git a/server/internal/integrations/dingtalk/replier_test.go b/server/internal/integrations/dingtalk/replier_test.go
new file mode 100644
index 0000000000..eb39f903f0
--- /dev/null
+++ b/server/internal/integrations/dingtalk/replier_test.go
@@ -0,0 +1,63 @@
+package dingtalk
+
+import (
+ "testing"
+
+ "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"
+)
+
+func TestIssueCreatedText(t *testing.T) {
+ issueID := pgtype.UUID{Valid: true}
+ if got := issueCreatedText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-42", IssueTitle: "Fix login"}); got != "✅ Created MUL-42 — Fix login" {
+ t.Fatalf("got %q", got)
+ }
+ if got := issueCreatedText(engine.Result{IssueID: issueID, IssueNumber: 7}); got != "✅ Created #7" {
+ t.Fatalf("fallback got %q", got)
+ }
+}
+
+func TestIssueDuplicateText(t *testing.T) {
+ issueID := pgtype.UUID{Bytes: [16]byte{9}, Valid: true}
+ got := issueDuplicateText(engine.Result{
+ IssueID: issueID, IssueIdentifier: "MUL-42", IssueTitle: "Fix login", IssueDuplicate: true,
+ })
+ if got != "⚠️ Not created — active issue MUL-42 already exists: Fix login" {
+ t.Fatalf("duplicate text = %q", got)
+ }
+}
+
+func TestDroppedReplyText(t *testing.T) {
+ issueMsg := channel.InboundMessage{Text: "[Image]", CommandText: "/issue login is broken", AddressedToBot: true}
+ cases := []struct {
+ name string
+ res engine.Result
+ msg channel.InboundMessage
+ want string
+ }{
+ {"non-member /issue gets refusal",
+ engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember},
+ issueMsg, issueNotMemberText},
+ {"revoked installation /issue gets disconnected notice",
+ engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonRevokedInstallation},
+ issueMsg, issueDisabledText},
+ {"duplicate /issue stays silent",
+ engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonDuplicate},
+ issueMsg, ""},
+ {"non-member plain chat stays silent",
+ engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember},
+ channel.InboundMessage{Text: "hello", AddressedToBot: true}, ""},
+ {"unaddressed group /issue stays silent",
+ engine.Result{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember},
+ channel.InboundMessage{Text: "/issue x", AddressedToBot: false}, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := droppedReplyText(tc.res, tc.msg); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
new file mode 100644
index 0000000000..ed67eb43db
--- /dev/null
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -0,0 +1,296 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// originDingTalkChat is the issue.origin_type label for issues created through
+// the DingTalk /issue command. Keep it aligned with the database CHECK
+// constraint, like the existing lark_chat and slack_chat channel origins.
+const originDingTalkChat = "dingtalk_chat"
+
+// This file is the DingTalk ResolverSet: the platform-specific seams the
+// channel-agnostic engine.Router runs the inbound pipeline through. It is built
+// entirely on the generic channel_* queries plus the shared engine.ChatSession,
+// mirroring the Feishu and Slack ResolverSets.
+
+// NewDingTalkResolverSet assembles the DingTalk ResolverSet over the generated
+// queries + a tx starter (for the shared session service). The replier delivers
+// the outbound binding-prompt / status / issue-created notices; pass a nil
+// engine.OutboundReplier to disable them. The classic robot send API exposes no
+// 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 {
+ set := engine.ResolverSet{
+ Installation: &installationResolver{q: q},
+ Identity: &identityResolver{q: q},
+ Dedup: &deduper{q: q},
+ Session: &sessionBinder{session: engine.NewChatSession(q, tx, TypeDingTalk, engine.SessionTitles{
+ Group: "DingTalk group",
+ Direct: "DingTalk direct message",
+ Fallback: "DingTalk chat",
+ })},
+ Audit: &auditor{q: q},
+ Replier: replier,
+ OriginType: originDingTalkChat,
+ }
+ // Guard against assigning a nil *ackNotifier into the interface field (which
+ // would make set.Typing a non-nil typed-nil); mirrors Slack/Feishu.
+ if ack != nil {
+ set.Typing = ack
+ }
+ if media != nil {
+ set.Media = media
+ }
+ return set
+}
+
+var (
+ _ 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
+// binding's config: enough to address a proactive reply back into the
+// originating conversation. StaffID is the lone recipient of a 1:1 chat; for a
+// group it is empty (the group is addressed by its conversation id).
+type dingtalkBindingConfig struct {
+ ConversationType string `json:"conversation_type"`
+ ConversationID string `json:"conversation_id"`
+ StaffID string `json:"staff_id,omitempty"`
+}
+
+// dingtalkSessionRouting derives the session-isolation key and the outbound
+// routing config from one inbound message. DingTalk has no threads, so a
+// conversation (1:1 or group) is one continuous session keyed by its
+// conversation id; the config carries everything the outbound path needs to send
+// back.
+func dingtalkSessionRouting(msg channel.InboundMessage) (bindingKey string, config []byte) {
+ chatID := msg.Source.ChatID
+ cfg := dingtalkBindingConfig{
+ ConversationType: convTypeGroup,
+ ConversationID: chatID,
+ }
+ if msg.Source.ChatType == channel.ChatTypeP2P {
+ cfg.ConversationType = convTypeP2P
+ cfg.StaffID = msg.Source.SenderID
+ }
+ raw, _ := json.Marshal(cfg)
+ return chatID, raw
+}
+
+// outboundTarget recovers the send target from a chat binding's config, falling
+// back to the channel_chat_id when the config is missing or unparsable.
+func outboundTarget(b db.ChannelChatSessionBinding) sendTarget {
+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: b.ChannelChatID}
+ if len(b.Config) > 0 {
+ var cfg dingtalkBindingConfig
+ if err := json.Unmarshal(b.Config, &cfg); err == nil {
+ if cfg.ConversationType != "" {
+ target.ConversationType = cfg.ConversationType
+ }
+ if cfg.ConversationID != "" {
+ target.ConversationID = cfg.ConversationID
+ }
+ target.StaffID = cfg.StaffID
+ }
+ }
+ return target
+}
+
+func decodeDingTalkRaw(msg channel.InboundMessage) (dingtalkRawEvent, error) {
+ var raw dingtalkRawEvent
+ if len(msg.Raw) == 0 {
+ return dingtalkRawEvent{}, errors.New("dingtalk: inbound message Raw is empty")
+ }
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ return dingtalkRawEvent{}, fmt.Errorf("decode dingtalk inbound raw: %w", err)
+ }
+ return raw, nil
+}
+
+func nullText(s string) pgtype.Text {
+ if s == "" {
+ return pgtype.Text{}
+ }
+ return pgtype.Text{String: s, Valid: true}
+}
+
+// ---- installation routing ----
+
+type installationResolver struct{ q *db.Queries }
+
+func (r *installationResolver) ResolveInstallation(ctx context.Context, msg channel.InboundMessage) (engine.ResolvedInstallation, error) {
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil {
+ return engine.ResolvedInstallation{}, err
+ }
+ // Route by the AppKey the receiving connection stamped into the envelope.
+ // Each installation has its own Stream connection, so the stamped AppKey
+ // uniquely identifies the installation (the DingTalk callback itself carries
+ // no robot code).
+ inst, err := r.q.GetChannelInstallationByAppID(ctx, db.GetChannelInstallationByAppIDParams{
+ ChannelType: string(TypeDingTalk),
+ AppID: raw.AppID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedInstallation{}, engine.ErrInstallationNotFound
+ }
+ return engine.ResolvedInstallation{}, err
+ }
+ return engine.ResolvedInstallation{
+ ID: inst.ID,
+ WorkspaceID: inst.WorkspaceID,
+ AgentID: inst.AgentID,
+ InstallerUserID: inst.InstallerUserID,
+ Active: inst.Status == "active",
+ Platform: inst,
+ }, nil
+}
+
+// ---- identity ----
+
+type identityResolver struct{ q *db.Queries }
+
+func (r *identityResolver) ResolveSender(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage) (engine.ResolvedIdentity, error) {
+ binding, err := r.q.GetChannelUserBindingByUserID(ctx, db.GetChannelUserBindingByUserIDParams{
+ InstallationID: inst.ID,
+ ChannelUserID: msg.Source.SenderID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderUnbound
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ // Binding existence no longer proves membership (no FK); re-check.
+ if _, err := r.q.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: binding.MulticaUserID,
+ WorkspaceID: inst.WorkspaceID,
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return engine.ResolvedIdentity{}, engine.ErrSenderNotMember
+ }
+ return engine.ResolvedIdentity{}, err
+ }
+ return engine.ResolvedIdentity{UserID: binding.MulticaUserID}, nil
+}
+
+// ---- dedup ----
+
+type deduper struct{ q *db.Queries }
+
+func (r *deduper) Claim(ctx context.Context, installationID pgtype.UUID, messageID string) (pgtype.UUID, error) {
+ claim, err := r.q.ClaimChannelInboundDedup(ctx, db.ClaimChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return pgtype.UUID{}, engine.ErrDuplicate
+ }
+ return pgtype.UUID{}, err
+ }
+ return claim.ClaimToken, nil
+}
+
+func (r *deduper) Mark(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messageID string, claimToken pgtype.UUID) error {
+ _, err := r.q.ReleaseChannelInboundDedup(ctx, db.ReleaseChannelInboundDedupParams{
+ InstallationID: installationID,
+ MessageID: messageID,
+ ClaimToken: claimToken,
+ })
+ return err
+}
+
+// ---- session bind / append ----
+
+type chatSession interface {
+ EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+ BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
+}
+
+type sessionBinder struct{ session chatSession }
+
+func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessionParams) (pgtype.UUID, error) {
+ bindingKey, config := dingtalkSessionRouting(p.Message)
+ return r.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID,
+ AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID,
+ Sender: p.Sender,
+ BindingKey: bindingKey,
+ BindingConfig: config,
+ ChatType: p.Message.Source.ChatType,
+ })
+}
+
+func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {
+ commandText := p.Message.CommandText
+ if commandText == "" {
+ commandText = p.Message.Text
+ }
+ return r.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ CommandText: commandText,
+ MessageID: p.Message.MessageID,
+ ThreadID: p.Message.Source.ThreadID,
+ ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ })
+}
+
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
+ return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ MediaRefs: p.MediaRefs,
+ })
+}
+
+// ---- audit ----
+
+type auditor struct{ q *db.Queries }
+
+func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channel.InboundMessage, reason engine.DropReason) error {
+ return r.q.RecordChannelInboundDrop(ctx, db.RecordChannelInboundDropParams{
+ ChannelType: string(TypeDingTalk),
+ EventType: "message",
+ DropReason: string(reason),
+ InstallationID: instID,
+ ChannelChatID: nullText(msg.Source.ChatID),
+ ChannelEventID: nullText(msg.EventID),
+ ChannelMessageID: nullText(msg.MessageID),
+ })
+}
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
new file mode 100644
index 0000000000..f00f6ea7f1
--- /dev/null
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -0,0 +1,108 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type captureChatSession struct{ append engine.AppendInput }
+
+func (c *captureChatSession) EnsureSession(context.Context, engine.EnsureSessionInput) (pgtype.UUID, error) {
+ return pgtype.UUID{}, nil
+}
+func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
+ c.append = in
+ return engine.AppendResult{}, nil
+}
+func (c *captureChatSession) BindMediaRefs(context.Context, engine.BindMediaInput) error { return nil }
+
+func TestNewDingTalkResolverSetUsesDatabaseBackedIssueOrigin(t *testing.T) {
+ set := NewDingTalkResolverSet(nil, nil, nil, nil, nil)
+ if set.OriginType != originDingTalkChat {
+ t.Fatalf("OriginType = %q, want %q", set.OriginType, originDingTalkChat)
+ }
+}
+
+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",
+ },
+ })
+ 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.SessionID != session || in.Sender != sender || in.InstallationID != inst || in.ClaimToken != claim {
+ t.Fatalf("mapped append input = %+v", in)
+ }
+}
+
+func TestDingTalkSessionRouting_P2PCarriesStaffID(t *testing.T) {
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-1",
+ ChatType: channel.ChatTypeP2P,
+ SenderID: "staff-7",
+ }}
+ key, cfg := dingtalkSessionRouting(msg)
+ if key != "cid-1" {
+ t.Errorf("binding key = %q, want conversation id", key)
+ }
+ var dc dingtalkBindingConfig
+ if err := json.Unmarshal(cfg, &dc); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if dc.ConversationType != convTypeP2P || dc.ConversationID != "cid-1" || dc.StaffID != "staff-7" {
+ t.Errorf("p2p config = %+v", dc)
+ }
+}
+
+func TestDingTalkSessionRouting_GroupOmitsStaffID(t *testing.T) {
+ msg := channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-2",
+ ChatType: channel.ChatTypeGroup,
+ SenderID: "staff-7",
+ }}
+ _, cfg := dingtalkSessionRouting(msg)
+ var dc dingtalkBindingConfig
+ _ = json.Unmarshal(cfg, &dc)
+ if dc.ConversationType != convTypeGroup || dc.StaffID != "" {
+ t.Errorf("group config must omit staff id: %+v", dc)
+ }
+}
+
+func TestOutboundTarget_RoundTripsBindingConfig(t *testing.T) {
+ _, cfg := dingtalkSessionRouting(channel.InboundMessage{Source: channel.Source{
+ ChatID: "cid-3",
+ ChatType: channel.ChatTypeP2P,
+ SenderID: "staff-3",
+ }})
+ 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)
+ }
+}
+
+func TestOutboundTarget_FallsBackToChatID(t *testing.T) {
+ target := outboundTarget(db.ChannelChatSessionBinding{ChannelChatID: "cid-4"})
+ if target.ConversationType != convTypeGroup || target.ConversationID != "cid-4" {
+ t.Errorf("missing config must fall back to a group send on chat id: %+v", target)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/token.go b/server/internal/integrations/dingtalk/token.go
new file mode 100644
index 0000000000..fdb009d599
--- /dev/null
+++ b/server/internal/integrations/dingtalk/token.go
@@ -0,0 +1,198 @@
+package dingtalk
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/sync/singleflight"
+)
+
+// This file is the outbound DingTalk Open-API client: an access_token cache plus
+// a JSON POST helper. DingTalk's access_token expires (~2h), unlike Slack's
+// static bot token, so it is cached in-process keyed by AppKey and refreshed
+// before expiry — the same shape as Feishu's tenant_access_token cache.
+
+// tokenSafetyMargin is subtracted from DingTalk's expireIn so a token is
+// refreshed before it actually expires, absorbing clock skew and in-flight use.
+const tokenSafetyMargin = 5 * time.Minute
+
+// tokenMintTimeout bounds the shared mint independently of any one caller.
+// Callers may abandon their own wait without cancelling the request every other
+// caller for the same AppKey is sharing through singleflight.
+const tokenMintTimeout = 10 * time.Second
+
+// Client caches access_tokens and posts robot messages. One instance is shared
+// across installations; the cache is keyed by AppKey so each installation's
+// token is independent. Safe for concurrent use.
+type Client struct {
+ httpClient *http.Client
+ apiBase string
+ now func() time.Time
+
+ mu sync.Mutex
+ tokens map[string]cachedToken
+
+ // minting collapses concurrent cache misses for the same AppKey into a
+ // single in-flight token request.
+ minting singleflight.Group
+}
+
+type cachedToken struct {
+ value string
+ expiresAt time.Time
+}
+
+// NewClient builds the outbound client. apiBase defaults to the DingTalk
+// Open-API host; tests point it at an httptest server.
+func NewClient(httpClient *http.Client, apiBase string) *Client {
+ if httpClient == nil {
+ httpClient = http.DefaultClient
+ }
+ if apiBase == "" {
+ apiBase = defaultAPIBase
+ }
+ return &Client{
+ httpClient: httpClient,
+ apiBase: strings.TrimRight(apiBase, "/"),
+ now: time.Now,
+ tokens: map[string]cachedToken{},
+ }
+}
+
+// accessToken returns a usable access_token for (appKey, appSecret), minting and
+// caching one when the cache is empty or stale.
+func (c *Client) accessToken(ctx context.Context, appKey, appSecret string) (string, error) {
+ if t, ok := c.cachedToken(appKey); ok {
+ return t, nil
+ }
+
+ // Collapse concurrent misses for the same AppKey into one mint: a burst of
+ // outbound sends (ack + reply) sharing an expired token would otherwise each
+ // fire a redundant token request and race to overwrite the cache. DingTalk
+ // rate-limits token issuance, so the fan-in also avoids tripping that limit.
+ result := c.minting.DoChan(appKey, func() (any, error) {
+ // A mint that finished while we queued behind the flight already
+ // refreshed the cache; reuse it instead of fetching again.
+ if t, ok := c.cachedToken(appKey); ok {
+ return t, nil
+ }
+ mintCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), tokenMintTimeout)
+ defer cancel()
+ token, expireIn, err := fetchAccessToken(mintCtx, c.httpClient, c.apiBase, appKey, appSecret)
+ if err != nil {
+ return "", err
+ }
+ ttl := time.Duration(expireIn) * time.Second
+ if ttl < tokenSafetyMargin*2 {
+ ttl = tokenSafetyMargin * 2
+ }
+ c.mu.Lock()
+ c.tokens[appKey] = cachedToken{value: token, expiresAt: c.now().Add(ttl - tokenSafetyMargin)}
+ c.mu.Unlock()
+ return token, nil
+ })
+ select {
+ case <-ctx.Done():
+ return "", ctx.Err()
+ case res := <-result:
+ if res.Err != nil {
+ return "", res.Err
+ }
+ return res.Val.(string), nil
+ }
+}
+
+// cachedToken returns the cached token for appKey if present and unexpired.
+func (c *Client) cachedToken(appKey string) (string, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if t, ok := c.tokens[appKey]; ok && t.expiresAt.After(c.now()) {
+ return t.value, true
+ }
+ return "", false
+}
+
+// invalidate drops the cached token for appKey so the next accessToken call
+// refreshes. Used after the API reports an expired/invalid token (HTTP 401).
+func (c *Client) invalidate(appKey string) {
+ c.mu.Lock()
+ delete(c.tokens, appKey)
+ c.mu.Unlock()
+}
+
+// messageFileDownloadURL resolves a robot-received message's downloadCode to
+// its temporary download URL via POST /v1.0/robot/messageFiles/download. It
+// refreshes the cached token once on a 401 (mirroring sender.sendOne). The
+// returned URL is a short-lived signed link — fetch it immediately.
+func (c *Client) messageFileDownloadURL(ctx context.Context, appKey, appSecret, robotCode, downloadCode string) (string, error) {
+ body := map[string]string{"robotCode": robotCode, "downloadCode": downloadCode}
+ var out messageFileDownloadResponse
+ token, err := c.accessToken(ctx, appKey, appSecret)
+ if err != nil {
+ return "", err
+ }
+ err = c.postJSON(ctx, messageFilesDownloadPath, 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, messageFilesDownloadPath, token, body, &out)
+ }
+ if err != nil {
+ return "", err
+ }
+ if out.DownloadUrl == "" {
+ return "", fmt.Errorf("dingtalk: messageFiles/download returned empty downloadUrl")
+ }
+ return out.DownloadUrl, nil
+}
+
+// postJSON posts body to path with the access token header and decodes a 2xx
+// response into out (out may be nil to ignore the body). It returns
+// errUnauthorized on HTTP 401 so the caller can refresh the token and retry.
+func (c *Client) postJSON(ctx context.Context, path, accessToken string, body, out any) error {
+ reqBody, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("dingtalk: marshal request: %w", err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.apiBase+path, bytes.NewReader(reqBody))
+ if err != nil {
+ return fmt.Errorf("dingtalk: build request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("x-acs-dingtalk-access-token", accessToken)
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("dingtalk: request %s: %w", path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+ respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+
+ if resp.StatusCode == http.StatusUnauthorized {
+ return errUnauthorized
+ }
+ if 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 fmt.Errorf("dingtalk: %s: http %d", path, resp.StatusCode)
+ }
+ if out != nil && len(respBody) > 0 {
+ if err := json.Unmarshal(respBody, out); err != nil {
+ return fmt.Errorf("dingtalk: decode %s response: %w", path, err)
+ }
+ }
+ return nil
+}
diff --git a/server/internal/integrations/dingtalk/ws_connector.go b/server/internal/integrations/dingtalk/ws_connector.go
new file mode 100644
index 0000000000..3c1d5b3b19
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_connector.go
@@ -0,0 +1,226 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// This file hand-rolls the DingTalk Stream WebSocket connection, replacing the
+// vendor stream SDK. It mirrors the Lark ws_connector: a single blocking run()
+// owns exactly one socket session. Reconnect/backoff/lease live in the shared
+// engine.Supervisor, so run() just returns — nil on a graceful close, an error
+// on a broken connection — and the supervisor decides when to redial.
+
+const (
+ streamPingInterval = 30 * time.Second
+ streamReadDeadline = 90 * time.Second
+ streamWriteTimeout = 10 * time.Second
+)
+
+// wsConn is the slice of *websocket.Conn the connector uses, extracted so tests
+// can inject a fake in-memory socket.
+type wsConn interface {
+ ReadMessage() (messageType int, p []byte, err error)
+ WriteMessage(messageType int, data []byte) error
+ WriteControl(messageType int, data []byte, deadline time.Time) error
+ SetReadDeadline(t time.Time) error
+ SetWriteDeadline(t time.Time) error
+ SetPongHandler(h func(appData string) error)
+ Close() error
+}
+
+// wsDialer opens a wsConn for a dial URL. The production dialer wraps gorilla;
+// tests inject a fake.
+type wsDialer interface {
+ dial(ctx context.Context, dialURL string) (wsConn, error)
+}
+
+type gorillaDialer struct{}
+
+func (gorillaDialer) dial(ctx context.Context, dialURL string) (wsConn, error) {
+ conn, _, err := websocket.DefaultDialer.DialContext(ctx, dialURL, nil)
+ if err != nil {
+ return nil, err
+ }
+ return conn, nil
+}
+
+// wsConnector runs one installation's Stream session.
+type wsConnector struct {
+ httpClient *http.Client
+ apiBase string
+ appKey string
+ appSecret string
+
+ dialer wsDialer
+ open func(ctx context.Context) (string, error) // dial-URL fetch; defaults to openConnection
+ onMessage func(ctx context.Context, data *botCallbackData) error
+ logger *slog.Logger
+
+ pingInterval time.Duration
+ readDeadline time.Duration
+ writeTimeout time.Duration
+}
+
+func (c *wsConnector) withDefaults() {
+ if c.dialer == nil {
+ c.dialer = gorillaDialer{}
+ }
+ if c.open == nil {
+ c.open = func(ctx context.Context) (string, error) {
+ return openConnection(ctx, c.httpClient, c.apiBase, c.appKey, c.appSecret)
+ }
+ }
+ if c.logger == nil {
+ c.logger = slog.Default()
+ }
+ if c.pingInterval == 0 {
+ c.pingInterval = streamPingInterval
+ }
+ if c.readDeadline == 0 {
+ c.readDeadline = streamReadDeadline
+ }
+ if c.writeTimeout == 0 {
+ c.writeTimeout = streamWriteTimeout
+ }
+}
+
+// run opens the connection and services frames until ctx is cancelled (returns
+// nil), the gateway sends a SYSTEM disconnect (returns nil), or the socket
+// breaks (returns the error, so the supervisor reconnects under backoff).
+func (c *wsConnector) run(ctx context.Context) error {
+ c.withDefaults()
+
+ dialURL, err := c.open(ctx)
+ if err != nil {
+ return fmt.Errorf("dingtalk stream: open connection: %w", err)
+ }
+ conn, err := c.dialer.dial(ctx, dialURL)
+ if err != nil {
+ // dialURL carries the single-use Stream ticket. Dialer errors may echo
+ // their input URL, so do not wrap them into the supervisor/log path.
+ return fmt.Errorf("dingtalk stream: dial failed (%T)", err)
+ }
+
+ runCtx, cancel := context.WithCancel(ctx)
+
+ var closeOnce sync.Once
+ closeConn := func() { closeOnce.Do(func() { _ = conn.Close() }) }
+
+ var writeMu sync.Mutex
+ writeResponse := func(resp dataFrameResponse) error {
+ b, err := json.Marshal(resp)
+ if err != nil {
+ return err
+ }
+ writeMu.Lock()
+ defer writeMu.Unlock()
+ _ = conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
+ return conn.WriteMessage(websocket.TextMessage, b)
+ }
+
+ done := make(chan struct{})
+ // Watchdog: gorilla's ReadMessage does not observe ctx, so closing the socket
+ // is what unblocks a read stuck in the syscall when the run ctx is cancelled.
+ go func() {
+ select {
+ case <-runCtx.Done():
+ closeConn()
+ case <-done:
+ }
+ }()
+
+ pingDone := make(chan struct{})
+ go func() {
+ defer close(pingDone)
+ ticker := time.NewTicker(c.pingInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-runCtx.Done():
+ return
+ case <-ticker.C:
+ writeMu.Lock()
+ err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(c.writeTimeout))
+ writeMu.Unlock()
+ if err != nil {
+ return // the read loop owns teardown
+ }
+ }
+ }
+ }()
+
+ conn.SetPongHandler(func(string) error {
+ return conn.SetReadDeadline(time.Now().Add(c.readDeadline))
+ })
+
+ defer func() {
+ cancel()
+ closeConn()
+ close(done)
+ <-pingDone
+ }()
+
+ for {
+ if err := conn.SetReadDeadline(time.Now().Add(c.readDeadline)); err != nil {
+ return fmt.Errorf("dingtalk stream: set read deadline: %w", err)
+ }
+ msgType, data, err := conn.ReadMessage()
+ if err != nil {
+ if runCtx.Err() != nil {
+ return nil // ctx cancelled → graceful stop
+ }
+ return fmt.Errorf("dingtalk stream: read: %w", err)
+ }
+ if msgType != websocket.TextMessage {
+ continue
+ }
+ var frame dataFrame
+ if err := json.Unmarshal(data, &frame); err != nil {
+ c.logger.WarnContext(runCtx, "dingtalk stream: malformed frame", "error", err)
+ continue
+ }
+
+ switch {
+ case frame.Type == frameTypeSystem && frame.topic() == systemTopicPing:
+ if err := writeResponse(newPongResponse(frame.messageID(), frame.Data)); err != nil {
+ if runCtx.Err() != nil {
+ return nil
+ }
+ return fmt.Errorf("dingtalk stream: write pong: %w", err)
+ }
+ case frame.Type == frameTypeSystem && frame.topic() == systemTopicDisconnect:
+ // Gateway asks us to reconnect; return cleanly and let the supervisor redial.
+ return nil
+ case frame.Type == frameTypeCallback && frame.topic() == botMessageTopic:
+ c.dispatchCallback(runCtx, &frame, writeResponse)
+ default:
+ c.logger.WarnContext(runCtx, "dingtalk stream: unhandled frame",
+ "type", frame.Type, "topic", frame.topic())
+ }
+ }
+}
+
+// dispatchCallback decodes a bot-message callback, hands it to onMessage, and
+// always ACKs (echoing the frame's messageId). A decode or handler error is
+// logged, never surfaced: DingTalk expires un-ACKed frames fast and the engine's
+// (installation, msgId) dedup guards any redelivery — matching the prior SDK
+// callback's always-ACK behavior.
+func (c *wsConnector) dispatchCallback(ctx context.Context, frame *dataFrame, writeResponse func(dataFrameResponse) error) {
+ var payload botCallbackData
+ if err := json.Unmarshal([]byte(frame.Data), &payload); err != nil {
+ c.logger.WarnContext(ctx, "dingtalk stream: decode callback", "error", err)
+ } else if err := c.onMessage(ctx, &payload); err != nil {
+ c.logger.WarnContext(ctx, "dingtalk stream: handler error", "error", err)
+ }
+ if err := writeResponse(newAckResponse(frame.messageID())); err != nil {
+ c.logger.WarnContext(ctx, "dingtalk stream: write ack", "error", err)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/ws_connector_test.go b/server/internal/integrations/dingtalk/ws_connector_test.go
new file mode 100644
index 0000000000..88b083a786
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_connector_test.go
@@ -0,0 +1,252 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/gorilla/websocket"
+)
+
+// fakeWSConn is a programmable in-memory wsConn for connector tests.
+type fakeWSConn struct {
+ frames chan []byte
+ closed chan struct{}
+
+ mu sync.Mutex
+ writes [][]byte
+ closeOnce sync.Once
+}
+
+func newFakeWSConn() *fakeWSConn {
+ return &fakeWSConn{
+ frames: make(chan []byte, 16),
+ closed: make(chan struct{}),
+ }
+}
+
+func (f *fakeWSConn) ReadMessage() (int, []byte, error) {
+ select {
+ case b := <-f.frames:
+ return websocket.TextMessage, b, nil
+ case <-f.closed:
+ return 0, nil, websocket.ErrCloseSent
+ }
+}
+
+func (f *fakeWSConn) WriteMessage(_ int, data []byte) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.writes = append(f.writes, append([]byte(nil), data...))
+ return nil
+}
+
+func (f *fakeWSConn) WriteControl(int, []byte, time.Time) error { return nil }
+func (f *fakeWSConn) SetReadDeadline(time.Time) error { return nil }
+func (f *fakeWSConn) SetWriteDeadline(time.Time) error { return nil }
+func (f *fakeWSConn) SetPongHandler(func(string) error) {}
+func (f *fakeWSConn) Close() error {
+ f.closeOnce.Do(func() { close(f.closed) })
+ return nil
+}
+
+func (f *fakeWSConn) responses(t *testing.T) []dataFrameResponse {
+ t.Helper()
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ var out []dataFrameResponse
+ for _, w := range f.writes {
+ var r dataFrameResponse
+ if err := json.Unmarshal(w, &r); err != nil {
+ t.Fatalf("write not a dataFrameResponse: %v", err)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+type fakeWSDialer struct{ conn wsConn }
+
+func (d fakeWSDialer) dial(context.Context, string) (wsConn, error) { return d.conn, nil }
+
+type failingWSDialer struct{}
+
+func (failingWSDialer) dial(_ context.Context, dialURL string) (wsConn, error) {
+ return nil, errors.New("dial failed for " + dialURL)
+}
+
+func newTestConnector(conn wsConn, onMessage func(context.Context, *botCallbackData) error) *wsConnector {
+ return &wsConnector{
+ dialer: fakeWSDialer{conn: conn},
+ open: func(context.Context) (string, error) { return "wss://test/ws?ticket=t", nil },
+ onMessage: onMessage,
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ pingInterval: time.Hour, // don't fire during tests
+ }
+}
+
+func mustFrame(t *testing.T, f dataFrame) []byte {
+ t.Helper()
+ b, err := json.Marshal(f)
+ if err != nil {
+ t.Fatalf("marshal frame: %v", err)
+ }
+ return b
+}
+
+const testCallbackData = `{"msgId":"m-1","msgtype":"text","senderStaffId":"s","conversationId":"c","conversationType":"1","text":{"content":"hi"}}`
+
+func TestConnector_CallbackInvokesHandlerAndAcks(t *testing.T) {
+ conn := newFakeWSConn()
+ var got *botCallbackData
+ gotCh := make(chan struct{})
+ c := newTestConnector(conn, func(_ context.Context, d *botCallbackData) error {
+ got = d
+ close(gotCh)
+ return nil
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ runErr := make(chan error, 1)
+ go func() { runErr <- c.run(ctx) }()
+
+ conn.frames <- mustFrame(t, dataFrame{
+ Type: frameTypeCallback,
+ Headers: map[string]string{"topic": botMessageTopic, "messageId": "mid-1"},
+ Data: testCallbackData,
+ })
+
+ select {
+ case <-gotCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("handler not invoked")
+ }
+ if got.MsgId != "m-1" || got.Text.Content != "hi" {
+ t.Errorf("callback decoded wrong: %+v", got)
+ }
+
+ cancel()
+ if err := <-runErr; err != nil {
+ t.Errorf("run returned error on cancel: %v", err)
+ }
+ resps := conn.responses(t)
+ if len(resps) == 0 || resps[0].Headers["messageId"] != "mid-1" || resps[0].Code != 200 {
+ t.Errorf("expected 200 ack echoing mid-1, got %+v", resps)
+ }
+}
+
+func TestConnector_RespondsToSystemPing(t *testing.T) {
+ conn := newFakeWSConn()
+ c := newTestConnector(conn, func(context.Context, *botCallbackData) error { return nil })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ runErr := make(chan error, 1)
+ go func() { runErr <- c.run(ctx) }()
+
+ conn.frames <- mustFrame(t, dataFrame{
+ Type: frameTypeSystem,
+ Headers: map[string]string{"topic": systemTopicPing, "messageId": "ping-1"},
+ Data: `{"k":"v"}`,
+ })
+
+ deadline := time.After(2 * time.Second)
+ for {
+ if resps := conn.responses(t); len(resps) > 0 {
+ if resps[0].Message != "ok" || resps[0].Headers["messageId"] != "ping-1" || resps[0].Data != `{"k":"v"}` {
+ t.Errorf("bad pong: %+v", resps[0])
+ }
+ break
+ }
+ select {
+ case <-deadline:
+ t.Fatal("no pong written")
+ case <-time.After(10 * time.Millisecond):
+ }
+ }
+ cancel()
+ <-runErr
+}
+
+func TestConnector_DisconnectFrameReturnsNil(t *testing.T) {
+ conn := newFakeWSConn()
+ c := newTestConnector(conn, func(context.Context, *botCallbackData) error { return nil })
+ runErr := make(chan error, 1)
+ go func() { runErr <- c.run(context.Background()) }()
+
+ conn.frames <- mustFrame(t, dataFrame{
+ Type: frameTypeSystem,
+ Headers: map[string]string{"topic": systemTopicDisconnect, "messageId": "d-1"},
+ })
+
+ select {
+ case err := <-runErr:
+ if err != nil {
+ t.Errorf("disconnect must return nil, got %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("run did not return on disconnect frame")
+ }
+}
+
+func TestConnector_CancelUnblocksRead(t *testing.T) {
+ conn := newFakeWSConn()
+ c := newTestConnector(conn, func(context.Context, *botCallbackData) error { return nil })
+ ctx, cancel := context.WithCancel(context.Background())
+ runErr := make(chan error, 1)
+ go func() { runErr <- c.run(ctx) }()
+
+ time.Sleep(50 * time.Millisecond) // read loop is now blocked in ReadMessage
+ cancel()
+ select {
+ case err := <-runErr:
+ if err != nil {
+ t.Errorf("cancel must return nil, got %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("cancel did not unblock the read loop")
+ }
+}
+
+func TestConnector_SkipsMalformedFrame(t *testing.T) {
+ conn := newFakeWSConn()
+ gotCh := make(chan struct{})
+ c := newTestConnector(conn, func(context.Context, *botCallbackData) error { close(gotCh); return nil })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ runErr := make(chan error, 1)
+ go func() { runErr <- c.run(ctx) }()
+
+ conn.frames <- []byte(`{not json`)
+ conn.frames <- mustFrame(t, dataFrame{
+ Type: frameTypeCallback,
+ Headers: map[string]string{"topic": botMessageTopic, "messageId": "m"},
+ Data: testCallbackData,
+ })
+
+ select {
+ case <-gotCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("connector did not survive a malformed frame")
+ }
+ cancel()
+ <-runErr
+}
+
+func TestConnector_DialErrorDoesNotExposeTicket(t *testing.T) {
+ c := &wsConnector{
+ dialer: failingWSDialer{},
+ open: func(context.Context) (string, error) {
+ return "wss://stream.example/ws?ticket=supersecret", nil
+ },
+ }
+ err := c.run(context.Background())
+ if err == nil || strings.Contains(err.Error(), "supersecret") || strings.Contains(err.Error(), "stream.example") {
+ t.Fatalf("dial error leaked endpoint credential: %v", err)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/ws_endpoint.go b/server/internal/integrations/dingtalk/ws_endpoint.go
new file mode 100644
index 0000000000..db930bdfc5
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_endpoint.go
@@ -0,0 +1,105 @@
+package dingtalk
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// This file opens a DingTalk Stream connection: a POST to the gateway that
+// returns a single-use WebSocket endpoint + ticket. It replaces the vendor SDK's
+// client.Start handshake. The returned URL (endpoint with the ticket appended)
+// is what the connector dials.
+
+const (
+ connectionsOpenPath = "/v1.0/gateway/connections/open"
+ streamUserAgent = "multica-dingtalk/1.0"
+ openConnectTimeout = 5 * time.Second
+)
+
+// streamSubscription is one {type, topic} entry in the open request. The chatbot
+// connection subscribes to the two SYSTEM control topics plus the bot-message
+// callback topic.
+type streamSubscription struct {
+ Type string `json:"type"`
+ Topic string `json:"topic"`
+}
+
+// chatbotSubscriptions is the fixed subscription set for a bot-message stream.
+func chatbotSubscriptions() []streamSubscription {
+ return []streamSubscription{
+ {Type: frameTypeSystem, Topic: systemTopicPing},
+ {Type: frameTypeSystem, Topic: systemTopicDisconnect},
+ {Type: frameTypeCallback, Topic: botMessageTopic},
+ }
+}
+
+type openConnectionRequest struct {
+ ClientID string `json:"clientId"`
+ ClientSecret string `json:"clientSecret"`
+ Subscriptions []streamSubscription `json:"subscriptions"`
+ UserAgent string `json:"ua"`
+}
+
+type openConnectionResponse struct {
+ Endpoint string `json:"endpoint"`
+ Ticket string `json:"ticket"`
+}
+
+// openConnection registers a Stream connection and returns the dial-ready wss
+// URL (endpoint?ticket=…). apiBase + httpClient come from the shared outbound
+// Client so tests can point them at an httptest server.
+func openConnection(ctx context.Context, httpClient *http.Client, apiBase, appKey, appSecret string) (string, error) {
+ if httpClient == nil {
+ httpClient = http.DefaultClient
+ }
+ reqBody, err := json.Marshal(openConnectionRequest{
+ ClientID: appKey,
+ ClientSecret: appSecret,
+ Subscriptions: chatbotSubscriptions(),
+ UserAgent: streamUserAgent,
+ })
+ if err != nil {
+ return "", fmt.Errorf("marshal open request: %w", err)
+ }
+
+ ctx, cancel := context.WithTimeout(ctx, openConnectTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBase+connectionsOpenPath, bytes.NewReader(reqBody))
+ if err != nil {
+ return "", fmt.Errorf("build open request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return "", fmt.Errorf("open connection: %w", err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return "", fmt.Errorf("open connection: status %d: %s", resp.StatusCode, string(body))
+ }
+ var out openConnectionResponse
+ if err := json.Unmarshal(body, &out); err != nil {
+ return "", fmt.Errorf("decode open response: %w", err)
+ }
+ if out.Endpoint == "" || out.Ticket == "" {
+ return "", fmt.Errorf("open connection: empty endpoint or ticket")
+ }
+ endpoint, err := url.Parse(out.Endpoint)
+ if err != nil || endpoint.Scheme != "wss" || endpoint.Host == "" {
+ return "", errors.New("open connection: invalid secure websocket endpoint")
+ }
+ query := endpoint.Query()
+ query.Set("ticket", out.Ticket)
+ endpoint.RawQuery = query.Encode()
+ return endpoint.String(), nil
+}
diff --git a/server/internal/integrations/dingtalk/ws_endpoint_test.go b/server/internal/integrations/dingtalk/ws_endpoint_test.go
new file mode 100644
index 0000000000..182976d0fb
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_endpoint_test.go
@@ -0,0 +1,76 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+func TestOpenConnection_ReturnsDialURL(t *testing.T) {
+ var gotBody openConnectionRequest
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != connectionsOpenPath {
+ t.Errorf("path = %q, want %q", r.URL.Path, connectionsOpenPath)
+ }
+ b, _ := io.ReadAll(r.Body)
+ _ = json.Unmarshal(b, &gotBody)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"endpoint":"wss://stream.example/ws","ticket":"tkt-123"}`))
+ }))
+ defer srv.Close()
+
+ got, err := openConnection(context.Background(), srv.Client(), srv.URL, "key-1", "secret-1")
+ if err != nil {
+ t.Fatalf("openConnection: %v", err)
+ }
+ if got != "wss://stream.example/ws?ticket=tkt-123" {
+ t.Errorf("dial url = %q", got)
+ }
+ if gotBody.ClientID != "key-1" || gotBody.ClientSecret != "secret-1" {
+ t.Errorf("credentials not sent: %+v", gotBody)
+ }
+ if len(gotBody.Subscriptions) != 3 {
+ t.Fatalf("want 3 subscriptions, got %d", len(gotBody.Subscriptions))
+ }
+ if gotBody.Subscriptions[2].Type != frameTypeCallback || gotBody.Subscriptions[2].Topic != botMessageTopic {
+ t.Errorf("callback subscription wrong: %+v", gotBody.Subscriptions[2])
+ }
+}
+
+func TestOpenConnection_ErrorsOnNon2xx(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"code":"unauthorized"}`))
+ }))
+ defer srv.Close()
+ _, err := openConnection(context.Background(), srv.Client(), srv.URL, "k", "s")
+ if err == nil || !strings.Contains(err.Error(), "401") {
+ t.Fatalf("want 401 error, got %v", err)
+ }
+}
+
+func TestOpenConnection_ErrorsOnEmptyEndpoint(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{"endpoint":"","ticket":""}`))
+ }))
+ defer srv.Close()
+ _, err := openConnection(context.Background(), srv.Client(), srv.URL, "k", "s")
+ if err == nil {
+ t.Fatal("want error on empty endpoint/ticket")
+ }
+}
+
+func TestOpenConnection_RejectsInsecureEndpoint(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"endpoint":"ws://stream.example/ws","ticket":"secret-ticket"}`))
+ }))
+ defer srv.Close()
+ _, err := openConnection(context.Background(), srv.Client(), srv.URL, "k", "s")
+ if err == nil || strings.Contains(err.Error(), "secret-ticket") {
+ t.Fatalf("insecure endpoint error = %v", err)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/ws_frame.go b/server/internal/integrations/dingtalk/ws_frame.go
new file mode 100644
index 0000000000..074e157cc0
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_frame.go
@@ -0,0 +1,67 @@
+package dingtalk
+
+// DingTalk Stream frames are JSON envelopes over the WebSocket. This file models
+// the inbound DataFrame and the DataFrameResponse we write back, plus the small
+// set of type/topic discriminators the chatbot connection uses. It replaces the
+// former dependency on the vendor stream SDK's payload package.
+
+const (
+ frameTypeSystem = "SYSTEM"
+ frameTypeCallback = "CALLBACK"
+
+ systemTopicPing = "ping"
+ systemTopicDisconnect = "disconnect"
+ botMessageTopic = "/v1.0/im/bot/messages/get"
+
+ frameResponseCodeOK = 200
+)
+
+// dataFrame is an inbound Stream frame. The gateway carries the routing key in
+// headers.topic and the correlation id in headers.messageId; data is the frame
+// body as a JSON string (a bot callback for the bot-message topic).
+type dataFrame struct {
+ Type string `json:"type"`
+ Headers map[string]string `json:"headers"`
+ Data string `json:"data"`
+}
+
+func (f *dataFrame) topic() string { return f.Headers["topic"] }
+func (f *dataFrame) messageID() string { return f.Headers["messageId"] }
+
+// dataFrameResponse is the ack we write back for every frame. The gateway
+// correlates it to the delivered frame by the echoed messageId header, so that
+// header is load-bearing; data stays empty for a plain callback ack (the actual
+// reply is delivered out-of-band over the Open API).
+type dataFrameResponse struct {
+ Code int `json:"code"`
+ Headers map[string]string `json:"headers"`
+ Message string `json:"message"`
+ Data string `json:"data"`
+}
+
+// newAckResponse builds a 200 ack echoing the frame's messageId.
+func newAckResponse(messageID string) dataFrameResponse {
+ return dataFrameResponse{
+ Code: frameResponseCodeOK,
+ Message: "",
+ Data: "",
+ Headers: map[string]string{
+ "messageId": messageID,
+ "contentType": "application/json",
+ },
+ }
+}
+
+// newPongResponse answers a SYSTEM ping. It echoes the ping's messageId and its
+// data body, mirroring the gateway's expected pong shape.
+func newPongResponse(messageID, data string) dataFrameResponse {
+ return dataFrameResponse{
+ Code: frameResponseCodeOK,
+ Message: "ok",
+ Data: data,
+ Headers: map[string]string{
+ "messageId": messageID,
+ "contentType": "application/json",
+ },
+ }
+}
diff --git a/server/internal/integrations/dingtalk/ws_frame_test.go b/server/internal/integrations/dingtalk/ws_frame_test.go
new file mode 100644
index 0000000000..6c10f0d5f9
--- /dev/null
+++ b/server/internal/integrations/dingtalk/ws_frame_test.go
@@ -0,0 +1,55 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestDataFrame_Accessors(t *testing.T) {
+ raw := `{"specVersion":"1.0","type":"CALLBACK","headers":{"topic":"/v1.0/im/bot/messages/get","messageId":"mid-1","contentType":"application/json"},"data":"{\"msgId\":\"m\"}"}`
+ var f dataFrame
+ if err := json.Unmarshal([]byte(raw), &f); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if f.Type != frameTypeCallback {
+ t.Errorf("type = %q, want %q", f.Type, frameTypeCallback)
+ }
+ if f.topic() != botMessageTopic {
+ t.Errorf("topic = %q, want %q", f.topic(), botMessageTopic)
+ }
+ if f.messageID() != "mid-1" {
+ t.Errorf("messageID = %q, want mid-1", f.messageID())
+ }
+ if f.Data != `{"msgId":"m"}` {
+ t.Errorf("data = %q", f.Data)
+ }
+}
+
+func TestNewAckResponse_EchoesMessageID(t *testing.T) {
+ ack := newAckResponse("mid-9")
+ if ack.Code != frameResponseCodeOK {
+ t.Errorf("code = %d, want %d", ack.Code, frameResponseCodeOK)
+ }
+ if ack.Headers["messageId"] != "mid-9" {
+ t.Errorf("messageId = %q, want mid-9", ack.Headers["messageId"])
+ }
+ if ack.Headers["contentType"] != "application/json" {
+ t.Errorf("contentType = %q", ack.Headers["contentType"])
+ }
+ if ack.Data != "" {
+ t.Errorf("ack data must be empty, got %q", ack.Data)
+ }
+}
+
+func TestNewPongResponse_EchoesData(t *testing.T) {
+ pong := newPongResponse("mid-2", `{"k":"v"}`)
+ if pong.Message != "ok" {
+ t.Errorf("message = %q, want ok", pong.Message)
+ }
+ if pong.Data != `{"k":"v"}` {
+ t.Errorf("pong must echo data, got %q", pong.Data)
+ }
+ if pong.Headers["messageId"] != "mid-2" {
+ t.Errorf("messageId = %q, want mid-2", pong.Headers["messageId"])
+ }
+}
diff --git a/server/migrations/259_issue_origin_dingtalk_chat.down.sql b/server/migrations/259_issue_origin_dingtalk_chat.down.sql
new file mode 100644
index 0000000000..df39e15e91
--- /dev/null
+++ b/server/migrations/259_issue_origin_dingtalk_chat.down.sql
@@ -0,0 +1,15 @@
+-- Revert to the pre-DingTalk origin list. Existing dingtalk_chat rows must be
+-- deleted or relabeled before this rollback can succeed.
+--
+-- The down path deliberately VALIDATEs in this same file, unlike the up path.
+-- Narrowing a CHECK can genuinely be violated by existing data, so this must
+-- fail closed while dingtalk_chat rows remain rather than silently leaving
+-- rows the constraint forbids. That means accepting the ACCESS EXCLUSIVE lock
+-- for the scan — an acceptable trade for an operator-driven rollback, which is
+-- rare and supervised, where a silently untrusted constraint would be worse.
+-- Same reasoning as 249_issue_subscriber_delegated.down.sql.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create'))
+ NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/migrations/259_issue_origin_dingtalk_chat.up.sql b/server/migrations/259_issue_origin_dingtalk_chat.up.sql
new file mode 100644
index 0000000000..d518edacb0
--- /dev/null
+++ b/server/migrations/259_issue_origin_dingtalk_chat.up.sql
@@ -0,0 +1,22 @@
+-- Extend issue.origin_type for issues created through DingTalk's /issue
+-- command. The shared channel Router stamps origin_type='dingtalk_chat' and
+-- origin_id=<chat_session.id>; without this CHECK entry every DingTalk issue
+-- creation fails with SQLSTATE 23514.
+--
+-- The CHECK is only WIDENED (one new allowed value), so every existing row
+-- already satisfies it. Add it NOT VALID so this statement takes ACCESS
+-- EXCLUSIVE on issue only briefly, without a full-table scan; migration 260
+-- runs the VALIDATE under SHARE UPDATE EXCLUSIVE, which does not block reads
+-- or writes. issue is a hot core table, so a plain validating ADD here would
+-- block all traffic on it for the length of the scan.
+--
+-- Keep the VALIDATE in its own migration file (the 197/198 pattern), NOT
+-- merely as a later statement in this one: the migration runner hands each
+-- file to a single conn.Exec, so every statement in a file shares one implicit
+-- transaction and the ACCESS EXCLUSIVE taken here would be held until the file
+-- finishes — carrying the strong lock straight through the validation scan and
+-- defeating the split.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat'))
+ NOT VALID;
diff --git a/server/migrations/260_issue_origin_dingtalk_chat_validate.down.sql b/server/migrations/260_issue_origin_dingtalk_chat_validate.down.sql
new file mode 100644
index 0000000000..23a183c301
--- /dev/null
+++ b/server/migrations/260_issue_origin_dingtalk_chat_validate.down.sql
@@ -0,0 +1,8 @@
+-- PostgreSQL cannot mark a validated constraint NOT VALID again. Recreate it
+-- to restore the state immediately after migration 259 (present, enforcing new
+-- writes, not yet validated). Mirrors
+-- 198_agent_task_attribution_strict_constraint_validate.down.sql.
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_origin_type_check;
+ALTER TABLE issue ADD CONSTRAINT issue_origin_type_check
+ CHECK (origin_type IN ('autopilot', 'quick_create', 'lark_chat', 'slack_chat', 'agent_create', 'dingtalk_chat'))
+ NOT VALID;
diff --git a/server/migrations/260_issue_origin_dingtalk_chat_validate.up.sql b/server/migrations/260_issue_origin_dingtalk_chat_validate.up.sql
new file mode 100644
index 0000000000..27b6dbdf7a
--- /dev/null
+++ b/server/migrations/260_issue_origin_dingtalk_chat_validate.up.sql
@@ -0,0 +1,9 @@
+-- Validate the widened issue_origin_type_check that migration 259 added
+-- NOT VALID. This takes SHARE UPDATE EXCLUSIVE while scanning issue, which
+-- permits normal SELECT/INSERT/UPDATE/DELETE traffic to continue — the whole
+-- point of splitting the two steps across migration files (the 197/198
+-- pattern).
+--
+-- 259 only WIDENED the allowed set, so every pre-existing row already
+-- satisfies the constraint and this scan cannot fail on legacy data.
+ALTER TABLE issue VALIDATE CONSTRAINT issue_origin_type_check;
diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.go
new file mode 100644
index 0000000000..2e89595a4a
--- /dev/null
+++ b/server/pkg/db/generated/dingtalk.sql.go
@@ -0,0 +1,135 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: dingtalk.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const deleteDingTalkInstallationForReplacement = `-- name: DeleteDingTalkInstallationForReplacement :one
+WITH retired AS (
+ DELETE FROM channel_installation ci
+ WHERE ci.id = $1
+ AND ci.workspace_id = $2
+ AND ci.agent_id = $3
+ AND ci.channel_type = 'dingtalk'
+ RETURNING ci.id
+),
+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_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+),
+cleared_binding_tokens AS (
+ DELETE FROM channel_binding_token
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_user_bindings AS (
+ DELETE FROM channel_user_binding
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_inbound_dedup AS (
+ DELETE FROM channel_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+detached_audit AS (
+ UPDATE channel_inbound_audit SET installation_id = NULL
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+detached_media_intents AS (
+ UPDATE channel_media_pending_object SET installation_id = NULL
+ WHERE installation_id IN (SELECT id FROM retired)
+)
+SELECT retired.id FROM retired
+`
+
+type DeleteDingTalkInstallationForReplacementParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// 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
+// old installation's identity, token, session, dedup, or outbound state may
+// cross into the new robot. The caller inserts a fresh installation in the same
+// transaction, giving the replacement a new installation_id that also fences
+// late writes and replies from the old connection.
+//
+// Chat sessions themselves remain as history, but their channel bindings and
+// outbound cards are removed. Audit and media-intent rows remain useful for
+// diagnostics / reconciliation, so their installation references are detached.
+func (q *Queries) DeleteDingTalkInstallationForReplacement(ctx context.Context, arg DeleteDingTalkInstallationForReplacementParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, deleteDingTalkInstallationForReplacement, arg.InstallationID, arg.WorkspaceID, arg.AgentID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
+const getDingTalkInstallationOwnerForUpdate = `-- name: GetDingTalkInstallationOwnerForUpdate :one
+SELECT id, COALESCE(config ->> 'app_id', '')::text AS app_id
+FROM channel_installation
+WHERE workspace_id = $1
+ AND agent_id = $2
+ AND channel_type = 'dingtalk'
+FOR UPDATE
+`
+
+type GetDingTalkInstallationOwnerForUpdateParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+type GetDingTalkInstallationOwnerForUpdateRow struct {
+ ID pgtype.UUID `json:"id"`
+ AppID string `json:"app_id"`
+}
+
+// Reads the current robot identity after LockDingTalkInstallationOwner has
+// serialized the logical owner slot. app_id is non-null for every DingTalk
+// installation; COALESCE treats malformed legacy config as a different robot,
+// which safely replaces it instead of preserving unknown identity state.
+func (q *Queries) GetDingTalkInstallationOwnerForUpdate(ctx context.Context, arg GetDingTalkInstallationOwnerForUpdateParams) (GetDingTalkInstallationOwnerForUpdateRow, error) {
+ row := q.db.QueryRow(ctx, getDingTalkInstallationOwnerForUpdate, arg.WorkspaceID, arg.AgentID)
+ var i GetDingTalkInstallationOwnerForUpdateRow
+ err := row.Scan(&i.ID, &i.AppID)
+ return i, err
+}
+
+const lockDingTalkInstallationOwner = `-- name: LockDingTalkInstallationOwner :exec
+
+SELECT pg_advisory_xact_lock(
+ hashtextextended(
+ ($1::uuid)::text || ':' ||
+ ($2::uuid)::text || ':dingtalk',
+ 0
+ )
+)
+`
+
+type LockDingTalkInstallationOwnerParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+}
+
+// DingTalk-specific installation identity operations. The underlying channel_*
+// tables are shared, but these replacement semantics belong to DingTalk's BYO
+// AppKey model and deliberately stay out of the shared channel query surface.
+// Serializes install / replacement decisions for one logical
+// (workspace, agent, channel) slot. A different-AppKey replacement deletes the
+// old row and inserts a fresh installation id; the advisory lock closes the
+// gap where two concurrent replacements could otherwise miss each other's new
+// row and update it in place, carrying identity state across robot boundaries.
+func (q *Queries) LockDingTalkInstallationOwner(ctx context.Context, arg LockDingTalkInstallationOwnerParams) error {
+ _, err := q.db.Exec(ctx, lockDingTalkInstallationOwner, arg.WorkspaceID, arg.AgentID)
+ return err
+}
diff --git a/server/pkg/db/queries/dingtalk.sql b/server/pkg/db/queries/dingtalk.sql
new file mode 100644
index 0000000000..5c26c6a424
--- /dev/null
+++ b/server/pkg/db/queries/dingtalk.sql
@@ -0,0 +1,79 @@
+-- DingTalk-specific installation identity operations. The underlying channel_*
+-- tables are shared, but these replacement semantics belong to DingTalk's BYO
+-- AppKey model and deliberately stay out of the shared channel query surface.
+
+-- name: LockDingTalkInstallationOwner :exec
+-- Serializes install / replacement decisions for one logical
+-- (workspace, agent, channel) slot. A different-AppKey replacement deletes the
+-- old row and inserts a fresh installation id; the advisory lock closes the
+-- gap where two concurrent replacements could otherwise miss each other's new
+-- row and update it in place, carrying identity state across robot boundaries.
+SELECT pg_advisory_xact_lock(
+ hashtextextended(
+ (sqlc.arg(workspace_id)::uuid)::text || ':' ||
+ (sqlc.arg(agent_id)::uuid)::text || ':dingtalk',
+ 0
+ )
+);
+
+-- name: GetDingTalkInstallationOwnerForUpdate :one
+-- Reads the current robot identity after LockDingTalkInstallationOwner has
+-- serialized the logical owner slot. app_id is non-null for every DingTalk
+-- installation; COALESCE treats malformed legacy config as a different robot,
+-- which safely replaces it instead of preserving unknown identity state.
+SELECT id, COALESCE(config ->> 'app_id', '')::text AS app_id
+FROM channel_installation
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND agent_id = sqlc.arg(agent_id)
+ AND channel_type = 'dingtalk'
+FOR UPDATE;
+
+-- 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
+-- old installation's identity, token, session, dedup, or outbound state may
+-- cross into the new robot. The caller inserts a fresh installation in the same
+-- transaction, giving the replacement a new installation_id that also fences
+-- late writes and replies from the old connection.
+--
+-- Chat sessions themselves remain as history, but their channel bindings and
+-- outbound cards are removed. Audit and media-intent rows remain useful for
+-- diagnostics / reconciliation, so their installation references are detached.
+WITH retired AS (
+ DELETE FROM channel_installation ci
+ WHERE ci.id = sqlc.arg(installation_id)
+ AND ci.workspace_id = sqlc.arg(workspace_id)
+ AND ci.agent_id = sqlc.arg(agent_id)
+ AND ci.channel_type = 'dingtalk'
+ RETURNING ci.id
+),
+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_message
+ WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
+),
+cleared_binding_tokens AS (
+ DELETE FROM channel_binding_token
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_user_bindings AS (
+ DELETE FROM channel_user_binding
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_inbound_dedup AS (
+ DELETE FROM channel_inbound_message_dedup
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+detached_audit AS (
+ UPDATE channel_inbound_audit SET installation_id = NULL
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+detached_media_intents AS (
+ UPDATE channel_media_pending_object SET installation_id = NULL
+ WHERE installation_id IN (SELECT id FROM retired)
+)
+SELECT retired.id FROM retired;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index d54694bb4e..aabcff4a2d 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -182,4 +182,9 @@ const (
// invalidate the Slack installations query on either.
EventSlackInstallationCreated = "slack_installation:created"
EventSlackInstallationRevoked = "slack_installation:revoked"
+
+ // DingTalk installation lifecycle follows the same create/revoke semantics
+ // as Slack's BYO channel installation.
+ EventDingTalkInstallationCreated = "dingtalk_installation:created"
+ EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"
)