Skip to content

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

Go

MUL-6661 feat(channels): add /new and /clear conversation controls (#7468)

YYClaw9e2d9b6d1ced
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdx
index a95d30685c..ac30b06b47 100644
--- a/apps/docs/content/docs/channels.ja.mdx
+++ b/apps/docs/content/docs/channels.ja.mdx
@@ -17,6 +17,8 @@ import { Callout } from "fumadocs-ui/components/callout";
| エージェントとの DM | 対応 | 対応 | 対応 | 対応 | 対応 |
| グループまたはチャンネル | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンションするとトリガー | Bot を @メンション、または Bot に返信するとトリガー |
| イシューの作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` スラッシュコマンド。エージェントが説明を整理してから作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 | `/issue` メッセージコマンド。入力内容からそのまま作成 |
+| 新しい Chat を開始 | `/new [メッセージ]` | DM: `/new [メッセージ]`、チャンネル/スレッド: `@Multica /new [メッセージ]` | `/new [メッセージ]` | `/new [メッセージ]` | `/new [メッセージ]` |
+| 現在の Chat のコンテキストをクリア | `/clear [メッセージ]` | DM: `/clear [メッセージ]`、チャンネル/スレッド: `@Multica /clear [メッセージ]` | `/clear [メッセージ]` | `/clear [メッセージ]` | `/clear [メッセージ]` |
| 接続方式 | プラットフォームの常時接続 | Socket Mode | Stream モード | プラットフォームの常時接続 | `getUpdates` long polling |
新規接続は現在、中国本土版の Feishu でのみ利用できます。既存の国際版 Lark 接続は、引き続き利用および管理できます。
@@ -48,6 +50,14 @@ Bot を @メンションしていないチャンネルメッセージは、エ
通常のメッセージはこの流れで処理されます。`/issue` はコマンドであり、チャットのターンではありません。Multica は元のプラットフォームに結果を返しますが、コマンド自体は Multica Chat に追加しません。Slack のネイティブスラッシュコマンドは、独立した非同期のタスク作成フローで処理されます。
+## 会話コンテキストを操作する
+
+`/new` は新しい Multica Chat を作成し、その外部会話からの後続メッセージを新しい Chat へルーティングします。`/new <メッセージ>` では、そのメッセージが最初のターンになります。以前の Chat は Multica に保存され、引き続き利用できます。
+
+`/clear` は現在の Multica Chat を維持したまま、エージェントから見えるコンテキストだけを新しくします。Chat の全履歴は Multica に残りますが、エージェントは境界より前のメッセージを取得できません。`/clear <メッセージ>` では、そのメッセージが新しいコンテキストの最初のターンになります。引数なしの `/clear` は次の実メッセージに適用されます。
+
+Slack の DM では、`/new` と `/clear` はネイティブスラッシュコマンドです。ネイティブ slash command payload ではチャンネル内の対象スレッドを特定できないため、対象スレッドで `@Multica /new [メッセージ]` または `@Multica /clear [メッセージ]` を送信してください。
+
## セッションの分離
- Feishu/Lark はチャットごとにセッションを分けます。同じチャットの後続メッセージは同じセッションを継続します。
diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdx
index 4959a52e14..39904dac2d 100644
--- a/apps/docs/content/docs/channels.ko.mdx
+++ b/apps/docs/content/docs/channels.ko.mdx
@@ -17,6 +17,8 @@ import { Callout } from "fumadocs-ui/components/callout";
| 에이전트와 DM | 지원 | 지원 | 지원 | 지원 | 지원 |
| 그룹 채팅 또는 채널 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하면 트리거 | Bot을 @멘션하거나 Bot에 답장하면 트리거 |
| 이슈 만들기 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` slash 명령으로 에이전트가 설명을 정리한 뒤 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 | `/issue` 메시지 명령으로 입력 내용을 바로 생성 |
+| 새 Chat 시작 | `/new [메시지]` | DM: `/new [메시지]`, 채널/thread: `@Multica /new [메시지]` | `/new [메시지]` | `/new [메시지]` | `/new [메시지]` |
+| 현재 Chat 컨텍스트 지우기 | `/clear [메시지]` | DM: `/clear [메시지]`, 채널/thread: `@Multica /clear [메시지]` | `/clear [메시지]` | `/clear [메시지]` | `/clear [메시지]` |
| 연결 방식 | 플랫폼 장기 연결 | Socket Mode | Stream 모드 | 플랫폼 장기 연결 | `getUpdates` long polling |
새 연결은 현재 중국 본토 버전 Feishu에서만 만들 수 있습니다. 기존 국제 버전 Lark 연결은 계속 사용하고 관리할 수 있습니다.
@@ -48,6 +50,14 @@ Bot을 @멘션하지 않은 채널 메시지는 에이전트를 트리거하지
일반 메시지는 위 흐름으로 처리됩니다. `/issue`는 명령이며 채팅 turn이 아닙니다. Multica는 원래 플랫폼에 처리 결과를 보내지만 명령 자체는 Multica Chat에 추가하지 않습니다. Slack의 기본 slash 명령은 별도의 비동기 태스크 생성 흐름으로 처리됩니다.
+## 대화 컨텍스트 제어
+
+`/new`은 새 Multica Chat을 만들고 해당 외부 대화의 후속 메시지를 새 Chat으로 라우팅합니다. `/new <메시지>`를 보내면 해당 메시지가 첫 번째 대화가 됩니다. 이전 Chat은 Multica에 저장된 상태로 계속 사용할 수 있습니다.
+
+`/clear`는 현재 Multica Chat을 유지하면서 에이전트에게 보이는 컨텍스트만 새로 시작합니다. 전체 Chat 기록은 Multica에 남지만 에이전트는 경계 이전의 메시지를 가져올 수 없습니다. `/clear <메시지>`는 해당 메시지를 새 컨텍스트의 첫 번째 대화로 사용하고, 인자 없는 `/clear`는 다음 실제 메시지에 적용됩니다.
+
+Slack DM에서는 `/new`과 `/clear`가 네이티브 slash 명령입니다. 네이티브 slash command payload로는 채널의 대상 thread를 식별할 수 없으므로 대상 thread에서 `@Multica /new [메시지]` 또는 `@Multica /clear [메시지]`를 보내세요.
+
## 대화 격리
- Feishu/Lark는 채팅별로 대화를 구분하며 같은 채팅의 후속 메시지는 기존 대화를 이어갑니다.
diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdx
index fff0e215d4..16815565af 100644
--- a/apps/docs/content/docs/channels.mdx
+++ b/apps/docs/content/docs/channels.mdx
@@ -17,6 +17,8 @@ Feishu/Lark, Slack, DingTalk, WeCom, and Telegram are supported today. They shar
| DM the agent | Supported | Supported | Supported | Supported | Supported |
| Groups or channels | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning the Bot | Triggered by @-mentioning or replying to 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 | `/issue` message command; creates the issue from your input as-is | `/issue` message command; creates the issue from your input as-is |
+| Start a new Chat | `/new [message]` | DM: `/new [message]`; channel/thread: `@Multica /new [message]` | `/new [message]` | `/new [message]` | `/new [message]` |
+| Clear the current Chat context | `/clear [message]` | DM: `/clear [message]`; channel/thread: `@Multica /clear [message]` | `/clear [message]` | `/clear [message]` | `/clear [message]` |
| Connection | Platform long connection | Socket Mode | Stream mode | Platform long connection | `getUpdates` long polling |
New connections are currently open only for mainland-China Feishu; existing international Lark connections keep working and can still be managed.
@@ -48,6 +50,14 @@ Channel messages that don't @-mention the Bot never trigger the agent and are no
Ordinary messages follow this flow. `/issue` is a command, not a chat turn: Multica posts the result back to the originating platform but does not add the command to Multica Chat. Slack's native slash command continues through its separate asynchronous issue-creation flow.
+## Conversation controls
+
+`/new` creates a new Multica Chat and routes later messages from that external conversation to it. `/new <message>` creates the Chat and uses the message as its first turn. The previous Chat remains stored and usable in Multica.
+
+`/clear` stays in the current Multica Chat but starts a new agent-visible context. The full Chat history remains available in Multica, while the agent cannot retrieve messages from before the boundary. `/clear <message>` uses the message as the first turn in the new context; a bare `/clear` applies to the next real message.
+
+On Slack, `/new` and `/clear` are native slash commands in a DM. A native slash-command payload does not identify a channel thread, so use `@Multica /new [message]` or `@Multica /clear [message]` inside the target thread.
+
## Session isolation
- Feishu/Lark separates sessions by chat; later messages in the same chat continue the same session.
diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdx
index 9fad5de8b8..59cef53e85 100644
--- a/apps/docs/content/docs/channels.zh.mdx
+++ b/apps/docs/content/docs/channels.zh.mdx
@@ -17,6 +17,8 @@ import { Callout } from "fumadocs-ui/components/callout";
| 私聊智能体 | 支持 | 支持 | 支持 | 支持 | 支持 |
| 群聊或频道 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 后触发 | @ Bot 或回复 Bot 后触发 |
| 创建 issue | `/issue` 消息命令,按输入直接创建 | `/issue` slash 命令,智能体整理描述后创建 | `/issue` 消息命令,按输入直接创建 | `/issue` 消息命令,按输入直接创建 | `/issue` 消息命令,按输入直接创建 |
+| 新建 Chat | `/new [消息]` | 私聊:`/new [消息]`;频道/thread:`@Multica /new [消息]` | `/new [消息]` | `/new [消息]` | `/new [消息]` |
+| 清空当前 Chat 上下文 | `/clear [消息]` | 私聊:`/clear [消息]`;频道/thread:`@Multica /clear [消息]` | `/clear [消息]` | `/clear [消息]` | `/clear [消息]` |
| 连接方式 | 平台长连接 | Socket Mode | Stream 模式 | 平台长连接 | `getUpdates` 长轮询 |
新连接目前只开放中国大陆版飞书;已有的国际版 Lark 连接仍可继续使用和管理。
@@ -48,6 +50,14 @@ Telegram 目前只处理文字消息。不支持的媒体消息会收到一句
普通消息按上述流程处理。`/issue` 是命令,不是对话轮次:Multica 会在原平台返回处理结果,但不会把命令加入 Multica Chat。Slack 原生 slash 命令仍按独立的异步创建任务流程处理。
+## 控制对话上下文
+
+`/new` 会创建一个新的 Multica Chat,并把这条外部会话的后续消息路由到新 Chat。`/new <消息>` 会同时把消息作为第一轮。旧 Chat 仍保存在 Multica 中,可以继续使用。
+
+`/clear` 不会新建 Chat,只会在当前 Multica Chat 中开启一段新的智能体可见上下文。完整 Chat 历史仍保存在 Multica 中,但智能体无法读取边界之前的消息。`/clear <消息>` 会把消息作为新上下文的第一轮;裸 `/clear` 会把边界应用到下一条真实消息。
+
+在 Slack 私聊中,`/new` 和 `/clear` 都是原生 slash 命令。原生 slash command payload 无法标识频道里的目标 thread,因此需要在目标 thread 中发送 `@Multica /new [消息]` 或 `@Multica /clear [消息]`。
+
## 会话隔离
- 飞书/Lark 按聊天区分会话;同一个聊天中的后续消息会继续原会话。
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
index 222f646df3..c1de9b7469 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx
@@ -58,12 +58,13 @@ DM とグループチャットのどちらでも、テキストと画像を混
`/issue <タイトル>` または `/issue <タイトル>{改行}<詳細説明>` を送ると、新しい Multica タスクが作成され、Bot に接続されたエージェントに自動的に割り当てられます。同じメッセージの画像も、添付ファイルとしてタスクに追加されます。通常の会話メッセージとは異なり、`/issue` コマンドは Multica の「[チャット](/chat)」に記録されません。
-### `/new` で最初から始める
+### `/new` で新しい Chat を開始する
-`/new` を送ると、次に送信に成功したメッセージをエージェントが新しいコンテキストで処理します。`/new <メッセージ>` を送ると、そのメッセージをすぐに新しいコンテキストで処理させることもできます。
+`/new` を送ると、空の新しい Multica Chat が作成され、その後の DingTalk メッセージは新しい Chat にルーティングされます。`/new <メッセージ>` では、そのメッセージが新しい Chat の最初のターンになります。以前の Chat は Multica に保存され、引き続き利用できます。
-`/new` コマンドは、エージェントに新しいコンテキストでメッセージを処理させるだけです。新しい Multica の「チャット」は作成されません。
+### `/clear` で現在のコンテキストをクリアする
+`/clear` を送ると、現在の Multica Chat を維持したまま、次のメッセージに新しいエージェント可視コンテキストが適用されます。`/clear <メッセージ>` では、そのメッセージが境界後の最初のターンになります。Chat の全履歴は Multica に表示されたままです。
## 接続を管理する
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
index fda0108066..5e6c93d18a 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx
@@ -58,12 +58,13 @@ DM과 그룹 채팅 모두 텍스트와 이미지가 함께 있는 메시지를
`/issue <제목>` 또는 `/issue <제목>{줄 바꿈}<상세 설명>`을 보내면 새 Multica 태스크가 만들어지고 봇에 연결된 에이전트에 자동으로 할당됩니다. 같은 메시지의 이미지도 첨부 파일로 태스크에 추가됩니다. 일반 대화 메시지와 달리 `/issue` 명령은 Multica의 “[채팅](/chat)”에 기록을 남기지 않습니다.
-### `/new`로 새로 시작하기
+### `/new`로 새 Chat 시작하기
-`/new`를 보내면 그다음으로 전송에 성공한 메시지를 에이전트가 새 맥락에서 처리합니다. `/new <메시지>`를 보내면 에이전트가 해당 메시지를 바로 새 맥락에서 처리하게 할 수도 있습니다.
+`/new`를 보내면 비어 있는 새 Multica Chat이 생성되고 이후 DingTalk 메시지가 새 Chat으로 라우팅됩니다. `/new <메시지>`를 보내면 해당 메시지가 새 Chat의 첫 번째 대화가 됩니다. 이전 Chat은 Multica에 저장된 채 계속 사용할 수 있습니다.
-`/new` 명령은 에이전트가 메시지를 새 맥락에서 처리하게만 할 뿐, 새로운 Multica “채팅”을 만들지는 않습니다.
+### `/clear`로 현재 컨텍스트 지우기
+`/clear`를 보내면 현재 Multica Chat은 유지되고 다음 메시지에 새 에이전트 컨텍스트가 적용됩니다. `/clear <메시지>`는 해당 메시지를 경계 이후의 첫 번째 대화로 사용합니다. 전체 Chat 기록은 Multica에 계속 표시됩니다.
## 연결 관리
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdx
index df8361be73..77b7560d6b 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx
@@ -58,12 +58,13 @@ Direct messages and group chats both support messages containing text and images
Send `/issue <title>` or `/issue <title>{newline}<detailed description>` to create a new Multica issue and automatically assign it to the agent connected to the Bot. Images in the same message are also added to the issue as attachments. Unlike regular chat messages, the `/issue` command leaves no record in Multica [Chat](/chat).
-### Start over with `/new`
+### Start a new Chat with `/new`
-Send `/new`, and the next message sent successfully will be processed by the agent in a fresh context. You can also send `/new <message>` to have the agent process that message immediately in a fresh context.
+Send `/new` to create a new empty Multica Chat and route later DingTalk messages to it. Send `/new <message>` to create the Chat and use that message as its first turn. The previous Chat remains stored and usable in Multica.
-The `/new` command only makes the agent process messages in a fresh context. It does not create a new Multica Chat.
+### Clear the current context with `/clear`
+Send `/clear` to keep the current Multica Chat while applying a fresh agent-visible context to the next message. Send `/clear <message>` to use that message as the first turn after the boundary. The complete Chat history remains visible in Multica.
## Manage connections
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
index 65d21a2f52..a4cc0e5d99 100644
--- a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx
@@ -58,12 +58,13 @@ import { Callout } from "fumadocs-ui/components/callout";
发送 `/issue <标题>` 或者 `/issue <标题>{换行}<详细描述>`,就可以创建一个新 Multica 任务,并自动指派给 Bot 连接着的智能体。同一条消息内的图片也会以附件的形式添加到该任务中。跟普通对话消息不一样的是,`/issue` 指令不会在 Multica 的“[对话](/chat)”中留下记录。
-### 使用 `/new` 重新开始
+### 使用 `/new` 新建 Chat
-发送 `/new`,再下一条成功发送的消息就会让智能体在全新的上下文中处理;也可以发送 `/new <消息>`,智能体会直接在全新的上下文中处理这条消息。
+发送 `/new` 会创建一个新的空 Multica Chat,后续钉钉消息会路由到新 Chat。发送 `/new <消息>` 会创建新 Chat,并把消息作为第一轮。之前的 Chat 仍保存在 Multica 中,可以继续使用。
-需要注意的是,`/new` 指令只是让智能体在全新的上下文中处理消息,并不会创建一个全新的 Multica “对话”。
+### 使用 `/clear` 清空当前上下文
+发送 `/clear` 会保留当前 Multica Chat,并把新的智能体可见上下文应用到下一条消息。发送 `/clear <消息>` 会把消息作为边界后的第一轮。完整 Chat 历史仍会显示在 Multica 中。
## 管理连接
diff --git a/apps/docs/content/docs/slack-bot-integration.ja.mdx b/apps/docs/content/docs/slack-bot-integration.ja.mdx
index 73d85bc296..bc66bf769d 100644
--- a/apps/docs/content/docs/slack-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.ja.mdx
@@ -1,11 +1,11 @@
---
title: Slack Bot
-description: エージェント用の Slack Bot を作成し、DM、チャンネル、/issue コマンドから利用します。
+description: エージェント用の Slack Bot を作成し、DM、チャンネル、/issue、/new、/clear コマンドから利用します。
---
import { Callout } from "fumadocs-ui/components/callout";
-Multica では、自分で作成した Slack app を使います。接続すると、チームメンバーは Bot へ DM を送る、チャンネルで @メンションする、`/issue` でイシューを作成するといった操作ができます。
+Multica では、自分で作成した Slack app を使います。接続すると、チームメンバーは Bot へ DM を送る、チャンネルで @メンションする、`/issue` でイシューを作成する、`/new` で新しい Multica Chat を開始する、`/clear` で現在の Chat のエージェントコンテキストをリセットするといった操作ができます。
1 つの Slack app に接続できる Multica エージェントは 1 つです。複数のエージェントを接続する場合は、エージェントごとに app を作成してください。
@@ -35,6 +35,12 @@ features:
- command: /issue
description: Create a Multica issue
usage_hint: "[description]"
+ - command: /new
+ description: Start a new Multica chat
+ usage_hint: "[message]"
+ - command: /clear
+ description: Clear the current Multica chat context
+ usage_hint: "[message]"
oauth_config:
scopes:
bot:
@@ -63,7 +69,11 @@ settings:
token_rotation_enabled: false
```
-作成前に、2 か所の `Multica` をエージェント名に変更してもかまいません。manifest の権限やイベントは削除しないでください。削除すると、DM、チャンネルでのメンション、返信、`/issue` が動作しないことがあります。
+作成前に、2 か所の `Multica` をエージェント名に変更してもかまいません。manifest の権限やイベントは削除しないでください。削除すると、DM、チャンネルでのメンション、返信、`/issue`、`/new`、`/clear` が動作しないことがあります。
+
+<Callout type="warning">
+Slack の slash command 名は workspace 全体で共有されます。インストール済みの別 app が `/new` または `/clear` を使用している場合、app の作成または更新時に競合するコマンドが拒否されます。競合を解消するか、メッセージ形式の `@Multica /new [メッセージ]` または `@Multica /clear [メッセージ]` を送信して、ネイティブ slash command のインターセプトを回避してください。
+</Callout>
<Callout type="warning">
添付ファイル対応が追加される前にこの Slack app をインストールしていた場合は、Bot scope に `files:read` を追加し、workspace に app を再インストールしてください。app を再インストールするまで、新しい scope は既存の Bot token に反映されません。
@@ -135,6 +145,20 @@ DM、または Bot を @ メンションしたチャンネルのメッセージ
このコマンドでは Bot の @メンションは不要です。Multica は説明を現在の Bot に対応するエージェントへ渡し、エージェントがタイトルと本文を整理してイシューを作成します。Slack には最初に自分だけが見える受付メッセージが表示されます。作成が完了すると、Multica のインボックスに通知が届きます。
+### `/new` で新しい Chat を開始する
+
+Bot との DM で `/new` を送ると、空の新しい Chat がすぐに作成され、Multica に表示されます。`/new <メッセージ>` では、そのメッセージが新しい Chat の最初のターンになります。引数なしの `/new` は、最初の有効なユーザーメッセージが届くまで「新しいチャット」と表示され、その後は既存の最初のメッセージに基づくタイトル処理が使われます。
+
+以前の Chat は Multica の Web、デスクトップ、モバイルに残り、引き続きメッセージを送信できます。新しい Chat に切り替わるのは、この Slack 会話からの後続メッセージだけです。
+
+チャンネルまたはスレッドでは、Slack のネイティブ slash command payload から対象スレッドを特定できません。対象スレッド内で `@Multica /new [メッセージ]` を送信してください。
+
+### `/clear` で現在の Chat のコンテキストをクリアする
+
+Bot との DM で `/clear` を送ると、現在の Multica Chat はそのまま維持され、エージェントから見えるコンテキストだけがリセットされます。Chat の全履歴は Multica に保存されたままです。`/clear <メッセージ>` では、そのメッセージが新しいコンテキストの最初のターンになります。引数なしの `/clear` は次の実メッセージに境界を適用します。
+
+チャンネルまたはスレッドでは、対象スレッド内で `@Multica /clear [メッセージ]` を送信してください。
+
## 接続を管理する
**設定 → 連携**を開くと、接続済みの Slack Bot をすべて確認できます。ワークスペースの owner と admin は接続を解除できます。
@@ -165,7 +189,7 @@ API サービスを再起動してから Slack app を接続します。この
- **app を検証できない**: manifest に `users:read` が含まれていることを確認します。権限を更新した後は app を再インストールしてください。
- **DM の入口がない**: `app_home.messages_tab_enabled` が `true` であることを確認します。
- **チャンネルで返信がない**: Bot がチャンネルに招待されており、メッセージで @メンションされていることを確認します。
-- **`/issue` がない**: manifest に slash command と `commands` scope が含まれていることを確認し、app を再インストールします。
+- **`/issue`、`/new`、または `/clear` がない**: manifest に 3 つの slash command と `commands` scope が含まれていることを確認し、app を再インストールします。Slack が `/new` または `/clear` は使用済みだと表示する場合は、`@Multica` のメッセージ形式を使うか、workspace 全体のコマンド競合を先に解消してください。
- **ファイルがエージェントに届かない**: manifest に `files:read` が含まれていること、scope を追加した後に app を再インストールしたことを確認し、ファイルが 20 MiB 以下かも確認します。
- **Bot が実行しない**: エージェントがアーカイブされていないことと、使用する[ランタイム](/daemon-runtimes)がオンラインであることを確認します。
diff --git a/apps/docs/content/docs/slack-bot-integration.ko.mdx b/apps/docs/content/docs/slack-bot-integration.ko.mdx
index 9f3f0566e9..f450bee2f7 100644
--- a/apps/docs/content/docs/slack-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.ko.mdx
@@ -1,11 +1,11 @@
---
title: Slack Bot
-description: 에이전트용 Slack Bot을 만들어 DM, 채널, /issue 명령에서 사용합니다.
+description: 에이전트용 Slack Bot을 만들어 DM, 채널, /issue, /new 및 /clear 명령에서 사용합니다.
---
import { Callout } from "fumadocs-ui/components/callout";
-Multica는 사용자가 직접 만든 Slack app을 사용합니다. 연결하면 팀 멤버가 Bot과 DM을 나누고 채널에서 @멘션하거나 `/issue`로 이슈를 만들 수 있습니다.
+Multica는 사용자가 직접 만든 Slack app을 사용합니다. 연결하면 팀 멤버가 Bot과 DM을 나누고, 채널에서 @멘션하고, `/issue`로 이슈를 만들고, `/new`으로 새 Multica Chat을 시작하거나 `/clear`로 현재 Chat의 에이전트 컨텍스트를 초기화할 수 있습니다.
Slack app 하나는 Multica 에이전트 하나에 대응합니다. 여러 에이전트를 연결하려면 에이전트마다 별도의 app을 만드세요.
@@ -35,6 +35,12 @@ features:
- command: /issue
description: Create a Multica issue
usage_hint: "[description]"
+ - command: /new
+ description: Start a new Multica chat
+ usage_hint: "[message]"
+ - command: /clear
+ description: Clear the current Multica chat context
+ usage_hint: "[message]"
oauth_config:
scopes:
bot:
@@ -63,7 +69,11 @@ settings:
token_rotation_enabled: false
```
-만들기 전에 두 `Multica` 값을 에이전트 이름으로 바꿀 수 있습니다. manifest의 권한이나 이벤트를 삭제하지 마세요. 삭제하면 DM, 채널 멘션, 답글, `/issue`가 작동하지 않을 수 있습니다.
+만들기 전에 두 `Multica` 값을 에이전트 이름으로 바꿀 수 있습니다. manifest의 권한이나 이벤트를 삭제하지 마세요. 삭제하면 DM, 채널 멘션, 답글, `/issue`, `/new`, `/clear`가 작동하지 않을 수 있습니다.
+
+<Callout type="warning">
+Slack slash command 이름은 workspace 전체에서 공유됩니다. 설치된 다른 app이 이미 `/new` 또는 `/clear`를 사용 중이면 app을 만들거나 업데이트할 때 충돌하는 명령이 거부됩니다. 충돌을 해결하거나 메시지 형식인 `@Multica /new [메시지]` 또는 `@Multica /clear [메시지]`를 보내 네이티브 slash command 가로채기를 우회하세요.
+</Callout>
<Callout type="warning">
첨부 파일 지원이 추가되기 전에 이 Slack app을 설치했다면 Bot scope에 `files:read`를 추가하고 workspace에 app을 다시 설치하세요. app을 다시 설치하기 전에는 새 scope가 기존 Bot token에 적용되지 않습니다.
@@ -135,6 +145,20 @@ DM이나 Bot을 @멘션한 채널 메시지에 파일을 그대로 첨부하세
이 명령에는 Bot @멘션이 필요 없습니다. Multica가 설명을 현재 Bot에 연결된 에이전트로 보내고 에이전트가 제목과 본문을 정리해 이슈를 만듭니다. Slack에는 먼저 나에게만 보이는 접수 메시지가 표시되며 생성이 끝나면 Multica 인박스에 알림이 도착합니다.
+### `/new`으로 새 Chat 시작하기
+
+Bot과의 DM에서 `/new`을 보내면 비어 있는 새 Chat이 즉시 생성되어 Multica에 표시됩니다. `/new <메시지>`를 보내면 해당 메시지가 새 Chat의 첫 번째 대화가 됩니다. 인자 없는 `/new`은 첫 번째 유효한 사용자 메시지가 도착할 때까지 “새 채팅”으로 표시되고, 이후에는 기존의 첫 메시지 제목 처리 방식을 따릅니다.
+
+이전 Chat은 Multica의 웹, 데스크톱, 모바일에 남아 있으며 계속 메시지를 보낼 수 있습니다. 이 Slack 대화의 후속 메시지만 새 Chat으로 라우팅됩니다.
+
+채널이나 thread에서는 Slack의 네이티브 slash command payload로 대상 thread를 식별할 수 없습니다. 대상 thread에서 `@Multica /new [메시지]`를 보내세요.
+
+### `/clear`로 현재 Chat 컨텍스트 지우기
+
+Bot과의 DM에서 `/clear`를 보내면 현재 Multica Chat은 유지되고 에이전트에게 보이는 컨텍스트만 초기화됩니다. 전체 Chat 기록은 Multica에 그대로 저장됩니다. `/clear <메시지>`는 해당 메시지를 새 컨텍스트의 첫 번째 대화로 사용하고, 인자 없는 `/clear`는 다음 실제 메시지에 경계를 적용합니다.
+
+채널이나 thread에서는 대상 thread에서 `@Multica /clear [메시지]`를 보내세요.
+
## 연결 관리
**설정 → 연동**에서 연결된 모든 Slack Bot을 확인할 수 있습니다. 워크스페이스 owner와 admin이 연결을 해제할 수 있습니다.
@@ -165,7 +189,7 @@ API 서비스를 다시 시작한 뒤 Slack app을 연결하세요. 이 키는
- **app을 확인할 수 없음**: manifest에 `users:read`가 포함되어 있는지 확인하고 권한을 업데이트한 뒤 app을 다시 설치합니다.
- **DM 메뉴가 없음**: `app_home.messages_tab_enabled`가 `true`인지 확인합니다.
- **채널에서 답변이 없음**: Bot이 채널에 초대되었고 메시지에서 @멘션했는지 확인합니다.
-- **`/issue`가 없음**: manifest에 slash command와 `commands` scope가 포함되어 있는지 확인하고 app을 다시 설치합니다.
+- **`/issue`, `/new` 또는 `/clear`가 없음**: manifest에 세 slash command와 `commands` scope가 포함되어 있는지 확인하고 app을 다시 설치합니다. Slack에서 `/new` 또는 `/clear`가 이미 사용 중이라고 표시되면 `@Multica` 메시지 형식을 사용하거나 workspace 수준의 명령 충돌을 먼저 해결하세요.
- **파일이 에이전트에 도착하지 않음**: manifest에 `files:read`가 포함되어 있는지, scope를 추가한 뒤 app을 다시 설치했는지 확인하고, 파일이 20 MiB 이하인지도 확인합니다.
- **Bot이 실행되지 않음**: 에이전트가 보관 처리되었는지, 사용하는 [런타임](/daemon-runtimes)이 온라인인지 확인합니다.
diff --git a/apps/docs/content/docs/slack-bot-integration.mdx b/apps/docs/content/docs/slack-bot-integration.mdx
index 87aad9fca2..d2fb324b66 100644
--- a/apps/docs/content/docs/slack-bot-integration.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.mdx
@@ -1,11 +1,11 @@
---
title: Slack Bot
-description: Create a Slack Bot for an agent and use it in DMs, channels, and the /issue command.
+description: Create a Slack Bot for an agent and use it in DMs, channels, and the /issue, /new, and /clear commands.
---
import { Callout } from "fumadocs-ui/components/callout";
-Multica uses your own Slack app. Once connected, team members can DM the Bot, @-mention it in a channel, or use `/issue` to create issues.
+Multica uses your own Slack app. Once connected, team members can DM the Bot, @-mention it in a channel, use `/issue` to create issues, use `/new` to start a new Multica Chat, or use `/clear` to reset the current Chat's agent context.
One Slack app maps to one Multica agent. To connect several agents, create a separate app for each.
@@ -35,6 +35,12 @@ features:
- command: /issue
description: Create a Multica issue
usage_hint: "[description]"
+ - command: /new
+ description: Start a new Multica chat
+ usage_hint: "[message]"
+ - command: /clear
+ description: Clear the current Multica chat context
+ usage_hint: "[message]"
oauth_config:
scopes:
bot:
@@ -63,7 +69,11 @@ settings:
token_rotation_enabled: false
```
-Before creating, you can replace both occurrences of `Multica` with the agent's name. Do not remove scopes or events from the manifest, or DMs, channel mentions, replies, or `/issue` may stop working.
+Before creating, you can replace both occurrences of `Multica` with the agent's name. Do not remove scopes or events from the manifest, or DMs, channel mentions, replies, `/issue`, `/new`, or `/clear` may stop working.
+
+<Callout type="warning">
+Slack slash-command names are workspace-global. If another installed app already owns `/new` or `/clear`, Slack rejects the conflicting command when you create or update the app. Resolve the collision, or send the message form — `@Multica /new [message]` or `@Multica /clear [message]` — to bypass native slash-command interception.
+</Callout>
<Callout type="warning">
If this Slack app was installed before attachment support was available, add the `files:read` Bot scope and reinstall the app to the workspace. Slack does not apply newly added scopes to the existing Bot token until the app is reinstalled.
@@ -137,6 +147,20 @@ In a channel or DM, type:
This command needs no @-mention. Multica hands the description to the agent behind the current Bot, which writes up the title and body and creates the issue. Slack first shows an acknowledgment visible only to you; when the issue is created, you get a notification in your Multica inbox.
+### Start a new Chat with `/new`
+
+In a DM with the Bot, `/new` immediately creates a new, visible empty Chat. `/new <message>` creates the Chat and uses the message as its first turn. A bare `/new` displays as **New chat** until the first effective user message arrives; the title then follows the existing first-message title behavior.
+
+The previous Chat remains available and writable in Multica on the web, desktop, and mobile. Only subsequent messages from this Slack conversation are routed to the new Chat.
+
+In a channel or thread, Slack's native slash-command payload does not identify the target thread. Send `@Multica /new [message]` in the target thread instead.
+
+### Clear the current Chat context with `/clear`
+
+In a DM with the Bot, `/clear` keeps the current Multica Chat and resets only the context visible to the agent. The complete Chat history remains stored and visible in Multica. `/clear <message>` uses the message as the first turn in the new context; a bare `/clear` applies the boundary to the next real message.
+
+In a channel or thread, send `@Multica /clear [message]` in the target thread so Multica can apply the boundary to the correct conversation.
+
## Manage connections
Open **Settings → Integrations** to view all connected Slack Bots. Workspace owners and admins can disconnect them.
@@ -167,7 +191,7 @@ Account binding links use `MULTICA_APP_URL`, falling back to `FRONTEND_ORIGIN` w
- **App can't be verified**: confirm the manifest includes `users:read`, then reinstall the app after updating permissions.
- **No DM entry point**: confirm `app_home.messages_tab_enabled` is `true`.
- **No reply in a channel**: confirm the Bot has been invited to the channel and the message @-mentions it.
-- **`/issue` doesn't exist**: confirm the manifest includes the slash command and the `commands` scope, then reinstall the app.
+- **`/issue`, `/new`, or `/clear` doesn't exist**: confirm the manifest includes all three slash commands and the `commands` scope, then reinstall the app. If Slack reports that `/new` or `/clear` is already taken, use the `@Multica` message form or resolve the workspace-level command collision first.
- **Files don't reach the agent**: confirm the manifest includes `files:read` and that the app was reinstalled after the scope was added, and check the file is 20 MiB or smaller.
- **The Bot doesn't run**: check whether the agent is archived and whether the [runtime](/daemon-runtimes) it uses is online.
diff --git a/apps/docs/content/docs/slack-bot-integration.zh.mdx b/apps/docs/content/docs/slack-bot-integration.zh.mdx
index 8a6b667591..70809d7fd3 100644
--- a/apps/docs/content/docs/slack-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/slack-bot-integration.zh.mdx
@@ -1,11 +1,11 @@
---
title: Slack Bot
-description: 为智能体创建一个 Slack Bot,在私聊、频道和 /issue 命令中使用它。
+description: 为智能体创建一个 Slack Bot,在私聊、频道以及 /issue、/new、/clear 命令中使用它。
---
import { Callout } from "fumadocs-ui/components/callout";
-Multica 使用你自己的 Slack app。连接后,团队成员可以私聊 Bot、在频道里 @ 它,或用 `/issue` 创建 issue。
+Multica 使用你自己的 Slack app。连接后,团队成员可以私聊 Bot、在频道里 @ 它、用 `/issue` 创建 issue、用 `/new` 新建 Multica Chat,或用 `/clear` 重置当前 Chat 的智能体上下文。
一个 Slack app 对应一个 Multica 智能体。需要接入多个智能体时,为每个智能体分别创建 app。
@@ -35,6 +35,12 @@ features:
- command: /issue
description: Create a Multica issue
usage_hint: "[description]"
+ - command: /new
+ description: Start a new Multica chat
+ usage_hint: "[message]"
+ - command: /clear
+ description: Clear the current Multica chat context
+ usage_hint: "[message]"
oauth_config:
scopes:
bot:
@@ -63,7 +69,11 @@ settings:
token_rotation_enabled: false
```
-创建前可以把两个 `Multica` 改成智能体的名字。不要删除 manifest 中的权限或事件,否则私聊、频道提及、回复或 `/issue` 可能无法工作。
+创建前可以把两个 `Multica` 改成智能体的名字。不要删除 manifest 中的权限或事件,否则私聊、频道提及、回复、`/issue`、`/new` 或 `/clear` 可能无法工作。
+
+<Callout type="warning">
+Slack slash command 名称在整个 workspace 中共享。如果其他已安装 app 占用了 `/new` 或 `/clear`,Slack 会在创建或更新 app 时拒绝冲突命令。可以先解决名称冲突,也可以发送消息形式的 `@Multica /new [消息]` 或 `@Multica /clear [消息]`,绕过原生 slash command 拦截。
+</Callout>
<Callout type="warning">
如果这个 Slack app 是在附件支持上线前安装的,请添加 `files:read` Bot scope,并将 app 重新安装到 workspace。在重新安装 app 前,新增 scope 不会应用到现有 Bot token。
@@ -137,6 +147,20 @@ Bot 只会响应明确 @ 它的频道消息。执行时,它会在权限允许
这条命令不需要 @ Bot。Multica 会把描述交给当前 Bot 对应的智能体,由它整理标题和正文并创建 issue。Slack 会先显示一条仅你可见的接收提示;创建完成后,你会在 Multica 收件箱中收到通知。
+### 用 `/new` 新建 Chat
+
+在与 Bot 的私聊中,发送 `/new` 会立即创建一个空的、可见的新 Chat;发送 `/new <消息>` 会把消息作为新 Chat 的第一轮。裸 `/new` 在第一条有效用户消息到来前显示为“新对话”,之后沿用现有的首条消息标题逻辑。
+
+旧 Chat 仍保留在 Multica 中,并可继续从 Web、桌面端或移动端发送消息;只有 Slack 这条外部会话的后续消息会切换到新 Chat。
+
+在频道或 thread 中,Slack 原生 slash command 的 payload 不包含目标 thread。请在目标 thread 里发送 `@Multica /new [消息]`。
+
+### 用 `/clear` 清空当前 Chat 上下文
+
+在与 Bot 的私聊中,`/clear` 会保留当前 Multica Chat,只重置智能体可见的上下文。完整 Chat 历史仍保存在 Multica 中。`/clear <消息>` 会把消息作为新上下文的第一轮;裸 `/clear` 会把边界应用到下一条真实消息。
+
+在频道或 thread 中,请在目标 thread 里发送 `@Multica /clear [消息]`,让 Multica 把边界应用到正确的会话。
+
## 管理连接
打开 **设置 → 集成** 可以查看所有已连接的 Slack Bot。工作区 owner 和 admin 可以断开连接。
@@ -167,7 +191,7 @@ openssl rand -base64 32
- **无法验证 app**:确认 manifest 包含 `users:read`,更新权限后重新安装 app。
- **私聊没有入口**:确认 `app_home.messages_tab_enabled` 为 `true`。
- **频道里没有回复**:确认 Bot 已被邀请进频道,并在消息中 @ 了它。
-- **`/issue` 不存在**:确认 manifest 包含 slash command 和 `commands` scope,随后重新安装 app。
+- **`/issue`、`/new` 或 `/clear` 不存在**:确认 manifest 包含这三个 slash command 和 `commands` scope,随后重新安装 app。如果 Slack 提示 `/new` 或 `/clear` 已被占用,请改用 `@Multica` 消息形式,或先解决 workspace 级命令冲突。
- **文件没有送达智能体**:确认 manifest 里包含 `files:read`,并且在添加该权限后重新安装过应用,同时确认文件不超过 20 MiB。
- **Bot 不执行**:检查智能体是否已归档,以及它使用的[运行时](/daemon-runtimes)是否在线。
diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
index b48458b39e..82ae36878f 100644
--- a/apps/docs/content/docs/telegram-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
@@ -44,7 +44,8 @@ Multica は Telegram で Bot を検証し、long polling と競合する webhook
- **DM**: @mention なしでテキストを送信します。
- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残りますが、Bot 宛てでない会話は収集されません。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。
-- **`/new <message>`**: 過去の文脈なしで実行します。他のメンバーへの返信で Bot を明示的に @mention した場合、選択した引用内容はこの新しい指示にも含まれます。`/new` だけなら次の空でないメッセージに適用されます。
+- **`/new` / `/new <message>`**: 空の新しい Multica Chat を作成し、その Telegram 会話の後続メッセージを新しい Chat にルーティングします。メッセージを付けた場合は新しい Chat の最初のターンになります。他のメンバーへの返信で Bot を明示的に @mention した場合、選択した引用内容も最初のターンに含まれます。
+- **`/clear` / `/clear <message>`**: 現在の Multica Chat を維持したまま、次の空でないメッセージに新しいエージェント可視コンテキストを適用します。メッセージを付けた場合は境界後の最初のターンになり、明示的に選択した返信の引用も保持されます。
- **`/issue <title>`**: Multica issue を作成します。2 行目以降は任意の説明です。`/issue@your_bot` 形式も利用できます。
Bot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は自動分割されます。最終返信はプロセス内で非同期に配信されます。通常、あるチャットのバックオフ待機は worker を占有しません。キャッシュが上限に達してバックオフ状態が圧縮されると、同じ Bot installation の他のチャットも安全側に遅延する場合があります。終端キューの容量は固定で、上限超過は明示的に拒否されてエラーとして記録されます。キューはサービス再起動後に復元されません。
diff --git a/apps/docs/content/docs/telegram-bot-integration.ko.mdx b/apps/docs/content/docs/telegram-bot-integration.ko.mdx
index 7bd9346d92..2a4f283323 100644
--- a/apps/docs/content/docs/telegram-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx
@@ -44,7 +44,8 @@ Multica는 Telegram에서 Bot을 검증하고 long polling과 충돌하는 webho
- **개인 채팅**: @mention 없이 텍스트를 보냅니다.
- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남지만 Bot을 지정하지 않은 그룹 대화는 수집하지 않습니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.
-- **`/new <message>`**: 이전 대화 맥락 없이 실행합니다. 다른 멤버의 메시지에 답장하면서 Bot을 명시적으로 @mention하면 선택한 인용 내용도 이 새 지시에 포함됩니다. `/new`만 보내면 다음 비어 있지 않은 메시지에 적용됩니다.
+- **`/new` / `/new <message>`**: 비어 있는 새 Multica Chat을 만들고 해당 Telegram 대화의 이후 메시지를 새 Chat으로 라우팅합니다. 메시지를 함께 보내면 새 Chat의 첫 번째 대화가 됩니다. 다른 멤버에게 답장하면서 Bot을 명시적으로 @mention하면 선택한 인용 내용도 첫 번째 대화에 포함됩니다.
+- **`/clear` / `/clear <message>`**: 현재 Multica Chat을 유지하면서 다음 비어 있지 않은 메시지에 새 에이전트 컨텍스트를 적용합니다. 메시지를 함께 보내면 경계 이후의 첫 번째 대화가 되며 명시적으로 선택한 답장 인용도 유지됩니다.
- **`/issue <title>`**: Multica issue를 만듭니다. 다음 줄은 선택 설명으로 사용됩니다. `/issue@your_bot` 형식도 지원합니다.
Bot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 자동으로 나뉩니다. 최종 응답은 프로세스 내에서 비동기로 전달됩니다. 일반적으로 한 채팅의 백오프 대기는 worker를 점유하지 않습니다. 캐시가 용량 한계에 도달해 백오프 상태를 압축하면 같은 Bot installation의 다른 채팅도 안전을 위해 지연될 수 있습니다. 최종 응답 큐의 용량은 고정되어 있으며 한도를 넘은 작업은 명시적으로 거부되고 오류로 기록됩니다. 큐는 서비스 재시작 후 복구되지 않습니다.
diff --git a/apps/docs/content/docs/telegram-bot-integration.mdx b/apps/docs/content/docs/telegram-bot-integration.mdx
index 518914bff1..4a2b2982aa 100644
--- a/apps/docs/content/docs/telegram-bot-integration.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.mdx
@@ -54,7 +54,8 @@ Add the Bot to a group, then either @-mention it or reply directly to one of its
### Commands
-- `/new <message>` runs the message without previous chat context. In an explicitly mentioned reply to another person, the selected quote remains attached to that fresh instruction. Sending `/new` by itself applies the fresh start to the next non-empty message.
+- `/new` creates a new empty Multica Chat and routes later messages in the Telegram conversation to it. `/new <message>` creates the Chat with that message as its first turn. In an explicitly mentioned reply to another person, the selected quote remains attached to that first turn.
+- `/clear` keeps the current Multica Chat and applies a fresh agent-visible context to the next non-empty message. `/clear <message>` uses that message as the first turn after the context boundary; an explicitly selected reply quote remains attached.
- `/issue <title>` creates a Multica issue; following lines are used as its optional description. `/issue` without a title returns usage guidance.
- Telegram command suffixes such as `/issue@your_bot` are supported in groups.
diff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
index 508f24ce36..3436200f4b 100644
--- a/apps/docs/content/docs/telegram-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
@@ -54,7 +54,8 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲
### 命令
-- `/new <消息>` 让这条消息不带旧上下文运行;在回复其他成员并明确 @ Bot 时,被选中的引用内容仍会随这条 fresh 指令进入上下文。单独发送 `/new` 会把 fresh 意图应用到下一条非空消息。
+- `/new` 创建一个新的空 Multica Chat,并把该 Telegram 对话的后续消息路由到新 Chat;`/new <消息>` 会把消息作为新 Chat 的第一轮。回复其他成员并明确 @ Bot 时,被选中的引用内容仍会附在第一轮中。
+- `/clear` 保留当前 Multica Chat,把新的智能体可见上下文应用到下一条非空消息;`/clear <消息>` 会把消息作为上下文边界后的第一轮,明确选择的回复引用仍会保留。
- `/issue <标题>` 创建 Multica issue,后续行作为可选描述;不带标题时返回用法提示。
- 群聊支持 `/issue@your_bot` 这种 Telegram 命令后缀。
diff --git a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
index dffedde497..3eb4beec6f 100644
--- a/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
+++ b/apps/mobile/app/(app)/[workspace]/(tabs)/chat.tsx
@@ -92,6 +92,7 @@ import { OfflineBanner } from "@/components/chat/offline-banner";
import { RuntimeRequiredBanner } from "@/components/chat/runtime-required-banner";
import { useChatSelectStore } from "@/data/chat-select-store";
import { isAgentRuntimeBound } from "@/lib/is-agent-runtime-bound";
+import { chatSessionDisplayTitle } from "@/lib/chat-session-title";
export default function ChatTab() {
const qc = useQueryClient();
@@ -450,7 +451,7 @@ export default function ChatTab() {
if (!activeSession) return;
Alert.alert(
"Delete this chat?",
- activeSession.title || "Untitled chat",
+ chatSessionDisplayTitle(activeSession.title),
[
{ text: "Cancel", style: "cancel" },
{
diff --git a/apps/mobile/app/(app)/[workspace]/chat-sessions.tsx b/apps/mobile/app/(app)/[workspace]/chat-sessions.tsx
index cf1ea13747..4a5b65db50 100644
--- a/apps/mobile/app/(app)/[workspace]/chat-sessions.tsx
+++ b/apps/mobile/app/(app)/[workspace]/chat-sessions.tsx
@@ -20,6 +20,7 @@ import { useDeleteChatSession } from "@/data/mutations/chat";
import { useChatSessionPickerStore } from "@/data/stores/chat-session-picker-store";
import { useWorkspaceStore } from "@/data/workspace-store";
import { cn } from "@/lib/utils";
+import { chatSessionDisplayTitle } from "@/lib/chat-session-title";
export default function ChatSessionsRoute() {
const wsId = useWorkspaceStore((s) => s.currentWorkspaceId);
@@ -31,7 +32,7 @@ export default function ChatSessionsRoute() {
const confirmDelete = (session: ChatSession) => {
Alert.alert(
"Delete this chat?",
- session.title || "Untitled chat",
+ chatSessionDisplayTitle(session.title),
[
{ text: "Cancel", style: "cancel" },
{
@@ -100,7 +101,7 @@ export default function ChatSessionsRoute() {
)}
numberOfLines={1}
>
- {session.title || "Untitled chat"}
+ {chatSessionDisplayTitle(session.title)}
</Text>
{archived ? (
<Text className="text-xs text-muted-foreground mt-0.5">
diff --git a/apps/mobile/components/chat/chat-title-button.tsx b/apps/mobile/components/chat/chat-title-button.tsx
index 5e4e1b58bd..3d938dd5a4 100644
--- a/apps/mobile/components/chat/chat-title-button.tsx
+++ b/apps/mobile/components/chat/chat-title-button.tsx
@@ -8,6 +8,7 @@ import { Pressable, View } from "react-native";
import type { Agent, ChatSession } from "@multica/core/types";
import { Text } from "@/components/ui/text";
import { ActorAvatar } from "@/components/ui/actor-avatar";
+import { chatSessionDisplayTitle } from "@/lib/chat-session-title";
interface Props {
currentSession: ChatSession | null;
@@ -21,7 +22,7 @@ export function ChatTitleButton({
onPress,
}: Props) {
const agentName = currentAgent?.name ?? "Chat";
- const subtitle = currentSession?.title || "New chat";
+ const subtitle = chatSessionDisplayTitle(currentSession?.title);
return (
<Pressable
diff --git a/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts b/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts
new file mode 100644
index 0000000000..d786ba2e1d
--- /dev/null
+++ b/apps/mobile/data/realtime/use-chat-sessions-realtime.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { invalidateQueries, subscriptionSetups } = vi.hoisted(() => ({
+ invalidateQueries: vi.fn(),
+ subscriptionSetups: [] as Array<(ws: MockWS, wsId: string) => Array<() => void>>,
+}));
+
+type EventHandler = (payload: unknown) => void;
+
+interface MockWS {
+ on: ReturnType<typeof vi.fn>;
+ onReconnect: ReturnType<typeof vi.fn>;
+}
+
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => ({ invalidateQueries }),
+}));
+
+vi.mock("@/lib/use-ws-subscriptions", () => ({
+ useWSSubscriptions: (setup: (ws: MockWS, wsId: string) => Array<() => void>) => {
+ subscriptionSetups.push(setup);
+ },
+}));
+
+vi.mock("@/data/api", () => ({ api: {} }));
+
+import { chatKeys } from "@/data/queries/chat";
+import { useChatSessionsRealtime } from "./use-chat-sessions-realtime";
+
+describe("useChatSessionsRealtime", () => {
+ beforeEach(() => {
+ invalidateQueries.mockReset();
+ subscriptionSetups.length = 0;
+ });
+
+ it("invalidates the workspace session list for channel-created chats", () => {
+ useChatSessionsRealtime();
+ expect(subscriptionSetups).toHaveLength(1);
+
+ const handlers = new Map<string, EventHandler>();
+ const ws: MockWS = {
+ on: vi.fn((event: string, handler: EventHandler) => {
+ handlers.set(event, handler);
+ return () => {};
+ }),
+ onReconnect: vi.fn(() => () => {}),
+ };
+
+ subscriptionSetups[0](ws, "workspace-1");
+ handlers.get("chat:session_created")?.({
+ workspace_id: "workspace-1",
+ chat_session_id: "channel-session-1",
+ });
+
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: chatKeys.sessions("workspace-1"),
+ });
+
+ invalidateQueries.mockClear();
+ handlers.get("chat:session_created")?.({
+ workspace_id: "workspace-2",
+ chat_session_id: "other-workspace-session",
+ });
+ expect(invalidateQueries).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts b/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
index b338ee4030..e23e8e6278 100644
--- a/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
+++ b/apps/mobile/data/realtime/use-chat-sessions-realtime.ts
@@ -36,6 +36,11 @@ export function useChatSessionsRealtime() {
// chat:session_read clears the unread flag (could be triggered from
// web/desktop on the same account).
ws.on("chat:session_read", invalidateSessions),
+ // A channel /new creates a visible session without navigating this
+ // device; refresh the list and leave the current screen untouched.
+ ws.on("chat:session_created", (payload) => {
+ if (payload.workspace_id === wsId) invalidateSessions();
+ }),
// chat:session_updated has no formal payload type yet — server
// emits {chat_session_id, title?, updated_at?}. Narrow inline.
ws.on("chat:session_updated", (p) => {
diff --git a/apps/mobile/lib/chat-session-title.test.ts b/apps/mobile/lib/chat-session-title.test.ts
new file mode 100644
index 0000000000..cdeddd68ae
--- /dev/null
+++ b/apps/mobile/lib/chat-session-title.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+import { chatSessionDisplayTitle } from "./chat-session-title";
+
+describe("chatSessionDisplayTitle", () => {
+ it("uses New chat for an explicitly empty channel-created Chat", () => {
+ expect(chatSessionDisplayTitle("")).toBe("New chat");
+ expect(chatSessionDisplayTitle(null)).toBe("New chat");
+ expect(chatSessionDisplayTitle(undefined)).toBe("New chat");
+ });
+
+ it("preserves a stored or manually renamed title", () => {
+ expect(chatSessionDisplayTitle("Investigate deploy")).toBe(
+ "Investigate deploy",
+ );
+ });
+});
diff --git a/apps/mobile/lib/chat-session-title.ts b/apps/mobile/lib/chat-session-title.ts
new file mode 100644
index 0000000000..e65308aeb2
--- /dev/null
+++ b/apps/mobile/lib/chat-session-title.ts
@@ -0,0 +1,5 @@
+export const NEW_CHAT_TITLE = "New chat";
+
+export function chatSessionDisplayTitle(title: string | null | undefined): string {
+ return title || NEW_CHAT_TITLE;
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 50b2701fe2..96451dbbe6 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -244,6 +244,8 @@ import {
ChatMessageListSchema,
ChatMessagesPageSchema,
ChatPendingTaskSchema,
+ ChatSessionListSchema,
+ ChatSessionSchema,
PrioritizeQueuedChatTaskResponseSchema,
SendChatMessageResponseSchema,
StartMikaOnboardingResponseSchema,
@@ -269,6 +271,8 @@ import {
EMPTY_ATTACHMENT,
EMPTY_CHAT_MESSAGE_LIST,
EMPTY_CHAT_PENDING_TASK,
+ EMPTY_CHAT_SESSION,
+ EMPTY_CHAT_SESSION_LIST,
EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
EMPTY_CLOUD_RUNTIME_NODE,
EMPTY_CLOUD_RUNTIME_NODE_LIST,
@@ -3109,13 +3113,19 @@ export class ApiClient {
workspaceSlug?: string,
): Promise<ChatSession[]> {
const query = params?.status ? `?status=${params.status}` : "";
- return this.fetch(`/api/chat/sessions${query}`, {
+ const raw: unknown = await this.fetch(`/api/chat/sessions${query}`, {
headers: workspaceHeader(workspaceSlug),
});
+ return parseWithFallback(raw, ChatSessionListSchema, EMPTY_CHAT_SESSION_LIST, {
+ endpoint: "GET /api/chat/sessions",
+ });
}
async getChatSession(id: string): Promise<ChatSession> {
- return this.fetch(`/api/chat/sessions/${id}`);
+ const raw: unknown = await this.fetch(`/api/chat/sessions/${id}`);
+ return parseWithFallback(raw, ChatSessionSchema, EMPTY_CHAT_SESSION, {
+ endpoint: "GET /api/chat/sessions/:id",
+ });
}
async createChatSession(
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 1d80fbbda3..5a715be67b 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -27,11 +27,14 @@ import {
DashboardUsageDailyListSchema,
ChatDraftRestoresResponseSchema,
ChatPendingTaskSchema,
+ ChatSessionListSchema,
+ ChatSessionSchema,
PrioritizeQueuedChatTaskResponseSchema,
CreateFeedbackResponseSchema,
DuplicateIssueErrorBodySchema,
EMPTY_CHAT_DRAFT_RESTORES,
EMPTY_CHAT_PENDING_TASK,
+ EMPTY_CHAT_SESSION,
EMPTY_PRIORITIZE_QUEUED_CHAT_TASK_RESPONSE,
EMPTY_CREATE_FEEDBACK_RESPONSE,
EMPTY_INBOX_ITEMS,
@@ -130,6 +133,75 @@ describe("ChildIssueProgressResponseSchema", () => {
});
});
+describe("ChatSessionSchema", () => {
+ const baseSession = {
+ id: "chat-1",
+ workspace_id: "ws-1",
+ agent_id: "agent-1",
+ creator_id: "user-1",
+ title: "Channel chat",
+ status: "active",
+ has_unread: false,
+ created_at: "2026-08-18T00:00:00Z",
+ updated_at: "2026-08-18T00:00:00Z",
+ };
+
+ it("accepts channel route metadata and leaves it absent for first-party Chats", () => {
+ expect(ChatSessionSchema.parse(baseSession).channel_source).toBeUndefined();
+
+ const parsed = ChatSessionSchema.parse({
+ ...baseSession,
+ channel_source: {
+ channel_type: "slack",
+ installation_id: "installation-1",
+ route_revision: 3,
+ },
+ is_current_channel_route: false,
+ });
+ expect(parsed.channel_source).toEqual({
+ channel_type: "slack",
+ installation_id: "installation-1",
+ route_revision: 3,
+ });
+ expect(parsed.is_current_channel_route).toBe(false);
+ });
+
+ it("degrades malformed session metadata without dropping the Chat", () => {
+ const parsed = ChatSessionSchema.parse({
+ ...baseSession,
+ channel_source: { channel_type: 42 },
+ is_current_channel_route: "yes",
+ });
+ expect(parsed.channel_source).toBeUndefined();
+ expect(parsed.is_current_channel_route).toBeUndefined();
+ expect(parsed.id).toBe("chat-1");
+
+ expect(parseWithFallback({ id: 42 }, ChatSessionSchema, EMPTY_CHAT_SESSION, {
+ endpoint: "GET /api/chat/sessions/:id",
+ })).toEqual(EMPTY_CHAT_SESSION);
+ });
+
+ it("drops one malformed list item without hiding the other Chats", () => {
+ const parsed = ChatSessionListSchema.parse([
+ baseSession,
+ { ...baseSession, id: 42 },
+ {
+ ...baseSession,
+ id: "onboarding-chat",
+ last_message: {
+ content: "Welcome",
+ role: "assistant",
+ created_at: "2026-08-18T00:00:00Z",
+ message_kind: "onboarding_opening",
+ },
+ },
+ ]);
+
+ expect(parsed.map((session) => session.id)).toEqual(["chat-1", "onboarding-chat"]);
+ expect(parsed[1]?.last_message?.message_kind).toBe("onboarding_opening");
+ });
+});
+
describe("IssueSchema (via ListIssuesResponseSchema)", () => {
it("keeps the issue while independently dropping a malformed source context", () => {
const parsed = ListIssuesResponseSchema.parse({
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 16b8b1f023..61684ed1ee 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -15,6 +15,7 @@ import type {
ChatMessage,
ChatDraftRestoresResponse,
ChatPendingTask,
+ ChatSession,
PrioritizeQueuedChatTaskResponse,
SendChatMessageResponse,
StartMikaOnboardingResponse,
@@ -1777,6 +1778,60 @@ export const CancelTaskResponseSchema = AgentTaskSchema.extend({
.transform((value) => value ?? undefined),
}).loose();
+const ChatLastMessageSchema = z.object({
+ content: z.string().default(""),
+ role: z.enum(["user", "assistant"]).catch("assistant"),
+ created_at: z.string().default(""),
+ failure_reason: z.string().nullable().optional(),
+ message_kind: z.enum([
+ "message",
+ "no_response",
+ "onboarding_kickoff",
+ "onboarding_opening",
+ ]).optional().catch(undefined),
+}).loose();
+
+const ChatChannelSourceSchema = z.object({
+ channel_type: z.string().default(""),
+ installation_id: z.string().default(""),
+ route_revision: z.number().default(0),
+}).loose();
+
+export const ChatSessionSchema: z.ZodType<ChatSession> = z.object({
+ id: z.string(),
+ workspace_id: z.string().default(""),
+ agent_id: z.string().default(""),
+ creator_id: z.string().default(""),
+ project_id: z.string().nullable().optional(),
+ title: z.string().default(""),
+ status: z.enum(["active", "archived"]).catch("active"),
+ has_unread: z.boolean().default(false),
+ unread_count: z.number().optional(),
+ last_message: ChatLastMessageSchema.nullable().optional().catch(undefined),
+ pinned: z.boolean().optional(),
+ channel_source: ChatChannelSourceSchema.optional().catch(undefined),
+ is_current_channel_route: z.boolean().optional().catch(undefined),
+ created_at: z.string().default(""),
+ updated_at: z.string().default(""),
+}).loose();
+
+export const EMPTY_CHAT_SESSION: ChatSession = {
+ id: "",
+ workspace_id: "",
+ agent_id: "",
+ creator_id: "",
+ title: "",
+ status: "active",
+ has_unread: false,
+ created_at: "",
+ updated_at: "",
+};
+export const ChatSessionListSchema = z
+ .array(ChatSessionSchema.catch(EMPTY_CHAT_SESSION))
+ .transform((sessions) => sessions.filter((session) => session.id !== ""))
+ .default([]);
+export const EMPTY_CHAT_SESSION_LIST: ChatSession[] = [];
+
// Deferred-cancellation draft restores
// (`GET /api/chat/sessions/{id}/draft-restores`, #5219) feed the composer
// directly: `content` becomes the draft text, `attachments` re-bind on
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index f27f91d102..9f31ed5a8f 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -275,6 +275,33 @@ describe("useRealtimeSync — ws instance change", () => {
expect(invalidateSpy).not.toHaveBeenCalled();
});
+
+ it("invalidates the current workspace chat list when a channel creates a session", () => {
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, stores), {
+ wrapper: createWrapper(qc),
+ });
+ const sessionCreated = vi
+ .mocked(ws.on)
+ .mock.calls.find(([event]) => event === "chat:session_created")?.[1];
+ expect(sessionCreated).toBeDefined();
+
+ (sessionCreated as (payload: unknown) => void)({
+ workspace_id: "ws-1",
+ chat_session_id: "channel-session-1",
+ });
+
+ expect(invalidateSpy).toHaveBeenCalledWith({
+ queryKey: chatKeys.sessions("ws-1"),
+ });
+
+ invalidateSpy.mockClear();
+ (sessionCreated as (payload: unknown) => void)({
+ workspace_id: "ws-2",
+ chat_session_id: "other-workspace-session",
+ });
+ expect(invalidateSpy).not.toHaveBeenCalled();
+ });
});
describe("useRealtimeSync — queued chat promotion", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 7d53e99b81..6652c6cd9c 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -116,6 +116,7 @@ import type {
ChatPendingTask,
ChatMessagesPage,
ChatSession,
+ ChatSessionCreatedPayload,
InvitationCreatedPayload,
} from "../types";
@@ -964,7 +965,7 @@ export function useRealtimeSync(
"daemon:heartbeat",
// Chat events are handled explicitly below; do not double-invalidate.
"chat:message", "chat:done", "chat:quick_actions", "chat:cancel_finalized", "chat:session_read",
- "chat:session_deleted", "chat:session_updated",
+ "chat:session_created", "chat:session_deleted", "chat:session_updated",
// task:message stays out of the prefix path because it fires per
// streamed message during a long run — invalidating the snapshot on
// every message would flood the network. Specific chat handlers below
@@ -1644,6 +1645,13 @@ export function useRealtimeSync(
invalidateSessionLists();
});
+ const unsubChatSessionCreated = ws.on("chat:session_created", (p) => {
+ const payload = p as ChatSessionCreatedPayload;
+ chatWsLogger.info("chat:session_created (global)", payload);
+ if (payload.workspace_id !== getCurrentWsId()) return;
+ invalidateSessionLists();
+ });
+
// chat:session_updated fires after the creator renames, pins, or archives
// a session in any tab/device. Patch the cached row inline so the dropdown
// and badges reflect the change without a full sessions-list refetch — see
@@ -1724,6 +1732,7 @@ export function useRealtimeSync(
unsubTaskCompleted();
unsubTaskFailed();
unsubChatSessionRead();
+ unsubChatSessionCreated();
unsubChatSessionDeleted();
unsubChatSessionUpdated();
if (taskMessageFlushTimer) clearTimeout(taskMessageFlushTimer);
diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.ts
index f49ef7e78f..b11f32f13f 100644
--- a/packages/core/types/chat.ts
+++ b/packages/core/types/chat.ts
@@ -77,6 +77,12 @@ export interface ChatLastMessage {
message_kind?: ChatMessageKind;
}
+export interface ChatChannelSource {
+ channel_type: string;
+ installation_id: string;
+ route_revision: number;
+}
+
export interface ChatSession {
id: string;
workspace_id: string;
@@ -98,6 +104,11 @@ export interface ChatSession {
/** True when the user has pinned this chat to the top of the list.
* Optional so older clients / non-list payloads stay valid. */
pinned?: boolean;
+ /** Present for Chats created by an external Channel. Historical Chats keep
+ * their source even after a newer route generation becomes current. */
+ channel_source?: ChatChannelSource;
+ /** Absent for first-party Chats. */
+ is_current_channel_route?: boolean;
created_at: string;
updated_at: string;
}
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index 88ae17792c..df159713ba 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -60,6 +60,7 @@ export type WSEventType =
| "chat:done"
| "chat:quick_actions"
| "chat:cancel_finalized"
+ | "chat:session_created"
| "chat:session_read"
| "chat:session_deleted"
| "chat:session_updated"
@@ -522,6 +523,20 @@ export interface InvitationRevokedPayload {
invitee_email: string;
}
+export interface ChatSessionCreatedPayload {
+ workspace_id: string;
+ chat_session_id: string;
+ agent_id: string;
+ creator_id: string;
+ title: string;
+ channel_source: {
+ channel_type: string;
+ installation_id: string;
+ route_revision: number;
+ };
+ is_current_channel_route: boolean;
+}
+
/**
* Maps every WSEventType to its payload interface. Events whose payload
* shape isn't formally typed (server emits an object the client doesn't
@@ -586,6 +601,7 @@ export interface WSEventPayloadMap {
"chat:done": ChatDonePayload;
"chat:quick_actions": ChatQuickActionsPayload;
"chat:cancel_finalized": ChatCancelFinalizedPayload;
+ "chat:session_created": ChatSessionCreatedPayload;
"chat:session_read": ChatSessionReadPayload;
"chat:session_deleted": ChatSessionDeletedPayload;
"chat:session_updated": unknown;
diff --git a/server/cmd/migrate/channel_chat_route_rollback_test.go b/server/cmd/migrate/channel_chat_route_rollback_test.go
new file mode 100644
index 0000000000..1c6238d7ae
--- /dev/null
+++ b/server/cmd/migrate/channel_chat_route_rollback_test.go
@@ -0,0 +1,104 @@
+package main
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestChannelChatRouteRollbackGuardRunsBeforeConcurrentIndexDrop(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ schema := "channel_route_rollback_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE chat_session (
+ id UUID PRIMARY KEY,
+ explicitly_created_at TIMESTAMPTZ
+ );
+ CREATE TABLE channel_chat_session_binding (
+ id UUID PRIMARY KEY,
+ chat_session_id UUID NOT NULL,
+ retired_at TIMESTAMPTZ
+ );
+ CREATE TABLE channel_outbound_message (
+ channel_message_id TEXT NOT NULL,
+ binding_id UUID NOT NULL,
+ route_revision BIGINT NOT NULL
+ );
+ CREATE INDEX idx_channel_outbound_message_binding_route
+ ON channel_outbound_message(binding_id, route_revision);
+ INSERT INTO chat_session (id, explicitly_created_at)
+ VALUES ('22222222-2222-2222-2222-222222222222', NULL);
+ INSERT INTO channel_chat_session_binding (id, chat_session_id, retired_at)
+ VALUES (
+ '11111111-1111-1111-1111-111111111111',
+ '22222222-2222-2222-2222-222222222222',
+ now()
+ );
+ `); err != nil {
+ t.Fatalf("create fixture: %v", err)
+ }
+
+ err = refuseChannelChatRouteHistoryRollbackWith(ctx, conn)
+ if err == nil || !strings.Contains(err.Error(), "cannot roll back channel chat routes") {
+ t.Fatalf("rollback error = %v, want route-history refusal", err)
+ }
+ var indexExists bool
+ if err := conn.QueryRow(ctx, `SELECT to_regclass('idx_channel_outbound_message_binding_route') IS NOT NULL`).Scan(&indexExists); err != nil {
+ t.Fatalf("check preserved index: %v", err)
+ }
+ if !indexExists {
+ t.Fatal("concurrent index was dropped despite refused rollback")
+ }
+
+ if _, err := conn.Exec(ctx, `
+ UPDATE channel_chat_session_binding SET retired_at = NULL;
+ UPDATE chat_session SET explicitly_created_at = now();
+ `); err != nil {
+ t.Fatalf("replace route history with an explicitly created active route: %v", err)
+ }
+ if err := refuseChannelChatRouteHistoryRollbackWith(ctx, conn); err == nil || !strings.Contains(err.Error(), "cannot roll back channel chat routes") {
+ t.Fatalf("rollback error = %v, want explicit channel Chat refusal", err)
+ }
+
+ if _, err := conn.Exec(ctx, `DELETE FROM channel_chat_session_binding`); err != nil {
+ t.Fatalf("clear route history: %v", err)
+ }
+ if err := refuseChannelChatRouteHistoryRollbackWith(ctx, conn); err != nil {
+ t.Fatalf("guard without route history: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `DROP INDEX CONCURRENTLY idx_channel_outbound_message_binding_route`); err != nil {
+ t.Fatalf("drop index after guard: %v", err)
+ }
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index a48765564e..31a650ad89 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/attributionbackfill"
+ "github.com/multica-ai/multica/server/internal/chatoriginbackfill"
"github.com/multica-ai/multica/server/internal/dbstartup"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/migrations"
@@ -264,6 +265,12 @@ var concurrentIndexCleanups = map[string]string{
"416_seat_capacity_operation_token_index": "idx_seat_capacity_outbox_operation_token",
"418_seat_capacity_due_index": "idx_seat_capacity_outbox_due",
"419_seat_capacity_share_join_index": "idx_seat_capacity_outbox_share_join",
+ "421_channel_chat_active_route_index": "idx_channel_chat_session_binding_active_route",
+ "423_channel_task_delivery_pkey_index": "channel_task_delivery_pkey",
+ "426_channel_outbound_message_id_index": "idx_channel_outbound_message_id",
+ "428_channel_task_delivery_binding_index": "idx_channel_task_delivery_binding",
+ "429_channel_task_delivery_installation_index": "idx_channel_task_delivery_installation",
+ "430_channel_outbound_message_binding_index": "idx_channel_outbound_message_binding_route",
}
// concurrentDownIndexCleanups covers every migration whose down direction
@@ -277,6 +284,7 @@ var concurrentDownIndexCleanups = map[string]string{
"256_drop_agent_task_queue_chat_pending_v2": "idx_agent_task_queue_chat_pending_v2",
"258_drop_pending_issue_agent_v1": "idx_one_pending_task_per_issue_agent",
"262_drop_agent_task_queue_terminal_completed_at_v1": "idx_agent_task_queue_terminal_completed_at",
+ "422_channel_chat_route_history": "channel_chat_session_binding_installation_id_channel_chat_i_key",
"300_drop_redundant_issue_workspace_number_index": "idx_issue_workspace_number",
"301_drop_redundant_sys_cron_job_plan_index": "idx_sys_cron_exec_job_plan",
"302_drop_redundant_channel_chat_session_binding_index": "idx_channel_chat_session_binding_session",
@@ -291,6 +299,7 @@ var preMigrationHooks = func() map[string]preMigrationHook {
hooks := map[string]preMigrationHook{
"103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,
"198_agent_task_attribution_strict_constraint_validate": runAttributionStrictHook,
+ "431_chat_explicit_origin_backfill": runChatOriginBackfillHook,
}
for version, index := range concurrentIndexCleanups {
hooks[version] = cleanupInvalidConcurrentIndexHook(index)
@@ -299,7 +308,7 @@ var preMigrationHooks = func() map[string]preMigrationHook {
}()
var preRollbackHooks = func() map[string]preMigrationHook {
- hooks := make(map[string]preMigrationHook, len(concurrentDownIndexCleanups)+len(sourceContextMigrationVersions))
+ hooks := make(map[string]preMigrationHook, len(concurrentDownIndexCleanups)+len(sourceContextMigrationVersions)+1)
for version, index := range concurrentDownIndexCleanups {
hooks[version] = cleanupInvalidConcurrentIndexHook(index)
}
@@ -309,6 +318,7 @@ var preRollbackHooks = func() map[string]preMigrationHook {
for _, version := range sourceContextMigrationVersions {
hooks[version] = ensureSourceContextRollbackSafe
}
+ hooks["430_channel_outbound_message_binding_index"] = refuseChannelChatRouteHistoryRollback
return hooks
}()
@@ -323,6 +333,38 @@ var sourceContextMigrationVersions = []string{
"414_issue_source_context_object_intent_context_index",
}
+type rowQuerier interface {
+ QueryRow(context.Context, string, ...any) pgx.Row
+}
+
+func refuseChannelChatRouteHistoryRollback(ctx context.Context, pool *pgxpool.Pool) error {
+ return refuseChannelChatRouteHistoryRollbackWith(ctx, pool)
+}
+
+func runChatOriginBackfillHook(ctx context.Context, pool *pgxpool.Pool) error {
+ _, err := chatoriginbackfill.Hook(ctx, pool, chatoriginbackfill.HookOptions{})
+ return err
+}
+
+func refuseChannelChatRouteHistoryRollbackWith(ctx context.Context, query rowQuerier) error {
+ var channelChatRouteStateExists bool
+ if err := query.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM channel_chat_session_binding AS binding
+ LEFT JOIN chat_session AS session ON session.id = binding.chat_session_id
+ WHERE binding.retired_at IS NOT NULL
+ OR session.explicitly_created_at IS NOT NULL
+ )
+ `).Scan(&channelChatRouteStateExists); err != nil {
+ return fmt.Errorf("check channel chat route state: %w", err)
+ }
+ if channelChatRouteStateExists {
+ return errors.New("cannot roll back channel chat routes after /new has created a channel Chat")
+ }
+ return nil
+}
+
var upMigrationConditions = map[string]migrationCondition{
// Fresh databases that successfully built the CJK-friendly bigram index do
// not need to build the trigram fallback only to remove it at migration 371.
diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.go
index a53f79ab64..78b3464952 100644
--- a/server/cmd/server/listeners.go
+++ b/server/cmd/server/listeners.go
@@ -87,6 +87,8 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
protocol.EventInboxBatchArchived: true,
protocol.EventInvitationCreated: true,
protocol.EventInvitationRevoked: true,
+ protocol.EventChatSessionCreated: true,
+ protocol.EventChatSessionUpdated: true,
}
// Helper: marshal event and send to a specific user.
@@ -175,6 +177,16 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {
}
})
+ // A Chat session is creator-private. Its initial title may be derived from
+ // the creator's first message, so the list-invalidation event must not be
+ // broadcast to every workspace member. ActorID is the creator on every
+ // producer path for this event.
+ for _, eventType := range []string{protocol.EventChatSessionCreated, protocol.EventChatSessionUpdated} {
+ bus.Subscribe(eventType, func(e events.Event) {
+ sendToRecipient(b, e, e.ActorID)
+ })
+ }
+
// member:added — also send to the invited user so they discover the new workspace.
// Pass excludeWorkspace so clients already in the target room (reached via
// BroadcastToWorkspace in SubscribeAll) don't receive the event twice.
diff --git a/server/cmd/server/listeners_scope_test.go b/server/cmd/server/listeners_scope_test.go
index 95d85c94ca..72357edb64 100644
--- a/server/cmd/server/listeners_scope_test.go
+++ b/server/cmd/server/listeners_scope_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "encoding/json"
"sync"
"testing"
@@ -18,6 +19,58 @@ type fakeBroadcaster struct {
broadcastCalled int
}
+func TestRegisterListeners_ChatSessionCreatedGoesOnlyToCreator(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventChatSessionCreated, WorkspaceID: "ws-1",
+ ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1",
+ Payload: protocol.ChatSessionCreatedPayload{
+ WorkspaceID: "ws-1", ChatSessionID: "chat-1", CreatorID: "creator-1",
+ Title: "private opening title",
+ },
+ })
+
+ if len(fb.workspaceCalls) != 0 {
+ t.Fatalf("private Chat create reached workspace fanout: %+v", fb.workspaceCalls)
+ }
+ if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "creator-1" {
+ t.Fatalf("creator fanout = %+v, want creator-1 once", fb.userCalls)
+ }
+ var frame struct {
+ Payload protocol.ChatSessionCreatedPayload `json:"payload"`
+ }
+ if err := json.Unmarshal(fb.userCalls[0].msg, &frame); err != nil {
+ t.Fatalf("decode creator frame: %v", err)
+ }
+ if frame.Payload.WorkspaceID != "ws-1" || frame.Payload.ChatSessionID != "chat-1" {
+ t.Fatalf("creator payload = %+v", frame.Payload)
+ }
+}
+
+func TestRegisterListeners_ChatSessionTitleUpdateGoesOnlyToCreator(t *testing.T) {
+ bus := events.New()
+ fb := &fakeBroadcaster{}
+ registerListeners(bus, fb)
+
+ bus.Publish(events.Event{
+ Type: protocol.EventChatSessionUpdated, WorkspaceID: "ws-1",
+ ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1",
+ Payload: protocol.ChatSessionUpdatedPayload{
+ ChatSessionID: "chat-1", Title: "private derived title",
+ },
+ })
+
+ if len(fb.workspaceCalls) != 0 {
+ t.Fatalf("private Chat title reached workspace fanout: %+v", fb.workspaceCalls)
+ }
+ if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "creator-1" {
+ t.Fatalf("creator fanout = %+v, want creator-1 once", fb.userCalls)
+ }
+}
+
type scopeCall struct {
scopeType, scopeID string
msg []byte
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 281a35cf01..c18b5a6466 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -491,7 +491,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// connection of its own outside the per-installation supervisor. The Router
// is the single shared inbound handler injected into every Channel.
channelRegistry := channel.NewRegistry()
- channelRouter := engine.NewRouter(h.IssueService, h.TaskService, queries, engine.RouterConfig{Logger: slog.Default()})
+ channelRouter := engine.NewRouter(h.IssueService, h.TaskService, queries, engine.RouterConfig{
+ Logger: slog.Default(), Lifecycle: h,
+ })
// Debounce the per-session run trigger so a burst of messages collapses
// into one agent run instead of one per message (MUL-2968).
channelRouter.EnableRunBatching(engine.DefaultChatRunBatchWindow)
@@ -742,8 +744,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// The bind link (/slack/bind) is a web-app page, so it must use the
// app URL (MULTICA_APP_URL ?? FRONTEND_ORIGIN), NOT MULTICA_PUBLIC_URL
// (the backend/API URL). Mirrors the Lark replier (appURLFromEnv).
- AppURL: appURLFromEnv(),
- Logger: slog.Default(),
+ AppURL: appURLFromEnv(),
+ Queries: queries,
+ Logger: slog.Default(),
})
// Typing indicator (MUL-3874): a 👀 reaction on the user's message
// while the agent works, cleared when the run finishes or fails.
@@ -774,16 +777,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// agent asks, instead of force-assembling it on every inbound.
h.SlackHistory = slack.NewHistory(queries, box.Open, slog.Default())
- // `/issue` slash command (MUL-3908): a real Slack slash command,
- // delivered over the same Socket Mode connection. It is a quick-create
- // entry point — the invoker's natural-language description is enqueued as
- // a quick-create task (no chat session or chat run) and the agent authors
- // the well-formed issue in the background — reusing the shared TaskService
- // + binding service. The invoker gets a private ephemeral acknowledgement
- // and a Multica notification when the issue lands.
+ // `/issue`, `/new`, and `/clear` are real Slack slash commands delivered
+ // over the same Socket Mode connection. `/issue` enqueues quick-create;
+ // the two session controls reuse the shared route/context and task
+ // services. Every outcome receives a private ephemeral acknowledgement.
slackSlash := slack.NewSlashCommandProcessor(slack.SlashCommandConfig{
Queries: queries,
Tasks: h.TaskService,
+ Control: slack.NewSlackDMControlStarter(queries, pool, h.TaskService, h),
Binding: slackBindingSvc,
AppURL: appURLFromEnv(),
Logger: slog.Default(),
@@ -843,9 +844,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
channelRouter.Register(dingtalk.TypeDingTalk, dingtalk.NewDingTalkResolverSet(queries, pool, replier, ack, media, botNames))
dingtalk.NewOutbound(queries, box.Open, dingtalkClient, slog.Default()).Register(bus)
dingtalk.RegisterDingTalk(channelRegistry, dingtalk.ChannelDeps{
- Decrypt: box.Open,
- Client: dingtalkClient,
- Logger: slog.Default(),
+ Decrypt: box.Open,
+ Client: dingtalkClient,
+ BotNames: botNames,
+ Logger: slog.Default(),
})
installSvc, installErr := dingtalk.NewInstallService(queries, pool, box, slog.Default())
if installErr != nil {
diff --git a/server/internal/chatoriginbackfill/backfill.go b/server/internal/chatoriginbackfill/backfill.go
new file mode 100644
index 0000000000..0d9b8abbfa
--- /dev/null
+++ b/server/internal/chatoriginbackfill/backfill.go
@@ -0,0 +1,125 @@
+// Package chatoriginbackfill marks legacy first-party Chats with the durable
+// origin signal introduced by the channel route migration.
+package chatoriginbackfill
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+// DefaultBatchSize bounds each statement so the migration does not rewrite
+// the full chat_session table in one transaction.
+const DefaultBatchSize = 1000
+
+type Result struct {
+ RowsVisited int64
+ RowsBackfilled int64
+ Pages int
+}
+
+// HookOptions has production-safe zero values. Table overrides exist only so
+// integration tests can point the hook at an isolated schema; callers must
+// provide trusted, already-quoted identifiers.
+type HookOptions struct {
+ Logger *slog.Logger
+ BatchSize int
+ SessionTable string
+ BindingTable string
+ MessageTable string
+}
+
+// Each page follows the chat_session primary key instead of repeatedly
+// scanning all previously visited rows. The update remains provenance-based:
+// a binding or any channel-ingested message is enough to keep a legacy Chat
+// classified as channel-originated even if one of those records was removed.
+const backfillPageSQL = `
+WITH page AS MATERIALIZED (
+ SELECT id
+ FROM %s
+ WHERE ($1::uuid IS NULL OR id > $1::uuid)
+ ORDER BY id
+ LIMIT $2
+), updated AS (
+ UPDATE %s AS session
+ SET explicitly_created_at = session.created_at
+ FROM page
+ WHERE session.id = page.id
+ AND session.explicitly_created_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM %s AS binding
+ WHERE binding.chat_session_id = session.id
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM %s AS message
+ WHERE message.chat_session_id = session.id
+ AND message.channel_ingested
+ )
+ RETURNING session.id
+)
+SELECT
+ COALESCE((SELECT id::text FROM page ORDER BY id DESC LIMIT 1), ''),
+ (SELECT count(*) FROM page),
+ (SELECT count(*) FROM updated)`
+
+// Hook walks legacy Chats in short, idempotent pages. The migration runner
+// invokes it only after migration 420 has added explicitly_created_at and while
+// the normal deployment contract keeps the server stopped. If a batch fails,
+// already updated rows remain valid and the next migrate run safely revisits
+// them before continuing from the primary-key cursor.
+func Hook(ctx context.Context, pool *pgxpool.Pool, opts HookOptions) (Result, error) {
+ log := opts.Logger
+ if log == nil {
+ log = slog.Default()
+ }
+ batchSize := opts.BatchSize
+ if batchSize <= 0 {
+ batchSize = DefaultBatchSize
+ }
+ sessionTable := opts.SessionTable
+ if sessionTable == "" {
+ sessionTable = "chat_session"
+ }
+ bindingTable := opts.BindingTable
+ if bindingTable == "" {
+ bindingTable = "channel_chat_session_binding"
+ }
+ messageTable := opts.MessageTable
+ if messageTable == "" {
+ messageTable = "chat_message"
+ }
+
+ query := fmt.Sprintf(backfillPageSQL, sessionTable, sessionTable, bindingTable, messageTable)
+ var result Result
+ var cursor any
+ for {
+ var nextCursor string
+ var visited, updated int64
+ if err := pool.QueryRow(ctx, query, cursor, batchSize).Scan(&nextCursor, &visited, &updated); err != nil {
+ return result, fmt.Errorf("backfill explicit Chat origin page: %w", err)
+ }
+ if visited == 0 {
+ break
+ }
+
+ result.Pages++
+ result.RowsVisited += visited
+ result.RowsBackfilled += updated
+ cursor = nextCursor
+ log.Info("Chat origin backfill: page complete",
+ "visited", visited,
+ "backfilled", updated,
+ "total_visited", result.RowsVisited,
+ "total_backfilled", result.RowsBackfilled)
+ }
+
+ log.Info("Chat origin backfill: complete",
+ "visited", result.RowsVisited,
+ "backfilled", result.RowsBackfilled,
+ "pages", result.Pages)
+ return result, nil
+}
diff --git a/server/internal/chattitle/title.go b/server/internal/chattitle/title.go
new file mode 100644
index 0000000000..4d92c065c5
--- /dev/null
+++ b/server/internal/chattitle/title.go
@@ -0,0 +1,42 @@
+package chattitle
+
+import (
+ "regexp"
+ "strings"
+ "unicode"
+)
+
+const deterministicTitleLimit = 30
+
+var (
+ markdownFence = regexp.MustCompile("```.*?```")
+ markdownMarks = regexp.MustCompile("[#*`>~_]")
+ markdownLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`)
+ titleSpace = regexp.MustCompile(`[[:space:]]+`)
+)
+
+// Derive mirrors the existing first-party deterministic title policy for
+// channel-created Chats. Go slices valid Unicode code points rather than UTF-16
+// code units, while preserving the same first-line, Markdown, whitespace, and
+// 30-character single-ellipsis behavior.
+func Derive(body string) string {
+ line := ""
+ for _, candidate := range strings.Split(body, "\n") {
+ if strings.TrimSpace(candidate) != "" {
+ line = candidate
+ break
+ }
+ }
+ line = markdownFence.ReplaceAllString(line, " ")
+ line = markdownMarks.ReplaceAllString(line, "")
+ line = markdownLink.ReplaceAllString(line, "$1")
+ line = strings.TrimSpace(titleSpace.ReplaceAllString(line, " "))
+ if line == "" {
+ return ""
+ }
+ runes := []rune(line)
+ if len(runes) <= deterministicTitleLimit {
+ return line
+ }
+ return strings.TrimRightFunc(string(runes[:deterministicTitleLimit-1]), unicode.IsSpace) + "…"
+}
diff --git a/server/internal/handler/agent_builder.go b/server/internal/handler/agent_builder.go
index 40d5f6c5d6..3cb1351d26 100644
--- a/server/internal/handler/agent_builder.go
+++ b/server/internal/handler/agent_builder.go
@@ -132,6 +132,11 @@ func (h *Handler) CreateAgentBuilderSession(w http.ResponseWriter, r *http.Reque
writeError(w, http.StatusInternalServerError, "failed to create agent builder session")
return
}
+ session, err = qtx.MarkChatSessionExplicitlyCreated(r.Context(), session.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to mark agent builder session explicit")
+ return
+ }
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to commit agent builder session")
return
diff --git a/server/internal/handler/agent_builder_test.go b/server/internal/handler/agent_builder_test.go
index 0d37b14d15..c499078849 100644
--- a/server/internal/handler/agent_builder_test.go
+++ b/server/internal/handler/agent_builder_test.go
@@ -80,6 +80,15 @@ func TestCreateAgentBuilderSessionCreatesIsolatedHiddenBuilder(t *testing.T) {
if firstModel != "builder-model-a" {
t.Fatalf("first builder model was mutated: got %q", firstModel)
}
+ var explicitlyCreated bool
+ if err := testPool.QueryRow(context.Background(), `
+ SELECT explicitly_created_at IS NOT NULL FROM chat_session WHERE id = $1
+ `, first.SessionID).Scan(&explicitlyCreated); err != nil {
+ t.Fatalf("load builder session origin: %v", err)
+ }
+ if !explicitlyCreated {
+ t.Fatal("builder session must be marked as an explicit first-party Chat")
+ }
w := httptest.NewRecorder()
testHandler.ListAgents(w, newRequest(http.MethodGet, "/api/agents", nil))
diff --git a/server/internal/handler/channel_context_lock_order_test.go b/server/internal/handler/channel_context_lock_order_test.go
index fc68188e44..a96b983a7a 100644
--- a/server/internal/handler/channel_context_lock_order_test.go
+++ b/server/internal/handler/channel_context_lock_order_test.go
@@ -125,6 +125,10 @@ func TestChannelContextLockOrder(t *testing.T) {
if err != nil {
t.Fatalf("load chat session: %v", err)
}
+ binding, err := queries.GetChannelChatSessionBindingBySessionAny(ctx, sessionID)
+ if err != nil {
+ t.Fatalf("load channel route: %v", err)
+ }
generationLocked := make(chan struct{})
releaseEnqueue := make(chan struct{})
@@ -141,14 +145,14 @@ func TestChannelContextLockOrder(t *testing.T) {
}
enqueueResult := make(chan error, 1)
go func() {
- _, err := enqueueService.EnqueueChannelChatTask(ctx, chatSession, initiator, true, 2)
+ _, err := enqueueService.EnqueueChannelChatTask(ctx, chatSession, initiator, true, 2, binding.ID, binding.RouteRevision)
enqueueResult <- err
}()
waitContextLockSignal(t, generationLocked, "enqueue did not lock generation")
bindingAttempted := make(chan struct{})
appendSession := engine.NewChatSession(queries, &contextLockTestStarter{
- pool: testPool, observeBefore: "LockChannelChatSessionBindingForContext", observed: bindingAttempted,
+ pool: testPool, observeBefore: "LockCurrentChannelChatSessionBindingBySession", observed: bindingAttempted,
}, channel.Type("slack"), engine.SessionTitles{Direct: "Lock order test"})
appendResult := make(chan error, 1)
go func() {
diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.go
index b0fe4007ca..b1df168cce 100644
--- a/server/internal/handler/channel_new_e2e_test.go
+++ b/server/internal/handler/channel_new_e2e_test.go
@@ -3,15 +3,20 @@ package handler
import (
"context"
"errors"
+ "sync"
"testing"
+ "time"
"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"
+ slackintegration "github.com/multica-ai/multica/server/internal/integrations/slack"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ slackapi "github.com/slack-go/slack"
)
// This test keeps only the external IM transport outside the process. From the
@@ -20,7 +25,7 @@ import (
// That is the repeatable server-side E2E boundary for a channel command: an
// adapter's only responsibility is translating its webhook/socket payload into
// channel.InboundMessage.
-func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {
+func TestChannelClearCommandE2EStartsFreshProviderSession(t *testing.T) {
if testHandler == nil {
t.Fatal("database-backed handler test fixture is required")
}
@@ -47,35 +52,35 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {
wantPriorWorkDir: "/tmp/old-provider-workdir",
},
{
- name: "bare /new applies to the next real message",
+ name: "bare /clear applies to the next real message",
channelType: channel.Type("slack"),
- text: "/new",
- commandText: "/new",
+ text: "/clear",
+ commandText: "/clear",
followUpText: "what model are you?",
wantStoredText: "what model are you?",
wantForceFresh: true,
},
{
- name: "Slack /new message starts without provider context",
+ name: "Slack /clear message starts without provider context",
channelType: channel.Type("slack"),
- text: "/new what model are you?",
- commandText: "/new what model are you?",
+ text: "/clear what model are you?",
+ commandText: "/clear what model are you?",
wantStoredText: "what model are you?",
wantForceFresh: true,
},
{
name: "Slack same-line /issue remains fresh-only",
channelType: channel.Type("slack"),
- text: "/new /issue investigate deploy",
- commandText: "/new /issue investigate deploy",
+ text: "/clear /issue investigate deploy",
+ commandText: "/clear /issue investigate deploy",
wantStoredText: "/issue investigate deploy",
wantForceFresh: true,
},
{
name: "Slack next-line /issue remains fresh-only",
channelType: channel.Type("slack"),
- text: "/new\n/issue investigate deploy",
- commandText: "/new\n/issue investigate deploy",
+ text: "/clear\n/issue investigate deploy",
+ commandText: "/clear\n/issue investigate deploy",
wantStoredText: "/issue investigate deploy",
wantForceFresh: true,
},
@@ -83,7 +88,7 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {
name: "Feishu same-line /issue remains fresh-only",
channelType: channel.TypeFeishu,
text: "/issue investigate deploy",
- commandText: "/new /issue investigate deploy",
+ commandText: "/clear /issue investigate deploy",
forceFresh: true,
wantStoredText: "/issue investigate deploy",
wantForceFresh: true,
@@ -92,7 +97,7 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {
name: "Feishu next-line /issue remains fresh-only",
channelType: channel.TypeFeishu,
text: "/issue investigate deploy",
- commandText: "/new\n/issue investigate deploy",
+ commandText: "/clear\n/issue investigate deploy",
forceFresh: true,
wantStoredText: "/issue investigate deploy",
wantForceFresh: true,
@@ -101,12 +106,644 @@ func TestChannelNewCommandE2EStartsFreshProviderSession(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- runChannelNewCommandE2E(t, tt.channelType, tt.text, tt.commandText, tt.forceFresh, tt.followUpText, tt.wantStoredText, tt.wantForceFresh, tt.wantPriorSession, tt.wantPriorWorkDir)
+ runChannelClearCommandE2E(t, tt.channelType, tt.text, tt.commandText, tt.forceFresh, tt.followUpText, tt.wantStoredText, tt.wantForceFresh, tt.wantPriorSession, tt.wantPriorWorkDir)
})
}
}
-func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, followUpText, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {
+// /new changes only the future inbound route. A task already queued from the
+// old generation must keep both its Multica Chat and exact external reply
+// target, while the new command gets a distinct Chat and delivery snapshot.
+func TestChannelChatCommandE2ERotatesRouteAndFreezesTaskDelivery(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ agentID, runtimeID, _ := createRuntimeGuardAgent(t, ctx)
+ queries := db.New(testPool)
+ channelType := channel.Type("slack")
+ bindingKey := "chat-route-" + t.Name()
+
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, $3, '{}'::jsonb, 'active', $4)
+ RETURNING id
+ `, testWorkspaceID, agentID, string(channelType), testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_outbound_message WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+
+ installation := engine.ResolvedInstallation{
+ ID: util.MustParseUUID(installationID), WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ AgentID: util.MustParseUUID(agentID), InstallerUserID: util.MustParseUUID(testUserID), Active: true,
+ }
+ chatSession := engine.NewChatSession(queries, testPool, channelType, engine.SessionTitles{
+ Direct: "Channel E2E conversation", Group: "Channel E2E group", Fallback: "Channel E2E conversation",
+ })
+ binder := &channelNewE2ESessionBinder{session: chatSession}
+ router := engine.NewRouter(nil, testHandler.TaskService, queries, engine.RouterConfig{})
+ // Hold ordinary runs in the debounce window until after /new retires the
+ // old route. Drain below then proves that the captured old generation still
+ // seals and receives the pending input instead of silently dropping it.
+ router.EnableRunBatching(time.Hour)
+ router.Register(channelType, engine.ResolverSet{
+ Installation: channelNewE2EInstallationResolver{installation: installation},
+ Identity: channelNewE2EIdentityResolver{userID: util.MustParseUUID(testUserID)},
+ Dedup: channelNewE2EDeduper{queries: queries}, Session: binder,
+ Audit: channelNewE2EAuditor{}, OriginType: "test_e2e_chat",
+ })
+
+ oldSessionID, err := binder.EnsureSession(ctx, engine.EnsureSessionParams{
+ Installation: installation, Sender: util.MustParseUUID(testUserID),
+ Message: channel.InboundMessage{Source: channel.Source{
+ ChannelType: channelType, ChatID: bindingKey, ChatType: channel.ChatTypeP2P,
+ }},
+ })
+ if err != nil {
+ t.Fatalf("seed old channel Chat: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE chat_session
+ SET title = 'Old topic', session_id = 'old-provider-session',
+ work_dir = '/tmp/old-provider-workdir', runtime_id = $2
+ WHERE id = $1
+ `, oldSessionID, runtimeID); err != nil {
+ t.Fatalf("seed old Chat state: %v", err)
+ }
+
+ send := func(eventID, messageID, text string) {
+ t.Helper()
+ if err := router.Handle(ctx, channel.InboundMessage{
+ EventID: eventID, MessageID: messageID, Type: channel.MsgTypeText,
+ Text: text, CommandText: text,
+ Source: channel.Source{ChannelType: channelType, ChatID: bindingKey,
+ ChatType: channel.ChatTypeP2P, SenderID: "platform-user-e2e"},
+ }); err != nil {
+ t.Fatalf("route %q: %v", text, err)
+ }
+ }
+ send("event-old", "message-old", "finish the old topic")
+ send("event-chat", "message-chat", "/new investigate the new topic")
+
+ var newSessionID, newBindingID string
+ var newRevision int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_session_id, id, route_revision
+ FROM channel_chat_session_binding
+ WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+ `, installationID, bindingKey).Scan(&newSessionID, &newBindingID, &newRevision); err != nil {
+ t.Fatalf("load current route: %v", err)
+ }
+ if newSessionID == util.UUIDToString(oldSessionID) {
+ t.Fatal("/new kept the old chat_session instead of creating a new one")
+ }
+ if newRevision != 2 {
+ t.Fatalf("new route revision = %d, want 2", newRevision)
+ }
+
+ var oldBindingID, oldEndMessageID string
+ var oldRevision int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT id, route_revision, history_end_message_id
+ FROM channel_chat_session_binding
+ WHERE chat_session_id = $1 AND retired_at IS NOT NULL
+ `, oldSessionID).Scan(&oldBindingID, &oldRevision, &oldEndMessageID); err != nil {
+ t.Fatalf("load retired route: %v", err)
+ }
+ if oldRevision != 1 || oldEndMessageID != "message-chat" {
+ t.Fatalf("retired route revision/end = %d/%q, want 1/message-chat", oldRevision, oldEndMessageID)
+ }
+ if !router.Drain(ctx) {
+ t.Fatal("drain timed out while flushing the pre-/new debounce window")
+ }
+
+ assertTaskDelivery := func(sessionID, wantBindingID, wantTarget string) {
+ t.Helper()
+ var taskID, taskStatus, bindingID, target string
+ if err := testPool.QueryRow(ctx, `
+ SELECT task.id, task.status, delivery.binding_id, delivery.channel_message_id
+ FROM agent_task_queue AS task
+ JOIN channel_task_delivery AS delivery ON delivery.task_id = task.id
+ WHERE task.chat_session_id = $1
+ ORDER BY task.created_at DESC LIMIT 1
+ `, sessionID).Scan(&taskID, &taskStatus, &bindingID, &target); err != nil {
+ t.Fatalf("load task delivery for %s: %v", sessionID, err)
+ }
+ if bindingID != wantBindingID || target != wantTarget {
+ t.Fatalf("task %s delivery = %s/%s, want %s/%s", taskID, bindingID, target, wantBindingID, wantTarget)
+ }
+ if taskStatus != "queued" {
+ t.Fatalf("task %s status = %s, want queued; /new must not cancel old work", taskID, taskStatus)
+ }
+ }
+ assertTaskDelivery(util.UUIDToString(oldSessionID), oldBindingID, "message-old")
+ assertTaskDelivery(newSessionID, newBindingID, "message-chat")
+
+ var oldTitle, oldProviderSession, oldWorkDir, oldStatus string
+ if err := testPool.QueryRow(ctx, `
+ SELECT title, session_id, work_dir, status FROM chat_session WHERE id = $1
+ `, oldSessionID).Scan(&oldTitle, &oldProviderSession, &oldWorkDir, &oldStatus); err != nil {
+ t.Fatalf("load old Chat: %v", err)
+ }
+ if oldTitle != "finish the old topic" || oldProviderSession != "old-provider-session" || oldWorkDir != "/tmp/old-provider-workdir" || oldStatus != "active" {
+ t.Fatalf("old Chat mutated: title=%q session=%q workdir=%q status=%q", oldTitle, oldProviderSession, oldWorkDir, oldStatus)
+ }
+
+ var newTitle string
+ var newProviderSession, newWorkDir pgtype.Text
+ var explicitlyCreated bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT title, session_id, work_dir, explicitly_created_at IS NOT NULL
+ FROM chat_session WHERE id = $1
+ `, newSessionID).Scan(&newTitle, &newProviderSession, &newWorkDir, &explicitlyCreated); err != nil {
+ t.Fatalf("load new Chat: %v", err)
+ }
+ if newTitle != "investigate the new topic" || newProviderSession.Valid || newWorkDir.Valid || !explicitlyCreated {
+ t.Fatalf("new Chat state: title=%q session=%v workdir=%v explicit=%t", newTitle, newProviderSession, newWorkDir, explicitlyCreated)
+ }
+ var storedNewText string
+ if err := testPool.QueryRow(ctx, `
+ SELECT content FROM chat_message
+ WHERE chat_session_id = $1 AND role = 'user' ORDER BY created_at ASC LIMIT 1
+ `, newSessionID).Scan(&storedNewText); err != nil {
+ t.Fatalf("load new Chat first message: %v", err)
+ }
+ if storedNewText != "investigate the new topic" {
+ t.Fatalf("new Chat first message = %q", storedNewText)
+ }
+
+ // A bare /new is also a durable route rotation, but it creates neither a
+ // synthetic user message nor a task. Its explicit-create marker is the
+ // authority that makes the empty Chat visible in normal list queries.
+ send("event-empty-chat", "message-empty-chat", "/new")
+ var emptySessionID string
+ var emptyRevision int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_session_id, route_revision
+ FROM channel_chat_session_binding
+ WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+ `, installationID, bindingKey).Scan(&emptySessionID, &emptyRevision); err != nil {
+ t.Fatalf("load bare /new route: %v", err)
+ }
+ if emptyRevision != 3 || emptySessionID == newSessionID {
+ t.Fatalf("bare /new route = session %s revision %d, want a third Chat/revision", emptySessionID, emptyRevision)
+ }
+ var emptyTitle string
+ var emptyExplicit bool
+ var emptyMessages, emptyTasks int
+ if err := testPool.QueryRow(ctx, `
+ SELECT session.title, session.explicitly_created_at IS NOT NULL,
+ (SELECT count(*) FROM chat_message WHERE chat_session_id = session.id),
+ (SELECT count(*) FROM agent_task_queue WHERE chat_session_id = session.id)
+ FROM chat_session AS session WHERE session.id = $1
+ `, emptySessionID).Scan(&emptyTitle, &emptyExplicit, &emptyMessages, &emptyTasks); err != nil {
+ t.Fatalf("load bare /new Chat: %v", err)
+ }
+ if emptyTitle != "" || !emptyExplicit || emptyMessages != 0 || emptyTasks != 0 {
+ t.Fatalf("bare /new state = title %q explicit %t messages %d tasks %d", emptyTitle, emptyExplicit, emptyMessages, emptyTasks)
+ }
+ listed, err := queries.ListChatSessionsByCreator(ctx, db.ListChatSessionsByCreatorParams{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID), CreatorID: util.MustParseUUID(testUserID),
+ })
+ if err != nil {
+ t.Fatalf("list Chats after bare /new: %v", err)
+ }
+ visible := false
+ for _, item := range listed {
+ if util.UUIDToString(item.ID) == emptySessionID {
+ visible = true
+ break
+ }
+ }
+ if !visible {
+ t.Fatal("bare /new Chat is absent from the normal Chat list")
+ }
+ metadata := []ChatSessionResponse{
+ {ID: util.UUIDToString(oldSessionID)},
+ {ID: newSessionID},
+ {ID: emptySessionID},
+ }
+ if err := testHandler.hydrateChatSessionChannelMetadata(ctx, metadata); err != nil {
+ t.Fatalf("hydrate Chat channel metadata: %v", err)
+ }
+ for i, wantRevision := range []int64{1, 2, 3} {
+ if metadata[i].ChannelSource == nil ||
+ metadata[i].ChannelSource.ChannelType != string(channelType) ||
+ metadata[i].ChannelSource.InstallationID != installationID ||
+ metadata[i].ChannelSource.RouteRevision != wantRevision {
+ t.Fatalf("Chat %d source metadata = %+v, want revision %d", i, metadata[i].ChannelSource, wantRevision)
+ }
+ wantCurrent := i == 2
+ if metadata[i].IsCurrentChannelRoute == nil || *metadata[i].IsCurrentChannelRoute != wantCurrent {
+ t.Fatalf("Chat %d current route = %v, want %t", i, metadata[i].IsCurrentChannelRoute, wantCurrent)
+ }
+ }
+
+ // The empty channel-created Chat remains writable from Multica. Its first
+ // direct turn initializes the same deterministic title, while the direct
+ // task deliberately gets no external delivery snapshot.
+ emptySessionUUID := util.MustParseUUID(emptySessionID)
+ emptySession, err := queries.GetChatSession(ctx, emptySessionUUID)
+ if err != nil {
+ t.Fatalf("load empty Chat for direct send: %v", err)
+ }
+ agent, err := queries.GetAgent(ctx, util.MustParseUUID(agentID))
+ if err != nil {
+ t.Fatalf("load agent for direct send: %v", err)
+ }
+ direct, err := testHandler.TaskService.SendDirectChatMessage(ctx, emptySession, agent, util.MustParseUUID(testUserID), "continue from the web client", nil, "member", util.MustParseUUID(testUserID))
+ if err != nil {
+ t.Fatalf("direct send to channel-created Chat: %v", err)
+ }
+ var directTitle string
+ var deliveryCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT session.title,
+ (SELECT count(*) FROM channel_task_delivery WHERE task_id = $2)
+ FROM chat_session AS session WHERE session.id = $1
+ `, emptySessionUUID, direct.Task.ID).Scan(&directTitle, &deliveryCount); err != nil {
+ t.Fatalf("load direct-send title/delivery: %v", err)
+ }
+ if directTitle != "continue from the web client" || direct.InitialTitle != directTitle || deliveryCount != 0 {
+ t.Fatalf("direct continuation title=%q initial=%q delivery=%d", directTitle, direct.InitialTitle, deliveryCount)
+ }
+
+ // The same cross-client path must also title an attachment-only first
+ // message from the first file that was actually bound.
+ send("event-attachment-chat", "message-attachment-chat", "/new")
+ var attachmentSessionID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_session_id FROM channel_chat_session_binding
+ WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+ `, installationID, bindingKey).Scan(&attachmentSessionID); err != nil {
+ t.Fatalf("load attachment-only Chat: %v", err)
+ }
+ var attachmentID pgtype.UUID
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO attachment (
+ workspace_id, chat_session_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ ) VALUES ($1, $2, 'member', $3, 'quarterly-plan.pdf', 'file:///tmp/quarterly-plan.pdf', 'application/pdf', 1)
+ RETURNING id
+ `, testWorkspaceID, attachmentSessionID, testUserID).Scan(&attachmentID); err != nil {
+ t.Fatalf("create direct attachment: %v", err)
+ }
+ attachmentSession, err := queries.GetChatSession(ctx, util.MustParseUUID(attachmentSessionID))
+ if err != nil {
+ t.Fatalf("load attachment-only Chat session: %v", err)
+ }
+ attachmentSend, err := testHandler.TaskService.SendDirectChatMessage(
+ ctx, attachmentSession, agent, util.MustParseUUID(testUserID), "", []pgtype.UUID{attachmentID},
+ "member", util.MustParseUUID(testUserID),
+ )
+ if err != nil {
+ t.Fatalf("send attachment-only first message: %v", err)
+ }
+ var attachmentTitle string
+ if err := testPool.QueryRow(ctx, `SELECT title FROM chat_session WHERE id = $1`, attachmentSessionID).Scan(&attachmentTitle); err != nil {
+ t.Fatalf("load attachment-only title: %v", err)
+ }
+ if attachmentTitle != "quarterly-plan.pdf" || attachmentSend.InitialTitle != attachmentTitle {
+ t.Fatalf("attachment-only title=%q initial=%q", attachmentTitle, attachmentSend.InitialTitle)
+ }
+}
+
+func TestChannelChatStaleTaskPreparationLeavesRouteAndChatUntouched(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ agentID, _, _ := createRuntimeGuardAgent(t, ctx)
+ queries := db.New(testPool)
+ bindingKey := "chat-atomic-" + t.Name()
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, 'slack', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+
+ sessions := engine.NewChatSession(queries, testPool, channel.Type("slack"), engine.SessionTitles{})
+ oldSessionID, err := sessions.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID), AgentID: util.MustParseUUID(agentID),
+ InstallationID: util.MustParseUUID(installationID), Sender: util.MustParseUUID(testUserID),
+ BindingKey: bindingKey, ChatType: channel.ChatTypeP2P,
+ })
+ if err != nil {
+ t.Fatalf("seed current Chat: %v", err)
+ }
+ var beforeCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_session WHERE agent_id = $1`, agentID).Scan(&beforeCount); err != nil {
+ t.Fatalf("count Chats before start: %v", err)
+ }
+
+ prepared, err := testHandler.TaskService.PrepareChatTaskEnqueue(ctx, util.MustParseUUID(agentID), util.MustParseUUID(testUserID))
+ if err != nil {
+ t.Fatalf("prepare task before runtime change: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, agentID); err != nil {
+ t.Fatalf("detach agent runtime after preparation: %v", err)
+ }
+ _, err = sessions.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: util.MustParseUUID(testWorkspaceID), AgentID: util.MustParseUUID(agentID),
+ InstallationID: util.MustParseUUID(installationID), Sender: util.MustParseUUID(testUserID),
+ BindingKey: bindingKey, ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: util.MustParseUUID(testUserID),
+ Body: "new topic", MessageID: "message-new-topic", PersistMessage: true,
+ BeforeCommit: func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {
+ _, enqueueErr := testHandler.TaskService.EnqueuePreparedChannelChatTaskInTx(
+ ctx, tx, session, util.MustParseUUID(testUserID), false, 1, prepared,
+ )
+ return enqueueErr
+ },
+ })
+ if !errors.Is(err, service.ErrChatTaskAgentNoRuntime) {
+ t.Fatalf("start with stale preparation error = %v, want no-runtime rejection", err)
+ }
+
+ var currentSessionID string
+ var revision int64
+ if err := testPool.QueryRow(ctx, `
+ SELECT chat_session_id, route_revision
+ FROM channel_chat_session_binding
+ WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+ `, installationID, bindingKey).Scan(&currentSessionID, &revision); err != nil {
+ t.Fatalf("load current route after rollback: %v", err)
+ }
+ var afterCount, taskCount int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_session WHERE agent_id = $1`, agentID).Scan(&afterCount); err != nil {
+ t.Fatalf("count Chats after start: %v", err)
+ }
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE agent_id = $1`, agentID).Scan(&taskCount); err != nil {
+ t.Fatalf("count tasks after start: %v", err)
+ }
+ if currentSessionID != util.UUIDToString(oldSessionID) || revision != 1 || afterCount != beforeCount || taskCount != 0 {
+ t.Fatalf("partial commit: current=%s revision=%d chats=%d/%d tasks=%d", currentSessionID, revision, afterCount, beforeCount, taskCount)
+ }
+}
+
+func TestSlackNativeNewCommandCreatesMessageTaskAndDeliveryAtomically(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ agentID, _, _ := createRuntimeGuardAgent(t, ctx)
+ queries := db.New(testPool)
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, 'slack', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+
+ installation := engine.ResolvedInstallation{
+ ID: util.MustParseUUID(installationID), WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ AgentID: util.MustParseUUID(agentID), InstallerUserID: util.MustParseUUID(testUserID), Active: true,
+ }
+ sessions := engine.NewChatSession(queries, testPool, channel.Type("slack"), engine.SessionTitles{})
+ starter := slackintegration.NewSlackDMControlStarter(queries, testPool, testHandler.TaskService, testHandler)
+ if err := starter.StartSlackDMChat(ctx, installation, util.MustParseUUID(testUserID), slackapi.SlashCommand{
+ ChannelID: "D-native-chat", Text: "investigate native command",
+ }, "envelope-native-chat"); err != nil {
+ t.Fatalf("StartSlackDMChat: %v", err)
+ }
+
+ var sessionID, title, content string
+ var routeRevision int64
+ var taskCount, deliveryCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT binding.chat_session_id, binding.route_revision, session.title,
+ message.content,
+ (SELECT count(*) FROM agent_task_queue AS task WHERE task.chat_session_id = session.id),
+ (SELECT count(*) FROM channel_task_delivery AS delivery
+ JOIN agent_task_queue AS task ON task.id = delivery.task_id
+ WHERE task.chat_session_id = session.id)
+ FROM channel_chat_session_binding AS binding
+ JOIN chat_session AS session ON session.id = binding.chat_session_id
+ JOIN chat_message AS message ON message.chat_session_id = session.id AND message.role = 'user'
+ WHERE binding.installation_id = $1 AND binding.channel_chat_id = 'D-native-chat'
+ AND binding.retired_at IS NULL
+ `, installationID).Scan(&sessionID, &routeRevision, &title, &content, &taskCount, &deliveryCount); err != nil {
+ t.Fatalf("load native /new state: %v", err)
+ }
+ if sessionID == "" || routeRevision != 1 || title != "investigate native command" || content != "investigate native command" || taskCount != 1 || deliveryCount != 1 {
+ t.Fatalf("native /new state: session=%s revision=%d title=%q content=%q tasks=%d deliveries=%d", sessionID, routeRevision, title, content, taskCount, deliveryCount)
+ }
+ var dedupProcessed bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT processed_at IS NOT NULL FROM channel_inbound_message_dedup
+ WHERE installation_id = $1 AND message_id = 'envelope-native-chat'
+ `, installationID).Scan(&dedupProcessed); err != nil {
+ t.Fatalf("load native /new dedup: %v", err)
+ }
+ if !dedupProcessed {
+ t.Fatal("native /new dedup was not marked processed")
+ }
+
+ var wg sync.WaitGroup
+ errs := make(chan error, 2)
+ for _, envelopeID := range []string{"envelope-native-chat-2", "envelope-native-chat-3"} {
+ wg.Add(1)
+ go func(id string) {
+ defer wg.Done()
+ errs <- starter.StartSlackDMChat(ctx, installation, util.MustParseUUID(testUserID), slackapi.SlashCommand{
+ ChannelID: "D-native-chat",
+ }, id)
+ }(envelopeID)
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("concurrent bare /new: %v", err)
+ }
+ }
+ var finalRevision int64
+ var finalSessionID string
+ var generations, activeRoutes int
+ if err := testPool.QueryRow(ctx, `
+ SELECT max(route_revision), count(*), count(*) FILTER (WHERE retired_at IS NULL),
+ max(chat_session_id::text) FILTER (WHERE retired_at IS NULL)
+ FROM channel_chat_session_binding
+ WHERE installation_id = $1 AND channel_chat_id = 'D-native-chat'
+ `, installationID).Scan(&finalRevision, &generations, &activeRoutes, &finalSessionID); err != nil {
+ t.Fatalf("load concurrent /new generations: %v", err)
+ }
+ if finalRevision != 3 || generations != 3 || activeRoutes != 1 {
+ t.Fatalf("concurrent /new generations: max=%d count=%d active=%d", finalRevision, generations, activeRoutes)
+ }
+ if _, err := sessions.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: util.MustParseUUID(finalSessionID), Sender: util.MustParseUUID(testUserID),
+ Body: "first public message", MessageID: "1700000000.000001",
+ }); err != nil {
+ t.Fatalf("append first message after native /new: %v", err)
+ }
+ var startID string
+ var pending bool
+ var closedRetired, openRetired int
+ if err := testPool.QueryRow(ctx, `
+ SELECT current.history_start_message_id, current.history_boundary_pending,
+ count(*) FILTER (
+ WHERE previous.retired_at IS NOT NULL
+ AND previous.history_end_message_id = current.history_start_message_id
+ ),
+ count(*) FILTER (
+ WHERE previous.retired_at IS NOT NULL
+ AND previous.history_end_message_id IS NULL
+ )
+ FROM channel_chat_session_binding AS current
+ JOIN channel_chat_session_binding AS previous
+ ON previous.installation_id = current.installation_id
+ AND previous.channel_chat_id = current.channel_chat_id
+ WHERE current.chat_session_id = $1
+ GROUP BY current.history_start_message_id, current.history_boundary_pending
+ `, finalSessionID).Scan(&startID, &pending, &closedRetired, &openRetired); err != nil {
+ t.Fatalf("load established native history boundary: %v", err)
+ }
+ if startID != "1700000000.000001" || pending || closedRetired != 2 || openRetired != 0 {
+ t.Fatalf("native boundary start=%q pending=%t closed_retired=%d open_retired=%d", startID, pending, closedRetired, openRetired)
+ }
+}
+
+func TestSlackNativeClearCommandKeepsChatAndAdvancesContextAtomically(t *testing.T) {
+ if testHandler == nil {
+ t.Fatal("database-backed handler test fixture is required")
+ }
+
+ ctx := context.Background()
+ agentID, _, _ := createRuntimeGuardAgent(t, ctx)
+ queries := db.New(testPool)
+ var installationID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO channel_installation (
+ workspace_id, agent_id, channel_type, config, status, installer_user_id
+ ) VALUES ($1, $2, 'slack', '{}'::jsonb, 'active', $3)
+ RETURNING id
+ `, testWorkspaceID, agentID, testUserID).Scan(&installationID); err != nil {
+ t.Fatalf("create channel installation: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ })
+
+ installation := engine.ResolvedInstallation{
+ ID: util.MustParseUUID(installationID), WorkspaceID: util.MustParseUUID(testWorkspaceID),
+ AgentID: util.MustParseUUID(agentID), InstallerUserID: util.MustParseUUID(testUserID), Active: true,
+ }
+ starter := slackintegration.NewSlackDMControlStarter(queries, testPool, testHandler.TaskService, testHandler)
+ if err := starter.ClearSlackDMContext(ctx, installation, util.MustParseUUID(testUserID), slackapi.SlashCommand{
+ ChannelID: "D-native-clear", Text: "/issue investigate native clear",
+ }, "envelope-native-clear-message"); err != nil {
+ t.Fatalf("ClearSlackDMContext with message: %v", err)
+ }
+
+ var sessionID, content, messageKind string
+ var routeRevision, contextRevision int64
+ var forceFresh, boundaryPending, dedupProcessed bool
+ var taskCount, deliveryCount, routeCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT binding.chat_session_id, binding.route_revision, binding.context_revision,
+ message.content, COALESCE(message.message_kind, ''), task.force_fresh_session,
+ generation.history_boundary_pending,
+ (SELECT count(*) FROM agent_task_queue AS queued WHERE queued.chat_session_id = binding.chat_session_id),
+ (SELECT count(*) FROM channel_task_delivery AS delivery WHERE delivery.task_id = task.id),
+ (SELECT count(*) FROM channel_chat_session_binding AS routes
+ WHERE routes.installation_id = binding.installation_id
+ AND routes.channel_chat_id = binding.channel_chat_id),
+ dedup.processed_at IS NOT NULL
+ FROM channel_chat_session_binding AS binding
+ JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = binding.chat_session_id
+ AND generation.revision = binding.context_revision
+ JOIN chat_message AS message ON message.chat_session_id = binding.chat_session_id AND message.role = 'user'
+ JOIN agent_task_queue AS task ON task.chat_session_id = binding.chat_session_id
+ JOIN channel_inbound_message_dedup AS dedup
+ ON dedup.installation_id = binding.installation_id
+ AND dedup.message_id = 'envelope-native-clear-message'
+ WHERE binding.installation_id = $1 AND binding.channel_chat_id = 'D-native-clear'
+ AND binding.retired_at IS NULL
+ `, installationID).Scan(
+ &sessionID, &routeRevision, &contextRevision, &content, &messageKind, &forceFresh,
+ &boundaryPending, &taskCount, &deliveryCount, &routeCount, &dedupProcessed,
+ ); err != nil {
+ t.Fatalf("load native /clear message state: %v", err)
+ }
+ if sessionID == "" || routeRevision != 1 || contextRevision != 2 || content != "/issue investigate native clear" || messageKind != "message" || !forceFresh || !boundaryPending || taskCount != 1 || deliveryCount != 1 || routeCount != 1 || !dedupProcessed {
+ t.Fatalf("native /clear message state: session=%s route=%d context=%d content=%q kind=%q fresh=%t pending=%t tasks=%d deliveries=%d routes=%d dedup=%t", sessionID, routeRevision, contextRevision, content, messageKind, forceFresh, boundaryPending, taskCount, deliveryCount, routeCount, dedupProcessed)
+ }
+
+ if err := starter.ClearSlackDMContext(ctx, installation, util.MustParseUUID(testUserID), slackapi.SlashCommand{
+ ChannelID: "D-native-clear",
+ }, "envelope-native-clear-bare"); err != nil {
+ t.Fatalf("bare ClearSlackDMContext: %v", err)
+ }
+ var currentSessionID string
+ var currentContextRevision int64
+ var currentBoundaryPending, bareDedupProcessed bool
+ var currentTaskCount, currentMessageCount, currentRouteCount int
+ if err := testPool.QueryRow(ctx, `
+ SELECT binding.chat_session_id, binding.context_revision,
+ generation.history_boundary_pending,
+ (SELECT count(*) FROM agent_task_queue AS task WHERE task.chat_session_id = binding.chat_session_id),
+ (SELECT count(*) FROM chat_message AS message WHERE message.chat_session_id = binding.chat_session_id AND message.role = 'user'),
+ (SELECT count(*) FROM channel_chat_session_binding AS routes
+ WHERE routes.installation_id = binding.installation_id
+ AND routes.channel_chat_id = binding.channel_chat_id),
+ dedup.processed_at IS NOT NULL
+ FROM channel_chat_session_binding AS binding
+ JOIN channel_chat_context_generation AS generation
+ ON generation.chat_session_id = binding.chat_session_id
+ AND generation.revision = binding.context_revision
+ JOIN channel_inbound_message_dedup AS dedup
+ ON dedup.installation_id = binding.installation_id
+ AND dedup.message_id = 'envelope-native-clear-bare'
+ WHERE binding.installation_id = $1 AND binding.channel_chat_id = 'D-native-clear'
+ AND binding.retired_at IS NULL
+ `, installationID).Scan(
+ &currentSessionID, &currentContextRevision, &currentBoundaryPending,
+ &currentTaskCount, &currentMessageCount, &currentRouteCount, &bareDedupProcessed,
+ ); err != nil {
+ t.Fatalf("load bare native /clear state: %v", err)
+ }
+ if currentSessionID != sessionID || currentContextRevision != 3 || !currentBoundaryPending || currentTaskCount != 1 || currentMessageCount != 1 || currentRouteCount != 1 || !bareDedupProcessed {
+ t.Fatalf("bare native /clear state: session=%s/%s context=%d pending=%t tasks=%d messages=%d routes=%d dedup=%t", currentSessionID, sessionID, currentContextRevision, currentBoundaryPending, currentTaskCount, currentMessageCount, currentRouteCount, bareDedupProcessed)
+ }
+}
+
+func runChannelClearCommandE2E(t *testing.T, channelType channel.Type, text, commandText string, adapterForceFresh bool, followUpText, wantStoredText string, wantForceFresh bool, wantPriorSession, wantPriorWorkDir string) {
t.Helper()
ctx := context.Background()
@@ -124,6 +761,8 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
t.Fatalf("create channel installation: %v", err)
}
t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, installationID)
+ testPool.Exec(context.Background(), `DELETE FROM channel_outbound_message WHERE installation_id = $1`, installationID)
testPool.Exec(context.Background(), `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)
testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
@@ -144,7 +783,7 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
binder := &channelNewE2ESessionBinder{session: chatSession}
// Seed the same channel conversation with a provider session/workdir. A
- // normal message resumes both; /new must leave them out of the daemon
+ // normal message resumes both; /clear must leave them out of the daemon
// claim while retaining the durable chat transcript.
sessionID, err := binder.EnsureSession(ctx, engine.EnsureSessionParams{
Installation: installation,
@@ -215,16 +854,16 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
SELECT count(*) FROM agent_task_queue
WHERE chat_session_id = $1 AND status NOT IN ('completed', 'failed', 'cancelled')
`, sessionID).Scan(&taskCount); err != nil {
- t.Fatalf("count tasks after bare /new: %v", err)
+ t.Fatalf("count tasks after bare /clear: %v", err)
}
if err := testPool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND role = 'user'`, sessionID).Scan(&userMessageCount); err != nil {
- t.Fatalf("count messages after bare /new: %v", err)
+ t.Fatalf("count messages after bare /clear: %v", err)
}
if err := testPool.QueryRow(ctx, `SELECT pending_fresh FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID).Scan(&pendingFresh); err != nil {
- t.Fatalf("load pending fresh after bare /new: %v", err)
+ t.Fatalf("load pending fresh after bare /clear: %v", err)
}
if taskCount != 0 || userMessageCount != 0 || !pendingFresh {
- t.Fatalf("bare /new state: tasks=%d messages=%d pending_fresh=%t, want 0/0/true", taskCount, userMessageCount, pendingFresh)
+ t.Fatalf("bare /clear state: tasks=%d messages=%d pending_fresh=%t, want 0/0/true", taskCount, userMessageCount, pendingFresh)
}
if err := router.Handle(ctx, channel.InboundMessage{
@@ -285,7 +924,7 @@ func runChannelNewCommandE2E(t *testing.T, channelType channel.Type, text, comma
t.Fatalf("count command-created issues: %v", err)
}
if issueCount != 0 {
- t.Fatalf("created issues = %d, want 0; /new must be mutually exclusive with /issue", issueCount)
+ t.Fatalf("created issues = %d, want 0; /clear must be mutually exclusive with /issue", issueCount)
}
var storedText string
@@ -381,7 +1020,29 @@ func (b *channelNewE2ESessionBinder) EnsureSession(ctx context.Context, p engine
})
}
-func (b *channelNewE2ESessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+func (b *channelNewE2ESessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ started, err := b.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: p.Message.Source.ChatID, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID,
+ ThreadID: p.Message.Source.ThreadID, ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds, PersistMessage: p.PersistMessage,
+ HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{
+ SessionID: started.SessionID, BindingID: started.BindingID,
+ RouteRevision: started.RouteRevision, Append: started.Append,
+ }, err
+}
+
+func (b *channelNewE2ESessionBinder) MarkPendingFresh(
+ ctx context.Context, sessionID pgtype.UUID, messageID string,
+) error {
return b.session.MarkPendingFresh(ctx, sessionID, messageID)
}
@@ -400,8 +1061,8 @@ func (b *channelNewE2ESessionBinder) AppendMessage(ctx context.Context, p engine
})
}
-func (b *channelNewE2ESessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return b.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (b *channelNewE2ESessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ return b.session.BindMediaRefsWithResult(ctx, engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index db82d84d29..24fe825084 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -138,6 +138,11 @@ func (h *Handler) CreateChatSession(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create chat session")
return
}
+ session, err = qtx.MarkChatSessionExplicitlyCreated(r.Context(), session.ID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to mark chat session explicit")
+ return
+ }
if err := tx.Commit(r.Context()); err != nil {
writeError(w, http.StatusInternalServerError, "failed to commit chat session create")
@@ -237,6 +242,10 @@ func (h *Handler) ListChatSessions(w http.ResponseWriter, r *http.Request) {
})
}
}
+ if err := h.hydrateChatSessionChannelMetadata(r.Context(), resp); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat channel metadata")
+ return
+ }
writeJSON(w, http.StatusOK, resp)
}
@@ -322,7 +331,15 @@ func (h *Handler) GetChatSession(w http.ResponseWriter, r *http.Request) {
return
}
- writeJSON(w, http.StatusOK, chatSessionToResponse(session))
+ resp := chatSessionToResponse(session)
+ // hydrateChatSessionChannelMetadata mutates the slice element, so retain a
+ // concrete slice here rather than passing a temporary value to writeJSON.
+ responses := []ChatSessionResponse{resp}
+ if err := h.hydrateChatSessionChannelMetadata(r.Context(), responses); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat channel metadata")
+ return
+ }
+ writeJSON(w, http.StatusOK, responses[0])
}
type UpdateChatSessionRequest struct {
@@ -893,9 +910,21 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// query error here is treated as "not first" so we simply skip generation
// (best-effort — never block the send).
hadUserMessage := true
- if existed, err := h.Queries.ChatSessionHasUserMessage(r.Context(), session.ID); err == nil {
+ if existed, err := h.Queries.ChatSessionHasPublicUserMessage(r.Context(), session.ID); err == nil {
hadUserMessage = existed
}
+ channelBacked := false
+ channelSourceKnown := true
+ if !hadUserMessage {
+ if _, err := h.Queries.GetChannelChatSessionBindingBySessionAny(r.Context(), session.ID); err == nil {
+ channelBacked = true
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ // Title generation is optional. If source authority is unavailable,
+ // skip it rather than risk treating a channel manual rename as an
+ // auto-generated fallback and overwriting it.
+ channelSourceKnown = false
+ }
+ }
// Persist the whole turn atomically (MUL-4351): the owning task, the user
// message bound to that task (so it belongs to the task's immutable input
@@ -921,6 +950,11 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
}
msg := sent.Message
task := sent.Task
+ currentTitle := session.Title
+ if sent.InitialTitle != "" {
+ currentTitle = sent.InitialTitle
+ h.ChannelChatTitleInitialized(session.WorkspaceID, session.CreatorID, session.ID, sent.InitialTitle)
+ }
// AttachmentIDs actually bound by the server. Requested-but-unbound ids are
// surfaced to the client so it can warn the user (see SendChatMessageResponse).
@@ -962,8 +996,9 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// silently keeps the original first-message-derived title. session.Title
// is the default/original title observed here and drives the CAS so a
// manual rename mid-generation is never clobbered.
- if !hadUserMessage {
- h.maybeGenerateChatTitleAsync(workspaceID, userID, session.ID, session.Title, req.Content)
+ shouldGenerateTitle := shouldGenerateFirstMessageTitle(hadUserMessage, currentTitle, sent.InitialTitle, channelBacked, channelSourceKnown)
+ if shouldGenerateTitle {
+ h.maybeGenerateChatTitleAsync(workspaceID, userID, session.ID, currentTitle, req.Content)
}
writeJSON(w, http.StatusCreated, SendChatMessageResponse{
@@ -976,6 +1011,19 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
})
}
+func shouldGenerateFirstMessageTitle(hadUserMessage bool, currentTitle, initializedTitle string, channelBacked, channelSourceKnown bool) bool {
+ if hadUserMessage || currentTitle == "" || !channelSourceKnown {
+ return false
+ }
+ if channelBacked {
+ // For an explicitly empty /new Chat, a pre-existing non-empty title is
+ // a manual rename. Only a title initialized by this send is eligible for
+ // the best-effort LLM replacement; otherwise manual naming always wins.
+ return initializedTitle != ""
+ }
+ return true
+}
+
type ChatMessagesCursorResponse struct {
CreatedAt string `json:"created_at"`
ID string `json:"id"`
@@ -1896,9 +1944,50 @@ type ChatSessionResponse struct {
LastMessage *ChatLastMessage `json:"last_message"`
// Pinned marks a chat the user has stuck to the top of the list. Populated
// by list endpoints and by the pin/unpin + single-session responses.
- Pinned bool `json:"pinned"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ Pinned bool `json:"pinned"`
+ // ChannelSource is present only for Chats created from an external channel.
+ // IsCurrentChannelRoute distinguishes the active route generation from an
+ // older Chat that remains readable and writable in Multica.
+ ChannelSource *ChatSessionChannelSourceResponse `json:"channel_source,omitempty"`
+ IsCurrentChannelRoute *bool `json:"is_current_channel_route,omitempty"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+type ChatSessionChannelSourceResponse struct {
+ ChannelType string `json:"channel_type"`
+ InstallationID string `json:"installation_id"`
+ RouteRevision int64 `json:"route_revision"`
+}
+
+func (h *Handler) hydrateChatSessionChannelMetadata(ctx context.Context, sessions []ChatSessionResponse) error {
+ if len(sessions) == 0 {
+ return nil
+ }
+ ids := make([]pgtype.UUID, 0, len(sessions))
+ for _, session := range sessions {
+ ids = append(ids, parseUUID(session.ID))
+ }
+ bindings, err := h.Queries.ListChannelChatSessionBindingsBySessions(ctx, ids)
+ if err != nil {
+ return err
+ }
+ bySession := make(map[string]db.ChannelChatSessionBinding, len(bindings))
+ for _, binding := range bindings {
+ bySession[uuidToString(binding.ChatSessionID)] = binding
+ }
+ for i := range sessions {
+ binding, ok := bySession[sessions[i].ID]
+ if !ok {
+ continue
+ }
+ current := !binding.RetiredAt.Valid
+ sessions[i].ChannelSource = &ChatSessionChannelSourceResponse{
+ ChannelType: binding.ChannelType, InstallationID: uuidToString(binding.InstallationID), RouteRevision: binding.RouteRevision,
+ }
+ sessions[i].IsCurrentChannelRoute = &current
+ }
+ return nil
}
// ChatLastMessage is a preview of a session's most recent message, used to
diff --git a/server/internal/handler/chat_archive_cancel_test.go b/server/internal/handler/chat_archive_cancel_test.go
index fdb790374a..b2a3103dd4 100644
--- a/server/internal/handler/chat_archive_cancel_test.go
+++ b/server/internal/handler/chat_archive_cancel_test.go
@@ -339,6 +339,14 @@ func bindChatSessionToChannel(t *testing.T, agentID, sessionID, channelChatID st
// channel_* rows have no FK to chat_session, so they outlive the session
// helper's cleanup; clear by deterministic key.
cleanup := func() {
+ testPool.Exec(context.Background(), `
+ DELETE FROM channel_task_delivery
+ WHERE binding_id IN (
+ SELECT id FROM channel_chat_session_binding WHERE chat_session_id = $1
+ )
+ `, sessionID)
+ testPool.Exec(context.Background(),
+ `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, sessionID)
testPool.Exec(context.Background(),
`DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
testPool.Exec(context.Background(),
@@ -356,9 +364,14 @@ func bindChatSessionToChannel(t *testing.T, agentID, sessionID, channelChatID st
t.Fatalf("create installation: %v", err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO channel_chat_session_binding
- (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
- VALUES ($1, $2, 'wecom', $3, 'group')
+ WITH binding AS (
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+ VALUES ($1, $2, 'wecom', $3, 'group')
+ RETURNING chat_session_id, context_revision
+ )
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ SELECT chat_session_id, context_revision FROM binding
`, sessionID, instID, channelChatID); err != nil {
t.Fatalf("bind session: %v", err)
}
diff --git a/server/internal/handler/chat_channel_command_visibility_test.go b/server/internal/handler/chat_channel_command_visibility_test.go
index 12934ca046..1ab6ec006d 100644
--- a/server/internal/handler/chat_channel_command_visibility_test.go
+++ b/server/internal/handler/chat_channel_command_visibility_test.go
@@ -84,6 +84,12 @@ func TestChannelCommandVisibility_SessionProjectionUsesPublicMessages(t *testing
mixedSessionID := createHandlerTestChatSession(t, agentID)
newerPublicSessionID := createHandlerTestChatSession(t, agentID)
base := time.Date(2026, 8, 7, 2, 0, 0, 0, time.UTC)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE chat_session SET explicitly_created_at = NULL
+ WHERE id = ANY($1::uuid[])
+ `, []string{commandOnlySessionID, mixedSessionID, newerPublicSessionID}); err != nil {
+ t.Fatalf("set session origin fixtures: %v", err)
+ }
insertChatVisibilityMessage(t, commandOnlySessionID, "/issue hidden only", "channel_command", true, base.Add(3*time.Second))
insertChatVisibilityMessage(t, mixedSessionID, "mixed public", "message", true, base)
@@ -142,6 +148,11 @@ func TestChannelCommandVisibility_CommandOnlySessionRejectsChatInteractionsButAl
agentID := createHandlerTestAgent(t, "ChannelCommandDirectAccessAgent", []byte("[]"))
commandOnlySessionID := createHandlerTestChatSession(t, agentID)
webEmptySessionID := createHandlerTestChatSession(t, agentID)
+ if _, err := testPool.Exec(context.Background(), `
+ UPDATE chat_session SET explicitly_created_at = NULL WHERE id = $1
+ `, commandOnlySessionID); err != nil {
+ t.Fatalf("set session origin fixtures: %v", err)
+ }
insertChatVisibilityMessage(t, commandOnlySessionID, "/issue hidden", "channel_command", true, time.Now())
get := func(sessionID string) *httptest.ResponseRecorder {
diff --git a/server/internal/handler/chat_channel_debounce_boundary_test.go b/server/internal/handler/chat_channel_debounce_boundary_test.go
index 1f24adda8d..d0ba2980b2 100644
--- a/server/internal/handler/chat_channel_debounce_boundary_test.go
+++ b/server/internal/handler/chat_channel_debounce_boundary_test.go
@@ -99,7 +99,8 @@ func TestChannelChat_ReplyLandingInsideDebounceWindowStillAnswersTheNextMessage(
t.Skip("database not available")
}
ctx := context.Background()
- _, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "channel debounce boundary")
+ agentID, sessionID, runtimeID, daemonID := setupDirectChatSession(t, ctx, "channel debounce boundary")
+ seedChannelBindingOfChatType(t, ctx, agentID, sessionID, "wecom", "p2p", "", "")
// Turn 1: message in, window expires, task claimed and running.
appendChannelUserMessage(t, ctx, sessionID, "测试下")
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 7bbdc09d09..516db493a3 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -20,8 +20,8 @@ func setupDirectChatSession(t *testing.T, ctx context.Context, title string) (ag
t.Helper()
agentID, runtimeID, daemonID = createRuntimeGuardAgent(t, ctx)
if err := testPool.QueryRow(ctx, `
- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
- VALUES ($1, $2, $3, $4)
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, explicitly_created_at)
+ VALUES ($1, $2, $3, $4, now())
RETURNING id
`, testWorkspaceID, agentID, testUserID, title).Scan(&sessionID); err != nil {
t.Fatalf("setup: create chat session: %v", err)
diff --git a/server/internal/handler/chat_project_context_test.go b/server/internal/handler/chat_project_context_test.go
index 19f4ef3653..47011b5307 100644
--- a/server/internal/handler/chat_project_context_test.go
+++ b/server/internal/handler/chat_project_context_test.go
@@ -32,8 +32,10 @@ func createChatSessionWithProjectForTest(t *testing.T, agentID, projectID string
var sessionID string
if err := testPool.QueryRow(context.Background(), `
- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status, project_id)
- VALUES ($1, $2, $3, 'Project context chat', 'active', $4)
+ INSERT INTO chat_session (
+ workspace_id, agent_id, creator_id, title, status, project_id, explicitly_created_at
+ )
+ VALUES ($1, $2, $3, 'Project context chat', 'active', $4, now())
RETURNING id
`, testWorkspaceID, agentID, testUserID, projectID).Scan(&sessionID); err != nil {
t.Fatalf("create chat session: %v", err)
diff --git a/server/internal/handler/chat_title.go b/server/internal/handler/chat_title.go
index e20202c03a..b4ace2718c 100644
--- a/server/internal/handler/chat_title.go
+++ b/server/internal/handler/chat_title.go
@@ -9,6 +9,7 @@ import (
"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"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -20,6 +21,35 @@ import (
// a chat title is a nicety, not worth pinning a goroutine for a minute.
const chatTitleGenTimeout = 20 * time.Second
+// ChannelChatStarted publishes list invalidation metadata without changing any
+// client's current navigation. The explicit empty Chat is already committed.
+func (h *Handler) ChannelChatStarted(event engine.ChannelChatStartedEvent) {
+ ws, user, session := uuidToString(event.WorkspaceID), uuidToString(event.CreatorID), uuidToString(event.SessionID)
+ h.publishChat(protocol.EventChatSessionCreated, ws, "member", user, session, protocol.ChatSessionCreatedPayload{
+ WorkspaceID: ws, ChatSessionID: session, AgentID: uuidToString(event.AgentID), CreatorID: user, Title: event.Title,
+ ChannelSource: protocol.ChatSessionChannelSource{
+ ChannelType: string(event.ChannelType), InstallationID: uuidToString(event.InstallationID), RouteRevision: event.RouteRevision,
+ },
+ IsCurrentChannelRoute: true,
+ })
+}
+
+// ChannelChatTitleInitialized publishes the deterministic first-message or
+// media fallback immediately. LLM title generation is optional, so clients
+// must not depend on its later CAS update to observe the committed title.
+func (h *Handler) ChannelChatTitleInitialized(workspaceID, creatorID, sessionID pgtype.UUID, title string) {
+ h.publishChat(protocol.EventChatSessionUpdated, uuidToString(workspaceID), "member", uuidToString(creatorID), uuidToString(sessionID), protocol.ChatSessionUpdatedPayload{
+ ChatSessionID: uuidToString(sessionID),
+ Title: title,
+ })
+}
+
+// GenerateChannelChatTitle reuses the existing LLM + CAS title path after the
+// shared engine has persisted its deterministic first-message fallback.
+func (h *Handler) GenerateChannelChatTitle(workspaceID, creatorID, sessionID pgtype.UUID, currentTitle, sourceText string) {
+ h.maybeGenerateChatTitleAsync(uuidToString(workspaceID), uuidToString(creatorID), sessionID, currentTitle, sourceText)
+}
+
// chatTitleSystemPrompt instructs the model to condense the opening of a
// conversation into a short, language-matched title. The rules mirror the
// acceptance criteria in MUL-4295: no quotes, no trailing punctuation, no
diff --git a/server/internal/handler/chat_title_test.go b/server/internal/handler/chat_title_test.go
index 789abe136d..b7a961adb5 100644
--- a/server/internal/handler/chat_title_test.go
+++ b/server/internal/handler/chat_title_test.go
@@ -378,3 +378,18 @@ func TestSanitizeChatTitle(t *testing.T) {
})
}
}
+
+func TestShouldGenerateFirstMessageTitlePreservesChannelManualRename(t *testing.T) {
+ if shouldGenerateFirstMessageTitle(false, "manual name", "", true, true) {
+ t.Fatal("channel manual rename was treated as an auto-generated title")
+ }
+ if !shouldGenerateFirstMessageTitle(false, "derived title", "derived title", true, true) {
+ t.Fatal("title initialized by the channel send should be eligible for refinement")
+ }
+ if shouldGenerateFirstMessageTitle(false, "unknown source", "", false, false) {
+ t.Fatal("source lookup failure must skip optional title generation")
+ }
+ if !shouldGenerateFirstMessageTitle(false, "first-party seed", "", false, true) {
+ t.Fatal("first-party Chat should retain the existing title refinement flow")
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 925aff499b..4374f30775 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2595,52 +2595,23 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.ChatIntro = !hasUser
}
}
- // Flag a channel-backed session so the daemon makes the agent aware it
- // is operating inside an IM conversation and not the Multica web app
- // (MUL-3871). Empty for a web-only chat session.
- //
- // The binding is read WITHOUT naming a channel. Every channel writes
- // the same channel_chat_session_binding row and differs only in
- // channel_type, and UNIQUE (chat_session_id) allows at most one, so
- // the row itself is the answer. Enumerating candidate channels here
- // was the bug twice over: the Slack-only lookup reported a Feishu
- // chat as web-backed (MUL-4899), and the {slack, feishu} list that
- // replaced it did the same to WeCom. Downstream that mis-flag makes
- // the brief inject `multica attachment upload` guidance into a
- // conversation that cannot carry attachments at all.
- //
- // ChatInThread stays Slack-only on purpose. It selects between
- // `multica chat history` and `multica chat thread`, and those two
- // endpoints are hardwired to h.SlackHistory (chat_history.go) — there
- // is no history reader on any other channel, so the flag has nothing
- // to select between there and must not imply one exists.
- //
- // chat_type rides along on the same row. It is what lets the
- // per-turn prompt tell the agent whether this chat_session is a room
- // shared by many people or a 1:1 with the bot; the prompt used to
- // describe every chat run as a private 1:1 whatever the room. The
- // shared session service writes the column for every channel
- // (channel/engine/session.go), so no channel needs naming here
- // either.
- if binding, berr := h.Queries.GetChannelChatSessionBindingBySessionAny(r.Context(), cs.ID); berr == nil {
- resp.ChatChannelType = binding.ChannelType
- resp.ChatType = binding.ChatType
- // Whether a file the agent produces reaches this
- // conversation is the server's question, not the daemon's.
- // It takes an adapter that goes back for the bound
- // attachment AND storage for it to go back to, and only
- // this process knows both. Answered here so the daemon
- // never has to infer it from the channel type — an
- // inference that promises delivery on any deployment
- // running WeCom without object storage.
- resp.ChatChannelDeliversFiles = h.channelDeliversFiles(binding.ChannelType)
- if binding.ChannelType == string(slack.TypeSlack) {
- // The latest trigger was a thread reply iff its reply-target
- // thread (last_thread_id) differs from its own message id (a
- // top-level @mention records its own ts as both).
- resp.ChatInThread = binding.LastThreadID.Valid && binding.LastThreadID.String != "" &&
- binding.LastThreadID.String != binding.LastMessageID.String
+ // A task-level delivery snapshot, not the Chat's historical binding,
+ // decides whether this run is operating for an external audience.
+ // Web/Desktop/Mobile turns in an old channel-originated Chat have no
+ // snapshot and remain private to Multica after /new rotates the route.
+ delivery, deliveryErr := h.Queries.GetChannelTaskDelivery(r.Context(), task.ID)
+ if deliveryErr == nil {
+ resp.ChatChannelType = delivery.ChannelType
+ resp.ChatType = delivery.ChatType
+ resp.ChatChannelDeliversFiles = h.channelDeliversFiles(delivery.ChannelType)
+ if delivery.ChannelType == string(slack.TypeSlack) {
+ resp.ChatInThread = delivery.ChannelThreadID.Valid &&
+ delivery.ChannelThreadID.String != "" &&
+ delivery.ChannelThreadID.String != delivery.ChannelMessageID.String
}
+ } else if !errors.Is(deliveryErr, pgx.ErrNoRows) {
+ return resp, deliveredCommentIDs, agentSkillCount, builtinSkillCount,
+ h.rejectClaimSourceLoad(r.Context(), task, deliveryErr, "channel task delivery", uuidToString(task.ID))
}
// A web chat can opt into the same durable project context as an
// issue-bound task.
diff --git a/server/internal/handler/daemon_claim_channel_type_test.go b/server/internal/handler/daemon_claim_channel_type_test.go
index 1dad172fca..9ec45d61c9 100644
--- a/server/internal/handler/daemon_claim_channel_type_test.go
+++ b/server/internal/handler/daemon_claim_channel_type_test.go
@@ -47,18 +47,48 @@ func seedChannelBindingOfChatType(t *testing.T, ctx context.Context, agentID, se
t.Fatalf("seed %s installation: %v", channelType, err)
}
if _, err := testPool.Exec(ctx, `
- INSERT INTO channel_chat_session_binding
- (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id)
- VALUES ($1, $2, $3, $4, $5, $6, $7)
+ WITH binding AS (
+ INSERT INTO channel_chat_session_binding
+ (chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING chat_session_id, context_revision
+ )
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ SELECT chat_session_id, context_revision FROM binding
`, sessionID, installationID, channelType, "C-TEST-"+channelType, chatType, lastMessageID, lastThreadID); err != nil {
t.Fatalf("seed %s binding: %v", channelType, err)
}
t.Cleanup(func() {
+ testPool.Exec(ctx, `
+ DELETE FROM channel_task_delivery
+ WHERE binding_id IN (
+ SELECT id FROM channel_chat_session_binding WHERE chat_session_id = $1
+ )
+ `, sessionID)
+ testPool.Exec(ctx, `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, sessionID)
testPool.Exec(ctx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, sessionID)
testPool.Exec(ctx, `DELETE FROM channel_installation WHERE id = $1`, installationID)
})
}
+func seedChannelTaskDelivery(t *testing.T, ctx context.Context, taskID, sessionID string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+ )
+ SELECT $1, id, installation_id, channel_type, channel_chat_id, chat_type,
+ last_message_id, last_thread_id, route_revision, config
+ FROM channel_chat_session_binding WHERE chat_session_id = $2
+ `, taskID, sessionID); err != nil {
+ t.Fatalf("seed channel task delivery: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE task_id = $1`, taskID)
+ })
+}
+
// claimedChatChannel is the channel-awareness slice of a claim response.
type claimedChatChannel struct {
ChannelType string `json:"chat_channel_type"`
@@ -101,7 +131,8 @@ func TestClaim_FeishuBoundSessionReportsChannelType(t *testing.T) {
// last_thread_id != last_message_id: the shape that would set ChatInThread on
// Slack. Feishu must still report false — there is no reader to thread into.
seedChannelBinding(t, ctx, agentID, sessionID, "feishu", "msg-1", "thread-9")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -120,7 +151,8 @@ func TestClaim_SlackBoundSessionStillReportsThreadState(t *testing.T) {
ctx := context.Background()
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "slack-backed chat")
seedChannelBinding(t, ctx, agentID, sessionID, "slack", "msg-1", "thread-9")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -148,7 +180,8 @@ func TestClaim_UnlistedChannelBoundSessionReportsChannelType(t *testing.T) {
ctx := context.Background()
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "wecom-backed chat")
seedChannelBinding(t, ctx, agentID, sessionID, "wecom", "msg-1", "thread-9")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -178,6 +211,23 @@ func TestClaim_UnboundSessionReportsNoChannelType(t *testing.T) {
}
}
+func TestClaim_ChannelOriginChatWithoutTaskDeliveryIsPrivateMulticaTurn(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "old channel chat continued in web")
+ seedChannelBinding(t, ctx, agentID, sessionID, "slack", "msg-1", "thread-9")
+ // Deliberately no channel_task_delivery: this is the shape produced by a
+ // Web/Desktop/Mobile send after /new moves the external route elsewhere.
+ insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ requeueTaskForClaim(t, ctx, sessionID)
+ claimed := claimChatChannelFields(t, runtimeID)
+ if claimed.ChannelType != "" || claimed.InThread || claimed.DeliversFiles {
+ t.Fatalf("private continuation leaked channel audience: %+v", claimed)
+ }
+}
+
// The room shape rides the same binding row as the channel type and must reach
// the daemon with it. Without it the per-turn prompt has no way to know that one
// chat_session is a room shared by many people, and it described every chat run
@@ -205,7 +255,8 @@ func TestClaim_BoundSessionReportsRoomShape(t *testing.T) {
t.Run(name, func(t *testing.T) {
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, name+" chat")
seedChannelBindingOfChatType(t, ctx, agentID, sessionID, tc.channelType, tc.chatType, "msg-1", "msg-1")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -287,7 +338,8 @@ func TestClaim_FileDeliveryIsTheDeploymentsAnswerNotTheChannelTypes(t *testing.T
declareFileDeliveryForTest(t, "wecom")
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "wecom chat with storage")
seedChannelBinding(t, ctx, agentID, sessionID, "wecom", "msg-1", "msg-1")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -303,7 +355,8 @@ func TestClaim_FileDeliveryIsTheDeploymentsAnswerNotTheChannelTypes(t *testing.T
declareFileDeliveryForTest(t) // nothing declared, as a storage-less deployment
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "wecom chat without storage")
seedChannelBinding(t, ctx, agentID, sessionID, "wecom", "msg-1", "msg-1")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
claimed := claimChatChannelFields(t, runtimeID)
@@ -319,7 +372,8 @@ func TestClaim_FileDeliveryIsTheDeploymentsAnswerNotTheChannelTypes(t *testing.T
declareFileDeliveryForTest(t, "wecom")
agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "slack chat alongside wecom")
seedChannelBinding(t, ctx, agentID, sessionID, "slack", "msg-1", "msg-1")
- insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ taskID := insertChannelChatTask(t, ctx, agentID, runtimeID, sessionID)
+ seedChannelTaskDelivery(t, ctx, taskID, sessionID)
requeueTaskForClaim(t, ctx, sessionID)
if claimed := claimChatChannelFields(t, runtimeID); claimed.DeliversFiles {
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index c3db50af63..82abf95cdf 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -36,8 +36,10 @@ func createHandlerTestChatSession(t *testing.T, agentID string) string {
var sessionID string
if err := testPool.QueryRow(context.Background(), `
- INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, status)
- VALUES ($1, $2, $3, $4, 'active')
+ INSERT INTO chat_session (
+ workspace_id, agent_id, creator_id, title, status, explicitly_created_at
+ )
+ VALUES ($1, $2, $3, $4, 'active', now())
RETURNING id
`, testWorkspaceID, agentID, testUserID, "Handler Test Chat Session").Scan(&sessionID); err != nil {
t.Fatalf("failed to create handler test chat session: %v", err)
diff --git a/server/internal/handler/mika_agent.go b/server/internal/handler/mika_agent.go
index ddd483e2c1..d8cb25b3db 100644
--- a/server/internal/handler/mika_agent.go
+++ b/server/internal/handler/mika_agent.go
@@ -306,6 +306,10 @@ func (h *Handler) getOrCreateMikaSession(ctx context.Context, agent db.Agent, wo
if err != nil {
return db.ChatSession{}, err
}
+ created, err = qtx.MarkChatSessionExplicitlyCreated(ctx, created.ID)
+ if err != nil {
+ return db.ChatSession{}, err
+ }
if err := tx.Commit(ctx); err != nil {
return db.ChatSession{}, err
}
diff --git a/server/internal/handler/mika_second_member_test.go b/server/internal/handler/mika_second_member_test.go
index a9a964cc82..e9a321e748 100644
--- a/server/internal/handler/mika_second_member_test.go
+++ b/server/internal/handler/mika_second_member_test.go
@@ -173,6 +173,16 @@ func TestCreateMikaAgent_SessionIsPerMemberAndStable(t *testing.T) {
if firstResp.OnboardingSession == nil {
t.Fatal("first call returned no onboarding session")
}
+ var explicitlyCreated bool
+ if err := testPool.QueryRow(context.Background(),
+ `SELECT explicitly_created_at IS NOT NULL FROM chat_session WHERE id = $1`,
+ firstResp.OnboardingSession.ID,
+ ).Scan(&explicitlyCreated); err != nil {
+ t.Fatalf("load Mika session origin: %v", err)
+ }
+ if !explicitlyCreated {
+ t.Fatal("Mika onboarding session must be marked as an explicit first-party Chat")
+ }
t.Cleanup(func() {
testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE creator_id = $1`, testUserID)
})
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 7db3958811..7783045525 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -44,6 +44,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"channel_installation": workspaceDelete,
"channel_media_pending_object": workspaceDeleteSettle,
"channel_outbound_card_message": workspaceDelete,
+ "channel_outbound_message": workspaceDelete,
+ "channel_task_delivery": workspaceDelete,
"channel_user_binding": workspaceDelete,
"chat_draft_restore": workspaceDelete,
"chat_message": workspaceDelete,
diff --git a/server/internal/integrations/channel/engine/batcher.go b/server/internal/integrations/channel/engine/batcher.go
index 3706e820c2..498f040127 100644
--- a/server/internal/integrations/channel/engine/batcher.go
+++ b/server/internal/integrations/channel/engine/batcher.go
@@ -20,7 +20,7 @@ type stoppableTimer interface {
// pendingBatcher debounces a per-(chat_session, context generation) run trigger.
// Each inbound message calls Schedule, which (re)arms one timer for that
// generation; when it goes quiet the latest flush runs exactly once. This
-// collapses an in-generation burst into one agent run while preserving /new as
+// collapses an in-generation burst into one agent run while preserving /clear as
// a hard batch boundary. Only the run trigger is debounced; chat_message rows,
// dedup, and frame ACK already happened synchronously upstream.
//
@@ -29,7 +29,7 @@ type stoppableTimer interface {
// debounced by one process. A hard crash inside the window drops the pending
// trigger (messages are durable; they just do not fire a run until the next
// message). Callers include the durable context revision in the key, so a
-// /new boundary can never replace the pending flush for the preceding context.
+// /clear boundary can never replace the pending flush for the preceding context.
// Graceful shutdown calls FlushAll so that boundary is not hit on a normal
// restart. Goroutine-safe; one instance is shared across supervisors.
type pendingBatcher struct {
diff --git a/server/internal/integrations/channel/engine/fresh_command.go b/server/internal/integrations/channel/engine/fresh_command.go
index 34ed0f72f3..d81c5f40c0 100644
--- a/server/internal/integrations/channel/engine/fresh_command.go
+++ b/server/internal/integrations/channel/engine/fresh_command.go
@@ -2,17 +2,67 @@ package engine
import "strings"
-const freshSessionCommandPrefix = "/new"
+const freshSessionCommandPrefix = "/clear"
+const newChatCommandPrefix = "/new"
-// ParseFreshSessionCommand extracts a first-line /new command from a channel
+// ControlCommandKind identifies the shared session-control directive on the
+// first non-empty line of an inbound channel message. Adapters may normalize
+// transport details (for example, a platform bot mention or rich-media
+// layout), but only Router applies these product semantics.
+type ControlCommandKind uint8
+
+const (
+ ControlCommandFreshSession ControlCommandKind = iota + 1
+ ControlCommandNewChat
+)
+
+// ControlCommand is one parsed channel session-control directive.
+type ControlCommand struct {
+ Kind ControlCommandKind
+ Body string
+}
+
+// ParseControlCommand classifies /clear and /new through one parser. Their
+// inbound syntax is intentionally identical; the only distinction is the
+// product action Router applies after normalization.
+func ParseControlCommand(body string) (ControlCommand, bool) {
+ if parsed, ok := parseLeadingCommand(body, newChatCommandPrefix); ok {
+ return ControlCommand{Kind: ControlCommandNewChat, Body: parsed}, true
+ }
+ if parsed, ok := parseLeadingCommand(body, freshSessionCommandPrefix); ok {
+ return ControlCommand{Kind: ControlCommandFreshSession, Body: parsed}, true
+ }
+ return ControlCommand{}, false
+}
+
+// ParseFreshSessionCommand extracts a first-line /clear command from a channel
// message. It returns the user prompt with the directive removed. The command
// is shared product behavior: every channel that reaches Router gets the same
// fresh-session affordance without reimplementing parsing in its adapter.
//
// Matching follows the /issue command rules: case-sensitive, token-bounded,
-// and only the first non-empty line can be a command. That means /new and
+// and only the first non-empty line can be a command. That means /clear and
// /issue are mutually exclusive on the same first line.
func ParseFreshSessionCommand(body string) (string, bool) {
+ command, ok := ParseControlCommand(body)
+ if !ok || command.Kind != ControlCommandFreshSession {
+ return "", false
+ }
+ return command.Body, true
+}
+
+// ParseNewChatCommand extracts the shared /new command. Parsing intentionally
+// matches /clear so adapters only normalize transport details; route rotation is
+// always owned by the shared engine.
+func ParseNewChatCommand(body string) (string, bool) {
+ command, ok := ParseControlCommand(body)
+ if !ok || command.Kind != ControlCommandNewChat {
+ return "", false
+ }
+ return command.Body, true
+}
+
+func parseLeadingCommand(body, prefix string) (string, bool) {
lines := strings.Split(body, "\n")
firstIdx := -1
@@ -27,11 +77,11 @@ func ParseFreshSessionCommand(body string) (string, bool) {
}
trimmed := strings.TrimLeft(lines[firstIdx], " \t")
- if !strings.HasPrefix(trimmed, freshSessionCommandPrefix) {
+ if !strings.HasPrefix(trimmed, prefix) {
return "", false
}
- rest := trimmed[len(freshSessionCommandPrefix):]
+ rest := trimmed[len(prefix):]
if rest != "" {
if r0 := rest[0]; r0 != ' ' && r0 != '\t' {
return "", false
diff --git a/server/internal/integrations/channel/engine/fresh_command_test.go b/server/internal/integrations/channel/engine/fresh_command_test.go
index 398a88da16..525bfb5961 100644
--- a/server/internal/integrations/channel/engine/fresh_command_test.go
+++ b/server/internal/integrations/channel/engine/fresh_command_test.go
@@ -2,6 +2,26 @@ package engine
import "testing"
+func TestParseControlCommandClassifiesSharedSyntax(t *testing.T) {
+ tests := []struct {
+ input string
+ kind ControlCommandKind
+ body string
+ }{
+ {input: "/clear reset this", kind: ControlCommandFreshSession, body: "reset this"},
+ {input: "/new start this", kind: ControlCommandNewChat, body: "start this"},
+ }
+ for _, tc := range tests {
+ command, ok := ParseControlCommand(tc.input)
+ if !ok || command.Kind != tc.kind || command.Body != tc.body {
+ t.Fatalf("ParseControlCommand(%q) = %+v, %v", tc.input, command, ok)
+ }
+ }
+ if command, ok := ParseControlCommand("please /new later"); ok {
+ t.Fatalf("mid-sentence control command matched: %+v", command)
+ }
+}
+
func TestParseFreshSessionCommand(t *testing.T) {
tests := []struct {
name string
@@ -9,13 +29,13 @@ func TestParseFreshSessionCommand(t *testing.T) {
wantMatch bool
wantBody string
}{
- {name: "new with same-line body", body: "/new start from scratch", wantMatch: true, wantBody: "start from scratch"},
- {name: "leading blank lines tolerated", body: "\n\n/new re-check the deploy", wantMatch: true, wantBody: "re-check the deploy"},
- {name: "multi-line body preserved", body: "/new title\nline one\nline two", wantMatch: true, wantBody: "title\nline one\nline two"},
- {name: "command alone produces empty body", body: "/new", wantMatch: true, wantBody: ""},
- {name: "prefix of token rejected", body: "/newness is not a command", wantMatch: false},
- {name: "mid-sentence command rejected", body: "please /new this run", wantMatch: false},
- {name: "wrong case rejected", body: "/New help", wantMatch: false},
+ {name: "clear with same-line body", body: "/clear start from scratch", wantMatch: true, wantBody: "start from scratch"},
+ {name: "leading blank lines tolerated", body: "\n\n/clear re-check the deploy", wantMatch: true, wantBody: "re-check the deploy"},
+ {name: "multi-line body preserved", body: "/clear title\nline one\nline two", wantMatch: true, wantBody: "title\nline one\nline two"},
+ {name: "command alone produces empty body", body: "/clear", wantMatch: true, wantBody: ""},
+ {name: "prefix of token rejected", body: "/clearness is not a command", wantMatch: false},
+ {name: "mid-sentence command rejected", body: "please /clear this run", wantMatch: false},
+ {name: "wrong case rejected", body: "/Clear help", wantMatch: false},
{name: "normal body rejected", body: "help me normally", wantMatch: false},
}
@@ -31,3 +51,32 @@ func TestParseFreshSessionCommand(t *testing.T) {
})
}
}
+
+func TestParseNewChatCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ body string
+ wantMatch bool
+ wantBody string
+ }{
+ {name: "new with same-line body", body: "/new investigate this", wantMatch: true, wantBody: "investigate this"},
+ {name: "leading blank lines tolerated", body: "\n\t\n/new\tkeep layout\nsecond line", wantMatch: true, wantBody: "keep layout\nsecond line"},
+ {name: "bare new", body: "/new", wantMatch: true, wantBody: ""},
+ {name: "new wins without reparsing body", body: "/new /issue ordinary text", wantMatch: true, wantBody: "/issue ordinary text"},
+ {name: "prefix rejected", body: "/newness", wantMatch: false},
+ {name: "wrong case rejected", body: "/New", wantMatch: false},
+ {name: "mid-sentence rejected", body: "please /new", wantMatch: false},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ body, ok := ParseNewChatCommand(tc.body)
+ if ok != tc.wantMatch {
+ t.Fatalf("match=%v want %v (body=%q)", ok, tc.wantMatch, body)
+ }
+ if body != tc.wantBody {
+ t.Errorf("body=%q want %q", body, tc.wantBody)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index 9c0998bcec..02e9560921 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -27,6 +27,7 @@ const (
OutcomeNeedsBinding Outcome = "needs_binding"
OutcomeIngested Outcome = "ingested"
OutcomeFreshPending Outcome = "fresh_pending"
+ OutcomeChatStarted Outcome = "chat_started"
OutcomeIssueUsage Outcome = "issue_usage"
OutcomeAgentOffline Outcome = "agent_offline"
OutcomeAgentArchived Outcome = "agent_archived"
@@ -49,10 +50,12 @@ const (
// consumed by the outbound side (OutboundReplier / typing). It mirrors the
// legacy lark.DispatchResult.
type Result struct {
- Outcome Outcome
- DropReason DropReason
- InstallationID pgtype.UUID
- ChatSessionID pgtype.UUID
+ Outcome Outcome
+ DropReason DropReason
+ InstallationID pgtype.UUID
+ ChatSessionID pgtype.UUID
+ ChannelBindingID pgtype.UUID
+ ChannelRouteRevision int64
// Sender is the platform-native sender id (e.g. Lark open_id), so the
// replier can target a binding prompt back to the sender.
Sender string
@@ -100,6 +103,30 @@ type EnsureSessionParams struct {
Message channel.InboundMessage
}
+// StartSessionParams carries a /new route rotation. Creator owns the new Chat;
+// Sender is the authenticated user who issued the command and initiated its
+// first context. They differ for group chats, where the installer owns the Chat
+// but the group member remains the turn initiator. PersistMessage is false only
+// for the bare control command; a media-only /new is a real first turn.
+type StartSessionParams struct {
+ Installation ResolvedInstallation
+ Creator pgtype.UUID
+ Sender pgtype.UUID
+ Message channel.InboundMessage
+ ClaimToken pgtype.UUID
+ MediaPendingSeconds float64
+ PersistMessage bool
+ HistoryBoundaryPending bool
+ BeforeCommit func(context.Context, pgx.Tx, db.ChatSession) error
+}
+
+type StartSessionResult struct {
+ SessionID pgtype.UUID
+ BindingID pgtype.UUID
+ RouteRevision int64
+ Append AppendResult
+}
+
// AppendParams carries the inputs for SessionBinder.AppendMessage. ClaimToken
// is the dedup owner-fence token; the binder runs the dedup Mark INSIDE its
// chat_message+session tx so the durable write and the Mark commit atomically.
@@ -133,6 +160,12 @@ type AppendResult struct {
// its authenticated sender snapshot. It re-arms debounce windows lost on
// process crash without borrowing the sender of a later generation.
PendingContexts []PendingContext
+ InitialTitle string
+ // BecameVisible is true only when this committed ordinary turn changed an
+ // implicit channel session from hidden orchestration state into a public Chat.
+ BecameVisible bool
+ BindingID pgtype.UUID
+ RouteRevision int64
}
// PendingContext identifies durable unowned input that needs a run timer. The
@@ -143,6 +176,28 @@ type PendingContext struct {
InitiatorUserID pgtype.UUID
}
+// ChannelChatLifecycle bridges committed channel Chat changes to the server's
+// existing realtime and best-effort title services without coupling the engine
+// package to HTTP handlers.
+type ChannelChatLifecycle interface {
+ ChannelChatStarted(event ChannelChatStartedEvent)
+ ChannelChatTitleInitialized(workspaceID, creatorID, sessionID pgtype.UUID, title string)
+ GenerateChannelChatTitle(workspaceID, creatorID, sessionID pgtype.UUID, currentTitle, sourceText string)
+}
+
+// ChannelChatStartedEvent contains enough committed metadata for clients to
+// add or invalidate a channel-created Chat without changing their navigation.
+type ChannelChatStartedEvent struct {
+ WorkspaceID pgtype.UUID
+ CreatorID pgtype.UUID
+ AgentID pgtype.UUID
+ SessionID pgtype.UUID
+ InstallationID pgtype.UUID
+ ChannelType channel.Type
+ RouteRevision int64
+ Title string
+}
+
// BindMediaParams carries stored media references to the post-append
// attachment transaction. MessageID is the durable chat_message whose pending
// marker the binder clears. IssueID selects issue ownership for an /issue turn;
@@ -162,6 +217,14 @@ type BindMediaParams struct {
MediaRefs []channel.MediaRef
}
+// BindMediaResult reports a title initialized only after the first media
+// attachment committed. The Router uses it to publish realtime state and run
+// the same best-effort LLM/CAS title flow as a text-first Chat.
+type BindMediaResult struct {
+ InitialTitle string
+ TitleSource string
+}
+
// IssueCommand is the parsed /issue command.
type IssueCommand struct {
Title string
@@ -179,6 +242,9 @@ var (
// ErrSenderNotMember: the sender is bound but not a workspace member →
// non_workspace_member drop.
ErrSenderNotMember = errors.New("engine: sender not a workspace member")
+ // ErrRouteChanged asks the Router to resolve the platform route again and
+ // retry the same claimed message before any durable write is made.
+ ErrRouteChanged = errors.New("engine: route changed")
// ErrDuplicate: Claim found the message already processed / in flight →
// duplicate drop.
ErrDuplicate = errors.New("engine: duplicate message")
@@ -216,9 +282,10 @@ type Deduper interface {
// rotated mid-flight.
type SessionBinder interface {
EnsureSession(ctx context.Context, p EnsureSessionParams) (pgtype.UUID, error)
+ StartSession(ctx context.Context, p StartSessionParams) (StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendMessage(ctx context.Context, p AppendParams) (AppendResult, error)
- BindMedia(ctx context.Context, p BindMediaParams) error
+ BindMedia(ctx context.Context, p BindMediaParams) (BindMediaResult, error)
}
// MediaResolver resolves platform media after the user message and dedup mark
@@ -349,7 +416,10 @@ type IssueCreator interface {
// TaskEnqueuer is the narrow subset of service.TaskService the Router needs to
// trigger a chat run. Shared across platforms.
type TaskEnqueuer interface {
- EnqueueChannelChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error)
+ EnqueueChannelChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64, bindingID pgtype.UUID, routeRevision int64) (db.AgentTaskQueue, error)
+ PrepareChatTaskEnqueue(ctx context.Context, agentID, initiatorUserID pgtype.UUID) (service.PreparedChatTaskEnqueue, error)
+ EnqueuePreparedChannelChatTaskInTx(ctx context.Context, tx pgx.Tx, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64, prepared service.PreparedChatTaskEnqueue) (db.AgentTaskQueue, error)
+ FinalizeChatTaskEnqueue(ctx context.Context, task db.AgentTaskQueue)
PromoteChannelChatTasksIfMediaReady(ctx context.Context, sessionID pgtype.UUID) error
PromoteDeferredChannelIssueTask(ctx context.Context, taskID pgtype.UUID) error
}
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index 0ac99ed2c3..18d2b1c595 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -8,6 +8,7 @@ import (
"sync"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -35,9 +36,10 @@ type Router struct {
mu sync.RWMutex
sets map[channel.Type]ResolverSet
- issues IssueCreator
- tasks TaskEnqueuer
- reader SessionReader
+ issues IssueCreator
+ tasks TaskEnqueuer
+ reader SessionReader
+ lifecycle ChannelChatLifecycle
batcher *pendingBatcher
@@ -74,6 +76,7 @@ type RouterConfig struct {
// Per-session ordering is unaffected. Defaults to 8.
MediaConcurrency int
Logger *slog.Logger
+ Lifecycle ChannelChatLifecycle
}
// NewRouter builds a Router around the shared (platform-agnostic) services:
@@ -99,6 +102,7 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cf
issues: issues,
tasks: tasks,
reader: reader,
+ lifecycle: cfg.Lifecycle,
replyTimeout: cfg.ReplyTimeout,
mediaTimeout: cfg.MediaTimeout,
mediaCtx: mediaCtx,
@@ -114,6 +118,12 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cf
// delay dwarfs every pipeline budget.
const DefaultMediaTimeout = 45 * time.Second
+// maxRouteChangeRetries bounds an in-process retry loop when a connector keeps
+// reporting a stale route. A healthy conflict converges after re-resolving the
+// current route; a persistent schema or database fault must surface instead of
+// keeping the webhook handler alive forever.
+const maxRouteChangeRetries = 8
+
// Dedup finalization is a short durability step after the claimed pipeline has
// selected a terminal outcome. The request context may already be cancelled,
// so preserve its values while giving Mark/Release a bounded opportunity to
@@ -188,18 +198,31 @@ func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {
msg.CommandText = msg.Text
}
- // /new is a channel-wide product command, not an adapter capability. Parse
- // the original command source here even when an adapter already set
- // ForceFresh, so bare-command classification stays identical across
- // platforms. Only rewrite Text when the adapter has not already stripped
- // the directive; Feishu enriches that stripped body before it reaches us.
+ // /new and /clear share one channel-wide parser. Adapters only normalize
+ // transport details; the semantic fork lives here so one inbound message has
+ // exactly one control-plane meaning.
+ control, hasControl := ParseControlCommand(msg.CommandText)
+ startChat := hasControl && control.Kind == ControlCommandNewChat
bareFresh := false
- if body, ok := ParseFreshSessionCommand(msg.CommandText); ok {
+ if startChat {
+ if parsedText, textOK := ParseControlCommand(msg.Text); textOK && parsedText.Kind == ControlCommandNewChat {
+ msg.Text = parsedText.Body
+ } else if msg.Text == msg.CommandText {
+ msg.Text = control.Body
+ }
+ // The consumed /new source must not be reinterpreted as /issue by a
+ // downstream classifier.
+ msg.CommandText = control.Body
+ } else if hasControl && control.Kind == ControlCommandFreshSession {
+ // Parse the original command source even when an adapter already set
+ // ForceFresh. Only rewrite Text when the adapter has not already stripped
+ // the directive; Feishu and rich-media adapters may have enriched or
+ // reconstructed that visible body before it reaches Router.
adapterAlreadyStripped := msg.ForceFresh
msg.ForceFresh = true
- bareFresh = body == ""
+ bareFresh = control.Body == ""
if !adapterAlreadyStripped {
- msg.Text = body
+ msg.Text = control.Body
}
}
@@ -211,11 +234,16 @@ func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {
return ErrNoResolverSet
}
- res, inst, err := r.dispatch(ctx, set, msg, bareFresh)
+ res, inst, err := r.dispatch(ctx, set, msg, bareFresh, startChat)
if err != nil {
+ outcome := "dispatch_failed"
+ if startChat {
+ outcome = "chat_start_failed"
+ }
r.logger.Error("channel router: dispatch error",
"channel_type", string(msg.Source.ChannelType),
"event_id", msg.EventID,
+ "outcome", outcome,
"error", err,
)
return err
@@ -242,7 +270,7 @@ func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {
// dispatch runs the pipeline and returns the typed result plus the resolved
// installation (needed by the outbound side). Mirrors lark.Dispatcher.Handle.
-func (r *Router) dispatch(ctx context.Context, set ResolverSet, msg channel.InboundMessage, bareFresh bool) (Result, ResolvedInstallation, error) {
+func (r *Router) dispatch(ctx context.Context, set ResolverSet, msg channel.InboundMessage, bareFresh, startChat bool) (Result, ResolvedInstallation, error) {
// 1. Route to installation. The adapter maps the platform routing key
// (carried on the message) to its installation row. These drop
// branches run BEFORE the dedup claim because they have no valid
@@ -277,7 +305,7 @@ func (r *Router) dispatch(ctx context.Context, set ResolverSet, msg channel.Inbo
claimed = true
}
- res, finalize, err := r.processClaimed(ctx, set, msg, inst, claimToken, bareFresh)
+ res, finalize, err := r.processClaimed(ctx, set, msg, inst, claimToken, bareFresh, startChat)
if claimed && finalize != finalizeNone {
finalizeCtx, finalizeCancel := context.WithTimeout(context.WithoutCancel(ctx), dedupFinalizeTimeout)
@@ -303,7 +331,7 @@ const (
// processClaimed runs the post-dedup pipeline. Mirrors
// lark.Dispatcher.processClaimed; see its boundary contract per step.
-func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channel.InboundMessage, inst ResolvedInstallation, claimToken pgtype.UUID, bareFresh bool) (Result, dedupFinalize, error) {
+func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channel.InboundMessage, inst ResolvedInstallation, claimToken pgtype.UUID, bareFresh, startChat bool) (Result, dedupFinalize, error) {
// 3. Group-mention filter (group chats only), before identity so an
// unbound user's idle group chatter never spams a binding card.
if msg.Source.ChatType == channel.ChatTypeGroup && !msg.AddressedToBot {
@@ -330,74 +358,161 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
}
}
- // 5. Resolve the chat_session. Group sessions are created by the INSTALLER
- // (stable workspace identity that won't churn with group membership);
- // p2p sessions by the sole human sender.
+ // 5-6. Resolve the current Chat route, then either append normally or
+ // atomically create the next Chat route with its optional first turn.
sessionCreator := identity.UserID
if msg.Source.ChatType == channel.ChatTypeGroup {
sessionCreator = inst.InstallerUserID
}
- sessionID, err := set.Session.EnsureSession(ctx, EnsureSessionParams{
- Installation: inst,
- Sender: sessionCreator,
- Message: msg,
- })
- if err != nil {
- // Single tx; an error rolled it back, nothing landed. Release.
- return Result{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
- }
- if bareFresh {
- // ForceFresh is a task-dispatch property. A bare command has no useful
- // task to dispatch, so remember the intent and apply it to the next real
- // message instead of writing or running an empty turn.
- if err := set.Session.MarkPendingFresh(ctx, sessionID, msg.MessageID); err != nil {
- return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)
- }
- return Result{
- Outcome: OutcomeFreshPending,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- Sender: msg.Source.SenderID,
- }, finalizeMark, nil
- }
- // 6. Append message + in-tx dedup Mark — the durable transition point.
- // The media budget is persisted only when the message actually carries
- // media: a plain text message must never wait behind the media semaphore
- // or fall back to the 45s deadline after a crash. It is a relative
- // duration — the append transaction anchors it to the DB clock, the same
- // clock every now()-based reader uses.
+
mediaPendingSeconds := 0.0
- // AppendMessage must classify this exact CommandText again when it marks the
- // durable message as a channel command. Platform binders must preserve the
- // source carried in AppendParams.Message; changing it would let the media
- // decision here disagree with the terminal outcome after the append.
- parsedCommand, _ := ParseIssueCommand(msg.CommandText)
+ var parsedCommand *IssueCommand
+ if !startChat {
+ parsedCommand, _ = ParseIssueCommand(msg.CommandText)
+ }
issueNeedsUsage := parsedCommand != nil && parsedCommand.Title == ""
hasMedia := set.Media != nil && set.Media.HasMedia(msg)
resolveMedia := !issueNeedsUsage && hasMedia
- // The local monotonic budget starts BEFORE the append: the DB anchors its
- // fallback at now() during the insert, so a post-commit local start would
- // end Δ(append latency) AFTER the durable deadline — a window where the
- // task is already claimable while the resolver still runs, handing the
- // agent a placeholder that binds moments later. Starting here keeps the
- // ordering local-gives-up ≤ durable-fallback-fires.
localMediaDeadline := time.Now().Add(r.mediaTimeout)
if resolveMedia {
mediaPendingSeconds = r.mediaTimeout.Seconds()
}
- appendRes, err := set.Session.AppendMessage(ctx, AppendParams{
- SessionID: sessionID,
- Sender: identity.UserID,
- InstallationID: inst.ID,
- Message: msg,
- ClaimToken: claimToken,
- MediaPendingSeconds: mediaPendingSeconds,
- })
- if err != nil {
- if errors.Is(err, ErrClaimLost) {
- return Result{}, finalizeNone, err
+
+ var sessionID pgtype.UUID
+ var appendRes AppendResult
+ var started StartSessionResult
+ var startedTask db.AgentTaskQueue
+ startTaskCommitted := false
+ routeChangeRetries := 0
+ for {
+ if ctxErr := ctx.Err(); ctxErr != nil {
+ return Result{}, finalizeRelease, ctxErr
+ }
+
+ if startChat {
+ startedTask = db.AgentTaskQueue{}
+ persistMessage := msg.CommandText != "" || hasMedia
+ var beforeCommit func(context.Context, pgx.Tx, db.ChatSession) error
+ if persistMessage && !msg.SkipAgentRun {
+ prepared, prepareErr := r.tasks.PrepareChatTaskEnqueue(ctx, inst.AgentID, identity.UserID)
+ if prepareErr != nil {
+ return Result{}, finalizeRelease, fmt.Errorf("prepare started chat task: %w", prepareErr)
+ }
+ beforeCommit = func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {
+ var enqueueErr error
+ startedTask, enqueueErr = r.tasks.EnqueuePreparedChannelChatTaskInTx(
+ ctx, tx, session, identity.UserID, false, 1, prepared,
+ )
+ return enqueueErr
+ }
+ }
+ started, err = set.Session.StartSession(ctx, StartSessionParams{
+ Installation: inst, Creator: sessionCreator, Sender: identity.UserID, Message: msg,
+ ClaimToken: claimToken, MediaPendingSeconds: mediaPendingSeconds,
+ PersistMessage: persistMessage, BeforeCommit: beforeCommit,
+ })
+ sessionID, appendRes = started.SessionID, started.Append
+ } else {
+ sessionID, err = set.Session.EnsureSession(ctx, EnsureSessionParams{
+ Installation: inst,
+ Sender: sessionCreator,
+ Message: msg,
+ })
+ }
+
+ if errors.Is(err, ErrRouteChanged) {
+ routeChangeRetries++
+ r.logger.Info("channel route changed; retrying inbound",
+ "outcome", "chat_route_retry", "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID, "attempt", routeChangeRetries,
+ )
+ if routeChangeRetries >= maxRouteChangeRetries {
+ return Result{}, finalizeRelease, fmt.Errorf(
+ "channel route did not stabilize after %d retries: %w",
+ maxRouteChangeRetries, ErrRouteChanged,
+ )
+ }
+ continue
+ }
+ if err != nil {
+ if errors.Is(err, ErrClaimLost) {
+ return Result{}, finalizeNone, err
+ }
+ return Result{}, finalizeRelease, fmt.Errorf("persist channel chat message: %w", err)
+ }
+
+ if startChat {
+ if startedTask.ID.Valid {
+ r.tasks.FinalizeChatTaskEnqueue(ctx, startedTask)
+ startTaskCommitted = true
+ }
+ r.notifyChatStarted(inst, sessionCreator, msg.Source.ChannelType, started)
+ if msg.CommandText == "" && !hasMedia {
+ finalize := finalizeMark
+ if appendRes.DedupMarked {
+ finalize = finalizeNone
+ }
+ return Result{
+ Outcome: OutcomeChatStarted, InstallationID: inst.ID,
+ ChatSessionID: sessionID, ChannelBindingID: started.BindingID,
+ ChannelRouteRevision: started.RouteRevision, Sender: msg.Source.SenderID,
+ }, finalize, nil
+ }
+ break
}
- return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
+
+ if bareFresh {
+ err = set.Session.MarkPendingFresh(ctx, sessionID, msg.MessageID)
+ if errors.Is(err, ErrRouteChanged) {
+ routeChangeRetries++
+ if routeChangeRetries >= maxRouteChangeRetries {
+ return Result{}, finalizeRelease, fmt.Errorf(
+ "channel route did not stabilize after %d retries: %w",
+ maxRouteChangeRetries, ErrRouteChanged,
+ )
+ }
+ continue
+ }
+ if err != nil {
+ return Result{}, finalizeRelease, fmt.Errorf("persist fresh command: %w", err)
+ }
+ return Result{
+ Outcome: OutcomeFreshPending,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ Sender: msg.Source.SenderID,
+ }, finalizeMark, nil
+ }
+
+ appendRes, err = set.Session.AppendMessage(ctx, AppendParams{
+ SessionID: sessionID,
+ Sender: identity.UserID,
+ InstallationID: inst.ID,
+ Message: msg,
+ ClaimToken: claimToken,
+ MediaPendingSeconds: mediaPendingSeconds,
+ })
+ if errors.Is(err, ErrRouteChanged) {
+ routeChangeRetries++
+ r.logger.Info("channel route changed; retrying inbound",
+ "outcome", "chat_route_retry", "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID, "attempt", routeChangeRetries,
+ )
+ if routeChangeRetries >= maxRouteChangeRetries {
+ return Result{}, finalizeRelease, fmt.Errorf(
+ "channel route did not stabilize after %d retries: %w",
+ maxRouteChangeRetries, ErrRouteChanged,
+ )
+ }
+ continue
+ }
+ if err != nil {
+ if errors.Is(err, ErrClaimLost) {
+ return Result{}, finalizeNone, err
+ }
+ return Result{}, finalizeRelease, fmt.Errorf("append user message: %w", err)
+ }
+ break
}
// Post-append paths must NOT Release (chat_message + Mark already
@@ -409,10 +524,16 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
}
res := Result{
- Outcome: OutcomeIngested,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- Sender: msg.Source.SenderID,
+ Outcome: OutcomeIngested,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ ChannelBindingID: appendRes.BindingID,
+ ChannelRouteRevision: appendRes.RouteRevision,
+ Sender: msg.Source.SenderID,
+ }
+ if startChat {
+ res.ChannelBindingID = started.BindingID
+ res.ChannelRouteRevision = started.RouteRevision
}
var mediaIssue db.Issue
var deferredIssueTaskID pgtype.UUID
@@ -501,11 +622,9 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// just quote the slash command back. The chat_message is still durable
// and the OutboundReplier still fires — only the debounced run trigger
// (and therefore the typing indicator) is suppressed.
- if !msg.SkipAgentRun {
+ if !msg.SkipAgentRun && !startTaskCommitted {
pendingContexts := appendRes.PendingContexts
if len(pendingContexts) == 0 {
- // Test and third-party SessionBinder implementations created before the
- // crash-recovery field still schedule the appended generation normally.
pendingContexts = []PendingContext{{
Revision: appendRes.ContextRevision, InitiatorUserID: identity.UserID,
}}
@@ -514,9 +633,15 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
revision := pending.Revision
forceFresh := revision == appendRes.ContextRevision && msg.ForceFresh
if revision == appendRes.ContextRevision {
- r.scheduleRunWithFresh(set, inst, msg, sessionID, identity.UserID, forceFresh, revision)
+ r.scheduleRunWithFresh(
+ set, inst, msg, sessionID, identity.UserID,
+ res.ChannelBindingID, res.ChannelRouteRevision, forceFresh, revision,
+ )
} else if pending.InitiatorUserID.Valid {
- r.scheduleRecoveredRun(set, inst, msg, sessionID, pending.InitiatorUserID, revision)
+ r.scheduleRecoveredRun(
+ set, inst, msg, sessionID, pending.InitiatorUserID,
+ res.ChannelBindingID, res.ChannelRouteRevision, revision,
+ )
} else {
slog.Warn("skipping recovered channel context without initiator snapshot",
"chat_session_id", util.UUIDToString(sessionID),
@@ -524,14 +649,43 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
)
}
}
- res.runScheduled = true
}
+ res.runScheduled = !msg.SkipAgentRun && (startTaskCommitted || !startChat)
if resolveMedia {
r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, pgtype.Text{}, "", deferredIssueTaskID, localMediaDeadline)
}
+ if appendRes.BecameVisible && !startChat {
+ r.notifyChatCreated(
+ inst, sessionCreator, msg.Source.ChannelType, sessionID,
+ appendRes.RouteRevision, appendRes.InitialTitle,
+ )
+ }
+ if appendRes.InitialTitle != "" && r.lifecycle != nil {
+ if !startChat && !appendRes.BecameVisible {
+ r.lifecycle.ChannelChatTitleInitialized(inst.WorkspaceID, sessionCreator, sessionID, appendRes.InitialTitle)
+ }
+ r.lifecycle.GenerateChannelChatTitle(inst.WorkspaceID, sessionCreator, sessionID, appendRes.InitialTitle, msg.Text)
+ }
return res, postAppendFinalize, nil
}
+func (r *Router) notifyChatStarted(inst ResolvedInstallation, creatorID pgtype.UUID, channelType channel.Type, started StartSessionResult) {
+ r.notifyChatCreated(
+ inst, creatorID, channelType, started.SessionID,
+ started.RouteRevision, started.Append.InitialTitle,
+ )
+}
+
+func (r *Router) notifyChatCreated(inst ResolvedInstallation, creatorID pgtype.UUID, channelType channel.Type, sessionID pgtype.UUID, routeRevision int64, title string) {
+ if r.lifecycle != nil {
+ r.lifecycle.ChannelChatStarted(ChannelChatStartedEvent{
+ WorkspaceID: inst.WorkspaceID, CreatorID: creatorID, AgentID: inst.AgentID,
+ SessionID: sessionID, InstallationID: inst.ID,
+ ChannelType: channelType, RouteRevision: routeRevision, Title: title,
+ })
+ }
+}
+
// enqueueMedia detaches remote media I/O from Handle while preserving message
// order within a chat session. Run scheduling is independent and durable: the
// task service defers a task to the persisted media deadline, then media
@@ -650,7 +804,7 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,
"message_id", msg.MessageID,
"error", err)
}
- bindErr := set.Session.BindMedia(finalizeCtx, BindMediaParams{
+ bindRes, bindErr := set.Session.BindMedia(finalizeCtx, BindMediaParams{
MessageID: chatMessageID,
SessionID: sessionID,
WorkspaceID: inst.WorkspaceID,
@@ -661,6 +815,14 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,
Body: resolved.Text,
MediaRefs: resolved.MediaRefs,
})
+ if bindErr == nil && bindRes.InitialTitle != "" && r.lifecycle != nil {
+ creatorID := identity.UserID
+ if msg.Source.ChatType == channel.ChatTypeGroup {
+ creatorID = inst.InstallerUserID
+ }
+ r.lifecycle.ChannelChatTitleInitialized(inst.WorkspaceID, creatorID, sessionID, bindRes.InitialTitle)
+ r.lifecycle.GenerateChannelChatTitle(inst.WorkspaceID, creatorID, sessionID, bindRes.InitialTitle, bindRes.TitleSource)
+ }
if bindErr != nil {
// Never delete inline: the attachments may or may not have landed
// (an ambiguous commit), but the intent rows are deleted in the SAME
@@ -704,31 +866,62 @@ func (r *Router) finishMediaQueue(key string, done chan struct{}) {
delete(r.mediaQueues, key)
}
-// scheduleRun hands the per-session run trigger to the debouncer (or fires it
-// inline when batching is disabled).
-func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, contextRevision int64) {
- r.scheduleRunWithFresh(set, inst, msg, sessionID, initiatorUserID, msg.ForceFresh, contextRevision)
-}
-
-func (r *Router) scheduleRunWithFresh(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, fresh bool, contextRevision int64) {
- r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision, true)
+// scheduleRunWithFresh hands the per-session/context run trigger to the
+// debouncer (or fires it inline when batching is disabled).
+func (r *Router) scheduleRunWithFresh(
+ set ResolverSet,
+ inst ResolvedInstallation,
+ msg channel.InboundMessage,
+ sessionID, initiatorUserID, bindingID pgtype.UUID,
+ routeRevision int64,
+ fresh bool,
+ contextRevision int64,
+) {
+ r.scheduleRunMode(
+ set, inst, msg, sessionID, initiatorUserID, bindingID,
+ routeRevision, fresh, contextRevision, true,
+ )
}
-func (r *Router) scheduleRecoveredRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, contextRevision int64) {
- r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, false, contextRevision, false)
+func (r *Router) scheduleRecoveredRun(
+ set ResolverSet,
+ inst ResolvedInstallation,
+ msg channel.InboundMessage,
+ sessionID, initiatorUserID, bindingID pgtype.UUID,
+ routeRevision, contextRevision int64,
+) {
+ r.scheduleRunMode(
+ set, inst, msg, sessionID, initiatorUserID, bindingID,
+ routeRevision, false, contextRevision, false,
+ )
}
-func (r *Router) scheduleRunMode(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, fresh bool, contextRevision int64, replace bool) {
+func (r *Router) scheduleRunMode(
+ set ResolverSet,
+ inst ResolvedInstallation,
+ msg channel.InboundMessage,
+ sessionID, initiatorUserID, bindingID pgtype.UUID,
+ routeRevision int64,
+ fresh bool,
+ contextRevision int64,
+ replace bool,
+) {
if r.batcher == nil {
- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision)
+ r.flushChatRun(
+ set, inst, msg, sessionID, initiatorUserID, bindingID,
+ routeRevision, fresh, contextRevision,
+ )
return
}
key := keyForSessionContext(sessionID, contextRevision)
flush := func() {
// A later message in this same durable context generation may replace
- // the closure. /new advances the generation and therefore uses a distinct
+ // the closure. /clear advances the generation and therefore uses a distinct
// batch key; the pre-boundary flush remains armed independently.
- r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, fresh, contextRevision)
+ r.flushChatRun(
+ set, inst, msg, sessionID, initiatorUserID, bindingID,
+ routeRevision, fresh, contextRevision,
+ )
}
if replace {
r.batcher.Schedule(key, flush)
@@ -744,7 +937,15 @@ const chatRunFlushTimeout = 10 * time.Second
// flushChatRun is the debounced run-trigger: reload session, enqueue exactly
// one chat task for the window, and emit the offline/archived notice (only
// known here now) via the replier. Errors are logged, not returned.
-func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID, forceFresh bool, contextRevision int64) {
+func (r *Router) flushChatRun(
+ set ResolverSet,
+ inst ResolvedInstallation,
+ msg channel.InboundMessage,
+ sessionID, initiatorUserID, bindingID pgtype.UUID,
+ routeRevision int64,
+ forceFresh bool,
+ contextRevision int64,
+) {
ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)
defer cancel()
@@ -755,7 +956,9 @@ func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg ch
r.clearTyping(ctx, set, sessionID)
return
}
- if _, err := r.tasks.EnqueueChannelChatTask(ctx, session, initiatorUserID, forceFresh, contextRevision); err != nil {
+ if _, err := r.tasks.EnqueueChannelChatTask(
+ ctx, session, initiatorUserID, forceFresh, contextRevision, bindingID, routeRevision,
+ ); err != nil {
// No task was enqueued, so no task lifecycle event will ever publish and
// the platform's bus-driven typing clear can never fire. Clear the
// indicator here (before any notice) so the "processing" reaction does
@@ -763,9 +966,9 @@ func (r *Router) flushChatRun(set ResolverSet, inst ResolvedInstallation, msg ch
r.clearTyping(ctx, set, sessionID)
switch {
case errors.Is(err, service.ErrChatTaskAgentNoRuntime):
- r.emitFlushReply(ctx, set, inst, msg, sessionID, OutcomeAgentOffline)
+ r.emitFlushReply(ctx, set, inst, msg, sessionID, bindingID, routeRevision, OutcomeAgentOffline)
case errors.Is(err, service.ErrChatTaskAgentArchived):
- r.emitFlushReply(ctx, set, inst, msg, sessionID, OutcomeAgentArchived)
+ r.emitFlushReply(ctx, set, inst, msg, sessionID, bindingID, routeRevision, OutcomeAgentArchived)
default:
r.logger.Error("channel router: flush enqueue chat task failed",
"chat_session_id", uuidString(sessionID), "err", err.Error())
@@ -783,15 +986,17 @@ func (r *Router) clearTyping(ctx context.Context, set ResolverSet, sessionID pgt
}
// emitFlushReply delivers an offline/archived notice for a flushed run.
-func (r *Router) emitFlushReply(ctx context.Context, set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, outcome Outcome) {
+func (r *Router) emitFlushReply(ctx context.Context, set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, bindingID pgtype.UUID, routeRevision int64, outcome Outcome) {
if set.Replier == nil {
return
}
set.Replier.Reply(ctx, inst, msg, Result{
- Outcome: outcome,
- InstallationID: inst.ID,
- ChatSessionID: sessionID,
- Sender: msg.Source.SenderID,
+ Outcome: outcome,
+ InstallationID: inst.ID,
+ ChatSessionID: sessionID,
+ ChannelBindingID: bindingID,
+ ChannelRouteRevision: routeRevision,
+ Sender: msg.Source.SenderID,
})
}
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index ee62b15059..3f1cdfdb4b 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -10,6 +10,7 @@ import (
"testing"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -96,15 +97,42 @@ type fakeBinder struct {
pendingFresh int
pendingErr error
ensureHook func()
+ ensureCalls int
+ startCalls int
+ lastStart StartSessionParams
+ startErr error
+ startErrs []error
}
func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {
+ f.ensureCalls++
f.lastEnsure = p
if f.ensureHook != nil {
f.ensureHook()
}
return f.ensureID, f.ensureErr
}
+func (f *fakeBinder) StartSession(ctx context.Context, p StartSessionParams) (StartSessionResult, error) {
+ f.mu.Lock()
+ f.startCalls++
+ f.lastStart = p
+ f.lastAppend = AppendParams{
+ InstallationID: p.Installation.ID, SessionID: f.ensureID,
+ Sender: p.Sender, Message: p.Message, ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ }
+ res, err := f.appendResult, f.startErr
+ if len(f.startErrs) >= f.startCalls {
+ err = f.startErrs[f.startCalls-1]
+ }
+ f.mu.Unlock()
+ if err == nil && p.BeforeCommit != nil {
+ err = p.BeforeCommit(ctx, nil, db.ChatSession{ID: f.ensureID})
+ }
+ return StartSessionResult{
+ SessionID: f.ensureID, BindingID: uid(80), RouteRevision: 2, Append: res,
+ }, err
+}
func (f *fakeBinder) MarkPendingFresh(_ context.Context, _ pgtype.UUID, _ string) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -129,11 +157,11 @@ func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendRes
}
return res, err
}
-func (f *fakeBinder) BindMedia(_ context.Context, p BindMediaParams) error {
+func (f *fakeBinder) BindMedia(_ context.Context, p BindMediaParams) (BindMediaResult, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.lastBind = p
- return f.bindErr
+ return BindMediaResult{}, f.bindErr
}
func (f *fakeBinder) boundMedia() BindMediaParams {
f.mu.Lock()
@@ -303,7 +331,11 @@ type fakeTasks struct {
initiator pgtype.UUID
initiators []pgtype.UUID
contextRevisions []int64
+ bindingIDs []pgtype.UUID
+ routeRevisions []int64
err error
+ prepared bool
+ prepareErr error
}
func (f *fakeTasks) PromoteChannelChatTasksIfMediaReady(_ context.Context, _ pgtype.UUID) error {
@@ -320,7 +352,7 @@ func (f *fakeTasks) PromoteDeferredChannelIssueTask(_ context.Context, taskID pg
return nil
}
-func (f *fakeTasks) EnqueueChannelChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64) (db.AgentTaskQueue, error) {
+func (f *fakeTasks) EnqueueChannelChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64, bindingID pgtype.UUID, routeRevision int64) (db.AgentTaskQueue, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.called = true
@@ -330,7 +362,25 @@ func (f *fakeTasks) EnqueueChannelChatTask(_ context.Context, _ db.ChatSession,
f.initiator = initiator
f.initiators = append(f.initiators, initiator)
f.contextRevisions = append(f.contextRevisions, contextRevision)
- return db.AgentTaskQueue{}, f.err
+ f.bindingIDs = append(f.bindingIDs, bindingID)
+ f.routeRevisions = append(f.routeRevisions, routeRevision)
+ return db.AgentTaskQueue{ID: uid(81)}, f.err
+}
+func (f *fakeTasks) PrepareChatTaskEnqueue(context.Context, pgtype.UUID, pgtype.UUID) (service.PreparedChatTaskEnqueue, error) {
+ f.mu.Lock()
+ f.prepared = true
+ err := f.prepareErr
+ f.mu.Unlock()
+ return service.PreparedChatTaskEnqueue{}, err
+}
+func (f *fakeTasks) EnqueuePreparedChannelChatTaskInTx(ctx context.Context, _ pgx.Tx, session db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64, _ service.PreparedChatTaskEnqueue) (db.AgentTaskQueue, error) {
+ return f.EnqueueChannelChatTask(ctx, session, initiator, forceFresh, contextRevision, pgtype.UUID{}, 0)
+}
+func (f *fakeTasks) FinalizeChatTaskEnqueue(context.Context, db.AgentTaskQueue) {}
+func (f *fakeTasks) wasPrepared() bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.prepared
}
func (f *fakeTasks) wasCalled() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.called }
func (f *fakeTasks) freshArg() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.forceFresh }
@@ -361,12 +411,33 @@ func (f *fakeTasks) initiatorArgs() []pgtype.UUID {
return append([]pgtype.UUID(nil), f.initiators...)
}
+func (f *fakeTasks) routeArgs() ([]pgtype.UUID, []int64) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]pgtype.UUID(nil), f.bindingIDs...), append([]int64(nil), f.routeRevisions...)
+}
+
type fakeReader struct {
session db.ChatSession
ws db.Workspace
sessErr error
}
+type fakeChannelChatLifecycle struct {
+ mu sync.Mutex
+ started []ChannelChatStartedEvent
+}
+
+func (f *fakeChannelChatLifecycle) ChannelChatStarted(event ChannelChatStartedEvent) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.started = append(f.started, event)
+}
+func (*fakeChannelChatLifecycle) ChannelChatTitleInitialized(pgtype.UUID, pgtype.UUID, pgtype.UUID, string) {
+}
+func (*fakeChannelChatLifecycle) GenerateChannelChatTitle(pgtype.UUID, pgtype.UUID, pgtype.UUID, string, string) {
+}
+
func (f *fakeReader) GetChatSession(_ context.Context, _ pgtype.UUID) (db.ChatSession, error) {
return f.session, f.sessErr
}
@@ -402,18 +473,19 @@ func p2pMessage(t *testing.T) channel.InboundMessage {
}
type harness struct {
- router *Router
- inst *fakeInstaller
- ident *fakeIdentity
- dedup *fakeDedup
- binder *fakeBinder
- audit *fakeAuditor
- replier *fakeReplier
- typing *fakeTyping
- media *fakeMedia
- issues *fakeIssues
- tasks *fakeTasks
- reader *fakeReader
+ router *Router
+ inst *fakeInstaller
+ ident *fakeIdentity
+ dedup *fakeDedup
+ binder *fakeBinder
+ audit *fakeAuditor
+ replier *fakeReplier
+ typing *fakeTyping
+ media *fakeMedia
+ issues *fakeIssues
+ tasks *fakeTasks
+ reader *fakeReader
+ lifecycle *fakeChannelChatLifecycle
}
func newHarness(t *testing.T) *harness {
@@ -425,19 +497,22 @@ func newHarness(t *testing.T) *harness {
binder: &fakeBinder{
ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"),
appendResult: AppendResult{
- MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),
- DedupMarked: true,
+ MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),
+ BindingID: uid(80),
+ RouteRevision: 2,
+ DedupMarked: true,
},
},
- audit: &fakeAuditor{},
- replier: &fakeReplier{},
- typing: &fakeTyping{},
- media: &fakeMedia{},
- issues: &fakeIssues{},
- tasks: &fakeTasks{},
- reader: &fakeReader{ws: db.Workspace{IssuePrefix: "MUL"}},
- }
- h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{Logger: discardLogger()})
+ audit: &fakeAuditor{},
+ replier: &fakeReplier{},
+ typing: &fakeTyping{},
+ media: &fakeMedia{},
+ issues: &fakeIssues{},
+ tasks: &fakeTasks{},
+ reader: &fakeReader{ws: db.Workspace{IssuePrefix: "MUL"}},
+ lifecycle: &fakeChannelChatLifecycle{},
+ }
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{Logger: discardLogger(), Lifecycle: h.lifecycle})
h.router.Register(channel.TypeFeishu, ResolverSet{
Installation: h.inst,
Identity: h.ident,
@@ -852,8 +927,8 @@ func TestRouter_ContextGenerationsUseIndependentBatchWindows(t *testing.T) {
sessionID := h.binder.ensureID
initiator := h.ident.id.UserID
- h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, 1)
- h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, 2)
+ h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 1)
+ h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 2)
if got := h.router.batcher.pendingCount(); got != 2 {
t.Fatalf("pending generation windows = %d, want 2", got)
}
@@ -934,8 +1009,8 @@ func TestRouter_RecoveryDoesNotDelayLiveOlderGeneration(t *testing.T) {
timers := &fakeTimerFactory{}
h.router.batcher = newTestBatcher(timers)
msg := p2pMessage(t)
- h.router.scheduleRun(h.router.sets[channel.TypeFeishu], h.inst.inst, msg,
- h.binder.ensureID, h.ident.id.UserID, 1)
+ h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg,
+ h.binder.ensureID, h.ident.id.UserID, pgtype.UUID{}, 1, false, 1)
h.binder.appendResult.ContextRevision = 2
h.binder.appendResult.PendingContexts = []PendingContext{
@@ -1493,6 +1568,29 @@ func TestRouter_FlushSuccess_DoesNotClearTyping(t *testing.T) {
if h.typing.settledCalls() != 0 {
t.Fatalf("successful flush must not clear the typing indicator, got %d OnSettled calls", h.typing.settledCalls())
}
+ bindingIDs, routeRevisions := h.tasks.routeArgs()
+ if len(bindingIDs) != 1 || bindingIDs[0] != uid(80) || len(routeRevisions) != 1 || routeRevisions[0] != 2 {
+ t.Fatalf("flush route proof = %+v/%v, want binding 80 revision 2", bindingIDs, routeRevisions)
+ }
+}
+
+func TestRouter_ImplicitFirstTurnPublishesSessionCreated(t *testing.T) {
+ h := newHarness(t)
+ h.binder.appendResult.BecameVisible = true
+ h.binder.appendResult.InitialTitle = "hello"
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ h.lifecycle.mu.Lock()
+ defer h.lifecycle.mu.Unlock()
+ if len(h.lifecycle.started) != 1 {
+ t.Fatalf("created events = %d, want 1", len(h.lifecycle.started))
+ }
+ event := h.lifecycle.started[0]
+ if event.SessionID != h.binder.ensureID || event.RouteRevision != h.binder.appendResult.RouteRevision || event.Title != "hello" {
+ t.Fatalf("created event = %+v", event)
+ }
}
func TestRouter_ForceFresh_Propagates(t *testing.T) {
@@ -1507,11 +1605,11 @@ func TestRouter_ForceFresh_Propagates(t *testing.T) {
}
}
-func TestRouter_NewCommand_ForcesFreshAndStripsDirective(t *testing.T) {
+func TestRouter_ClearCommand_ForcesFreshAndStripsDirective(t *testing.T) {
h := newHarness(t)
msg := p2pMessage(t)
msg.Source.ChannelType = channel.Type("test-channel")
- msg.Text = "/new answer with the current model"
+ msg.Text = "/clear answer with the current model"
h.router.Register(msg.Source.ChannelType, ResolverSet{
Installation: h.inst,
Identity: h.ident,
@@ -1525,17 +1623,183 @@ func TestRouter_NewCommand_ForcesFreshAndStripsDirective(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
if !h.tasks.freshArg() {
- t.Fatal("/new must enqueue a fresh provider session")
+ t.Fatal("/clear must enqueue a fresh provider session")
}
if got := h.binder.lastAppend.Message.Text; got != "answer with the current model" {
t.Fatalf("appended text=%q, want command stripped", got)
}
- if got := h.binder.lastAppend.Message.CommandText; got != "/new answer with the current model" {
+ if got := h.binder.lastAppend.Message.CommandText; got != "/clear answer with the current model" {
t.Fatalf("command text=%q, want original user text", got)
}
}
-func TestRouter_NewCommandDoesNotReparseStrippedBodyAsIssue(t *testing.T) {
+func TestRouter_BareNewStartsExplicitSessionWithoutEmptyTurn(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ msg := p2pMessage(t)
+ msg.Text = "/new"
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.startCalls != 1 || h.binder.lastStart.PersistMessage {
+ t.Fatalf("start calls=%d persist=%v", h.binder.startCalls, h.binder.lastStart.PersistMessage)
+ }
+ if h.tasks.wasCalled() || h.typing.calls() != 0 {
+ t.Fatal("bare /new must not enqueue a task or start typing")
+ }
+ if len(h.lifecycle.started) != 1 || h.lifecycle.started[0].SessionID != h.binder.ensureID {
+ t.Fatalf("chat-start lifecycle events=%+v", h.lifecycle.started)
+ }
+}
+
+func TestRouter_NewBodyIsFirstOrdinaryTurnAndEnqueuedAtomically(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ msg := p2pMessage(t)
+ msg.Text = "/new /issue investigate deploy"
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.startCalls != 1 || !h.binder.lastStart.PersistMessage {
+ t.Fatalf("start calls=%d persist=%v", h.binder.startCalls, h.binder.lastStart.PersistMessage)
+ }
+ if got := h.binder.lastStart.Message.Text; got != "/issue investigate deploy" {
+ t.Fatalf("first turn=%q", got)
+ }
+ if h.issues.called {
+ t.Fatal("/new body must not be reparsed as an /issue command")
+ }
+ if !h.tasks.wasPrepared() || !h.tasks.wasCalled() || h.tasks.calls() != 1 {
+ t.Fatalf("prepared=%v calls=%d", h.tasks.wasPrepared(), h.tasks.calls())
+ }
+ if h.binder.lastStart.BeforeCommit == nil {
+ t.Fatal("/new task enqueue was not attached to the route-creation transaction")
+ }
+}
+
+func TestRouter_PreNormalizedMediaNewStartsSessionWithoutPersistingDirective(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.Type = channel.MsgTypeImage
+ msg.Text = "[Image]\n点评一下"
+ msg.CommandText = "/new\n点评一下"
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.startCalls != 1 || !h.binder.lastStart.PersistMessage {
+ t.Fatalf("start calls=%d persist=%v", h.binder.startCalls, h.binder.lastStart.PersistMessage)
+ }
+ if got := h.binder.lastStart.Message.Text; got != "[Image]\n点评一下" {
+ t.Fatalf("first turn=%q, want normalized rich-media body", got)
+ }
+ if got := h.binder.lastStart.Message.CommandText; got != "点评一下" {
+ t.Fatalf("command source=%q, want consumed /new body", got)
+ }
+}
+
+func TestRouter_PreNormalizedMediaBeforeBareNewStartsSession(t *testing.T) {
+ h := newHarness(t)
+ msg := p2pMessage(t)
+ msg.Type = channel.MsgTypeImage
+ msg.Text = "[Image]"
+ msg.CommandText = "/new"
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.startCalls != 1 || !h.binder.lastStart.PersistMessage {
+ t.Fatalf("start calls=%d persist=%v, want media turn in a new Chat", h.binder.startCalls, h.binder.lastStart.PersistMessage)
+ }
+ if got := h.binder.lastStart.Message.Text; got != "[Image]" {
+ t.Fatalf("first turn=%q, want image without the consumed directive", got)
+ }
+ if got := h.binder.lastStart.Message.CommandText; got != "" {
+ t.Fatalf("command source=%q, want consumed bare /new", got)
+ }
+}
+
+func TestRouter_GroupChatKeepsInstallerAsCreatorAndSenderAsInitiator(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ msg := p2pMessage(t)
+ msg.Source.ChatType = channel.ChatTypeGroup
+ msg.AddressedToBot = true
+ msg.Text = "/new start a group topic"
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.lastStart.Creator != h.inst.inst.InstallerUserID {
+ t.Fatalf("group Chat creator=%v, want installer %v", h.binder.lastStart.Creator, h.inst.inst.InstallerUserID)
+ }
+ if h.binder.lastStart.Sender != h.ident.id.UserID {
+ t.Fatalf("group Chat initiator=%v, want sender %v", h.binder.lastStart.Sender, h.ident.id.UserID)
+ }
+}
+
+func TestRouter_ChatTaskPreparationFailureDoesNotStartSession(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ h.tasks.prepareErr = service.ErrChatTaskAgentNoRuntime
+ msg := p2pMessage(t)
+ msg.Text = "/new prepare outside transaction"
+ err := h.router.Handle(context.Background(), msg)
+ if !errors.Is(err, service.ErrChatTaskAgentNoRuntime) {
+ t.Fatalf("Handle error=%v, want no-runtime rejection", err)
+ }
+ if !h.tasks.wasPrepared() || h.tasks.wasCalled() {
+ t.Fatalf("prepared=%v enqueue=%v", h.tasks.wasPrepared(), h.tasks.wasCalled())
+ }
+ if h.binder.startCalls != 0 {
+ t.Fatalf("StartSession calls=%d, want 0", h.binder.startCalls)
+ }
+}
+
+func TestRouter_ChatStartRetriesOneRouteConflictWithoutDuplicateTask(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ h.binder.startErrs = []error{ErrRouteChanged, nil}
+ msg := p2pMessage(t)
+ msg.Text = "/new retry this turn"
+
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.binder.startCalls != 2 {
+ t.Fatalf("StartSession calls = %d, want one retry", h.binder.startCalls)
+ }
+ if h.tasks.calls() != 1 {
+ t.Fatalf("task enqueue calls = %d, want only the committed attempt", h.tasks.calls())
+ }
+ if len(h.lifecycle.started) != 1 {
+ t.Fatalf("chat-start lifecycle events = %d, want one", len(h.lifecycle.started))
+ }
+}
+
+func TestRouter_ChatStartCapsPersistentRouteConflictsAndReleasesClaim(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+ h.binder.startErr = ErrRouteChanged
+ msg := p2pMessage(t)
+ msg.Text = "/new cannot stabilize"
+
+ err := h.router.Handle(context.Background(), msg)
+ if !errors.Is(err, ErrRouteChanged) {
+ t.Fatalf("Handle error = %v, want route conflict", err)
+ }
+ if h.binder.startCalls != maxRouteChangeRetries {
+ t.Fatalf("StartSession calls = %d, want cap %d", h.binder.startCalls, maxRouteChangeRetries)
+ }
+ if h.tasks.calls() != 0 || len(h.lifecycle.started) != 0 {
+ t.Fatalf("failed route wrote side effects: tasks=%d lifecycle=%d", h.tasks.calls(), len(h.lifecycle.started))
+ }
+ if h.dedup.releases() != 1 || h.dedup.marks() != 0 {
+ t.Fatalf("dedup finalize = releases:%d marks:%d, want 1/0", h.dedup.releases(), h.dedup.marks())
+ }
+}
+
+func TestRouter_ClearCommandDoesNotReparseStrippedBodyAsIssue(t *testing.T) {
tests := []struct {
name string
channelType channel.Type
@@ -1546,27 +1810,27 @@ func TestRouter_NewCommandDoesNotReparseStrippedBodyAsIssue(t *testing.T) {
{
name: "Slack same line",
channelType: channel.Type("slack"),
- text: "/new /issue investigate deploy",
- commandText: "/new /issue investigate deploy",
+ text: "/clear /issue investigate deploy",
+ commandText: "/clear /issue investigate deploy",
},
{
name: "Slack next line",
channelType: channel.Type("slack"),
- text: "/new\n/issue investigate deploy",
- commandText: "/new\n/issue investigate deploy",
+ text: "/clear\n/issue investigate deploy",
+ commandText: "/clear\n/issue investigate deploy",
},
{
name: "Feishu same line",
channelType: channel.TypeFeishu,
text: "/issue investigate deploy",
- commandText: "/new /issue investigate deploy",
+ commandText: "/clear /issue investigate deploy",
forceFresh: true,
},
{
name: "Feishu next line",
channelType: channel.TypeFeishu,
text: "/issue investigate deploy",
- commandText: "/new\n/issue investigate deploy",
+ commandText: "/clear\n/issue investigate deploy",
forceFresh: true,
},
}
@@ -1595,10 +1859,10 @@ func TestRouter_NewCommandDoesNotReparseStrippedBodyAsIssue(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
if h.issues.called {
- t.Fatal("/new must not be re-parsed as /issue after its directive is stripped")
+ t.Fatal("/clear must not be re-parsed as /issue after its directive is stripped")
}
if !h.binder.lastAppend.Message.ForceFresh {
- t.Fatal("/new must still request a fresh provider session")
+ t.Fatal("/clear must still request a fresh provider session")
}
})
}
@@ -1608,8 +1872,8 @@ func TestRouter_AdapterFreshBodyIsNotParsedAgain(t *testing.T) {
h := newHarness(t)
msg := p2pMessage(t)
msg.ForceFresh = true
- msg.Text = "<recent_context>\n/new from history\n</recent_context>\n\ncurrent prompt"
- msg.CommandText = "/new current prompt"
+ msg.Text = "<recent_context>\n/clear from history\n</recent_context>\n\ncurrent prompt"
+ msg.CommandText = "/clear current prompt"
if err := h.router.Handle(context.Background(), msg); err != nil {
t.Fatalf("unexpected error: %v", err)
@@ -1624,7 +1888,7 @@ func TestRouter_BareFreshPersistsIntentAndRepliesWithoutEmptyTurn(t *testing.T)
h.media.noMedia = true
reset := p2pMessage(t)
- reset.Text = "/new"
+ reset.Text = "/clear"
if err := h.router.Handle(context.Background(), reset); err != nil {
t.Fatalf("bare fresh Handle: %v", err)
}
@@ -1657,7 +1921,7 @@ func TestRouter_AdapterBareFreshUsesOriginalCommandText(t *testing.T) {
reset := p2pMessage(t)
reset.Text = "<recent_context>old topic</recent_context>"
- reset.CommandText = "/new"
+ reset.CommandText = "/clear"
reset.ForceFresh = true
if err := h.router.Handle(context.Background(), reset); err != nil {
t.Fatalf("bare fresh Handle: %v", err)
@@ -1679,7 +1943,7 @@ func TestRouter_BareFreshPersistenceFailureDoesNotAcknowledge(t *testing.T) {
h.binder.pendingErr = errors.New("database unavailable")
reset := p2pMessage(t)
- reset.Text = "/new"
+ reset.Text = "/clear"
if err := h.router.Handle(context.Background(), reset); err == nil {
t.Fatal("bare fresh must fail when its durable intent cannot be stored")
}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 0e61c9fe2d..c997115b25 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -47,7 +47,17 @@ type SessionQueries interface {
LockWorkspaceForChatSessionCreate(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ CreateChannelChatSessionBindingGeneration(ctx context.Context, arg db.CreateChannelChatSessionBindingGenerationParams) (db.ChannelChatSessionBinding, error)
+ LockCurrentChannelChatSessionBinding(ctx context.Context, arg db.LockCurrentChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
+ LockCurrentChannelChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (db.ChannelChatSessionBinding, error)
+ RetireChannelChatSessionBinding(ctx context.Context, arg db.RetireChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)
LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error)
+ GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
+ ChatSessionHasPublicUserMessage(ctx context.Context, id pgtype.UUID) (bool, error)
+ MarkChatSessionExplicitlyCreated(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
+ InitializeChatSessionTitle(ctx context.Context, arg db.InitializeChatSessionTitleParams) (db.ChatSession, error)
+ ReplaceImplicitChatSessionTitle(ctx context.Context, arg db.ReplaceImplicitChatSessionTitleParams) (db.ChatSession, error)
+ InitializeChatSessionMediaTitle(ctx context.Context, arg db.InitializeChatSessionMediaTitleParams) (db.ChatSession, error)
CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
ListUnownedChannelChatContextRevisions(ctx context.Context, chatSessionID pgtype.UUID) ([]PendingContext, error)
ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error
@@ -60,7 +70,6 @@ type SessionQueries interface {
TouchChatSession(ctx context.Context, id pgtype.UUID) error
LockChannelChatSessionBindingForContext(ctx context.Context, chatSessionID pgtype.UUID) (db.ChannelChatSessionBinding, error)
LockChannelChatContextGenerationByRevision(ctx context.Context, arg db.LockChannelChatContextGenerationByRevisionParams) (db.ChannelChatContextGeneration, error)
- EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error
AdvanceChannelChatContextGeneration(ctx context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error)
ResolveChannelChatContextHistoryStart(ctx context.Context, arg db.ResolveChannelChatContextHistoryStartParams) error
SetChannelChatContextInitiator(ctx context.Context, arg db.SetChannelChatContextInitiatorParams) (pgtype.UUID, error)
@@ -94,9 +103,48 @@ func (a dbSessionQueries) CreateChannelChatSessionBinding(ctx context.Context, a
CreatedAt: row.CreatedAt, PendingFresh: row.PendingFresh, ContextRevision: row.ContextRevision,
}, err
}
+func (a dbSessionQueries) CreateChannelChatSessionBindingGeneration(ctx context.Context, arg db.CreateChannelChatSessionBindingGenerationParams) (db.ChannelChatSessionBinding, error) {
+ row, err := a.q.CreateChannelChatSessionBindingGeneration(ctx, arg)
+ return db.ChannelChatSessionBinding{
+ ID: row.ID, ChatSessionID: row.ChatSessionID, InstallationID: row.InstallationID,
+ ChannelType: row.ChannelType, ChannelChatID: row.ChannelChatID, ChatType: row.ChatType,
+ LastMessageID: row.LastMessageID, LastThreadID: row.LastThreadID, Config: row.Config,
+ CreatedAt: row.CreatedAt, PendingFresh: row.PendingFresh, ContextRevision: row.ContextRevision,
+ RouteRevision: row.RouteRevision, RetiredAt: row.RetiredAt,
+ HistoryStartMessageID: row.HistoryStartMessageID, HistoryEndMessageID: row.HistoryEndMessageID,
+ HistoryBoundaryPending: row.HistoryBoundaryPending,
+ }, err
+}
+func (a dbSessionQueries) LockCurrentChannelChatSessionBinding(ctx context.Context, arg db.LockCurrentChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ return a.q.LockCurrentChannelChatSessionBinding(ctx, arg)
+}
+func (a dbSessionQueries) LockCurrentChannelChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (db.ChannelChatSessionBinding, error) {
+ return a.q.LockCurrentChannelChatSessionBindingBySession(ctx, chatSessionID)
+}
+func (a dbSessionQueries) RetireChannelChatSessionBinding(ctx context.Context, arg db.RetireChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ return a.q.RetireChannelChatSessionBinding(ctx, arg)
+}
func (a dbSessionQueries) LockChatSessionForAppend(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
return a.q.LockChatSessionForAppend(ctx, id)
}
+func (a dbSessionQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {
+ return a.q.GetChatSession(ctx, id)
+}
+func (a dbSessionQueries) ChatSessionHasPublicUserMessage(ctx context.Context, id pgtype.UUID) (bool, error) {
+ return a.q.ChatSessionHasPublicUserMessage(ctx, id)
+}
+func (a dbSessionQueries) MarkChatSessionExplicitlyCreated(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {
+ return a.q.MarkChatSessionExplicitlyCreated(ctx, id)
+}
+func (a dbSessionQueries) InitializeChatSessionTitle(ctx context.Context, arg db.InitializeChatSessionTitleParams) (db.ChatSession, error) {
+ return a.q.InitializeChatSessionTitle(ctx, arg)
+}
+func (a dbSessionQueries) ReplaceImplicitChatSessionTitle(ctx context.Context, arg db.ReplaceImplicitChatSessionTitleParams) (db.ChatSession, error) {
+ return a.q.ReplaceImplicitChatSessionTitle(ctx, arg)
+}
+func (a dbSessionQueries) InitializeChatSessionMediaTitle(ctx context.Context, arg db.InitializeChatSessionMediaTitleParams) (db.ChatSession, error) {
+ return a.q.InitializeChatSessionMediaTitle(ctx, arg)
+}
func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
return a.q.CreateChatMessage(ctx, arg)
}
@@ -145,9 +193,6 @@ func (a dbSessionQueries) LockChannelChatSessionBindingForContext(ctx context.Co
func (a dbSessionQueries) LockChannelChatContextGenerationByRevision(ctx context.Context, arg db.LockChannelChatContextGenerationByRevisionParams) (db.ChannelChatContextGeneration, error) {
return a.q.LockChannelChatContextGenerationByRevision(ctx, arg)
}
-func (a dbSessionQueries) EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error {
- return a.q.EnsureChannelChatContextGeneration(ctx, chatSessionID)
-}
func (a dbSessionQueries) AdvanceChannelChatContextGeneration(ctx context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error) {
return a.q.AdvanceChannelChatContextGeneration(ctx, arg)
}
@@ -164,9 +209,11 @@ func (a dbSessionQueries) MarkChannelInboundDedupProcessed(ctx context.Context,
return a.q.MarkChannelInboundDedupProcessed(ctx, arg)
}
-// SessionTitles are the per-platform display titles a freshly created
-// chat_session gets (the first message has not been appended yet, so the title
-// cannot be derived from content). The adapter supplies its own wording.
+// SessionTitles is retained in the constructor surface for adapter
+// compatibility. New implicit channel Chats deliberately start with an empty
+// persisted title: their first effective user message initializes the shared
+// deterministic title, and clients already render the brief empty interval as
+// a localized "New chat" fallback.
type SessionTitles struct {
Group string
Direct string
@@ -285,7 +332,7 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess
WorkspaceID: in.WorkspaceID,
AgentID: in.AgentID,
CreatorID: in.Sender,
- Title: s.titles.forType(in.ChatType),
+ Title: "",
})
if err != nil {
return pgtype.UUID{}, fmt.Errorf("create chat session: %w", err)
@@ -328,10 +375,205 @@ type AppendInput struct {
Body string
CommandText string
MessageID string
+ DedupMessageID string
ThreadID string
ClaimToken pgtype.UUID
MediaPendingSeconds float64
ForceFresh bool
+ // BeforeCommit adds work that must be atomic with this message and its
+ // context-generation change. Native slash commands use it to snapshot and
+ // enqueue the task before the message becomes visible.
+ BeforeCommit func(context.Context, pgx.Tx, db.ChatSession, int64, pgtype.UUID, int64) error
+}
+
+// StartSessionInput is the shared, transactional implementation of /new.
+// The adapter supplies only its route key/config and optional platform fence.
+type StartSessionInput struct {
+ EnsureSessionInput
+ // Initiator is the authenticated sender of the /new command. Sender in the
+ // embedded EnsureSessionInput remains the owner of the newly created Chat.
+ Initiator pgtype.UUID
+ Body string
+ MessageID string
+ DedupMessageID string
+ ThreadID string
+ ClaimToken pgtype.UUID
+ MediaPendingSeconds float64
+ PersistMessage bool
+ HistoryBoundaryPending bool
+ BeforeWrite func(context.Context, pgx.Tx) error
+ // BeforeCommit can add work that must be atomic with the route rotation and
+ // first message. The newly created session is visible through tx, but none of
+ // these writes are externally observable until StartSession commits.
+ BeforeCommit func(context.Context, pgx.Tx, db.ChatSession) error
+}
+
+// StartSession atomically retires the current route generation, creates an
+// explicitly visible Chat, installs the next generation, and optionally writes
+// the command body as its first ordinary user message.
+func (s *ChatSession) StartSession(ctx context.Context, in StartSessionInput) (StartSessionResult, error) {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return StartSessionResult{}, fmt.Errorf("begin start chat tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.q.WithTx(tx)
+ if _, err := qtx.LockWorkspaceForChatSessionCreate(ctx, in.WorkspaceID); err != nil {
+ return StartSessionResult{}, fmt.Errorf("lock workspace for start chat: %w", err)
+ }
+
+ lookup := db.GetChannelChatSessionBindingParams{InstallationID: in.InstallationID, ChannelChatID: in.BindingKey}
+ current, currentErr := qtx.GetChannelChatSessionBinding(ctx, lookup)
+ if currentErr != nil && !errors.Is(currentErr, pgx.ErrNoRows) {
+ return StartSessionResult{}, fmt.Errorf("load current chat route: %w", currentErr)
+ }
+ nextRevision := int64(1)
+ if currentErr == nil {
+ // Preserve the global chat_session -> binding lock order used by append.
+ if _, err := qtx.LockChatSessionForAppend(ctx, current.ChatSessionID); err != nil {
+ return StartSessionResult{}, fmt.Errorf("lock prior chat session: %w", err)
+ }
+ locked, err := qtx.LockCurrentChannelChatSessionBinding(ctx, db.LockCurrentChannelChatSessionBindingParams{
+ InstallationID: in.InstallationID,
+ ChannelChatID: in.BindingKey,
+ })
+ if err != nil || locked.ID != current.ID {
+ return StartSessionResult{}, ErrRouteChanged
+ }
+ if in.BeforeWrite != nil {
+ if err := in.BeforeWrite(ctx, tx); err != nil {
+ return StartSessionResult{}, err
+ }
+ }
+ historyEnd := locked.LastMessageID
+ if in.HistoryBoundaryPending && in.MessageID == "" {
+ // A native command has no public platform cursor. Keep the old end
+ // open until the next real inbound atomically closes it and opens the
+ // pending generation at the same message id.
+ historyEnd = pgtype.Text{}
+ } else if in.MessageID != "" {
+ historyEnd = textOrNull(in.MessageID)
+ }
+ if _, err := qtx.RetireChannelChatSessionBinding(ctx, db.RetireChannelChatSessionBindingParams{
+ ID: locked.ID, HistoryEndMessageID: historyEnd,
+ }); err != nil {
+ return StartSessionResult{}, fmt.Errorf("retire current chat route: %w", err)
+ }
+ nextRevision = locked.RouteRevision + 1
+ } else if in.BeforeWrite != nil {
+ if err := in.BeforeWrite(ctx, tx); err != nil {
+ return StartSessionResult{}, err
+ }
+ }
+
+ title := ""
+ if in.PersistMessage {
+ title = deriveFirstMessageTitle(in.Body, in.MediaPendingSeconds > 0)
+ }
+ session, err := qtx.CreateChatSession(ctx, db.CreateChatSessionParams{
+ ID: dbid.NewV7(), WorkspaceID: in.WorkspaceID, AgentID: in.AgentID,
+ CreatorID: in.Sender, Title: title,
+ })
+ if err != nil {
+ return StartSessionResult{}, fmt.Errorf("create started chat session: %w", err)
+ }
+ if _, err := qtx.MarkChatSessionExplicitlyCreated(ctx, session.ID); err != nil {
+ return StartSessionResult{}, fmt.Errorf("mark started chat explicit: %w", err)
+ }
+ config := in.BindingConfig
+ if len(config) == 0 {
+ config = []byte("{}")
+ }
+ startMessageID := textOrNull(in.MessageID)
+ binding, err := qtx.CreateChannelChatSessionBindingGeneration(ctx, db.CreateChannelChatSessionBindingGenerationParams{
+ ChatSessionID: session.ID, InstallationID: in.InstallationID,
+ ChannelType: string(s.channelType), ChannelChatID: in.BindingKey,
+ ChatType: string(in.ChatType), Config: config, RouteRevision: nextRevision,
+ HistoryStartMessageID: startMessageID,
+ HistoryBoundaryPending: in.HistoryBoundaryPending && in.MessageID == "",
+ })
+ if err != nil {
+ if isUniqueViolation(err) {
+ return StartSessionResult{}, ErrRouteChanged
+ }
+ return StartSessionResult{}, fmt.Errorf("create next chat route: %w", err)
+ }
+ result := StartSessionResult{SessionID: session.ID, BindingID: binding.ID, RouteRevision: binding.RouteRevision}
+ result.Append.InitialTitle = title
+ result.Append.BindingID = binding.ID
+ result.Append.RouteRevision = binding.RouteRevision
+ result.Append.ContextRevision = 1
+ if in.PersistMessage {
+ if _, err := qtx.SetChannelChatContextInitiator(ctx, db.SetChannelChatContextInitiatorParams{
+ ChatSessionID: session.ID, Revision: 1, InitiatorUserID: in.Initiator,
+ }); err != nil {
+ return StartSessionResult{}, fmt.Errorf("snapshot started chat initiator: %w", err)
+ }
+ msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ID: dbid.NewV7(), ChatSessionID: session.ID, Role: "user", Content: in.Body,
+ ChannelMediaPendingSecs: pgtype.Float8{Float64: in.MediaPendingSeconds, Valid: in.MediaPendingSeconds > 0},
+ ChannelIngested: pgtype.Bool{Bool: true, Valid: true},
+ ChannelContextRevision: pgtype.Int8{Int64: 1, Valid: true},
+ })
+ if err != nil {
+ return StartSessionResult{}, fmt.Errorf("create first chat message: %w", err)
+ }
+ if err := qtx.TouchChatSession(ctx, session.ID); err != nil {
+ return StartSessionResult{}, fmt.Errorf("touch started chat: %w", err)
+ }
+ result.Append.MessageID = msg.ID
+ result.Append.PendingContexts = []PendingContext{{Revision: 1, InitiatorUserID: in.Initiator}}
+ }
+ if in.MessageID != "" {
+ if err := qtx.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
+ ReplyChatSessionID: session.ID, LastMessageID: textOrNull(in.MessageID), LastThreadID: textOrNull(in.ThreadID),
+ }); err != nil {
+ return StartSessionResult{}, fmt.Errorf("set started chat reply target: %w", err)
+ }
+ }
+ dedupMessageID := in.DedupMessageID
+ if dedupMessageID == "" {
+ dedupMessageID = in.MessageID
+ }
+ if in.ClaimToken.Valid && dedupMessageID != "" {
+ rows, err := qtx.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: in.InstallationID, MessageID: dedupMessageID, ClaimToken: in.ClaimToken,
+ })
+ if err != nil {
+ return StartSessionResult{}, fmt.Errorf("mark start chat dedup: %w", err)
+ }
+ if rows == 0 {
+ return StartSessionResult{}, ErrClaimLost
+ }
+ result.Append.DedupMarked = true
+ }
+ if in.BeforeCommit != nil {
+ if err := in.BeforeCommit(ctx, tx, session); err != nil {
+ return StartSessionResult{}, err
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return StartSessionResult{}, fmt.Errorf("commit start chat: %w", err)
+ }
+ startOutcome := "chat_started"
+ if in.PersistMessage {
+ startOutcome = "chat_started_with_message"
+ }
+ slog.Info("channel chat route started",
+ "outcome", startOutcome,
+ "channel_type", string(s.channelType),
+ "source_chat_session_id", utilUUID(current.ChatSessionID),
+ "new_chat_session_id", utilUUID(session.ID),
+ "chat_route_generation", binding.RouteRevision,
+ )
+ return result, nil
+}
+
+func utilUUID(id pgtype.UUID) string {
+ if !id.Valid {
+ return ""
+ }
+ return uuid.UUID(id.Bytes).String()
}
// BindMediaInput links already-uploaded media to either an /issue target or a
@@ -375,19 +617,47 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
commandSource = in.Body
}
cmd, _ := ParseIssueCommand(commandSource)
-
// Context paths acquire chat_session before binding and generation. This
// also keeps the later TouchChatSession update from introducing the reverse
// binding -> chat_session edge against task enqueue.
if _, err := qtx.LockChatSessionForAppend(ctx, in.SessionID); err != nil {
return AppendResult{}, fmt.Errorf("lock chat session for append: %w", err)
}
- binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, in.SessionID)
+ binding, err := qtx.LockCurrentChannelChatSessionBindingBySession(ctx, in.SessionID)
if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return AppendResult{}, ErrRouteChanged
+ }
return AppendResult{}, fmt.Errorf("lock channel chat binding: %w", err)
}
- if err := qtx.EnsureChannelChatContextGeneration(ctx, in.SessionID); err != nil {
- return AppendResult{}, fmt.Errorf("ensure channel chat context: %w", err)
+ // The binding lock serializes ordinary appends in route order. Determine
+ // first-turn visibility and initialize its fallback title only after that
+ // fence, so two concurrent inbound messages cannot both announce creation or
+ // let the second message win the title race.
+ currentSession, err := qtx.GetChatSession(ctx, in.SessionID)
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("reload chat session for append: %w", err)
+ }
+ hadPublicUserMessage, err := qtx.ChatSessionHasPublicUserMessage(ctx, in.SessionID)
+ if err != nil {
+ return AppendResult{}, fmt.Errorf("check public chat history: %w", err)
+ }
+ becameVisible := cmd == nil && !hadPublicUserMessage && !currentSession.ExplicitlyCreatedAt.Valid
+ initializedTitle := ""
+ if cmd == nil {
+ title := deriveFirstMessageTitle(in.Body, in.MediaPendingSeconds > 0)
+ if becameVisible {
+ if _, err := qtx.ReplaceImplicitChatSessionTitle(ctx, db.ReplaceImplicitChatSessionTitleParams{ID: in.SessionID, Title: title}); err != nil {
+ return AppendResult{}, fmt.Errorf("replace implicit chat title: %w", err)
+ }
+ initializedTitle = title
+ } else if title != "" {
+ if _, err := qtx.InitializeChatSessionTitle(ctx, db.InitializeChatSessionTitleParams{ID: in.SessionID, Title: title}); err == nil {
+ initializedTitle = title
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return AppendResult{}, fmt.Errorf("initialize chat title: %w", err)
+ }
+ }
}
contextState, err := qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
ChatSessionID: in.SessionID, Revision: binding.ContextRevision,
@@ -396,10 +666,10 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
return AppendResult{}, fmt.Errorf("lock channel chat context: %w", err)
}
contextRevision := binding.ContextRevision
- if in.ForceFresh || (binding.PendingFresh && !contextState.PendingFresh) {
+ if in.ForceFresh {
advanced, err := qtx.AdvanceChannelChatContextGeneration(ctx, db.AdvanceChannelChatContextGenerationParams{
ChatSessionID: in.SessionID, CurrentRevision: contextRevision,
- HistoryBoundaryMessageID: textOrNull(in.MessageID), HasMessageBody: true,
+ HistoryBoundaryMessageID: textOrNull(in.MessageID), HasMessageBody: in.MessageID != "",
})
if err != nil {
return AppendResult{}, fmt.Errorf("advance channel chat context: %w", err)
@@ -449,19 +719,23 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
// its reply back into the originating topic.
if in.MessageID != "" {
if err := qtx.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
- ChatSessionID: in.SessionID,
- LastMessageID: textOrNull(in.MessageID),
- LastThreadID: textOrNull(in.ThreadID),
+ ReplyChatSessionID: in.SessionID,
+ LastMessageID: textOrNull(in.MessageID),
+ LastThreadID: textOrNull(in.ThreadID),
}); err != nil {
return AppendResult{}, fmt.Errorf("update reply target: %w", err)
}
}
markedInTx := false
- if in.ClaimToken.Valid && in.MessageID != "" {
+ dedupMessageID := in.DedupMessageID
+ if dedupMessageID == "" {
+ dedupMessageID = in.MessageID
+ }
+ if in.ClaimToken.Valid && dedupMessageID != "" {
rows, err := qtx.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
InstallationID: in.InstallationID,
- MessageID: in.MessageID,
+ MessageID: dedupMessageID,
ClaimToken: in.ClaimToken,
})
if err != nil {
@@ -474,6 +748,11 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
}
markedInTx = true
}
+ if in.BeforeCommit != nil {
+ if err := in.BeforeCommit(ctx, tx, currentSession, contextRevision, binding.ID, binding.RouteRevision); err != nil {
+ return AppendResult{}, err
+ }
+ }
if err := tx.Commit(ctx); err != nil {
return AppendResult{}, fmt.Errorf("commit: %w", err)
@@ -484,12 +763,31 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
DedupMarked: markedInTx,
ContextRevision: contextRevision,
PendingContexts: pendingContexts,
+ InitialTitle: initializedTitle,
+ BecameVisible: becameVisible,
+ BindingID: binding.ID,
+ RouteRevision: binding.RouteRevision,
}, nil
}
-// MarkPendingFresh persists a bare `/new` command. Non-bare `/new` messages
+// MarkPendingFresh persists a bare `/clear` command. Non-bare `/clear` messages
// mark the same flag inside AppendUserMessage's transaction instead.
func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
+ return s.MarkPendingFreshWithDedup(ctx, sessionID, messageID, pgtype.UUID{}, "", pgtype.UUID{})
+}
+
+// MarkPendingFreshWithDedup atomically advances the context generation and
+// finalizes an optional transport dedup claim. A native slash command has no
+// public platform cursor, so messageID may be empty while dedupMessageID holds
+// the durable Socket Mode envelope id.
+func (s *ChatSession) MarkPendingFreshWithDedup(
+ ctx context.Context,
+ sessionID pgtype.UUID,
+ messageID string,
+ installationID pgtype.UUID,
+ dedupMessageID string,
+ claimToken pgtype.UUID,
+) error {
tx, err := s.tx.Begin(ctx)
if err != nil {
return fmt.Errorf("begin fresh context tx: %w", err)
@@ -499,13 +797,13 @@ func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUI
if _, err := qtx.LockChatSessionForAppend(ctx, sessionID); err != nil {
return fmt.Errorf("lock chat session for fresh context: %w", err)
}
- binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, sessionID)
+ binding, err := qtx.LockCurrentChannelChatSessionBindingBySession(ctx, sessionID)
if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return ErrRouteChanged
+ }
return fmt.Errorf("lock channel chat binding: %w", err)
}
- if err := qtx.EnsureChannelChatContextGeneration(ctx, sessionID); err != nil {
- return fmt.Errorf("ensure channel chat context: %w", err)
- }
_, err = qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
ChatSessionID: sessionID, Revision: binding.ContextRevision,
})
@@ -518,6 +816,19 @@ func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUI
}); err != nil {
return fmt.Errorf("advance channel chat context: %w", err)
}
+ if claimToken.Valid && dedupMessageID != "" {
+ rows, err := qtx.MarkChannelInboundDedupProcessed(ctx, db.MarkChannelInboundDedupProcessedParams{
+ InstallationID: installationID,
+ MessageID: dedupMessageID,
+ ClaimToken: claimToken,
+ })
+ if err != nil {
+ return fmt.Errorf("mark fresh context dedup: %w", err)
+ }
+ if rows == 0 {
+ return ErrClaimLost
+ }
+ }
if err := tx.Commit(ctx); err != nil {
return fmt.Errorf("commit fresh context: %w", err)
}
@@ -529,32 +840,42 @@ func (s *ChatSession) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUI
// media-pending marker. A failure rolls back the attachment rows, then clears
// the marker separately so the placeholder can be promoted immediately for
// graceful degradation.
+// BindMediaRefs preserves the established error-only API used by adapter test
+// doubles and direct callers.
func (s *ChatSession) BindMediaRefs(ctx context.Context, in BindMediaInput) error {
+ _, err := s.BindMediaRefsWithResult(ctx, in)
+ return err
+}
+
+// BindMediaRefsWithResult additionally reports first-media title initialization
+// to production adapters so the Router can publish and refine that title.
+func (s *ChatSession) BindMediaRefsWithResult(ctx context.Context, in BindMediaInput) (BindMediaResult, error) {
+ var result BindMediaResult
tx, err := s.tx.Begin(ctx)
if err != nil {
- return fmt.Errorf("begin media tx: %w", err)
+ return result, fmt.Errorf("begin media tx: %w", err)
}
defer tx.Rollback(ctx)
qtx := s.q.WithTx(tx)
if len(in.MediaRefs) > 0 {
- if err := s.bindMediaRefs(ctx, qtx, in); err != nil {
+ if err := s.bindMediaRefs(ctx, qtx, in, &result); err != nil {
_ = tx.Rollback(ctx)
if clearErr := s.clearMediaPending(ctx, s.q, in); clearErr != nil {
- return errors.Join(err, clearErr)
+ return BindMediaResult{}, errors.Join(err, clearErr)
}
- return err
+ return BindMediaResult{}, err
}
}
if err := s.clearMediaPending(ctx, qtx, in); err != nil {
- return err
+ return BindMediaResult{}, err
}
if err := tx.Commit(ctx); err != nil {
// An ambiguous commit needs no adjudication: the intent-ledger rows
// were deleted in this same transaction, so commit landed ⇔ intents
// gone, atomically. Either way the reconciler settles the objects.
- return fmt.Errorf("commit media: %w", err)
+ return BindMediaResult{}, fmt.Errorf("commit media: %w", err)
}
- return nil
+ return result, nil
}
func (s *ChatSession) clearMediaPending(ctx context.Context, q SessionQueries, in BindMediaInput) error {
@@ -567,7 +888,7 @@ func (s *ChatSession) clearMediaPending(ctx context.Context, q SessionQueries, i
return nil
}
-func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in BindMediaInput) error {
+func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in BindMediaInput, result *BindMediaResult) error {
if !in.WorkspaceID.Valid {
return errors.New("bind media refs: workspace_id is required")
}
@@ -658,6 +979,29 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
if len(ids) == 0 {
return nil
}
+ if !in.IssueID.Valid {
+ for _, media := range created {
+ source := media.ref.Filename
+ if strings.TrimSpace(source) == "" {
+ source = mediaTypeTitle(media.ref.Type)
+ }
+ title := DeriveChatTitle(source)
+ if title == "" {
+ continue
+ }
+ if _, err := qtx.InitializeChatSessionMediaTitle(ctx, db.InitializeChatSessionMediaTitleParams{
+ ID: in.SessionID, MessageID: in.MessageID, Title: title,
+ }); err != nil {
+ if !errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("initialize media chat title: %w", err)
+ }
+ } else {
+ result.InitialTitle = title
+ result.TitleSource = source
+ }
+ break
+ }
+ }
if in.IssueID.Valid {
issueMarkdown := make([]string, 0, len(created))
replacements := make([]inlineMediaReplacement, 0, len(created))
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index dc57f33f29..0c3e9539d7 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -43,34 +43,41 @@ func sessionPersistenceTestDB(t *testing.T) *pgxpool.Pool {
}
type sessionPersistenceFixture struct {
- workspaceID pgtype.UUID
- userID pgtype.UUID
- agentID pgtype.UUID
- sessionID pgtype.UUID
+ workspaceID pgtype.UUID
+ userID pgtype.UUID
+ agentID pgtype.UUID
+ sessionID pgtype.UUID
+ installationID pgtype.UUID
+ channelChatID string
}
func seedSessionPersistenceFixture(t *testing.T, pool *pgxpool.Pool) sessionPersistenceFixture {
f := seedSessionPersistenceFixtureWithoutChannel(t, pool)
ctx := context.Background()
- var installationID pgtype.UUID
if err := pool.QueryRow(ctx, `
INSERT INTO channel_installation (
workspace_id, agent_id, channel_type, config, status, installer_user_id
) VALUES ($1, $2, 'lark', '{}'::jsonb, 'active', $3)
RETURNING id
- `, f.workspaceID, f.agentID, f.userID).Scan(&installationID); err != nil {
+ `, f.workspaceID, f.agentID, f.userID).Scan(&f.installationID); err != nil {
t.Fatalf("create channel installation: %v", err)
}
+ f.channelChatID = "channel-media-" + fmt.Sprint(time.Now().UnixNano())
if _, err := db.New(pool).CreateChannelChatSessionBinding(ctx, db.CreateChannelChatSessionBindingParams{
- ChatSessionID: f.sessionID, InstallationID: installationID, ChannelType: "lark",
- ChannelChatID: "channel-media-" + fmt.Sprint(time.Now().UnixNano()), ChatType: "p2p", Config: []byte("{}"),
+ ChatSessionID: f.sessionID, InstallationID: f.installationID, ChannelType: "lark",
+ ChannelChatID: f.channelChatID, ChatType: "p2p", Config: []byte("{}"),
}); err != nil {
t.Fatalf("create channel binding: %v", err)
}
t.Cleanup(func() {
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, f.sessionID)
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, f.sessionID)
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
+ _, _ = pool.Exec(context.Background(), `
+ DELETE FROM channel_chat_context_generation
+ WHERE chat_session_id IN (
+ SELECT chat_session_id FROM channel_chat_session_binding WHERE installation_id = $1
+ )
+ `, f.installationID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, f.installationID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, f.installationID)
})
return f
}
@@ -121,107 +128,82 @@ func seedSessionPersistenceFixtureWithoutChannel(t *testing.T, pool *pgxpool.Poo
RETURNING id`, f.workspaceID, f.agentID, f.userID).Scan(&f.sessionID); err != nil {
t.Fatalf("create chat session: %v", err)
}
-
return f
}
-func TestAppendUserMessage_AdvancesPendingFreshForBindingCreatedByLegacyServer(t *testing.T) {
+func TestChannelRouteRevisionContinuesAfterCurrentBindingIsRemoved(t *testing.T) {
pool := sessionPersistenceTestDB(t)
- fixture := seedSessionPersistenceFixtureWithoutChannel(t, pool)
+ fixture := seedSessionPersistenceFixture(t, pool)
ctx := context.Background()
queries := db.New(pool)
- session := NewChatSession(queries, pool, channel.TypeFeishu, SessionTitles{})
-
- var installationID pgtype.UUID
- if err := pool.QueryRow(ctx, `
- INSERT INTO channel_installation (
- workspace_id, agent_id, channel_type, config, status, installer_user_id
- )
- VALUES ($1, $2, 'lark', '{}'::jsonb, 'active', $3)
- RETURNING id
- `, fixture.workspaceID, fixture.agentID, fixture.userID).Scan(&installationID); err != nil {
- t.Fatalf("create legacy installation: %v", err)
- }
- t.Cleanup(func() {
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, fixture.sessionID)
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, fixture.sessionID)
- _, _ = pool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
- })
+ session := NewChatSession(queries, pool, channel.Type("lark"), SessionTitles{})
- // Simulate an old server running after the schema migration: it creates the
- // legacy binding shape, writes a normal turn, then records a bare /new only
- // on channel_chat_session_binding. No generation row exists yet.
if _, err := pool.Exec(ctx, `
- INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type
- )
- VALUES ($1, $2, 'lark', 'legacy-created-binding', 'p2p')
- `, fixture.sessionID, installationID); err != nil {
- t.Fatalf("create legacy binding: %v", err)
- }
- if _, err := pool.Exec(ctx, `
- INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
- VALUES ($1, 'user', 'old context', TRUE)
- `, fixture.sessionID); err != nil {
- t.Fatalf("create legacy context message: %v", err)
- }
- if _, err := pool.Exec(ctx, `
- UPDATE channel_chat_session_binding SET pending_fresh = TRUE
- WHERE chat_session_id = $1
- `, fixture.sessionID); err != nil {
- t.Fatalf("mark legacy pending fresh: %v", err)
- }
-
- result, err := session.AppendUserMessage(ctx, AppendInput{
- SessionID: fixture.sessionID,
- Sender: fixture.userID,
- Body: "new context",
- MessageID: "new-context-message",
+ UPDATE channel_chat_session_binding
+ SET retired_at = now()
+ WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+ `, fixture.installationID, fixture.channelChatID); err != nil {
+ t.Fatalf("retire first route: %v", err)
+ }
+ secondSession, err := session.EnsureSession(ctx, EnsureSessionInput{
+ WorkspaceID: fixture.workspaceID, AgentID: fixture.agentID,
+ InstallationID: fixture.installationID, Sender: fixture.userID,
+ BindingKey: fixture.channelChatID, ChatType: channel.ChatTypeP2P,
})
if err != nil {
- t.Fatalf("append through new server: %v", err)
+ t.Fatalf("ensure route after archive: %v", err)
}
- if result.ContextRevision != 2 {
- t.Fatalf("new message revision = %d, want 2", result.ContextRevision)
+ var secondRevision int64
+ if err := pool.QueryRow(ctx, `
+ SELECT route_revision FROM channel_chat_session_binding
+ WHERE chat_session_id = $1
+ `, secondSession).Scan(&secondRevision); err != nil {
+ t.Fatalf("load recreated route: %v", err)
}
- if len(result.PendingContexts) != 2 || result.PendingContexts[0].Revision != 1 || result.PendingContexts[1].Revision != 2 {
- t.Fatalf("pending contexts = %v, want revisions [1 2]", result.PendingContexts)
+ if secondRevision != 2 {
+ t.Fatalf("recreated route revision = %d, want 2", secondRevision)
}
- if result.PendingContexts[0].InitiatorUserID.Valid {
- t.Fatalf("legacy context initiator = %v, want missing fail-closed snapshot", result.PendingContexts[0].InitiatorUserID)
+ if _, err := pool.Exec(ctx, `
+ UPDATE channel_chat_session_binding SET retired_at = now()
+ WHERE chat_session_id = $1
+ `, secondSession); err != nil {
+ t.Fatalf("retire recreated route: %v", err)
+ }
+ started, err := session.StartSession(ctx, StartSessionInput{EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: fixture.workspaceID, AgentID: fixture.agentID,
+ InstallationID: fixture.installationID, Sender: fixture.userID,
+ BindingKey: fixture.channelChatID, ChatType: channel.ChatTypeP2P,
+ }})
+ if err != nil {
+ t.Fatalf("start route after archive: %v", err)
}
- if result.PendingContexts[1].InitiatorUserID != fixture.userID {
- t.Fatalf("new context initiator = %v, want %v", result.PendingContexts[1].InitiatorUserID, fixture.userID)
+ if started.RouteRevision != 3 || started.Append.RouteRevision != 3 {
+ t.Fatalf("started route revisions = result:%d append:%d, want 3", started.RouteRevision, started.Append.RouteRevision)
}
+}
- var bindingRevision int64
- var revisions []int64
- if err := pool.QueryRow(ctx, `
- SELECT context_revision FROM channel_chat_session_binding
- WHERE chat_session_id = $1
- `, fixture.sessionID).Scan(&bindingRevision); err != nil {
- t.Fatalf("load repaired binding revision: %v", err)
- }
- rows, err := pool.Query(ctx, `
- SELECT revision FROM channel_chat_context_generation
- WHERE chat_session_id = $1 ORDER BY revision
- `, fixture.sessionID)
+func TestAppendUserMessageReplacesLegacyImplicitChannelTitle(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+ session := NewChatSession(db.New(pool), pool, channel.Type("lark"), SessionTitles{})
+
+ res, err := session.AppendUserMessage(ctx, AppendInput{
+ SessionID: fixture.sessionID, Sender: fixture.userID,
+ InstallationID: fixture.installationID, Body: "Real first title", MessageID: "m-title",
+ })
if err != nil {
- t.Fatalf("list repaired generations: %v", err)
+ t.Fatalf("append first channel message: %v", err)
}
- defer rows.Close()
- for rows.Next() {
- var revision int64
- if err := rows.Scan(&revision); err != nil {
- t.Fatalf("scan repaired generation: %v", err)
- }
- revisions = append(revisions, revision)
+ if !res.BecameVisible || res.InitialTitle != "Real first title" {
+ t.Fatalf("append result = %+v, want newly visible deterministic title", res)
}
- if err := rows.Err(); err != nil {
- t.Fatalf("iterate repaired generations: %v", err)
+ var title string
+ if err := pool.QueryRow(ctx, `SELECT title FROM chat_session WHERE id = $1`, fixture.sessionID).Scan(&title); err != nil {
+ t.Fatalf("load initialized title: %v", err)
}
- if bindingRevision != 2 || len(revisions) != 2 || revisions[0] != 1 || revisions[1] != 2 {
- t.Fatalf("repaired context = binding:%d generations:%v, want 2/[1 2]", bindingRevision, revisions)
+ if title != "Real first title" {
+ t.Fatalf("persisted title = %q, want %q", title, "Real first title")
}
}
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 4e575ff68a..e51df878f2 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -6,6 +6,7 @@ import (
"fmt"
"testing"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
@@ -57,11 +58,32 @@ func (s fakeTxStarter) Begin(context.Context) (pgx.Tx, error) {
return &fakeTx{}, nil
}
+type recordingTx struct {
+ pgx.Tx
+ commits int
+ rollbacks int
+}
+
+func (t *recordingTx) Commit(context.Context) error {
+ t.commits++
+ return nil
+}
+
+func (t *recordingTx) Rollback(context.Context) error {
+ t.rollbacks++
+ return nil
+}
+
+type recordingTxStarter struct{ tx *recordingTx }
+
+func (s recordingTxStarter) Begin(context.Context) (pgx.Tx, error) { return s.tx, nil }
+
// fakeSessionQueries is an in-memory SessionQueries for unit tests.
type fakeSessionQueries struct {
bindings map[string]pgtype.UUID
nextSession byte
createdSessions int
+ lastSessionCreate db.CreateChatSessionParams
messages []string
messageID pgtype.UUID
lastCreate db.CreateChatMessageParams
@@ -79,14 +101,20 @@ type fakeSessionQueries struct {
issueMediaDescription string
reconcilerOwnedKeys map[string]bool
issueLookupErr error
+ initializedMediaTitle string
+ initializedTitle string
+ explicitlyCreated bool
+ hasPublicUserMessage bool
+ sessionTitle string
+ routeRetired bool
+ lastRetire db.RetireChannelChatSessionBindingParams
markRows int64 // MarkChannelInboundDedupProcessed result
+ lastMark db.MarkChannelInboundDedupProcessedParams
pendingFresh bool
- legacyPendingFresh bool
contextRevision int64
contextInitiator pgtype.UUID
boundaryPending bool
- ensureContextErr error
lockContextErr error
advanceContextErr error
resolveContextErr error
@@ -106,7 +134,7 @@ func (f *fakeSessionQueries) WithTx(tx pgx.Tx) SessionQueries { return f }
func (f *fakeSessionQueries) GetChannelChatSessionBinding(_ context.Context, arg db.GetChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
if id, ok := f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)]; ok {
- return db.ChannelChatSessionBinding{ChatSessionID: id}, nil
+ return db.ChannelChatSessionBinding{ID: uid(89), ChatSessionID: id}, nil
}
return db.ChannelChatSessionBinding{}, pgx.ErrNoRows
}
@@ -116,9 +144,10 @@ func (f *fakeSessionQueries) LockWorkspaceForChatSessionCreate(_ context.Context
return id, nil
}
-func (f *fakeSessionQueries) CreateChatSession(_ context.Context, _ db.CreateChatSessionParams) (db.ChatSession, error) {
+func (f *fakeSessionQueries) CreateChatSession(_ context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error) {
f.nextSession++
f.createdSessions++
+ f.lastSessionCreate = arg
return db.ChatSession{ID: uid(f.nextSession)}, nil
}
@@ -133,13 +162,89 @@ func (f *fakeSessionQueries) CreateChannelChatSessionBinding(_ context.Context,
return db.ChannelChatSessionBinding{ChatSessionID: arg.ChatSessionID}, nil
}
+func (f *fakeSessionQueries) CreateChannelChatSessionBindingGeneration(_ context.Context, arg db.CreateChannelChatSessionBindingGenerationParams) (db.ChannelChatSessionBinding, error) {
+ f.lastConfig = arg.Config
+ f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)] = arg.ChatSessionID
+ return db.ChannelChatSessionBinding{ID: uid(90), ChatSessionID: arg.ChatSessionID, RouteRevision: arg.RouteRevision}, nil
+}
+
+func (f *fakeSessionQueries) LockCurrentChannelChatSessionBinding(_ context.Context, arg db.LockCurrentChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ if id, ok := f.bindings[bindKey(arg.InstallationID, arg.ChannelChatID)]; ok {
+ return db.ChannelChatSessionBinding{ID: uid(89), ChatSessionID: id, RouteRevision: 1}, nil
+ }
+ return db.ChannelChatSessionBinding{}, pgx.ErrNoRows
+}
+
+func (f *fakeSessionQueries) LockCurrentChannelChatSessionBindingBySession(_ context.Context, sessionID pgtype.UUID) (db.ChannelChatSessionBinding, error) {
+ if !f.routeRetired {
+ return db.ChannelChatSessionBinding{
+ ID: uid(89), ChatSessionID: sessionID, ContextRevision: f.contextRevision,
+ PendingFresh: f.pendingFresh, RouteRevision: 1,
+ }, nil
+ }
+ for _, id := range f.bindings {
+ if id == sessionID {
+ return db.ChannelChatSessionBinding{
+ ID: uid(89), ChatSessionID: id, ContextRevision: f.contextRevision,
+ PendingFresh: f.pendingFresh, RouteRevision: 1,
+ }, nil
+ }
+ }
+ return db.ChannelChatSessionBinding{}, pgx.ErrNoRows
+}
+
+func (f *fakeSessionQueries) RetireChannelChatSessionBinding(_ context.Context, arg db.RetireChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error) {
+ f.lastRetire = arg
+ return db.ChannelChatSessionBinding{}, nil
+}
+
func (f *fakeSessionQueries) LockChatSessionForAppend(_ context.Context, id pgtype.UUID) (pgtype.UUID, error) {
return id, nil
}
+func (f *fakeSessionQueries) GetChatSession(_ context.Context, id pgtype.UUID) (db.ChatSession, error) {
+ return db.ChatSession{
+ ID: id,
+ Title: f.sessionTitle,
+ ExplicitlyCreatedAt: pgtype.Timestamptz{Valid: f.explicitlyCreated},
+ }, nil
+}
+
+func (f *fakeSessionQueries) ChatSessionHasPublicUserMessage(context.Context, pgtype.UUID) (bool, error) {
+ return f.hasPublicUserMessage, nil
+}
+
+func (f *fakeSessionQueries) MarkChatSessionExplicitlyCreated(_ context.Context, id pgtype.UUID) (db.ChatSession, error) {
+ f.explicitlyCreated = true
+ return db.ChatSession{ID: id}, nil
+}
+
+func (f *fakeSessionQueries) InitializeChatSessionTitle(_ context.Context, arg db.InitializeChatSessionTitleParams) (db.ChatSession, error) {
+ if f.sessionTitle != "" || f.hasPublicUserMessage {
+ return db.ChatSession{}, pgx.ErrNoRows
+ }
+ f.initializedTitle = arg.Title
+ f.sessionTitle = arg.Title
+ return db.ChatSession{ID: arg.ID, Title: arg.Title}, nil
+}
+
+func (f *fakeSessionQueries) ReplaceImplicitChatSessionTitle(_ context.Context, arg db.ReplaceImplicitChatSessionTitleParams) (db.ChatSession, error) {
+ f.initializedTitle = arg.Title
+ f.sessionTitle = arg.Title
+ return db.ChatSession{ID: arg.ID, Title: arg.Title}, nil
+}
+
+func (f *fakeSessionQueries) InitializeChatSessionMediaTitle(_ context.Context, arg db.InitializeChatSessionMediaTitleParams) (db.ChatSession, error) {
+ f.initializedMediaTitle = arg.Title
+ return db.ChatSession{ID: arg.ID, Title: arg.Title}, nil
+}
+
func (f *fakeSessionQueries) CreateChatMessage(_ context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
f.messages = append(f.messages, arg.Content)
f.lastCreate = arg
+ if arg.Role == "user" && (!arg.MessageKind.Valid || arg.MessageKind.String != channelCommandMessageKind) {
+ f.hasPublicUserMessage = true
+ }
return db.ChatMessage{ID: f.messageID}, nil
}
@@ -207,7 +312,7 @@ func (f *fakeSessionQueries) LockChannelChatSessionBindingForContext(context.Con
return db.ChannelChatSessionBinding{}, f.lockContextErr
}
return db.ChannelChatSessionBinding{
- ContextRevision: f.contextRevision, PendingFresh: f.legacyPendingFresh,
+ ContextRevision: f.contextRevision,
}, nil
}
@@ -221,10 +326,6 @@ func (f *fakeSessionQueries) LockChannelChatContextGenerationByRevision(context.
}, nil
}
-func (f *fakeSessionQueries) EnsureChannelChatContextGeneration(context.Context, pgtype.UUID) error {
- return f.ensureContextErr
-}
-
func (f *fakeSessionQueries) AdvanceChannelChatContextGeneration(_ context.Context, arg db.AdvanceChannelChatContextGenerationParams) (db.AdvanceChannelChatContextGenerationRow, error) {
if f.advanceContextErr != nil {
return db.AdvanceChannelChatContextGenerationRow{}, f.advanceContextErr
@@ -256,7 +357,8 @@ func (f *fakeSessionQueries) UpdateChannelChatSessionBindingReplyTarget(context.
return nil
}
-func (f *fakeSessionQueries) MarkChannelInboundDedupProcessed(context.Context, db.MarkChannelInboundDedupProcessedParams) (int64, error) {
+func (f *fakeSessionQueries) MarkChannelInboundDedupProcessed(_ context.Context, arg db.MarkChannelInboundDedupProcessedParams) (int64, error) {
+ f.lastMark = arg
return f.markRows, nil
}
@@ -276,6 +378,9 @@ func TestEnsureSession_CreateThenReuse(t *testing.T) {
if f.createdSessions != 1 {
t.Fatalf("createdSessions = %d, want 1", f.createdSessions)
}
+ if f.lastSessionCreate.Title != "" {
+ t.Fatalf("implicit Chat title = %q, want empty until first effective message", f.lastSessionCreate.Title)
+ }
id2, err := s.EnsureSession(context.Background(), in)
if err != nil {
@@ -289,6 +394,230 @@ func TestEnsureSession_CreateThenReuse(t *testing.T) {
}
}
+func TestStartSessionCreatesExplicitEmptyGeneration(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ result, err := s.StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7),
+ BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ },
+ MessageID: "command-1", ClaimToken: uid(8),
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if !result.SessionID.Valid || len(f.messages) != 0 {
+ t.Fatalf("session=%v messages=%v", result.SessionID.Valid, f.messages)
+ }
+ if f.createdSessions != 1 || f.markRows != 1 {
+ t.Fatalf("created=%d markRows=%d", f.createdSessions, f.markRows)
+ }
+ if !f.lastSessionCreate.ID.Valid || uuid.UUID(f.lastSessionCreate.ID.Bytes).Version() != 7 {
+ t.Fatalf("started Chat id = %v, want an explicit UUIDv7", f.lastSessionCreate.ID)
+ }
+}
+
+func TestStartSessionBodyCreatesOrdinaryFirstMessageAndTitle(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ result, err := s.StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7),
+ BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: uid(8), Body: "# 发布检查", MessageID: "command-1", ClaimToken: uid(9), PersistMessage: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if len(f.messages) != 1 || f.messages[0] != "# 发布检查" {
+ t.Fatalf("messages=%v", f.messages)
+ }
+ if f.lastCreate.MessageKind.Valid {
+ t.Fatalf("message kind=%q, want ordinary", f.lastCreate.MessageKind.String)
+ }
+ if f.lastSessionCreate.CreatorID != uid(7) {
+ t.Fatalf("Chat creator=%v, want route owner %v", f.lastSessionCreate.CreatorID, uid(7))
+ }
+ if f.contextInitiator != uid(8) || len(result.Append.PendingContexts) != 1 || result.Append.PendingContexts[0].InitiatorUserID != uid(8) {
+ t.Fatalf("context initiator=%v pending=%+v, want command sender %v", f.contextInitiator, result.Append.PendingContexts, uid(8))
+ }
+}
+
+func TestStartSessionMediaBeforeTextUsesUserTextForTitle(t *testing.T) {
+ f := newFake()
+ result, err := newTestSession(f).StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7),
+ BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: uid(7), Body: "[Image]\n点评一下", MediaPendingSeconds: 45, PersistMessage: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if f.lastSessionCreate.Title != "点评一下" || result.Append.InitialTitle != "点评一下" {
+ t.Fatalf("media-before-text title = stored %q result %q, want user text", f.lastSessionCreate.Title, result.Append.InitialTitle)
+ }
+}
+
+func TestStartSessionRunsBeforeCommitInOwningTransaction(t *testing.T) {
+ f := newFake()
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ called := false
+ result, err := s.StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7),
+ BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: uid(7), Body: "ship it", PersistMessage: true,
+ BeforeCommit: func(_ context.Context, gotTx pgx.Tx, session db.ChatSession) error {
+ called = true
+ if gotTx != tx {
+ t.Fatal("BeforeCommit did not receive StartSession's transaction")
+ }
+ if !session.ID.Valid {
+ t.Fatal("BeforeCommit did not receive the created Chat")
+ }
+ return nil
+ },
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if !called || result.SessionID != uid(1) || tx.commits != 1 {
+ t.Fatalf("called=%v session=%v commits=%d", called, result.SessionID, tx.commits)
+ }
+}
+
+func TestStartSessionBeforeCommitFailurePreventsCommit(t *testing.T) {
+ f := newFake()
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ wantErr := errors.New("enqueue failed")
+ _, err := s.StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{
+ WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7),
+ BindingKey: "chatA", ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: uid(7), Body: "ship it", PersistMessage: true,
+ BeforeCommit: func(context.Context, pgx.Tx, db.ChatSession) error { return wantErr },
+ })
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("error=%v, want %v", err, wantErr)
+ }
+ if tx.commits != 0 || tx.rollbacks == 0 {
+ t.Fatalf("commits=%d rollbacks=%d, want no commit and rollback", tx.commits, tx.rollbacks)
+ }
+}
+
+func TestAppendUserMessageRunsBeforeCommitWithNativeDedup(t *testing.T) {
+ f := newFake()
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ called := false
+ result, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Sender: uid(2), InstallationID: uid(3),
+ Body: "start clean", CommandText: "/clear", ForceFresh: true,
+ DedupMessageID: "env-clear", ClaimToken: uid(4),
+ BeforeCommit: func(_ context.Context, gotTx pgx.Tx, session db.ChatSession, contextRevision int64, bindingID pgtype.UUID, routeRevision int64) error {
+ called = true
+ if gotTx != tx || session.ID != uid(1) {
+ t.Fatalf("callback tx/session = %v/%v", gotTx == tx, session.ID)
+ }
+ if contextRevision != 2 || bindingID != uid(89) || routeRevision != 1 {
+ t.Fatalf("callback context/binding/route = %d/%v/%d", contextRevision, bindingID, routeRevision)
+ }
+ if f.lastMark.MessageID != "env-clear" {
+ t.Fatalf("dedup message = %q", f.lastMark.MessageID)
+ }
+ return nil
+ },
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if !called || !result.DedupMarked || result.ContextRevision != 2 || !f.boundaryPending || f.replyTargets != 0 || tx.commits != 1 {
+ t.Fatalf("called=%t marked=%t revision=%d pending=%t replies=%d commits=%d", called, result.DedupMarked, result.ContextRevision, f.boundaryPending, f.replyTargets, tx.commits)
+ }
+}
+
+func TestAppendUserMessageBeforeCommitFailureRollsBackNativeTurn(t *testing.T) {
+ f := newFake()
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ wantErr := errors.New("enqueue failed")
+ _, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Sender: uid(2), Body: "start clean", ForceFresh: true,
+ BeforeCommit: func(context.Context, pgx.Tx, db.ChatSession, int64, pgtype.UUID, int64) error {
+ return wantErr
+ },
+ })
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("error=%v, want %v", err, wantErr)
+ }
+ if tx.commits != 0 || tx.rollbacks == 0 {
+ t.Fatalf("commits=%d rollbacks=%d, want no commit and rollback", tx.commits, tx.rollbacks)
+ }
+}
+
+func TestMarkPendingFreshWithDedupIsAtomic(t *testing.T) {
+ f := newFake()
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ if err := s.MarkPendingFreshWithDedup(context.Background(), uid(1), "", uid(2), "env-clear", uid(3)); err != nil {
+ t.Fatalf("MarkPendingFreshWithDedup: %v", err)
+ }
+ if f.lastMark.MessageID != "env-clear" || f.lastMark.InstallationID != uid(2) || !f.boundaryPending || tx.commits != 1 {
+ t.Fatalf("mark=%+v pending=%t commits=%d", f.lastMark, f.boundaryPending, tx.commits)
+ }
+}
+
+func TestMarkPendingFreshWithDedupRejectsLostClaim(t *testing.T) {
+ f := newFake()
+ f.markRows = 0
+ tx := &recordingTx{}
+ s := newChatSessionWith(f, recordingTxStarter{tx: tx}, channel.Type("slack"), SessionTitles{})
+ err := s.MarkPendingFreshWithDedup(context.Background(), uid(1), "", uid(2), "env-clear", uid(3))
+ if !errors.Is(err, ErrClaimLost) {
+ t.Fatalf("error=%v, want ErrClaimLost", err)
+ }
+ if tx.commits != 0 || tx.rollbacks == 0 {
+ t.Fatalf("commits=%d rollbacks=%d, want no commit and rollback", tx.commits, tx.rollbacks)
+ }
+}
+
+func TestStartSessionPendingSlackBoundaryLeavesRetiredEndOpen(t *testing.T) {
+ f := newFake()
+ f.bindings[bindKey(uid(1), "chatA")] = uid(7)
+ s := newTestSession(f)
+ _, err := s.StartSession(context.Background(), StartSessionInput{
+ EnsureSessionInput: EnsureSessionInput{WorkspaceID: uid(2), AgentID: uid(3), InstallationID: uid(1), Sender: uid(7), BindingKey: "chatA", ChatType: channel.ChatTypeP2P},
+ HistoryBoundaryPending: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if f.lastRetire.HistoryEndMessageID.Valid {
+ t.Fatalf("retired end=%q, want open until first real inbound", f.lastRetire.HistoryEndMessageID.String)
+ }
+}
+
+func TestAppendUserMessageRejectsRetiredGeneration(t *testing.T) {
+ f := newFake()
+ f.routeRetired = true
+ s := newTestSession(f)
+ _, err := s.AppendUserMessage(context.Background(), AppendInput{SessionID: uid(1), Body: "stale"})
+ if !errors.Is(err, ErrRouteChanged) {
+ t.Fatalf("error=%v, want ErrRouteChanged", err)
+ }
+ if len(f.messages) != 0 {
+ t.Fatalf("retired generation received %d messages", len(f.messages))
+ }
+}
+
func TestEnsureSession_RaceUniqueViolation(t *testing.T) {
f := newFake()
f.createBindingErr = &pgconn.PgError{Code: "23505"}
@@ -380,6 +709,9 @@ func TestAppendUserMessage_PlainText(t *testing.T) {
if len(f.messages) != 1 || f.messages[0] != "hello there" {
t.Errorf("messages = %v", f.messages)
}
+ if res.InitialTitle != "hello there" {
+ t.Errorf("initial title = %q, want first effective channel message", res.InitialTitle)
+ }
if f.touched != 1 || f.replyTargets != 1 {
t.Errorf("touched=%d replyTargets=%d, want 1/1", f.touched, f.replyTargets)
}
@@ -463,6 +795,57 @@ func TestAppendUserMessage_OrdinaryTurnKeepsDefaultMessageKind(t *testing.T) {
}
}
+func TestAppendUserMessageReportsOnlyImplicitFirstTurnAsNewlyVisible(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ explicitlyCreated bool
+ hadPublicUser bool
+ initialTitle string
+ wantBecameVisible bool
+ wantInitializedTitle string
+ }{
+ {name: "implicit first turn replaces legacy title", initialTitle: "Legacy channel title", wantBecameVisible: true, wantInitializedTitle: "hello"},
+ {name: "explicit empty chat first turn", explicitlyCreated: true, wantInitializedTitle: "hello"},
+ {name: "implicit chat later turn", hadPublicUser: true, initialTitle: "first title"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newFake()
+ f.explicitlyCreated = tc.explicitlyCreated
+ f.hasPublicUserMessage = tc.hadPublicUser
+ f.sessionTitle = tc.initialTitle
+ res, err := newTestSession(f).AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "hello", CommandText: "hello", MessageID: "m1",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.BecameVisible != tc.wantBecameVisible {
+ t.Fatalf("BecameVisible = %t, want %t", res.BecameVisible, tc.wantBecameVisible)
+ }
+ if f.initializedTitle != tc.wantInitializedTitle {
+ t.Fatalf("initialized title = %q, want %q", f.initializedTitle, tc.wantInitializedTitle)
+ }
+ })
+ }
+}
+
+func TestAppendUserMessageClearsLegacyTitleForImplicitMediaFirstTurn(t *testing.T) {
+ f := newFake()
+ f.sessionTitle = "Legacy channel title"
+ res, err := newTestSession(f).AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Body: "[Image]", MessageID: "m1", MediaPendingSeconds: 10,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if !res.BecameVisible {
+ t.Fatal("media first turn did not make the implicit Chat visible")
+ }
+ if f.sessionTitle != "" || res.InitialTitle != "" {
+ t.Fatalf("media first turn title = stored %q result %q, want empty until attachment bind", f.sessionTitle, res.InitialTitle)
+ }
+}
+
func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
f := newFake()
s := newTestSession(f)
@@ -531,6 +914,34 @@ func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
}
}
+func TestBindMediaRefs_InitializesPlaceholderOnlyFirstMessageFromFilename(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1), Sender: uid(7), Body: "[Image]", MessageID: "om_image",
+ MediaPendingSeconds: 45,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.InitialTitle != "" {
+ t.Fatalf("placeholder-only append initialized title %q before filename resolution", res.InitialTitle)
+ }
+ err = s.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: res.MessageID, SessionID: uid(1), WorkspaceID: uid(9), Sender: uid(7), Body: "[Image]",
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeImage, StorageKey: "image-key", StorageURL: "https://cdn.example.test/image-key",
+ Filename: "incident screenshot.png", MimeType: "image/png",
+ }},
+ })
+ if err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+ if f.initializedMediaTitle != "incident screenshot.png" {
+ t.Fatalf("media title = %q, want attachment filename", f.initializedMediaTitle)
+ }
+}
+
func TestComposeInlineMediaBody_PartialResolutionKeepsFailedPlaceholderInPlace(t *testing.T) {
body := "[Image]\n这是啥?\n[Image]\n这又是啥?"
got, changed := composeInlineMediaBody(body, []inlineMediaReplacement{{
@@ -817,21 +1228,6 @@ func TestAppendUserMessage_ResolvesBareFreshBoundaryOnNextMessage(t *testing.T)
}
}
-func TestAppendUserMessage_AdvancesLegacyPendingFreshFromRollingDeploy(t *testing.T) {
- f := newFake()
- f.legacyPendingFresh = true
- s := newTestSession(f)
- res, err := s.AppendUserMessage(context.Background(), AppendInput{
- SessionID: uid(1), Body: "next", MessageID: "next-ts",
- })
- if err != nil {
- t.Fatalf("AppendUserMessage: %v", err)
- }
- if f.contextRevision != 2 || res.ContextRevision != 2 || f.lastCreate.ChannelContextRevision.Int64 != 2 {
- t.Fatalf("legacy pending fresh context = generation:%d result:%d row:%d, want 2", f.contextRevision, res.ContextRevision, f.lastCreate.ChannelContextRevision.Int64)
- }
-}
-
func TestAppendUserMessage_ContextGenerationFailuresDoNotWriteMessage(t *testing.T) {
testErr := errors.New("context generation failed")
tests := []struct {
@@ -839,7 +1235,6 @@ func TestAppendUserMessage_ContextGenerationFailuresDoNotWriteMessage(t *testing
setup func(*fakeSessionQueries)
input AppendInput
}{
- {name: "ensure", setup: func(f *fakeSessionQueries) { f.ensureContextErr = testErr }},
{name: "lock", setup: func(f *fakeSessionQueries) { f.lockContextErr = testErr }},
{name: "advance", setup: func(f *fakeSessionQueries) { f.advanceContextErr = testErr }, input: AppendInput{ForceFresh: true}},
{name: "resolve", setup: func(f *fakeSessionQueries) {
@@ -893,7 +1288,6 @@ func TestMarkPendingFresh_ContextGenerationFailuresRollBack(t *testing.T) {
name string
setup func(*fakeSessionQueries)
}{
- {name: "ensure", setup: func(f *fakeSessionQueries) { f.ensureContextErr = testErr }},
{name: "lock", setup: func(f *fakeSessionQueries) { f.lockContextErr = testErr }},
{name: "advance", setup: func(f *fakeSessionQueries) { f.advanceContextErr = testErr }},
}
diff --git a/server/internal/integrations/channel/engine/title.go b/server/internal/integrations/channel/engine/title.go
new file mode 100644
index 0000000000..65cba8c982
--- /dev/null
+++ b/server/internal/integrations/channel/engine/title.go
@@ -0,0 +1,47 @@
+package engine
+
+import (
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/chattitle"
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// DeriveChatTitle is the deterministic fallback shared by channel-created
+// Chats. It measures Unicode code points, including the trailing ellipsis.
+func DeriveChatTitle(body string) string {
+ return chattitle.Derive(body)
+}
+
+func deriveFirstMessageTitle(body string, hasMedia bool) string {
+ if hasMedia {
+ body = withoutMediaPlaceholderLines(body)
+ }
+ return DeriveChatTitle(body)
+}
+
+func withoutMediaPlaceholderLines(body string) string {
+ lines := make([]string, 0, strings.Count(body, "\n")+1)
+ for _, line := range strings.Split(body, "\n") {
+ switch strings.TrimSpace(line) {
+ case "[Image]", "[File]", "[Audio]", "[Video]":
+ continue
+ default:
+ lines = append(lines, line)
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+
+func mediaTypeTitle(kind channel.MsgType) string {
+ switch kind {
+ case channel.MsgTypeImage:
+ return "Image chat"
+ case channel.MsgTypeAudio:
+ return "Audio chat"
+ case channel.MsgTypeVideo:
+ return "Video chat"
+ default:
+ return "File chat"
+ }
+}
diff --git a/server/internal/integrations/channel/engine/title_test.go b/server/internal/integrations/channel/engine/title_test.go
new file mode 100644
index 0000000000..22d82cc2ea
--- /dev/null
+++ b/server/internal/integrations/channel/engine/title_test.go
@@ -0,0 +1,36 @@
+package engine
+
+import "testing"
+
+func TestDeriveChatTitle(t *testing.T) {
+ tests := []struct{ input, want string }{
+ {"\n# 发布检查\n后续", "发布检查"},
+ {"[部署文档](https://example.com) **失败**", "部署文档 失败"},
+ {"![架构图](https://example.com/a.png)", "架构图"},
+ {"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三", "一二三四五六七八九十一二三四五六七八九十一二三四五六七八九…"},
+ {"12345678901234567890123456 890123", "12345678901234567890123456 89…"},
+ }
+ for _, tc := range tests {
+ if got := DeriveChatTitle(tc.input); got != tc.want {
+ t.Errorf("DeriveChatTitle(%q)=%q want %q", tc.input, got, tc.want)
+ }
+ }
+}
+
+func TestDeriveFirstMessageTitle_MediaPlaceholderWaitsForFilename(t *testing.T) {
+ if got := deriveFirstMessageTitle("[Image]\n[File]", true); got != "" {
+ t.Fatalf("placeholder-only media title = %q, want empty until media metadata is available", got)
+ }
+ if got := deriveFirstMessageTitle("[Image]\n点评一下", true); got != "点评一下" {
+ t.Fatalf("media-before-text title = %q, want user text", got)
+ }
+ if got := deriveFirstMessageTitle("Inspect this\n[Image]", true); got != "Inspect this" {
+ t.Fatalf("text plus media title = %q, want user text", got)
+ }
+ if got := deriveFirstMessageTitle("Use [Image] literally\n[Image]", true); got != "Use [Image] literally" {
+ t.Fatalf("inline literal placeholder title = %q, want user text preserved", got)
+ }
+ if got := deriveFirstMessageTitle("[Image]", false); got != "[Image]" {
+ t.Fatalf("literal text title = %q, want the user-authored text", got)
+ }
+}
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 6d5f5ab06b..e523cc3c55 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -165,7 +165,7 @@ type InboundMessage struct {
AddressedToBot bool
// ForceFresh asks the core to start a fresh agent session for this message
- // instead of resuming the prior one. Router recognizes the shared /new text
+ // instead of resuming the prior one. Router recognizes the shared /clear text
// command; adapters may also set this flag for a native platform affordance.
ForceFresh bool
diff --git a/server/internal/integrations/dingtalk/bot_identity.go b/server/internal/integrations/dingtalk/bot_identity.go
index bfe0fbfa7c..20b2b7945e 100644
--- a/server/internal/integrations/dingtalk/bot_identity.go
+++ b/server/internal/integrations/dingtalk/bot_identity.go
@@ -131,6 +131,14 @@ func (r *BotNameResolver) Resolve(ctx context.Context, installation db.ChannelIn
if err != nil {
return "", err
}
+ return r.resolveCredentials(ctx, credentials, conversationID)
+}
+
+// resolveCredentials is the adapter-ingest entry point. The Stream channel
+// already owns the decrypted credentials, so normalization can share the exact
+// same cache and OpenAPI implementation as group-presence discovery without a
+// database round trip or a second resolver.
+func (r *BotNameResolver) resolveCredentials(ctx context.Context, credentials credentials, conversationID string) (string, error) {
identityKey := "identity\x00" + credentials.AppKey + "\x00" + credentials.RobotCode
if cached, ok := r.cached(identityKey); ok {
return cached.name, cached.err
diff --git a/server/internal/integrations/dingtalk/bot_identity_test.go b/server/internal/integrations/dingtalk/bot_identity_test.go
index f33a6f0783..a04be50709 100644
--- a/server/internal/integrations/dingtalk/bot_identity_test.go
+++ b/server/internal/integrations/dingtalk/bot_identity_test.go
@@ -188,6 +188,35 @@ func TestBotNameResolverCachesSuccessfulIdentityAcrossGroups(t *testing.T) {
}
}
+func TestBotNameResolverSharesCacheBetweenChannelCredentialsAndInstallation(t *testing.T) {
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == accessTokenPath {
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ return
+ }
+ calls.Add(1)
+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"release","name":"Release Bot"}]}`))
+ }))
+ defer srv.Close()
+
+ resolver := NewBotNameResolver(NewClient(nil, srv.URL), nil)
+ name, err := resolver.resolveCredentials(context.Background(), credentials{
+ AppKey: "app", AppSecret: "secret", RobotCode: "release",
+ }, "group-a")
+ if err != nil || name != "Release Bot" {
+ t.Fatalf("channel credential resolution = %q, %v", name, err)
+ }
+ name, err = resolver.Resolve(context.Background(), botIdentityInstallation(t, "app", "release"), "group-b")
+ if err != nil || name != "Release Bot" {
+ t.Fatalf("installation resolution = %q, %v", name, err)
+ }
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("shared resolver API calls = %d, want 1", got)
+ }
+}
+
func TestBotNameResolverCachesTransientAndBrieflyCachesPermissionFailure(t *testing.T) {
groupCalls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/integrations/dingtalk/byo_install_db_test.go b/server/internal/integrations/dingtalk/byo_install_db_test.go
index e74694cadf..626b40b46a 100644
--- a/server/internal/integrations/dingtalk/byo_install_db_test.go
+++ b/server/internal/integrations/dingtalk/byo_install_db_test.go
@@ -56,6 +56,8 @@ func TestRegisterBYO_DifferentAppKey_IsolatesIdentityStateDB(t *testing.T) {
multicaUserID = "d1470000-0000-4000-8000-000000000004"
oldInstallID = "d1470000-0000-4000-8000-000000000010"
chatSessionID = "d1470000-0000-4000-8000-000000000020"
+ bindingID = "d1470000-0000-4000-8000-000000000021"
+ taskID = "d1470000-0000-4000-8000-000000000022"
mediaMessageID = "d1470000-0000-4000-8000-000000000030"
oldAppKey = "dingtalk_identity_old_app"
newAppKey = "dingtalk_identity_new_app"
@@ -68,6 +70,8 @@ func TestRegisterBYO_DifferentAppKey_IsolatesIdentityStateDB(t *testing.T) {
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_outbound_message WHERE installation_id = $1`, oldInstallID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE installation_id = $1`, oldInstallID)
_, _ = pool.Exec(context.Background(), `DELETE FROM channel_chat_context_generation 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)
@@ -95,9 +99,9 @@ INSERT INTO channel_user_binding (workspace_id, multica_user_id, installation_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)
+INSERT INTO channel_chat_session_binding (id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type)
+VALUES ($1, $2, $3, 'dingtalk', $4, 'p2p')
+`, bindingID, chatSessionID, oldInstallID, chatID)
exec(`
INSERT INTO channel_chat_context_generation (chat_session_id, revision)
VALUES ($1, 1)
@@ -111,6 +115,18 @@ INSERT INTO channel_outbound_card_message (chat_session_id, channel_type, channe
VALUES ($1, 'dingtalk', $2, 'old-outbound-message')
`, chatSessionID, chatID)
exec(`
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id,
+ chat_type, route_revision
+) VALUES ($1, $2, $3, 'dingtalk', $4, 'p2p', 1)
+`, taskID, bindingID, oldInstallID, chatID)
+ exec(`
+INSERT INTO channel_outbound_message (
+ installation_id, channel_type, channel_message_id, binding_id,
+ route_revision, task_id, outbound_kind
+) VALUES ($1, 'dingtalk', 'old-route-reply', $2, 1, $3, 'task_reply')
+`, oldInstallID, bindingID, taskID)
+ exec(`
INSERT INTO channel_inbound_message_dedup (installation_id, message_id)
VALUES ($1, 'dingtalk-identity-old-message')
`, oldInstallID)
@@ -171,6 +187,8 @@ VALUES ($1, $2, $3, 'https://storage.example.test/old-image', $4)
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 task delivery", `SELECT count(*) FROM channel_task_delivery WHERE installation_id = $1`, 0, oldInstallID)
+ assertCount("old route ledger", `SELECT count(*) FROM channel_outbound_message WHERE installation_id = $1`, 0, oldInstallID)
assertCount("old chat context", `SELECT count(*) FROM channel_chat_context_generation WHERE chat_session_id = $1`, 1, chatSessionID)
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)
diff --git a/server/internal/integrations/dingtalk/dingtalk_channel.go b/server/internal/integrations/dingtalk/dingtalk_channel.go
index a57da54513..b1e803575b 100644
--- a/server/internal/integrations/dingtalk/dingtalk_channel.go
+++ b/server/internal/integrations/dingtalk/dingtalk_channel.go
@@ -32,6 +32,7 @@ type dingtalkChannel struct {
appKey string
appSecret string // decrypted — opens the Stream connection + mints tokens
client *Client
+ botNames *BotNameResolver
handler channel.InboundHandler
logger *slog.Logger
// dispatch runs inbound jobs off the socket read loop on per-conversation
@@ -39,6 +40,10 @@ type dingtalkChannel struct {
// it survives redials, and in-flight jobs deliberately outlive the socket.
dispatch *dispatcher
slot *dispatchSlot
+ // releaseDispatchSlot removes the closed slot from the factory registry
+ // after a lifecycle stop. It is compare-by-slot, so an overlapping rebuild
+ // can replace the registry entry without an older generation deleting it.
+ releaseDispatchSlot func()
// 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
@@ -46,6 +51,14 @@ type dingtalkChannel struct {
stopDispatch atomic.Bool
}
+// inboundJob is the adapter-private payload accepted by the asynchronous
+// dispatcher. Keeping the original callback until the worker runs lets Bot
+// identity resolution happen before normalization without blocking the Stream
+// read loop or leaking DingTalk-specific fields into channel.InboundMessage.
+type inboundJob struct {
+ callback botCallbackData
+}
+
func (c *dingtalkChannel) Type() channel.Type { return TypeDingTalk }
func (c *dingtalkChannel) Capabilities() channel.Capability {
@@ -71,13 +84,24 @@ func (c *dingtalkChannel) Disconnect(ctx context.Context) error {
// 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) {
+ go func() {
+ <-c.dispatch.done
+ c.releaseClosedDispatchSlot()
+ }()
return fmt.Errorf("dingtalk: dispatcher drain: %w", ctx.Err())
}
+ c.releaseClosedDispatchSlot()
return nil
}
+func (c *dingtalkChannel) releaseClosedDispatchSlot() {
+ c.slot.current.CompareAndSwap(c, nil)
+ if c.releaseDispatchSlot != nil {
+ c.releaseDispatchSlot()
+ }
+}
+
// 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.
@@ -125,8 +149,7 @@ func (c *dingtalkChannel) Connect(ctx context.Context) (err error) {
// 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 {
+ if data == nil || data.SenderStaffId == "" {
// 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
@@ -139,13 +162,47 @@ func (c *dingtalkChannel) onMessage(ctx context.Context, data *botCallbackData)
}
return nil
}
- c.dispatch.enqueue(msg.Source.ChatID, msg)
+ job := inboundJob{callback: cloneBotCallbackData(data)}
+ c.dispatch.enqueue(data.ConversationId, job)
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) {
+func cloneBotCallbackData(data *botCallbackData) botCallbackData {
+ cloned := *data
+ cloned.AtUsers = append([]botCallbackAtUser(nil), data.AtUsers...)
+ cloned.Content = append(json.RawMessage(nil), data.Content...)
+ return cloned
+}
+
+// runInbound is the dispatcher's job body. Resolve the current Bot's readable
+// identity before flattening the callback, then hand the normalized message to
+// the shared engine and surface pipeline errors the way the old inline path did.
+func (c *dingtalkChannel) runInbound(ctx context.Context, job inboundJob) {
+ data := &job.callback
+ botName := ""
+ if data.ConversationType == convTypeGroup && data.IsInAtList && c.botNames != nil {
+ resolved, err := c.botNames.resolveCredentials(ctx, credentials{
+ AppKey: c.appKey, AppSecret: c.appSecret, RobotCode: c.robotCode,
+ }, data.ConversationId)
+ if err != nil {
+ if errors.Is(err, errMissingChatManagePermission) {
+ c.logger.DebugContext(ctx, "dingtalk: Bot name unavailable without qyapi_chat_manage",
+ "app_id", c.appID, "conversation_id", data.ConversationId)
+ } else {
+ c.logger.WarnContext(ctx, "dingtalk: could not resolve Bot name before normalization",
+ "error", err, "app_id", c.appID, "conversation_id", data.ConversationId)
+ }
+ } else {
+ botName = resolved
+ }
+ }
+ msg, ok := inboundFromCallbackWithBotName(data, c.appID, botName)
+ if !ok {
+ 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
+ }
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)
@@ -180,11 +237,14 @@ func (c *dingtalkChannel) notifyIssueDispatchError(msg channel.InboundMessage) {
// 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.
+// the Client owns the outbound token cache + transport; BotNames is shared with
+// group-presence discovery so ingest normalization and metadata observe one
+// authoritative identity cache.
type ChannelDeps struct {
- Decrypt Decrypter
- Client *Client
- Logger *slog.Logger
+ Decrypt Decrypter
+ Client *Client
+ BotNames *BotNameResolver
+ Logger *slog.Logger
}
// dispatchSlot keeps one conversation dispatcher alive across the channel
@@ -196,6 +256,62 @@ type dispatchSlot struct {
queue *dispatcher
}
+type dispatchSlotRegistry struct {
+ mu sync.Mutex
+ byAppID map[string]*dispatchSlot
+}
+
+func newDispatchSlotRegistry() *dispatchSlotRegistry {
+ return &dispatchSlotRegistry{byAppID: make(map[string]*dispatchSlot)}
+}
+
+func (r *dispatchSlotRegistry) assign(ch *dingtalkChannel, logger *slog.Logger) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ slot := r.byAppID[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, job inboundJob) {
+ if current := slot.current.Load(); current != nil {
+ current.runInbound(ctx, job)
+ }
+ }, logger)
+ r.byAppID[ch.appID] = slot
+ }
+ slot.current.Store(ch)
+ ch.dispatch = slot.queue
+ ch.slot = slot
+ ch.releaseDispatchSlot = func() { r.release(ch.appID, slot) }
+ slot.mu.Unlock()
+}
+
+func (r *dispatchSlotRegistry) release(appID string, slot *dispatchSlot) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.byAppID[appID] != slot {
+ return
+ }
+ slot.mu.Lock()
+ defer slot.mu.Unlock()
+ if slot.current.Load() == nil && slot.queue.isClosed() {
+ delete(r.byAppID, appID)
+ }
+}
+
+func (r *dispatchSlotRegistry) size() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return len(r.byAppID)
+}
+
// RegisterDingTalk registers the per-installation DingTalk Factory so the
// engine.Supervisor builds + supervises one dingtalkChannel per active
// installation.
@@ -204,6 +320,10 @@ func RegisterDingTalk(reg *channel.Registry, deps ChannelDeps) {
}
func newDingTalkFactory(deps ChannelDeps) channel.Factory {
+ return newDingTalkFactoryWithRegistry(deps, newDispatchSlotRegistry())
+}
+
+func newDingTalkFactoryWithRegistry(deps ChannelDeps, slots *dispatchSlotRegistry) channel.Factory {
logger := deps.Logger
if logger == nil {
logger = slog.Default()
@@ -212,8 +332,6 @@ func newDingTalkFactory(deps ChannelDeps) channel.Factory {
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 {
@@ -232,6 +350,7 @@ func newDingTalkFactory(deps ChannelDeps) channel.Factory {
appKey: ic.AppID,
appSecret: appSecret,
client: dtClient,
+ botNames: deps.BotNames,
handler: cfg.Handler,
logger: logger,
}
@@ -239,29 +358,7 @@ func newDingTalkFactory(deps ChannelDeps) channel.Factory {
// 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()
+ slots.assign(ch, logger)
return ch, nil
}
}
diff --git a/server/internal/integrations/dingtalk/dingtalk_channel_test.go b/server/internal/integrations/dingtalk/dingtalk_channel_test.go
index c64f8b04a6..2fdc37202a 100644
--- a/server/internal/integrations/dingtalk/dingtalk_channel_test.go
+++ b/server/internal/integrations/dingtalk/dingtalk_channel_test.go
@@ -27,7 +27,8 @@ func TestNewDingTalkFactory_DecryptsAndBuilds(t *testing.T) {
AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealed),
})
- factory := newDingTalkFactory(ChannelDeps{Decrypt: box.Open})
+ botNames := NewBotNameResolver(nil, nil)
+ factory := newDingTalkFactory(ChannelDeps{Decrypt: box.Open, BotNames: botNames})
built, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
if err != nil {
t.Fatalf("factory: %v", err)
@@ -42,6 +43,9 @@ func TestNewDingTalkFactory_DecryptsAndBuilds(t *testing.T) {
if dc.appSecret != "plain-secret" {
t.Errorf("app secret = %q, want decrypted plain-secret", dc.appSecret)
}
+ if dc.botNames != botNames {
+ t.Fatal("factory did not wire the shared BotNameResolver into the channel")
+ }
if dc.Type() != TypeDingTalk {
t.Errorf("Type() = %q", dc.Type())
}
@@ -133,6 +137,80 @@ func TestDingTalkChannel_DisconnectClosesOnlyCurrentCancelledGeneration(t *testi
}
}
+func TestDingTalkChannel_DisconnectReleasesClosedDispatcherSlot(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-release",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ slots := newDispatchSlotRegistry()
+ factory := newDingTalkFactoryWithRegistry(ChannelDeps{}, slots)
+ built, err := factory(channel.Config{Type: TypeDingTalk, Raw: cfg, Handler: noopHandler})
+ if err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ if got := slots.size(); got != 1 {
+ t.Fatalf("registered dispatcher slots = %d, want 1", got)
+ }
+
+ c := built.(*dingtalkChannel)
+ c.stopDispatch.Store(true)
+ if err := c.Disconnect(context.Background()); err != nil {
+ t.Fatalf("disconnect: %v", err)
+ }
+ if got := slots.size(); got != 0 {
+ t.Fatalf("registered dispatcher slots after lifecycle stop = %d, want 0", got)
+ }
+}
+
+func TestDingTalkChannel_DisconnectTimeoutReleasesSlotAfterWorkerExits(t *testing.T) {
+ cfg, _ := json.Marshal(installConfig{
+ AppID: "appkey-release-after-timeout",
+ AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret")),
+ })
+ started := make(chan struct{})
+ release := make(chan struct{})
+ slots := newDispatchSlotRegistry()
+ factory := newDingTalkFactoryWithRegistry(ChannelDeps{}, slots)
+ built, err := factory(channel.Config{
+ Type: TypeDingTalk,
+ Raw: cfg,
+ Handler: func(context.Context, channel.InboundMessage) error {
+ close(started)
+ <-release
+ return nil
+ },
+ })
+ if err != nil {
+ t.Fatalf("build: %v", err)
+ }
+ c := built.(*dingtalkChannel)
+ c.dispatch.enqueue("conv-A", dispatchMsg("conv-A", "first"))
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("dispatch worker did not start")
+ }
+
+ c.stopDispatch.Store(true)
+ disconnectCtx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
+ defer cancel()
+ if err := c.Disconnect(disconnectCtx); !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("disconnect error = %v, want deadline exceeded", err)
+ }
+ if got := slots.size(); got != 1 {
+ t.Fatalf("registered dispatcher slots before worker exit = %d, want 1", got)
+ }
+ close(release)
+
+ deadline := time.Now().Add(time.Second)
+ for slots.size() != 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ if got := slots.size(); got != 0 {
+ t.Fatalf("registered dispatcher slots after worker exit = %d, want 0", got)
+ }
+}
+
func TestDingTalkChannel_DisconnectDrainsQueuedMessagesBeforeReplacement(t *testing.T) {
cfg, _ := json.Marshal(installConfig{
AppID: "appkey-drain",
@@ -296,6 +374,70 @@ func TestOnMessage_ReturnsWithoutWaitingForHandler(t *testing.T) {
}
}
+func TestOnMessage_ReturnsBeforeBotNameLookupAndQueuesCallbackSnapshot(t *testing.T) {
+ lookupStarted := make(chan struct{})
+ releaseLookup := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == accessTokenPath {
+ _, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))
+ return
+ }
+ close(lookupStarted)
+ <-releaseLookup
+ _, _ = w.Write([]byte(`{"chatbotInstanceVOList":[{"robotCode":"robot-1","name":"Multica Bot - Local"}]}`))
+ }))
+ defer srv.Close()
+
+ handled := make(chan channel.InboundMessage, 1)
+ client := NewClient(nil, srv.URL)
+ c := &dingtalkChannel{
+ appID: "appkey-1", robotCode: "robot-1", appKey: "appkey-1", appSecret: "secret",
+ client: client, botNames: NewBotNameResolver(client, nil), logger: slog.Default(),
+ handler: func(_ context.Context, msg channel.InboundMessage) error {
+ handled <- msg
+ return nil
+ },
+ }
+ c.dispatch = newDispatcher(c.runInbound, c.logger)
+ data := &botCallbackData{
+ ConversationId: "cid-1", ConversationType: convTypeGroup, IsInAtList: true,
+ SenderStaffId: "staff-1", MsgId: "msg-1", Msgtype: "text",
+ Text: botCallbackText{Content: "@Multica Bot - Local /new inspect this"},
+ }
+ returned := make(chan struct{})
+ go func() {
+ _ = c.onMessage(context.Background(), data)
+ close(returned)
+ }()
+ select {
+ case <-returned:
+ case <-time.After(time.Second):
+ t.Fatal("onMessage waited for Bot-name resolution instead of returning for ACK")
+ }
+ select {
+ case <-lookupStarted:
+ case <-time.After(time.Second):
+ t.Fatal("queued worker did not start Bot-name resolution")
+ }
+
+ // The Stream decoder owns data only for the callback. A queued job must not
+ // retain aliases to mutable slices from that object.
+ data.Text.Content = "mutated after enqueue"
+ data.AtUsers = append(data.AtUsers, botCallbackAtUser{StaffId: "mutated"})
+ data.Content = append(data.Content, []byte("mutated")...)
+ close(releaseLookup)
+
+ select {
+ case msg := <-handled:
+ if msg.Text != "/new inspect this" || msg.CommandText != msg.Text {
+ t.Fatalf("queued callback snapshot normalized to %q/%q", msg.Text, msg.CommandText)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("queued callback was not handled after Bot-name resolution")
+ }
+}
+
// A handler error on a plain chat turn stays silent — only /issue commands
// warrant the dispatch-error notice.
func TestNotifyIssueDispatchError_GatesOnIssueCommand(t *testing.T) {
diff --git a/server/internal/integrations/dingtalk/dispatch.go b/server/internal/integrations/dingtalk/dispatch.go
index 4a6955d91c..463a79ec94 100644
--- a/server/internal/integrations/dingtalk/dispatch.go
+++ b/server/internal/integrations/dingtalk/dispatch.go
@@ -5,8 +5,6 @@ import (
"log/slog"
"sync"
"time"
-
- "github.com/multica-ai/multica/server/internal/integrations/channel"
)
// Tunables for the inbound dispatcher. Remote media resolution is detached by
@@ -42,14 +40,14 @@ const (
// 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)
+ handle func(ctx context.Context, job inboundJob)
logger *slog.Logger
sem chan struct{}
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
- queues map[string][]channel.InboundMessage
+ queues map[string][]inboundJob
active map[string]bool
closed bool
pending int
@@ -58,7 +56,7 @@ type dispatcher struct {
done chan struct{}
}
-func newDispatcher(handle func(ctx context.Context, msg channel.InboundMessage), logger *slog.Logger) *dispatcher {
+func newDispatcher(handle func(ctx context.Context, job inboundJob), logger *slog.Logger) *dispatcher {
if logger == nil {
logger = slog.Default()
}
@@ -69,36 +67,36 @@ func newDispatcher(handle func(ctx context.Context, msg channel.InboundMessage),
sem: make(chan struct{}, maxDispatchWorkers),
ctx: ctx,
cancel: cancel,
- queues: make(map[string][]channel.InboundMessage),
+ queues: make(map[string][]inboundJob),
active: make(map[string]bool),
maxPending: maxDispatchPending,
done: make(chan struct{}),
}
}
-// enqueue appends msg to its conversation's queue and starts a drain worker
+// enqueue appends a raw inbound job 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) {
+func (d *dispatcher) enqueue(convID string, job inboundJob) {
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)
+ "conversation_id", convID, "msg_id", job.callback.MsgId)
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)
+ "conversation_id", convID, "msg_id", job.callback.MsgId)
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)
+ "conversation_id", convID, "msg_id", job.callback.MsgId)
return
}
- d.queues[convID] = append(d.queues[convID], msg)
+ d.queues[convID] = append(d.queues[convID], job)
d.pending++
start := !d.active[convID]
if start {
@@ -133,7 +131,7 @@ func (d *dispatcher) drain(convID string) {
d.mu.Unlock()
return
}
- msg := q[0]
+ job := q[0]
d.queues[convID] = q[1:]
d.mu.Unlock()
@@ -148,7 +146,7 @@ func (d *dispatcher) drain(convID string) {
return
}
ctx, cancel := context.WithTimeout(d.ctx, dispatchJobTimeout)
- d.handle(ctx, msg)
+ d.handle(ctx, job)
cancel()
<-d.sem
d.mu.Lock()
diff --git a/server/internal/integrations/dingtalk/dispatch_test.go b/server/internal/integrations/dingtalk/dispatch_test.go
index 6dd9f5b1ea..53a86f6935 100644
--- a/server/internal/integrations/dingtalk/dispatch_test.go
+++ b/server/internal/integrations/dingtalk/dispatch_test.go
@@ -6,26 +6,25 @@ import (
"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 dispatchMsg(conv, id string) inboundJob {
+ return inboundJob{callback: botCallbackData{
+ ConversationId: conv, ConversationType: convTypeP2P,
+ SenderStaffId: "staff-1", MsgId: id, Msgtype: "text",
+ Text: botCallbackText{Content: "hello"},
+ }}
}
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) {
+ d := newDispatcher(func(_ context.Context, job inboundJob) {
// Jitter so an ordering bug actually reorders.
- time.Sleep(time.Duration(len(msg.MessageID)%3) * time.Millisecond)
+ time.Sleep(time.Duration(len(job.callback.MsgId)%3) * time.Millisecond)
mu.Lock()
- got = append(got, msg.MessageID)
+ got = append(got, job.callback.MsgId)
mu.Unlock()
done <- struct{}{}
}, nil)
@@ -55,8 +54,8 @@ func TestDispatcher_SerialPerConversation(t *testing.T) {
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 {
+ d := newDispatcher(func(_ context.Context, job inboundJob) {
+ switch job.callback.ConversationId {
case "conv-A":
<-blockA
case "conv-B":
@@ -80,7 +79,7 @@ func TestDispatcher_OverflowDrops(t *testing.T) {
release := make(chan struct{})
var handled int
var mu sync.Mutex
- d := newDispatcher(func(_ context.Context, _ channel.InboundMessage) {
+ d := newDispatcher(func(_ context.Context, _ inboundJob) {
<-release
mu.Lock()
handled++
@@ -116,9 +115,9 @@ func TestDispatcher_OverflowDrops(t *testing.T) {
func TestDispatcher_GlobalPendingLimitBoundsDistinctConversations(t *testing.T) {
release := make(chan struct{})
done := make(chan string, 3)
- d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ d := newDispatcher(func(_ context.Context, job inboundJob) {
<-release
- done <- msg.MessageID
+ done <- job.callback.MsgId
}, nil)
d.maxPending = 2
@@ -168,8 +167,8 @@ func TestDispatcher_GlobalPendingLimitBoundsDistinctConversations(t *testing.T)
func TestDispatcher_WorkerExitsAndRestarts(t *testing.T) {
done := make(chan string, 2)
- d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
- done <- msg.MessageID
+ d := newDispatcher(func(_ context.Context, job inboundJob) {
+ done <- job.callback.MsgId
}, nil)
d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
@@ -198,10 +197,10 @@ func TestDispatcher_DrainAndCloseFinishesAcceptedJobsAndRejectsNewOnes(t *testin
release := make(chan struct{})
started := make(chan struct{}, 1)
done := make(chan string, 2)
- d := newDispatcher(func(_ context.Context, msg channel.InboundMessage) {
+ d := newDispatcher(func(_ context.Context, job inboundJob) {
started <- struct{}{}
<-release
- done <- msg.MessageID
+ done <- job.callback.MsgId
}, nil)
d.enqueue("conv-A", dispatchMsg("conv-A", "first"))
@@ -257,7 +256,7 @@ func TestDispatcher_DrainAndCloseFinishesAcceptedJobsAndRejectsNewOnes(t *testin
func TestDispatcher_CloseDeadlineCancelsInFlightJob(t *testing.T) {
started := make(chan struct{})
cancelled := make(chan struct{})
- d := newDispatcher(func(ctx context.Context, _ channel.InboundMessage) {
+ d := newDispatcher(func(ctx context.Context, _ inboundJob) {
close(started)
<-ctx.Done()
close(cancelled)
diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.go
index aec58b9d55..fc585f839b 100644
--- a/server/internal/integrations/dingtalk/inbound.go
+++ b/server/internal/integrations/dingtalk/inbound.go
@@ -3,6 +3,8 @@ package dingtalk
import (
"encoding/json"
"strings"
+ "unicode"
+ "unicode/utf8"
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
@@ -20,20 +22,27 @@ import (
// reads; DingTalk sends more, which we ignore. Replaces the vendor SDK's
// chatbot.BotCallbackDataModel.
type botCallbackData struct {
- ConversationId string `json:"conversationId"`
- ConversationTitle string `json:"conversationTitle"`
- ConversationType string `json:"conversationType"`
- SenderStaffId string `json:"senderStaffId"`
- MsgId string `json:"msgId"`
- Msgtype string `json:"msgtype"`
- IsInAtList bool `json:"isInAtList"`
- Text botCallbackText `json:"text"`
+ ConversationId string `json:"conversationId"`
+ ConversationTitle string `json:"conversationTitle"`
+ ConversationType string `json:"conversationType"`
+ AtUsers []botCallbackAtUser `json:"atUsers"`
+ ChatbotUserId string `json:"chatbotUserId"`
+ 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 botCallbackAtUser struct {
+ DingtalkId string `json:"dingtalkId"`
+ StaffId string `json:"staffId"`
+}
+
type botCallbackText struct {
Content string `json:"content"`
}
@@ -108,6 +117,14 @@ const (
// 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) {
+ return inboundFromCallbackWithBotName(data, appID, "")
+}
+
+// inboundFromCallbackWithBotName translates one callback using only a Bot name
+// verified for this installation through DingTalk's group Bot list API. An
+// empty name is deliberately fail-closed: the adapter preserves every visible
+// mention rather than guessing its span from whitespace.
+func inboundFromCallbackWithBotName(data *botCallbackData, appID, botName string) (channel.InboundMessage, bool) {
if data == nil {
return channel.InboundMessage{}, false
}
@@ -135,7 +152,7 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
switch data.Msgtype {
case "text":
msg.Type = channel.MsgTypeText
- msg.Text = strings.TrimSpace(data.Text.Content)
+ msg.Text = strings.TrimSpace(normalizeDingTalkBotMention(data, data.Text.Content, botName))
msg.CommandText = msg.Text
return withDingTalkRaw(msg, rawEvent), true
@@ -164,6 +181,7 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
// identity-gated feedback rather than a silent adapter drop.
return mediaUnreadableMsg(msg, rawEvent), true
}
+ normalizeDingTalkRichTextBotMention(data, rc.RichText, botName)
var (
text strings.Builder
commandText strings.Builder
@@ -196,7 +214,7 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
}
msg.Text = strings.TrimSpace(text.String())
msg.CommandText = strings.TrimSpace(commandText.String())
- normalizeDingTalkRichTextFreshLayout(&msg, rc.RichText, len(rawEvent.Media) > 0)
+ normalizeDingTalkRichTextControlLayout(&msg, rc.RichText, len(rawEvent.Media) > 0)
return withDingTalkRaw(msg, rawEvent), true
case "audio":
@@ -216,15 +234,14 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
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) {
+// normalizeDingTalkRichTextControlLayout strips either session-control
+// directive from the visible rich-text body before the shared Router handles
+// it, preserving interleaved image placeholders that Router cannot reconstruct
+// from CommandText. The original command source remains available to Router;
+// the adapter never applies /new route rotation or reclassifies a remainder.
+func normalizeDingTalkRichTextControlLayout(msg *channel.InboundMessage, items []richTextItem, hasMedia bool) {
+ control, ok := engine.ParseControlCommand(msg.CommandText)
+ if !ok || (control.Body == "" && !hasMedia) {
return
}
@@ -238,13 +255,15 @@ func normalizeDingTalkRichTextFreshLayout(msg *channel.InboundMessage, items []r
if firstText < 0 {
return
}
- firstBody, ok := engine.ParseFreshSessionCommand(items[firstText].Text)
- if !ok {
+ firstControl, ok := engine.ParseControlCommand(items[firstText].Text)
+ if !ok || firstControl.Kind != control.Kind {
return
}
- msg.ForceFresh = true
- items[firstText].Text = firstBody
+ if control.Kind == engine.ControlCommandFreshSession {
+ msg.ForceFresh = true
+ }
+ items[firstText].Text = firstControl.Body
var visible strings.Builder
for _, item := range items {
visible.WriteString(item.Text)
@@ -256,13 +275,111 @@ func normalizeDingTalkRichTextFreshLayout(msg *channel.InboundMessage, items []r
}
}
msg.Text = strings.TrimSpace(visible.String())
- if body == "" {
- // A media-bearing `/new` is a real turn, not the shared bare-command
+ if control.Kind == engine.ControlCommandFreshSession && control.Body == "" {
+ // A media-bearing `/clear` is a real turn, not the shared bare-command
// sentinel. ForceFresh carries the already-consumed directive.
msg.CommandText = msg.Text
}
}
+// normalizeDingTalkRichTextBotMention removes the bot-addressing envelope from
+// whichever text run contains it. DingTalk can place that run before or after
+// media and independently from the run containing a control command.
+func normalizeDingTalkRichTextBotMention(data *botCallbackData, items []richTextItem, botName string) {
+ runs := make([]string, len(items))
+ for i := range items {
+ runs[i] = items[i].Text
+ }
+ removeDingTalkBotMention(data, runs, botName)
+ for i := range items {
+ items[i].Text = runs[i]
+ }
+}
+
+// normalizeDingTalkBotMention removes the bot-addressing token wherever it
+// appears in a plain-text message.
+func normalizeDingTalkBotMention(data *botCallbackData, text, botName string) string {
+ runs := []string{text}
+ removeDingTalkBotMention(data, runs, botName)
+ return runs[0]
+}
+
+type dingTalkMentionSpan struct {
+ run int
+ start, end int
+}
+
+func removeDingTalkBotMention(data *botCallbackData, runs []string, botName string) {
+ botName = strings.TrimSpace(botName)
+ if data == nil || data.ConversationType != convTypeGroup || !data.IsInAtList || botName == "" {
+ return
+ }
+ mentions := exactDingTalkBotMentionSpans(runs, botName)
+ for i := len(mentions) - 1; i >= 0; i-- {
+ span := mentions[i]
+ prefix := runs[span.run][:span.start]
+ suffix := runs[span.run][span.end:]
+ switch {
+ case strings.TrimSpace(prefix) == "":
+ prefix = ""
+ suffix = trimLeftHorizontalSpace(suffix)
+ case strings.TrimSpace(suffix) == "":
+ prefix = trimRightHorizontalSpace(prefix)
+ suffix = ""
+ default:
+ suffix = trimLeftHorizontalSpace(suffix)
+ }
+ runs[span.run] = prefix + suffix
+ }
+}
+
+func exactDingTalkBotMentionSpans(runs []string, botName string) []dingTalkMentionSpan {
+ literal := "@" + botName
+ var spans []dingTalkMentionSpan
+ for run, text := range runs {
+ for offset := 0; offset < len(text); {
+ relative := strings.Index(text[offset:], literal)
+ if relative < 0 {
+ break
+ }
+ start := offset + relative
+ end := start + len(literal)
+ if dingTalkMentionLeftBoundary(text[:start]) && dingTalkMentionRightBoundary(text[end:]) {
+ spans = append(spans, dingTalkMentionSpan{run: run, start: start, end: end})
+ }
+ offset = end
+ }
+ }
+ return spans
+}
+
+func dingTalkMentionLeftBoundary(prefix string) bool {
+ if prefix == "" {
+ return true
+ }
+ r, _ := utf8.DecodeLastRuneInString(prefix)
+ return unicode.IsSpace(r)
+}
+
+func dingTalkMentionRightBoundary(suffix string) bool {
+ if suffix == "" {
+ return true
+ }
+ r, _ := utf8.DecodeRuneInString(suffix)
+ // DingTalk supplies no mention span. Only whitespace/end can prove that the
+ // verified full name ended here; punctuation may itself extend another
+ // display name (for example "Bot-DEV"), so fail closed on it.
+ return unicode.IsSpace(r)
+}
+
+func trimLeftHorizontalSpace(value string) string {
+ return strings.TrimLeft(value, " \t\u3000")
+}
+
+func trimRightHorizontalSpace(value string) string {
+ return strings.TrimRight(value, " \t\u3000")
+}
+
func withDingTalkRaw(msg channel.InboundMessage, rawEvent dingtalkRawEvent) channel.InboundMessage {
msg.Raw, _ = json.Marshal(rawEvent)
return msg
diff --git a/server/internal/integrations/dingtalk/inbound_bot_name_test.go b/server/internal/integrations/dingtalk/inbound_bot_name_test.go
new file mode 100644
index 0000000000..79b11a1f7f
--- /dev/null
+++ b/server/internal/integrations/dingtalk/inbound_bot_name_test.go
@@ -0,0 +1,316 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+const verifiedTestBotName = "Multica Bot - Local"
+
+func TestInboundFromCallbackWithBotName_PlainTextRemovesOnlyVerifiedBot(t *testing.T) {
+ tests := []struct {
+ name string
+ content string
+ want string
+ wantCommand bool
+ }{
+ {
+ name: "bot before chat",
+ content: "@Multica Bot - Local /new inspect this",
+ want: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "bot after chat",
+ content: "/new @Multica Bot - Local inspect this",
+ want: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "bot after body",
+ content: "/new inspect this @Multica Bot - Local",
+ want: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "repeated bot mentions",
+ content: "@Multica Bot - Local @Multica Bot - Local /new inspect this",
+ want: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "other mention before bot",
+ content: "@Alice @Multica Bot - Local /new inspect this",
+ want: "@Alice /new inspect this",
+ wantCommand: false,
+ },
+ {
+ name: "other mention after command",
+ content: "@Multica Bot - Local /new inspect this with @Alice",
+ want: "/new inspect this with @Alice",
+ wantCommand: true,
+ },
+ {
+ name: "different bot preserved",
+ content: "@Multica Bot - DEV @Multica Bot - Local /new inspect this",
+ want: "@Multica Bot - DEV /new inspect this",
+ wantCommand: false,
+ },
+ {
+ name: "longer name preserved",
+ content: "@Multica Bot - Locality /new inspect this",
+ want: "@Multica Bot - Locality /new inspect this",
+ wantCommand: false,
+ },
+ {
+ name: "punctuation-extended name preserved",
+ content: "@Multica Bot - Local-DEV /new inspect this",
+ want: "@Multica Bot - Local-DEV /new inspect this",
+ wantCommand: false,
+ },
+ {
+ name: "embedded literal preserved",
+ content: "quote@Multica Bot - Local /new inspect this",
+ want: "quote@Multica Bot - Local /new inspect this",
+ wantCommand: false,
+ },
+ {
+ name: "mid sentence command stays prose",
+ content: "@Multica Bot - Local please /new later",
+ want: "please /new later",
+ wantCommand: false,
+ },
+ {
+ name: "blank line before command",
+ content: "@Multica Bot - Local\n\n/new inspect this",
+ want: "/new inspect this",
+ wantCommand: true,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.Text.Content = tc.content
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", verifiedTestBotName)
+ if !ok {
+ t.Fatal("expected addressed group text")
+ }
+ if msg.Text != tc.want || msg.CommandText != tc.want {
+ t.Fatalf("normalized text/command = %q/%q, want %q", msg.Text, msg.CommandText, tc.want)
+ }
+ _, command := engine.ParseNewChatCommand(msg.CommandText)
+ if command != tc.wantCommand {
+ t.Fatalf("ParseNewChatCommand(%q) = %v, want %v", msg.CommandText, command, tc.wantCommand)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallbackWithBotName_RichTextPreservesMediaAndOtherMentions(t *testing.T) {
+ tests := []struct {
+ name string
+ content string
+ wantText string
+ wantCommandText string
+ wantCommand bool
+ }{
+ {
+ name: "image bot command text",
+ content: `{"richText":[
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"@Multica Bot - Local /new inspect this"}
+ ]}`,
+ wantText: "[Image]\ninspect this",
+ wantCommandText: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "bot image command text image",
+ content: `{"richText":[
+ {"text":"@Multica Bot - Local "},
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"/new inspect this"},
+ {"type":"picture","downloadCode":"dl-2"}
+ ]}`,
+ wantText: "[Image]\ninspect this\n[Image]",
+ wantCommandText: "/new inspect this",
+ wantCommand: true,
+ },
+ {
+ name: "command keeps colleague mention",
+ content: `{"richText":[
+ {"text":"@Multica Bot - Local /new ask @Alice"},
+ {"type":"picture","downloadCode":"dl-1"}
+ ]}`,
+ wantText: "ask @Alice\n[Image]",
+ wantCommandText: "/new ask @Alice",
+ wantCommand: true,
+ },
+ {
+ name: "colleague before command remains anchor",
+ content: `{"richText":[
+ {"text":"@Alice @Multica Bot - Local /new inspect this"},
+ {"type":"picture","downloadCode":"dl-1"}
+ ]}`,
+ wantText: "@Alice /new inspect this\n[Image]",
+ wantCommandText: "@Alice /new inspect this",
+ wantCommand: false,
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(tc.content)
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", verifiedTestBotName)
+ if !ok {
+ t.Fatal("expected addressed group richText")
+ }
+ if msg.Text != tc.wantText || msg.CommandText != tc.wantCommandText {
+ t.Fatalf("normalized text/command = %q/%q, want %q/%q", msg.Text, msg.CommandText, tc.wantText, tc.wantCommandText)
+ }
+ _, command := engine.ParseNewChatCommand(msg.CommandText)
+ if command != tc.wantCommand {
+ t.Fatalf("ParseNewChatCommand(%q) = %v, want %v", msg.CommandText, command, tc.wantCommand)
+ }
+ if got := strings.Count(msg.Text, "[Image]"); got != strings.Count(tc.wantText, "[Image]") {
+ t.Fatalf("image placeholder count = %d in %q", got, msg.Text)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallbackWithBotName_FailClosedWithoutVerifiedName(t *testing.T) {
+ tests := []struct {
+ name string
+ msgtype string
+ text string
+ content string
+ want string
+ command bool
+ }{
+ {
+ name: "plain single-token bot before command",
+ text: "@YYClaw /new inspect this",
+ want: "@YYClaw /new inspect this",
+ },
+ {
+ name: "plain multiword bot before command",
+ text: "@Multica Bot - Local /new inspect this",
+ want: "@Multica Bot - Local /new inspect this",
+ },
+ {
+ name: "plain callback without visible bot",
+ text: "/new inspect this",
+ want: "/new inspect this",
+ command: true,
+ },
+ {
+ name: "plain command before unknown bot",
+ text: "/new inspect this @Multica Bot - Local",
+ want: "/new inspect this @Multica Bot - Local",
+ command: true,
+ },
+ {
+ name: "rich text preserves unknown bot",
+ msgtype: "richText",
+ content: `{"richText":[{"text":"@Multica Bot - Local /new inspect this"}]}`,
+ want: "@Multica Bot - Local /new inspect this",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ if tc.msgtype == "richText" {
+ cb.Msgtype = tc.msgtype
+ cb.Content = json.RawMessage(tc.content)
+ } else {
+ cb.Text.Content = tc.text
+ }
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", "")
+ if !ok || msg.Text != tc.want || msg.CommandText != tc.want {
+ t.Fatalf("permissionless normalization: ok=%v text/command=%q/%q, want %q", ok, msg.Text, msg.CommandText, tc.want)
+ }
+ _, command := engine.ParseNewChatCommand(msg.CommandText)
+ if command != tc.command {
+ t.Fatalf("permissionless command classification = %v for %q, want %v", command, msg.CommandText, tc.command)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallbackWithBotName_DoesNotStripPrivateOrUnaddressedText(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ convType string
+ atBot bool
+ }{
+ {name: "private", convType: convTypeP2P, atBot: false},
+ {name: "unaddressed group", convType: convTypeGroup, atBot: false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(tc.convType, tc.atBot)
+ cb.Text.Content = "@Multica Bot - Local /new inspect this"
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", verifiedTestBotName)
+ if !ok || msg.Text != cb.Text.Content {
+ t.Fatalf("non-addressing text changed: ok=%v text=%q", ok, msg.Text)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallbackWithBotName_AllSharedCommandsKeepFirstTextLineContract(t *testing.T) {
+ tests := []struct {
+ name string
+ content string
+ parse func(string) bool
+ }{
+ {
+ name: "chat",
+ content: "@Multica Bot - Local /new inspect this",
+ parse: func(body string) bool {
+ _, ok := engine.ParseNewChatCommand(body)
+ return ok
+ },
+ },
+ {
+ name: "new",
+ content: "@Multica Bot - Local /clear inspect this",
+ parse: func(body string) bool {
+ _, ok := engine.ParseFreshSessionCommand(body)
+ return ok
+ },
+ },
+ {
+ name: "issue",
+ content: "@Multica Bot - Local /issue login failed",
+ parse: func(body string) bool {
+ _, ok := engine.ParseIssueCommand(body)
+ return ok
+ },
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.Text.Content = tc.content
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", verifiedTestBotName)
+ if !ok || !tc.parse(msg.CommandText) {
+ t.Fatalf("normalized %s command was not recognized: ok=%v CommandText=%q", tc.name, ok, msg.CommandText)
+ }
+
+ cb.Text.Content = "@Multica Bot - Local please " + strings.TrimPrefix(tc.content, "@Multica Bot - Local ")
+ msg, ok = inboundFromCallbackWithBotName(cb, "appkey-A", verifiedTestBotName)
+ if !ok || tc.parse(msg.CommandText) {
+ t.Fatalf("mid-sentence %s was promoted: ok=%v CommandText=%q", tc.name, ok, msg.CommandText)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.go
index d92a10a452..96ff8cd9e6 100644
--- a/server/internal/integrations/dingtalk/inbound_test.go
+++ b/server/internal/integrations/dingtalk/inbound_test.go
@@ -53,30 +53,30 @@ func TestInboundFromCallback_GroupAddressing(t *testing.T) {
func TestInboundFromCallback_LeavesFreshCommandForSharedRouter(t *testing.T) {
cb := textCallback(convTypeP2P, false)
- cb.Text.Content = " /new start over "
+ cb.Text.Content = " /clear start over "
msg, ok := inboundFromCallback(cb, "appkey-A")
if !ok {
- t.Fatal("expected /new message")
+ t.Fatal("expected /clear 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)
+ if msg.Text != "/clear start over" || msg.CommandText != msg.Text || msg.ForceFresh {
+ t.Fatalf("DingTalk must leave /clear classification to the shared Router: %+v", msg)
}
}
func TestInboundFromCallback_BareFreshStaysForSharedPendingPath(t *testing.T) {
cb := textCallback(convTypeP2P, false)
- cb.Text.Content = " /new "
+ cb.Text.Content = " /clear "
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)
+ if !ok || msg.Text != "/clear" || msg.CommandText != "/clear" || msg.ForceFresh {
+ t.Fatalf("bare /clear 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"
+ cb.Text.Content = "/clear /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 {
+ if !ok || msg.ForceFresh || msg.Text != "/clear /issue calculate 1+2" || msg.CommandText != msg.Text {
t.Fatalf("combined commands must remain untouched for shared classification: ok=%v msg=%+v", ok, msg)
}
}
@@ -124,14 +124,14 @@ func TestInboundFromCallback_RichTextTracksGeneratedMarkersPastUserPlaceholders(
cb := textCallback(convTypeP2P, false)
cb.Msgtype = "richText"
cb.Content = json.RawMessage(`{"richText":[
- {"text":"/new Use [Image] literally"},
+ {"text":"/clear Use [Image] literally"},
{"type":"picture","downloadCode":"dl-1"},
{"text":" and another [Image] literally"},
{"type":"picture","downloadCode":"dl-2"}
]}`)
msg, ok := inboundFromCallback(cb, "appkey-A")
- if !ok || !msg.ForceFresh || strings.Contains(msg.Text, "/new") {
- t.Fatalf("expected normalized richText /new message: ok=%v msg=%+v", ok, msg)
+ if !ok || !msg.ForceFresh || strings.Contains(msg.Text, "/clear") {
+ t.Fatalf("expected normalized richText /clear message: ok=%v msg=%+v", ok, msg)
}
raw, err := decodeDingTalkRaw(msg)
if err != nil || len(raw.Media) != 2 {
@@ -147,23 +147,161 @@ func TestInboundFromCallback_RichTextDoesNotPrivatelyComposeFreshAndIssue(t *tes
cb.Msgtype = "richText"
cb.Content = json.RawMessage(`{"richText":[
{"type":"picture","downloadCode":"dl-1"},
- {"text":"/new /issue inspect image"}
+ {"text":"/clear /issue inspect image"}
]}`)
msg, ok := inboundFromCallback(cb, "appkey-A")
- if !ok || !msg.ForceFresh || msg.CommandText != "/new /issue inspect image" {
+ if !ok || !msg.ForceFresh || msg.CommandText != "/clear /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)
+ if !strings.Contains(msg.Text, "[Image]") || strings.Contains(msg.Text, "/clear") || !strings.Contains(msg.Text, "/issue inspect image") {
+ t.Fatalf("rich-text visible body lost media or /clear layout stripping: %q", msg.Text)
+ }
+}
+
+func TestInboundFromCallback_GroupRichTextBotMentionControlWithMedia(t *testing.T) {
+ for _, tc := range []struct {
+ command string
+ content string
+ atUsers []botCallbackAtUser
+ wantCommandText string
+ wantText string
+ wantFresh bool
+ }{
+ {
+ command: "/clear", content: `{"richText":[
+ {"text":"@YYClaw /clear"},
+ {"type":"picture","downloadCode":"dl-1"}
+ ]}`, wantCommandText: "[Image]", wantText: "[Image]", wantFresh: true,
+ },
+ {
+ command: "/new image after", content: `{"richText":[
+ {"text":"@YYClaw /new 测试图片在后"},
+ {"type":"picture","downloadCode":"dl-1"}
+ ]}`, wantCommandText: "/new 测试图片在后", wantText: "测试图片在后\n[Image]", wantFresh: false,
+ },
+ {
+ command: "/new image before", content: `{"richText":[
+ {"text":"@YYClaw "},
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"/new 测试图片在前"}
+ ]}`,
+ atUsers: []botCallbackAtUser{
+ {DingtalkId: "$:someone-else"},
+ {DingtalkId: "$:LW]bot-user"},
+ },
+ wantCommandText: "/new 测试图片在前", wantText: "[Image]\n测试图片在前", wantFresh: false,
+ },
+ } {
+ t.Run(tc.command, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.Msgtype = "richText"
+ // DingTalk's isInAtList is authoritative. atUsers may be absent or
+ // contain opaque ids that cannot be compared with chatbotUserId.
+ cb.ChatbotUserId = "$:LWCP_v1:bot-user"
+ cb.AtUsers = tc.atUsers
+ cb.Content = json.RawMessage(tc.content)
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", "YYClaw")
+ if !ok {
+ t.Fatal("expected group richText message")
+ }
+ if msg.CommandText != tc.wantCommandText {
+ t.Fatalf("bot addressing must be removed before shared command parsing: %q", msg.CommandText)
+ }
+ if msg.Text != tc.wantText {
+ t.Fatalf("visible body must remove bot mention and %s while preserving media: got %q want %q", tc.command, msg.Text, tc.wantText)
+ }
+ if msg.ForceFresh != tc.wantFresh {
+ t.Fatalf("ForceFresh = %v, want %v", msg.ForceFresh, tc.wantFresh)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallback_P2PRichTextChatAfterImageStripsDirective(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":"/new\n点评一下"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok {
+ t.Fatal("expected p2p richText message")
+ }
+ if msg.CommandText != "/new\n点评一下" {
+ t.Fatalf("shared router must retain the original control source: %q", msg.CommandText)
+ }
+ if msg.Text != "[Image]\n点评一下" {
+ t.Fatalf("visible body must strip /new without moving the image: %q", msg.Text)
+ }
+ if msg.ForceFresh {
+ t.Fatal("/new must not be represented as /clear's ForceFresh semantic")
+ }
+}
+
+func TestInboundFromCallback_GroupTextBotMentionUsesSameControlNormalization(t *testing.T) {
+ for _, tc := range []struct {
+ name, content, want string
+ }{
+ {name: "before command", content: " @YYClaw /new start clean", want: "/new start clean"},
+ {name: "after command", content: "/new @YYClaw start clean", want: "/new start clean"},
+ {name: "after body", content: "/new start clean @YYClaw", want: "/new start clean"},
+ {name: "fresh command", content: "/clear @YYClaw start clean", want: "/clear start clean"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.ChatbotUserId = "$:LWCP_v1:bot-user"
+ cb.AtUsers = []botCallbackAtUser{{DingtalkId: "$:LW]bot-user"}}
+ cb.Text.Content = tc.content
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", "YYClaw")
+ if !ok || msg.Text != tc.want || msg.CommandText != tc.want {
+ t.Fatalf("%s group addressing normalization: ok=%v msg=%+v", tc.name, ok, msg)
+ }
+ })
+ }
+}
+
+func TestInboundFromCallback_DoesNotPromoteMidSentenceControlCommand(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.ChatbotUserId = "$:bot-user"
+ cb.AtUsers = []botCallbackAtUser{{DingtalkId: "$:bot-user"}}
+ cb.Text.Content = "@YYClaw please /new later"
+ msg, ok := inboundFromCallbackWithBotName(cb, "appkey-A", "YYClaw")
+ if !ok || msg.Text != "please /new later" || msg.CommandText != msg.Text {
+ t.Fatalf("a mid-sentence command must remain prose: ok=%v msg=%+v", ok, msg)
+ }
+}
+
+func TestInboundFromCallback_DoesNotStripUnaddressedLeadingMention(t *testing.T) {
+ cb := textCallback(convTypeGroup, false)
+ cb.ChatbotUserId = "$:LWCP_v1:bot-user"
+ cb.AtUsers = []botCallbackAtUser{{DingtalkId: "$:someone-else"}}
+ cb.Text.Content = "@Alice /new discuss this"
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.Text != "@Alice /new discuss this" || msg.CommandText != msg.Text {
+ t.Fatalf("an unverified colleague mention must remain untouched: ok=%v msg=%+v", ok, msg)
+ }
+}
+
+func TestInboundFromCallback_DoesNotGuessAmongMultipleVisibleMentions(t *testing.T) {
+ cb := textCallback(convTypeGroup, true)
+ cb.AtUsers = []botCallbackAtUser{
+ {DingtalkId: "$:someone-else", StaffId: "alice"},
+ {DingtalkId: "$:LW]bot-user"},
+ }
+ cb.Text.Content = "/new @Alice discuss this with @YYClaw"
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || msg.Text != cb.Text.Content || msg.CommandText != msg.Text {
+ t.Fatalf("ambiguous visible mentions must remain untouched: ok=%v msg=%+v", ok, msg)
}
}
func TestInboundFromCallback_RichTextBareFreshWithoutMediaStaysForSharedPendingPath(t *testing.T) {
cb := textCallback(convTypeP2P, false)
cb.Msgtype = "richText"
- cb.Content = json.RawMessage(`{"richText":[{"text":" /new "}]}`)
+ cb.Content = json.RawMessage(`{"richText":[{"text":" /clear "}]}`)
msg, ok := inboundFromCallback(cb, "appkey-A")
- if !ok || msg.ForceFresh || msg.Text != "/new" || msg.CommandText != "/new" {
+ if !ok || msg.ForceFresh || msg.Text != "/clear" || msg.CommandText != "/clear" {
t.Fatalf("text-only bare fresh = %+v, ok=%v", msg, ok)
}
}
@@ -172,7 +310,7 @@ func TestInboundFromCallback_RichTextBareFreshWithMediaPreservesMediaTurn(t *tes
cb := textCallback(convTypeP2P, false)
cb.Msgtype = "richText"
cb.Content = json.RawMessage(`{"richText":[
- {"text":"/new"},
+ {"text":"/clear"},
{"type":"picture","downloadCode":"dl-1"}
]}`)
msg, ok := inboundFromCallback(cb, "appkey-A")
@@ -185,11 +323,11 @@ func TestInboundFromCallback_RichTextRunsDoNotCreatePrivateCommandComposition(t
cb := textCallback(convTypeP2P, false)
cb.Msgtype = "richText"
cb.Content = json.RawMessage(`{"richText":[
- {"text":"/new"},
+ {"text":"/clear"},
{"text":"/issue split title"}
]}`)
msg, ok := inboundFromCallback(cb, "appkey-A")
- if !ok || msg.ForceFresh || msg.Text != "/new/issue split title" || msg.CommandText != msg.Text {
+ if !ok || msg.ForceFresh || msg.Text != "/clear/issue split title" || msg.CommandText != msg.Text {
t.Fatalf("split rich-text runs must remain ordinary text: %+v, ok=%v", msg, ok)
}
}
diff --git a/server/internal/integrations/dingtalk/outbound.go b/server/internal/integrations/dingtalk/outbound.go
index a9b0602408..e12c79bac1 100644
--- a/server/internal/integrations/dingtalk/outbound.go
+++ b/server/internal/integrations/dingtalk/outbound.go
@@ -21,7 +21,7 @@ import (
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)
+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
}
@@ -80,16 +80,17 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
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),
- })
+ delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- return nil // not a DingTalk session (Feishu / Slack / web-only)
+ return nil // direct Multica task or violated snapshot invariant: fail closed
}
- return fmt.Errorf("lookup dingtalk chat binding: %w", err)
+ return fmt.Errorf("lookup dingtalk task delivery: %w", err)
+ }
+ if delivery.ChannelType != string(TypeDingTalk) {
+ return nil
}
+ binding := bindingFromTaskDelivery(delivery)
task, err := o.q.GetAgentTask(ctx, taskID)
if err != nil {
return fmt.Errorf("load agent task: %w", err)
@@ -122,6 +123,16 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return nil
}
+func bindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {
+ return db.ChannelChatSessionBinding{
+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,
+ ChannelType: delivery.ChannelType, ChannelChatID: delivery.ChannelChatID,
+ ChatType: delivery.ChatType,
+ LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,
+ RouteRevision: delivery.RouteRevision, Config: delivery.Config,
+ }
+}
+
// 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.
diff --git a/server/internal/integrations/dingtalk/outbound_test.go b/server/internal/integrations/dingtalk/outbound_test.go
index c0039dc7bc..fbe11bd0e1 100644
--- a/server/internal/integrations/dingtalk/outbound_test.go
+++ b/server/internal/integrations/dingtalk/outbound_test.go
@@ -1,12 +1,44 @@
package dingtalk
import (
+ "context"
"testing"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
"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"
)
+type noDeliveryOutboundQueries struct{}
+
+func (noDeliveryOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ return db.ChannelTaskDelivery{}, pgx.ErrNoRows
+}
+func (noDeliveryOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
+ panic("GetAgentTask must not run without a task delivery snapshot")
+}
+func (noDeliveryOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pgtype.UUID) (bool, error) {
+ panic("TaskHasChannelIngestedMessages must not run without a task delivery snapshot")
+}
+func (noDeliveryOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
+ panic("GetChannelInstallation must not run without a task delivery snapshot")
+}
+
+func TestOutboundFailsClosedWithoutTaskDeliverySnapshot(t *testing.T) {
+ o := NewOutbound(noDeliveryOutboundQueries{}, nil, nil, nil)
+ event := events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: "11111111-1111-1111-1111-111111111111",
+ ChatSessionID: "22222222-2222-2222-2222-222222222222",
+ Payload: protocol.ChatDonePayload{Content: "must stay in Multica"},
+ }
+ if err := o.processEvent(context.Background(), event); err != nil {
+ t.Fatalf("processEvent: %v", err)
+ }
+}
+
func TestEventContent(t *testing.T) {
cases := []struct {
name string
diff --git a/server/internal/integrations/dingtalk/replier.go b/server/internal/integrations/dingtalk/replier.go
index 3af655f809..c648fa99e9 100644
--- a/server/internal/integrations/dingtalk/replier.go
+++ b/server/internal/integrations/dingtalk/replier.go
@@ -34,6 +34,7 @@ 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."
freshPendingText = "✅ Fresh start ready. Your next chat message will run without previous context."
+ chatStartedText = "✅ Started a new Multica chat. Your next message will enter it."
issueUsageText = "Please include an issue title. Use:\n\n`/issue <title>`\n\n`[description]` (optional)"
issueUsageWithMediaText = "Please add a title and resend with the image (*image can come before or after the command*):\n\n`/issue <title>`\n\n`[description]` (optional)"
// Refusals for dropped /issue commands, carried over from the deleted
@@ -128,6 +129,10 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
r.logger.WarnContext(ctx, "dingtalk replier: fresh-start confirmation failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
+ case engine.OutcomeChatStarted:
+ if err := r.post(ctx, inst, msg, chatStartedText); err != nil {
+ r.logger.WarnContext(ctx, "dingtalk replier: new-chat confirmation failed", "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
case engine.OutcomeIssueUsage:
text := issueUsageText
if res.IssueUsageHadMedia {
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index b5eb111e79..e87b03a317 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -238,6 +238,7 @@ func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messa
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
@@ -319,6 +320,53 @@ func (o *groupPresenceObserver) RecordActivity(ctx context.Context, installation
return err
}
+func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ bindingKey, config := dingtalkSessionRouting(p.Message)
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ if err != nil {
+ return engine.StartSessionResult{}, err
+ }
+ if err := r.groupPresence.Observe(ctx, p.Installation, p.Message); err != nil {
+ logger := slog.Default()
+ if r.groupPresence != nil && r.groupPresence.logger != nil {
+ logger = r.groupPresence.logger
+ }
+ logger.WarnContext(ctx, "dingtalk: could not record group presence",
+ "installation_id", p.Installation.ID,
+ "conversation_id", p.Message.Source.ChatID,
+ "error", err,
+ )
+ }
+ if p.PersistMessage {
+ if err := r.groupPresence.RecordActivity(ctx, p.Installation.ID, p.Message); err != nil {
+ logger := slog.Default()
+ if r.groupPresence != nil && r.groupPresence.logger != nil {
+ logger = r.groupPresence.logger
+ }
+ logger.WarnContext(ctx, "dingtalk: could not record group activity",
+ "installation_id", p.Installation.ID,
+ "conversation_id", p.Message.Source.ChatID,
+ "error", err,
+ )
+ }
+ }
+ return engine.StartSessionResult{
+ SessionID: result.SessionID, BindingID: result.BindingID,
+ RouteRevision: result.RouteRevision, Append: result.Append,
+ }, nil
+}
+
type sessionBinder struct {
session chatSession
groupPresence *groupPresenceObserver
@@ -395,8 +443,8 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
return result, nil
}
-func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ in := engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
@@ -406,7 +454,13 @@ func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams)
IssueCommandText: p.IssueCommandText,
Body: p.Body,
MediaRefs: p.MediaRefs,
- })
+ }
+ if richer, ok := r.session.(interface {
+ BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
+ }); ok {
+ return richer.BindMediaRefsWithResult(ctx, in)
+ }
+ return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}
// ---- audit ----
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index db04548360..3182c270d1 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -49,6 +49,7 @@ type captureChatSession struct {
ensure engine.EnsureSessionInput
ensureCalls int
ensureErr error
+ start engine.StartSessionInput
append engine.AppendInput
appendErr error
media engine.BindMediaInput
@@ -59,6 +60,10 @@ func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSe
c.ensureCalls++
return pgtype.UUID{}, c.ensureErr
}
+func (c *captureChatSession) StartSession(_ context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {
+ c.start = in
+ return engine.StartSessionResult{}, c.ensureErr
+}
func (c *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID, string) error { return nil }
func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
c.append = in
@@ -140,6 +145,35 @@ func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {
}
}
+func TestSessionBinder_StartSessionCarriesDingTalkRouteAndFirstTurn(t *testing.T) {
+ capture := &captureChatSession{}
+ binder := &sessionBinder{session: capture}
+ _, err := binder.StartSession(context.Background(), engine.StartSessionParams{
+ Installation: engine.ResolvedInstallation{
+ ID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},
+ WorkspaceID: pgtype.UUID{Bytes: [16]byte{2}, Valid: true},
+ AgentID: pgtype.UUID{Bytes: [16]byte{3}, Valid: true},
+ },
+ Creator: pgtype.UUID{Bytes: [16]byte{4}, Valid: true},
+ Sender: pgtype.UUID{Bytes: [16]byte{5}, Valid: true},
+ Message: channel.InboundMessage{
+ MessageID: "m1", Text: "first turn",
+ Source: channel.Source{ChatID: "cid-platform", ChatType: channel.ChatTypeGroup, ThreadID: "thread-1"},
+ },
+ PersistMessage: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ got := capture.start
+ if got.BindingKey != "cid-platform" || got.MessageID != "m1" || got.ThreadID != "thread-1" || got.Body != "first turn" || !got.PersistMessage {
+ t.Fatalf("start mapping wrong: %+v", got)
+ }
+ if got.Sender != (pgtype.UUID{Bytes: [16]byte{4}, Valid: true}) || got.Initiator != (pgtype.UUID{Bytes: [16]byte{5}, Valid: true}) {
+ t.Fatalf("creator/initiator mapping wrong: %+v", got)
+ }
+}
+
func TestSessionBinder_GroupUsesInstallationDefaultAgent(t *testing.T) {
installationID := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}
workspaceID := pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
@@ -319,7 +353,7 @@ func TestSessionBinder_MapsMediaBodyAndIssueTarget(t *testing.T) {
base := pgtype.Text{String: "[Image]\nfix login", Valid: true}
capture := &captureChatSession{}
binder := &sessionBinder{session: capture}
- if err := binder.BindMedia(context.Background(), engine.BindMediaParams{
+ if _, err := binder.BindMedia(context.Background(), engine.BindMediaParams{
MessageID: message, SessionID: session, WorkspaceID: workspace, Sender: sender,
IssueID: issue, IssueDescriptionBase: base, IssueCommandText: "/issue fix login", Body: "[Image]\nfix login", MediaRefs: []channel.MediaRef{ref},
}); err != nil {
diff --git a/server/internal/integrations/lark/channel_store.go b/server/internal/integrations/lark/channel_store.go
index 9274d794ef..6012418ce7 100644
--- a/server/internal/integrations/lark/channel_store.go
+++ b/server/internal/integrations/lark/channel_store.go
@@ -294,11 +294,19 @@ func (s *ChannelStore) GetLarkChatSessionBindingBySession(ctx context.Context, c
return chatSessionBindingFromRow(row), nil
}
+func (s *ChannelStore) GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ return s.Queries.GetChannelTaskDelivery(ctx, taskID)
+}
+
+func (s *ChannelStore) GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
+ return s.Queries.GetChannelChatSessionBindingBySession(ctx, arg)
+}
+
func (s *ChannelStore) UpdateLarkChatSessionBindingReplyTarget(ctx context.Context, arg UpdateChatSessionBindingReplyTargetParams) error {
return s.Queries.UpdateChannelChatSessionBindingReplyTarget(ctx, db.UpdateChannelChatSessionBindingReplyTargetParams{
- ChatSessionID: arg.ChatSessionID,
- LastMessageID: arg.LastMessageID,
- LastThreadID: arg.LastThreadID,
+ ReplyChatSessionID: arg.ChatSessionID,
+ LastMessageID: arg.LastMessageID,
+ LastThreadID: arg.LastThreadID,
})
}
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 774228d0f1..09a563637a 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -159,11 +159,29 @@ func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID,
// unit-tested with a fake; *engine.ChatSession is the production value.
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
+func (r *feishuSessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ bindingKey, config := larkSessionRouting(p.Message)
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{SessionID: result.SessionID, BindingID: result.BindingID, RouteRevision: result.RouteRevision, Append: result.Append}, err
+}
+
type feishuSessionBinder struct{ session chatSession }
// larkBindingConfig is the opaque outbound routing persisted on the chat
@@ -226,8 +244,8 @@ func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.Append
})
}
-func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ in := engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
@@ -237,7 +255,13 @@ func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaP
IssueCommandText: p.IssueCommandText,
Body: p.Body,
MediaRefs: p.MediaRefs,
- })
+ }
+ if richer, ok := r.session.(interface {
+ BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
+ }); ok {
+ return richer.BindMediaRefsWithResult(ctx, in)
+ }
+ return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}
// ---- audit ----
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index 3aa131ac1b..e11353105c 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -5,10 +5,12 @@ import (
"encoding/json"
"testing"
+ "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"
)
func binderUUID(b byte) pgtype.UUID {
@@ -22,10 +24,16 @@ func binderUUID(b byte) pgtype.UUID {
// engine.ChatSession, so the (platform-specific) mapping is unit-tested.
type fakeChatSession struct {
ensureIn engine.EnsureSessionInput
+ startIn engine.StartSessionInput
appendIn engine.AppendInput
mediaIn engine.BindMediaInput
}
+func (f *fakeChatSession) StartSession(_ context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {
+ f.startIn = in
+ return engine.StartSessionResult{SessionID: binderUUID(43)}, nil
+}
+
func (f *fakeChatSession) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
f.ensureIn = in
return binderUUID(42), nil
@@ -97,6 +105,43 @@ func TestFeishuSessionBinder_TopicMessageIsolatesByThread(t *testing.T) {
}
}
+func TestFeishuSessionBinder_StartSessionMapping(t *testing.T) {
+ f := &fakeChatSession{}
+ b := &feishuSessionBinder{session: f}
+ beforeCommit := func(context.Context, pgx.Tx, db.ChatSession) error { return nil }
+
+ result, err := b.StartSession(context.Background(), engine.StartSessionParams{
+ Installation: engine.ResolvedInstallation{ID: binderUUID(1), WorkspaceID: binderUUID(2), AgentID: binderUUID(3)},
+ Creator: binderUUID(6),
+ Sender: binderUUID(7),
+ ClaimToken: binderUUID(9),
+ Message: channel.InboundMessage{
+ MessageID: "om_1", Text: "first turn",
+ Source: channel.Source{ChatID: "oc_chat", ChatType: channel.ChatTypeGroup, ThreadID: "omt_topic1"},
+ },
+ MediaPendingSeconds: 45,
+ PersistMessage: true,
+ HistoryBoundaryPending: true,
+ BeforeCommit: beforeCommit,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if result.SessionID != binderUUID(43) {
+ t.Fatalf("SessionID = %+v, want shared-session result", result.SessionID)
+ }
+ got := f.startIn
+ if got.BindingKey != "oc_chat:omt_topic1" || got.ThreadID != "omt_topic1" || got.Body != "first turn" || got.MessageID != "om_1" {
+ t.Fatalf("start route/message mapping wrong: %+v", got)
+ }
+ if got.Sender != binderUUID(6) || got.Initiator != binderUUID(7) {
+ t.Fatalf("creator/initiator mapping wrong: %+v", got)
+ }
+ if got.ClaimToken != binderUUID(9) || got.MediaPendingSeconds != 45 || !got.PersistMessage || !got.HistoryBoundaryPending || got.BeforeCommit == nil {
+ t.Fatalf("start transaction mapping wrong: %+v", got)
+ }
+}
+
// TestLarkSessionRouting unit-tests the pure key-derivation contract.
func TestLarkSessionRouting(t *testing.T) {
cases := []struct {
@@ -163,7 +208,7 @@ func TestFeishuSessionBinder_BindMediaMapping(t *testing.T) {
f := &fakeChatSession{}
b := &feishuSessionBinder{session: f}
ref := channel.MediaRef{Type: channel.MsgTypeImage, StorageURL: "https://cdn.example.test/image.png"}
- if err := b.BindMedia(context.Background(), engine.BindMediaParams{
+ if _, err := b.BindMedia(context.Background(), engine.BindMediaParams{
MessageID: binderUUID(4),
SessionID: binderUUID(1),
WorkspaceID: binderUUID(2),
diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.go
index 3d81f6e097..3e0169ffc6 100644
--- a/server/internal/integrations/lark/feishu_types.go
+++ b/server/internal/integrations/lark/feishu_types.go
@@ -72,8 +72,9 @@ const (
OutcomeNeedsBinding Outcome = "needs_binding"
// OutcomeIngested — the message landed and a run was (or will be) enqueued.
OutcomeIngested Outcome = "ingested"
- // OutcomeFreshPending — a bare /new was persisted for the next chat turn.
+ // OutcomeFreshPending — a bare /clear was persisted for the next chat turn.
OutcomeFreshPending Outcome = "fresh_pending"
+ OutcomeChatStarted Outcome = "chat_started"
// OutcomeIssueUsage — /issue was sent without its required title.
OutcomeIssueUsage Outcome = "issue_usage"
// OutcomeAgentOffline — landed, but the agent has no runtime bound.
diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.go
index 03593d6c39..e3b5a3b36f 100644
--- a/server/internal/integrations/lark/inbound_enricher.go
+++ b/server/internal/integrations/lark/inbound_enricher.go
@@ -152,13 +152,22 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds
if freshSource == "" {
freshSource = msg.Body
}
- if body, ok := engine.ParseFreshSessionCommand(freshSource); ok {
- msg.ForceFreshSession = true
- msg.Body = body
+ startChat := false
+ if control, ok := engine.ParseControlCommand(freshSource); ok {
+ msg.Body = control.Body
+ switch control.Kind {
+ case engine.ControlCommandFreshSession:
+ msg.ForceFreshSession = true
+ case engine.ControlCommandNewChat:
+ // A new Chat must not inherit adapter-generated recent context from
+ // the route's previous Chat. Explicit quote/forward context is still
+ // expanded below because the user attached it to this command.
+ startChat = true
+ }
}
isForward := msg.MessageType == larkMsgTypeMergeForward
- wantRecent := e.recentContextSize > 0 && msg.ChatType == ChatTypeGroup && msg.AddressedToBot
+ wantRecent := !startChat && e.recentContextSize > 0 && msg.ChatType == ChatTypeGroup && msg.AddressedToBot
if msg.ParentID == "" && !isForward && !wantRecent {
// Nothing to expand and no group prefetch wanted — no network call.
return msg
diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.go
index 158b31e4d5..461d2f3d64 100644
--- a/server/internal/integrations/lark/inbound_enricher_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_test.go
@@ -185,19 +185,19 @@ func TestEnrichFreshSessionStripsCommandAndSetsFlag(t *testing.T) {
fake := newEnricherFake()
in := InboundMessage{
MessageType: "text",
- Body: "/new rebuild the plan",
- CommandBody: "/new rebuild the plan",
+ Body: "/clear rebuild the plan",
+ CommandBody: "/clear rebuild the plan",
}
out := enrich(t, fake, in, InboundEnricherConfig{})
if !out.ForceFreshSession {
- t.Fatalf("ForceFreshSession should be true for /new")
+ t.Fatalf("ForceFreshSession should be true for /clear")
}
if out.Body != "rebuild the plan" {
t.Fatalf("Body should have directive stripped; got %q", out.Body)
}
- if out.CommandBody != "/new rebuild the plan" {
+ if out.CommandBody != "/clear rebuild the plan" {
t.Fatalf("CommandBody should remain the original command source; got %q", out.CommandBody)
}
}
@@ -211,15 +211,15 @@ func TestEnrichFreshSessionPreservesQuotedContext(t *testing.T) {
in := InboundMessage{
MessageType: "text",
MessageID: "om_child",
- Body: "/new handle this independently",
- CommandBody: "/new handle this independently",
+ Body: "/clear handle this independently",
+ CommandBody: "/clear handle this independently",
ParentID: "om_parent",
}
out := enrich(t, fake, in, InboundEnricherConfig{})
if !out.ForceFreshSession {
- t.Fatalf("ForceFreshSession should be true for /new")
+ t.Fatalf("ForceFreshSession should be true for /clear")
}
if !strings.Contains(out.Body, `<quoted_message message_id="om_parent"`) {
t.Fatalf("quoted context should be preserved; body=%q", out.Body)
@@ -227,11 +227,65 @@ func TestEnrichFreshSessionPreservesQuotedContext(t *testing.T) {
if !strings.HasSuffix(out.Body, "handle this independently") {
t.Fatalf("directive should be stripped from user prose; body=%q", out.Body)
}
- if strings.Contains(out.Body, "/new") {
+ if strings.Contains(out.Body, "/clear") {
t.Fatalf("stored/enriched body should not include the directive; body=%q", out.Body)
}
}
+func TestEnrichNewChatExcludesAutomaticRecentContext(t *testing.T) {
+ t.Parallel()
+
+ fake := newEnricherFake()
+ fake.byChat["oc_group"] = []LarkMessage{textMsg("om_old", "ou_old", "previous chat context", "1")}
+ in := InboundMessage{
+ Body: "/new start clean",
+ CommandBody: "/new start clean",
+ ChatID: "oc_group",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ MessageType: "text",
+ MessageID: "om_trigger",
+ }
+
+ out := enrich(t, fake, in, InboundEnricherConfig{RecentContextSize: 10})
+
+ if out.Body != "start clean" {
+ t.Fatalf("Body = %q, want only the new Chat message", out.Body)
+ }
+ if len(fake.listCalls) != 0 {
+ t.Fatalf("recent-context list calls = %d, want 0", len(fake.listCalls))
+ }
+}
+
+func TestEnrichNewChatPreservesExplicitQuotedContext(t *testing.T) {
+ t.Parallel()
+
+ fake := newEnricherFake()
+ fake.byID["om_parent"] = []LarkMessage{textMsg("om_parent", "ou_parent", "explicit context", "1")}
+ in := InboundMessage{
+ Body: "/new answer this",
+ CommandBody: "/new answer this",
+ ChatID: "oc_group",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ParentID: "om_parent",
+ }
+
+ out := enrich(t, fake, in, InboundEnricherConfig{RecentContextSize: 10})
+
+ if !strings.Contains(out.Body, "explicit context") || !strings.Contains(out.Body, "answer this") {
+ t.Fatalf("Body = %q, want quoted context and command body", out.Body)
+ }
+ if strings.Contains(out.Body, "<recent_context") {
+ t.Fatalf("Body = %q, must not contain automatic recent context", out.Body)
+ }
+ if len(fake.listCalls) != 0 {
+ t.Fatalf("recent-context list calls = %d, want 0", len(fake.listCalls))
+ }
+}
+
// TestEnrichMergeForwardSortsByCreateTime ensures children are ordered
// chronologically regardless of the order Lark returns them.
func TestEnrichMergeForwardSortsByCreateTime(t *testing.T) {
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index f4c87fb70c..8dc525e5c0 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -144,6 +144,7 @@ func (defaultRenderer) Render(in RenderInput) (CardRender, error) {
type PatcherQueries interface {
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)
GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error)
GetLarkInstallation(ctx context.Context, id pgtype.UUID) (Installation, error)
@@ -339,13 +340,21 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
return nil
}
- binding, err := p.queries.GetLarkChatSessionBindingBySession(ctx, chatSessionID)
+ delivery, err := p.queries.GetChannelTaskDelivery(ctx, taskID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- // Web-only chat session — not a Lark target.
+ // Direct Multica task or violated snapshot invariant — fail closed.
return nil
}
- return fmt.Errorf("lookup chat session binding: %w", err)
+ return fmt.Errorf("lookup lark task delivery: %w", err)
+ }
+ if delivery.ChannelType != channelTypeFeishu {
+ return nil
+ }
+ binding := ChatSessionBinding{
+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,
+ ChannelChatID: delivery.ChannelChatID, ChatType: delivery.ChatType, Config: delivery.Config,
+ LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,
}
// Only bound sessions reach here, so classify the task origin before
diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.go
index 35cde911d9..4efb6a523f 100644
--- a/server/internal/integrations/lark/outbound_test.go
+++ b/server/internal/integrations/lark/outbound_test.go
@@ -23,6 +23,8 @@ type fakePatcherQueries struct {
taskChannelIngested bool
binding ChatSessionBinding
bindingErr error
+ delivery db.ChannelTaskDelivery
+ deliveryErr error
installation Installation
installationErr error
agent db.Agent
@@ -40,6 +42,21 @@ func (f *fakePatcherQueries) GetAgentTask(ctx context.Context, id pgtype.UUID) (
func (f *fakePatcherQueries) TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error) {
return f.taskChannelIngested, nil
}
+func (f *fakePatcherQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ if f.bindingErr != nil {
+ return db.ChannelTaskDelivery{}, f.bindingErr
+ }
+ if f.delivery.ChannelType == "" && f.binding.InstallationID.Valid {
+ return db.ChannelTaskDelivery{
+ BindingID: f.binding.ID, InstallationID: f.binding.InstallationID,
+ ChannelType: channelTypeFeishu, ChannelChatID: f.binding.ChannelChatID,
+ ChatType: f.binding.ChatType,
+ ChannelMessageID: f.binding.LastMessageID, ChannelThreadID: f.binding.LastThreadID,
+ Config: f.binding.Config,
+ }, f.deliveryErr
+ }
+ return f.delivery, f.deliveryErr
+}
func (f *fakePatcherQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {
return db.ChatSession{}, nil
}
diff --git a/server/internal/integrations/lark/outcome_replier.go b/server/internal/integrations/lark/outcome_replier.go
index ff163df000..4ba0035755 100644
--- a/server/internal/integrations/lark/outcome_replier.go
+++ b/server/internal/integrations/lark/outcome_replier.go
@@ -52,7 +52,7 @@ type noopReplier struct {
func (n *noopReplier) Reply(ctx context.Context, inst Installation, msg InboundMessage, res DispatchResult) {
switch res.Outcome {
- case OutcomeNeedsBinding, OutcomeAgentOffline, OutcomeAgentArchived, OutcomeFreshPending, OutcomeIssueUsage:
+ case OutcomeNeedsBinding, OutcomeAgentOffline, OutcomeAgentArchived, OutcomeFreshPending, OutcomeChatStarted, OutcomeIssueUsage:
n.log.Warn("lark outcome replier: outbound reply skipped (replier not wired)",
"outcome", string(res.Outcome),
"installation_id", uuidString(inst.ID),
@@ -187,6 +187,10 @@ func (r *LarkOutcomeReplier) Reply(ctx context.Context, inst Installation, msg I
"err", err.Error(),
)
}
+ case OutcomeChatStarted:
+ if err := r.sendChatNotice(ctx, inst, msg, chatStartedCopy); err != nil {
+ r.log.Warn("lark outcome replier: new-chat confirmation failed", "installation_id", uuidString(inst.ID), "chat_id", string(msg.ChatID), "err", err.Error())
+ }
case OutcomeIssueUsage:
copy := issueUsageCopy
if res.IssueUsageHadMedia {
@@ -409,7 +413,8 @@ func renderNoticeCard(header, body string) (string, error) {
const (
agentOfflineCopy = "Agent 当前离线,消息已记录。下次 daemon 上线后会自动继续处理。"
agentArchivedCopy = "这个 Agent 已被归档,无法继续处理消息。请联系工作区管理员恢复或重新绑定。"
- freshPendingCopy = "✅ 已准备开始新对话。你的下一条聊天消息将不带之前的上下文运行。"
+ freshPendingCopy = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"
+ chatStartedCopy = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"
issueUsageCopy = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"
issueUsageWithMediaCopy = "请添加标题,并与图片或视频一起重新发送(*图片或视频可以位于命令之前或之后*):\n\n`/issue <标题>`\n`[描述]`(可选)"
)
diff --git a/server/internal/integrations/slack/channel.go b/server/internal/integrations/slack/channel.go
index cd314670ee..f48c55ca46 100644
--- a/server/internal/integrations/slack/channel.go
+++ b/server/internal/integrations/slack/channel.go
@@ -6,9 +6,11 @@ import (
"fmt"
"log/slog"
+ "github.com/jackc/pgx/v5/pgtype"
"github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/util"
)
// TypeSlack is the channel discriminator for the Slack adapter. It is defined
@@ -37,6 +39,14 @@ type slackSender struct {
// SendResult carries every posted chunk timestamp and keeps MessageID as the
// timestamp of the last chunk for existing callers.
func (c *slackSender) Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+ return c.send(ctx, out, slack.SlackMetadata{})
+}
+
+func (c *slackSender) SendWithMetadata(ctx context.Context, out channel.OutboundMessage, metadata slack.SlackMetadata) (channel.SendResult, error) {
+ return c.send(ctx, out, metadata)
+}
+
+func (c *slackSender) send(ctx context.Context, out channel.OutboundMessage, metadata slack.SlackMetadata) (channel.SendResult, error) {
if c.api == nil {
return channel.SendResult{}, errors.New("slack: api client not configured")
}
@@ -50,6 +60,9 @@ func (c *slackSender) Send(ctx context.Context, out channel.OutboundMessage) (ch
slack.MsgOptionText(chunk, false),
slack.MsgOptionDisableLinkUnfurl(),
}
+ if metadata.EventType != "" {
+ opts = append(opts, slack.MsgOptionMetadata(metadata))
+ }
if threadTS != "" {
opts = append(opts, slack.MsgOptionTS(threadTS))
}
@@ -63,6 +76,14 @@ func (c *slackSender) Send(ctx context.Context, out channel.OutboundMessage) (ch
return channel.SendResult{MessageID: lastTS, MessageIDs: messageIDs}, nil
}
+const slackOutboundMetadataEvent = "multica_channel_outbound"
+
+func outboundMetadata(bindingID pgtype.UUID, routeRevision int64, kind string) slack.SlackMetadata {
+ return slack.SlackMetadata{EventType: slackOutboundMetadataEvent, EventPayload: map[string]any{
+ "binding_id": util.UUIDToString(bindingID), "route_revision": routeRevision, "kind": kind,
+ }}
+}
+
// newSlackSender builds a Send-only client from decoded credentials and a
// configured API client. Kept separate from the outbound subscriber so tests
// can inject a client pointed at an httptest server.
diff --git a/server/internal/integrations/slack/channel_test.go b/server/internal/integrations/slack/channel_test.go
index 10ff4f3995..251b19ffd9 100644
--- a/server/internal/integrations/slack/channel_test.go
+++ b/server/internal/integrations/slack/channel_test.go
@@ -2,6 +2,7 @@ package slack
import (
"context"
+ "encoding/json"
"net/http"
"net/http/httptest"
"net/url"
@@ -29,6 +30,29 @@ func TestChunkMessage(t *testing.T) {
}
}
+func TestSendWithMetadataTagsEverySlackMessage(t *testing.T) {
+ var gotForm url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _ = r.ParseForm()
+ gotForm = r.PostForm
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"ok":true,"channel":"C123","ts":"1.1"}`))
+ }))
+ defer srv.Close()
+ c := newSlackSender(credentials{TeamID: "T1"}, slack.New("xoxb-test", slack.OptionAPIURL(srv.URL+"/")), nil)
+ metadata := outboundMetadata(uid(3), 2, "control_ack")
+ if _, err := c.SendWithMetadata(context.Background(), channel.OutboundMessage{ChatID: "C123", Text: "started"}, metadata); err != nil {
+ t.Fatalf("SendWithMetadata: %v", err)
+ }
+ var got slack.SlackMetadata
+ if err := json.Unmarshal([]byte(gotForm.Get("metadata")), &got); err != nil {
+ t.Fatalf("decode metadata %q: %v", gotForm.Get("metadata"), err)
+ }
+ if got.EventType != slackOutboundMetadataEvent || got.EventPayload["kind"] != "control_ack" {
+ t.Fatalf("metadata=%+v", got)
+ }
+}
+
func TestSend(t *testing.T) {
var gotForm url.Values
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/integrations/slack/history.go b/server/internal/integrations/slack/history.go
index c13664155e..9a7ce147d8 100644
--- a/server/internal/integrations/slack/history.go
+++ b/server/internal/integrations/slack/history.go
@@ -16,6 +16,7 @@ import (
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -38,6 +39,7 @@ type historyQueries interface {
GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
ListChannelOutboundMessageIDsForContext(ctx context.Context, arg db.ListChannelOutboundMessageIDsForContextParams) ([]string, error)
+ ListChannelOutboundMessagesByIDs(ctx context.Context, arg db.ListChannelOutboundMessagesByIDsParams) ([]db.ChannelOutboundMessage, error)
}
// historyClient is the slice of the slack-go Web API the reader calls. The real
@@ -79,11 +81,15 @@ func NewHistory(q historyQueries, decrypt Decrypter, logger *slog.Logger) *Histo
// slackTarget is the resolved per-session read context: a bot-token client plus
// the session's pinned channel and its own thread root.
type slackTarget struct {
- client historyClient
- installationID pgtype.UUID
- channelID string
- threadRoot string // the session's own thread (empty for a DM)
- botUserID string
+ client historyClient
+ installationID pgtype.UUID
+ bindingID pgtype.UUID
+ channelID string
+ threadRoot string // the session's own thread (empty for a DM)
+ botUserID string
+ historyStart string
+ historyEnd string
+ boundaryPending bool
}
// resolve maps a chat_session to its Slack channel + bot client. The channel is
@@ -117,11 +123,15 @@ func (h *History) resolve(ctx context.Context, chatSessionID pgtype.UUID) (slack
}
channelID, threadRoot := historyTarget(binding)
return slackTarget{
- client: h.newClient(creds.BotToken),
- installationID: binding.InstallationID,
- channelID: channelID,
- threadRoot: threadRoot,
- botUserID: creds.BotUserID,
+ client: h.newClient(creds.BotToken),
+ installationID: binding.InstallationID,
+ bindingID: binding.ID,
+ channelID: channelID,
+ threadRoot: threadRoot,
+ botUserID: creds.BotUserID,
+ historyStart: binding.HistoryStartMessageID.String,
+ historyEnd: binding.HistoryEndMessageID.String,
+ boundaryPending: binding.HistoryBoundaryPending,
}, nil
}
@@ -134,27 +144,33 @@ func (h *History) ChannelOverview(ctx context.Context, chatSessionID pgtype.UUID
if err != nil {
return channel.HistoryPage{}, err
}
- if opts.BoundaryPending || historyCursorReachedStart(opts.Before, opts.After) {
+ start, end := historyBounds(opts, t)
+ if opts.BoundaryPending || t.boundaryPending || historyCursorReachedStart(opts.Before, start) {
return channel.HistoryPage{ChannelType: string(TypeSlack)}, nil
}
limit := clampHistoryLimit(opts.Limit)
- latest, oldest, inclusive := historyWindow(opts)
+ latest, oldest, inclusive := historyWindow(opts.Before, start, end)
resp, err := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
- ChannelID: t.channelID,
- Latest: latest,
- Oldest: oldest,
- Inclusive: inclusive,
- Limit: limit,
+ ChannelID: t.channelID,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
+ Limit: limit,
+ IncludeAllMetadata: true,
})
if err != nil {
return channel.HistoryPage{}, fmt.Errorf("read slack channel: %w", err)
}
- nextCursor := historyNextCursor(resp.Messages, limit)
- allowedBotMessages, err := h.allowedBotMessages(ctx, chatSessionID, t, opts, resp.Messages)
+ nextCursor := historyNextCursor(resp.Messages, limit, start)
+ raw, err := h.filterRouteGeneration(ctx, t, resp.Messages, start, end)
if err != nil {
return channel.HistoryPage{}, err
}
- raw := filterHistoryWindow(resp.Messages, opts, t.botUserID, allowedBotMessages)
+ allowedBotMessages, err := h.allowedBotMessages(ctx, chatSessionID, t, opts, raw)
+ if err != nil {
+ return channel.HistoryPage{}, err
+ }
+ raw = filterContextGeneration(raw, opts, start, end, t.botUserID, allowedBotMessages)
page := normalizePage(ctx, t.client, h.logger, raw, t.botUserID, limit, true)
page.NextCursor = nextCursor
page.ChannelType = string(TypeSlack)
@@ -175,7 +191,8 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
if ts == "" {
ts = t.threadRoot // the session's own thread
}
- if opts.BoundaryPending {
+ start, end := historyBounds(opts, t)
+ if opts.BoundaryPending || t.boundaryPending {
return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
}
@@ -183,45 +200,51 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
if ts == "" {
// No thread to read (a DM, or a group whose root could not be recovered):
// fall back to the channel's linear conversation.
- if historyCursorReachedStart(opts.Before, opts.After) {
+ if historyCursorReachedStart(opts.Before, start) {
return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
}
- latest, oldest, inclusive := historyWindow(opts)
+ latest, oldest, inclusive := historyWindow(opts.Before, start, end)
resp, herr := t.client.GetConversationHistoryContext(ctx, &slack.GetConversationHistoryParameters{
- ChannelID: t.channelID,
- Latest: latest,
- Oldest: oldest,
- Inclusive: inclusive,
- Limit: limit,
+ ChannelID: t.channelID,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
+ Limit: limit,
+ IncludeAllMetadata: true,
})
if herr != nil {
return channel.HistoryPage{}, fmt.Errorf("read slack thread: %w", herr)
}
raw = resp.Messages
} else {
- if historyCursorReachedStart(opts.Before, opts.After) {
+ if historyCursorReachedStart(opts.Before, start) {
return channel.HistoryPage{ChannelType: string(TypeSlack), ThreadID: ts}, nil
}
- latest, oldest, inclusive := historyWindow(opts)
+ latest, oldest, inclusive := historyWindow(opts.Before, start, end)
msgs, _, _, rerr := t.client.GetConversationRepliesContext(ctx, &slack.GetConversationRepliesParameters{
- ChannelID: t.channelID,
- Timestamp: ts,
- Latest: latest,
- Oldest: oldest,
- Inclusive: inclusive,
- Limit: limit,
+ ChannelID: t.channelID,
+ Timestamp: ts,
+ Latest: latest,
+ Oldest: oldest,
+ Inclusive: inclusive,
+ Limit: limit,
+ IncludeAllMetadata: true,
})
if rerr != nil {
return channel.HistoryPage{}, fmt.Errorf("read slack thread: %w", rerr)
}
raw = msgs
}
- nextCursor := historyNextCursor(raw, limit)
+ nextCursor := historyNextCursor(raw, limit, start)
+ raw, err = h.filterRouteGeneration(ctx, t, raw, start, end)
+ if err != nil {
+ return channel.HistoryPage{}, err
+ }
allowedBotMessages, err := h.allowedBotMessages(ctx, chatSessionID, t, opts, raw)
if err != nil {
return channel.HistoryPage{}, err
}
- raw = filterHistoryWindow(raw, opts, t.botUserID, allowedBotMessages)
+ raw = filterContextGeneration(raw, opts, start, end, t.botUserID, allowedBotMessages)
page := normalizePage(ctx, t.client, h.logger, raw, t.botUserID, limit, false)
page.NextCursor = nextCursor
page.ChannelType = string(TypeSlack)
@@ -229,13 +252,25 @@ func (h *History) Thread(ctx context.Context, chatSessionID pgtype.UUID, threadI
return page, nil
}
-func historyWindow(opts channel.HistoryOptions) (latest, oldest string, inclusive bool) {
- latest = opts.Before
- if opts.Until != "" && (latest == "" || slackTSLess(opts.Until, latest)) {
- latest = opts.Until
+func historyBounds(opts channel.HistoryOptions, target slackTarget) (start, end string) {
+ start = opts.After
+ if target.historyStart != "" && (start == "" || slackTSLess(start, target.historyStart)) {
+ start = target.historyStart
+ }
+ end = opts.Until
+ if target.historyEnd != "" && (end == "" || slackTSLess(target.historyEnd, end)) {
+ end = target.historyEnd
}
- if opts.Before == "" {
- return latest, opts.After, opts.After != "" || opts.Until != ""
+ return start, end
+}
+
+func historyWindow(before, start, end string) (latest, oldest string, inclusive bool) {
+ latest = before
+ if end != "" && (latest == "" || slackTSLess(end, latest)) {
+ latest = end
+ }
+ if before == "" {
+ return latest, start, start != "" || end != ""
}
return latest, "", false
}
@@ -244,7 +279,7 @@ func historyCursorReachedStart(before, start string) bool {
return before != "" && start != "" && !slackTSLess(start, before)
}
-func historyNextCursor(raw []slack.Message, limit int) string {
+func historyNextCursor(raw []slack.Message, limit int, historyStart string) string {
if len(raw) < limit || len(raw) == 0 {
return ""
}
@@ -254,9 +289,66 @@ func historyNextCursor(raw []slack.Message, limit int) string {
oldest = raw[i].Timestamp
}
}
+ if historyStart != "" && !slackTSLess(historyStart, oldest) {
+ return ""
+ }
return oldest
}
+func (h *History) filterRouteGeneration(ctx context.Context, target slackTarget, raw []slack.Message, start, end string) ([]slack.Message, error) {
+ window := raw[:0]
+ ids := make([]string, 0, len(raw))
+ for _, message := range raw {
+ if start != "" && slackTSLess(message.Timestamp, start) {
+ continue
+ }
+ if end != "" && !slackTSLess(message.Timestamp, end) {
+ continue
+ }
+ window = append(window, message)
+ ids = append(ids, message.Timestamp)
+ }
+ if len(window) == 0 {
+ return window, nil
+ }
+ rows, err := h.q.ListChannelOutboundMessagesByIDs(ctx, db.ListChannelOutboundMessagesByIDsParams{
+ InstallationID: target.installationID, ChannelMessageIds: ids,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("load slack outbound route ledger: %w", err)
+ }
+ owners := make(map[string]db.ChannelOutboundMessage, len(rows))
+ for _, row := range rows {
+ owners[row.ChannelMessageID] = row
+ }
+ result := window[:0]
+ for _, message := range window {
+ if message.Metadata.EventType == slackOutboundMetadataEvent {
+ kind, _ := message.Metadata.EventPayload["kind"].(string)
+ bindingID, _ := message.Metadata.EventPayload["binding_id"].(string)
+ if kind == "control_ack" || (bindingID != "" && bindingID != util.UUIDToString(target.bindingID)) {
+ continue
+ }
+ }
+ if owner, ok := owners[message.Timestamp]; ok {
+ if owner.OutboundKind == "control_ack" || owner.BindingID != target.bindingID {
+ continue
+ }
+ }
+ if message.Timestamp == target.historyStart {
+ text := strings.TrimSpace(strings.ReplaceAll(message.Text, "<@"+target.botUserID+">", ""))
+ if body, command := engine.ParseNewChatCommand(text); command {
+ if body == "" {
+ continue
+ }
+ message.Text = body
+ }
+ }
+ result = append(result, message)
+ }
+ return result, nil
+}
+
func (h *History) allowedBotMessages(ctx context.Context, chatSessionID pgtype.UUID, target slackTarget, opts channel.HistoryOptions, raw []slack.Message) (map[string]struct{}, error) {
if opts.ContextRevision <= 1 {
return nil, nil
@@ -288,17 +380,17 @@ func (h *History) allowedBotMessages(ctx context.Context, chatSessionID pgtype.U
return allowed, nil
}
-func filterHistoryWindow(raw []slack.Message, opts channel.HistoryOptions, botUserID string, allowedBotMessages map[string]struct{}) []slack.Message {
+func filterContextGeneration(raw []slack.Message, opts channel.HistoryOptions, start, end, botUserID string, allowedBotMessages map[string]struct{}) []slack.Message {
out := raw[:0]
for _, message := range raw {
- if opts.After != "" && slackTSLess(message.Timestamp, opts.After) {
+ if start != "" && slackTSLess(message.Timestamp, start) {
continue
}
- if opts.Until != "" && !slackTSLess(message.Timestamp, opts.Until) {
+ if end != "" && !slackTSLess(message.Timestamp, end) {
continue
}
// Slack timestamps alone are not a causal boundary: a reply from an old
- // task may be posted after /new. From generation 2 onward, trust an
+ // task may be posted after /clear. From generation 2 onward, trust an
// assistant message only when its provider id was persisted on a task in
// this exact generation. Human and third-party bot messages still follow
// the provider time window. Unknown own-bot output fails closed for agent
diff --git a/server/internal/integrations/slack/history_route_test.go b/server/internal/integrations/slack/history_route_test.go
new file mode 100644
index 0000000000..b205e1e235
--- /dev/null
+++ b/server/internal/integrations/slack/history_route_test.go
@@ -0,0 +1,120 @@
+package slack
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/slack-go/slack"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestHistoryRouteBoundaryPendingReturnsEmptyWithoutSlackRead(t *testing.T) {
+ binding := dmBinding()
+ binding.HistoryBoundaryPending = true
+ client := &fakeHistoryClient{historyMsgs: []slack.Message{msg("U1", "old", "1.0")}}
+ page, err := newTestHistory(&fakeHistoryQueries{binding: binding, inst: activeSlackInstall()}, client).
+ Thread(context.Background(), uid(1), "", channel.HistoryOptions{})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if client.historyCalls != 0 || len(page.Messages) != 0 {
+ t.Fatalf("calls=%d messages=%v", client.historyCalls, page.Messages)
+ }
+}
+
+func TestHistoryAppliesRouteAndContextIntersection(t *testing.T) {
+ binding := dmBinding()
+ binding.HistoryStartMessageID = pgtype.Text{String: "2.0", Valid: true}
+ binding.HistoryEndMessageID = pgtype.Text{String: "5.0", Valid: true}
+ client := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("U1", "before route", "1.0"), msg("U1", "route start", "2.0"),
+ msg("U1", "context start", "3.0"), msg("U1", "context end", "4.0"),
+ msg("U1", "route end", "5.0"),
+ }}
+ page, err := newTestHistory(&fakeHistoryQueries{binding: binding, inst: activeSlackInstall()}, client).
+ Thread(context.Background(), uid(1), "", channel.HistoryOptions{After: "3.0", Until: "4.0"})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if client.lastHistory.Oldest != "3.0" || client.lastHistory.Latest != "4.0" || !client.lastHistory.Inclusive {
+ t.Fatalf("params=%+v", client.lastHistory)
+ }
+ if len(page.Messages) != 1 || page.Messages[0].TS != "3.0" {
+ t.Fatalf("messages=%+v", page.Messages)
+ }
+}
+
+func TestHistoryNormalizesNewChatBoundaryMessage(t *testing.T) {
+ binding := dmBinding()
+ binding.HistoryStartMessageID = pgtype.Text{String: "2.0", Valid: true}
+ client := &fakeHistoryClient{historyMsgs: []slack.Message{
+ msg("U1", "<@UBOT> /new investigate latency\nwith traces", "2.0"),
+ }}
+ page, err := newTestHistory(&fakeHistoryQueries{binding: binding, inst: activeSlackInstall()}, client).
+ Thread(context.Background(), uid(1), "", channel.HistoryOptions{})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if len(page.Messages) != 1 || page.Messages[0].Text != "investigate latency\nwith traces" {
+ t.Fatalf("boundary message = %+v", page.Messages)
+ }
+}
+
+func TestHistoryFiltersTaggedControlAckAndForeignRoute(t *testing.T) {
+ binding := dmBinding()
+ current := msg("UBOT", "current reply", "3.0")
+ current.Metadata = outboundMetadata(binding.ID, 2, "task_reply")
+ ack := msg("UBOT", "started", "2.5")
+ ack.Metadata = outboundMetadata(binding.ID, 2, "control_ack")
+ foreign := msg("UBOT", "late old reply", "2.0")
+ foreign.Metadata = outboundMetadata(uid(9), 1, "task_reply")
+ client := &fakeHistoryClient{historyMsgs: []slack.Message{current, ack, foreign}}
+ page, err := newTestHistory(&fakeHistoryQueries{binding: binding, inst: activeSlackInstall()}, client).
+ Thread(context.Background(), uid(1), "", channel.HistoryOptions{})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if !client.lastHistory.IncludeAllMetadata {
+ t.Fatal("history read did not request Slack message metadata")
+ }
+ if len(page.Messages) != 1 || page.Messages[0].TS != "3.0" {
+ t.Fatalf("metadata route filter returned %+v", page.Messages)
+ }
+}
+
+func TestHistoryFiltersControlAckFromLedgerWithoutMetadata(t *testing.T) {
+ binding := dmBinding()
+ q := &fakeHistoryQueries{binding: binding, inst: activeSlackInstall(), outbound: []db.ChannelOutboundMessage{{
+ ChannelMessageID: "2.0", BindingID: binding.ID, OutboundKind: "control_ack",
+ }}}
+ client := &fakeHistoryClient{historyMsgs: []slack.Message{msg("UBOT", "started", "2.0"), msg("U1", "hello", "3.0")}}
+ page, err := newTestHistory(q, client).Thread(context.Background(), uid(1), "", channel.HistoryOptions{})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if len(page.Messages) != 1 || page.Messages[0].TS != "3.0" {
+ t.Fatalf("ledger control filter returned %+v", page.Messages)
+ }
+}
+
+func TestHistoryCursorAdvancesWhenFullRawPageIsRouteFiltered(t *testing.T) {
+ binding := dmBinding()
+ filtered := []slack.Message{
+ msg("UBOT", "ack 3", "3.0"), msg("UBOT", "ack 2", "2.0"), msg("UBOT", "ack 1", "1.0"),
+ }
+ for i := range filtered {
+ filtered[i].Metadata = outboundMetadata(binding.ID, 2, "control_ack")
+ }
+ client := &fakeHistoryClient{historyMsgs: filtered}
+ page, err := newTestHistory(&fakeHistoryQueries{binding: binding, inst: activeSlackInstall()}, client).
+ Thread(context.Background(), uid(1), "", channel.HistoryOptions{Limit: 3})
+ if err != nil {
+ t.Fatalf("Thread: %v", err)
+ }
+ if len(page.Messages) != 0 || page.NextCursor != "1.0" {
+ t.Fatalf("filtered page messages=%+v cursor=%q, want empty/1.0", page.Messages, page.NextCursor)
+ }
+}
diff --git a/server/internal/integrations/slack/history_test.go b/server/internal/integrations/slack/history_test.go
index 6d447ecfaa..db2417cedc 100644
--- a/server/internal/integrations/slack/history_test.go
+++ b/server/internal/integrations/slack/history_test.go
@@ -20,6 +20,8 @@ type fakeHistoryQueries struct {
instErr error
messageIDs []string
messageIDsErr error
+ outbound []db.ChannelOutboundMessage
+ outboundErr error
}
func (f *fakeHistoryQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
@@ -34,6 +36,10 @@ func (f *fakeHistoryQueries) ListChannelOutboundMessageIDsForContext(context.Con
return f.messageIDs, f.messageIDsErr
}
+func (f *fakeHistoryQueries) ListChannelOutboundMessagesByIDs(context.Context, db.ListChannelOutboundMessagesByIDsParams) ([]db.ChannelOutboundMessage, error) {
+ return f.outbound, f.outboundErr
+}
+
type fakeHistoryClient struct {
historyMsgs []slack.Message
repliesMsgs []slack.Message
@@ -92,6 +98,7 @@ func groupBinding(threadRoot string) db.ChannelChatSessionBinding {
func dmBinding() db.ChannelChatSessionBinding {
return db.ChannelChatSessionBinding{
+ ID: uid(3),
InstallationID: uid(2),
ChannelChatID: "D1",
ChatType: string(channel.ChatTypeP2P),
@@ -159,7 +166,7 @@ func TestChannelOverviewScopesAndSanitizesFreshGeneration(t *testing.T) {
q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
fc := &fakeHistoryClient{historyMsgs: []slack.Message{
msg("U1", "new reply", "104.000000"),
- msg("U1", "/new current question", "103.000000"),
+ msg("U1", "/clear current question", "103.000000"),
msg("U1", "old context", "102.000000"),
}}
h := newTestHistory(q, fc)
@@ -185,7 +192,7 @@ func TestChannelOverviewExcludesLateReplyFromPreviousGeneration(t *testing.T) {
fc := &fakeHistoryClient{historyMsgs: []slack.Message{
msg("UBOT", "current generation answer", "104.000000"),
msg("UBOT", "late previous generation answer", "103.500000"),
- msg("U1", "/new current question", "103.000000"),
+ msg("U1", "/clear current question", "103.000000"),
}}
h := newTestHistory(q, fc)
page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
@@ -203,7 +210,7 @@ func TestChannelOverviewFailsClosedForUnknownOwnBotReply(t *testing.T) {
q := &fakeHistoryQueries{binding: groupBinding("100.000000"), inst: activeSlackInstall()}
fc := &fakeHistoryClient{historyMsgs: []slack.Message{
msg("UBOT", "unattributed answer", "104.000000"),
- msg("U1", "/new current question", "103.000000"),
+ msg("U1", "/clear current question", "103.000000"),
}}
h := newTestHistory(q, fc)
page, err := h.ChannelOverview(context.Background(), uid(9), channel.HistoryOptions{
diff --git a/server/internal/integrations/slack/outbound.go b/server/internal/integrations/slack/outbound.go
index 13c6c31983..7faf87012c 100644
--- a/server/internal/integrations/slack/outbound.go
+++ b/server/internal/integrations/slack/outbound.go
@@ -25,15 +25,16 @@ import (
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)
+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
SetChatMessageChannelOutboundProvenanceByTask(ctx context.Context, arg db.SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error)
+ RecordChannelOutboundMessage(ctx context.Context, arg db.RecordChannelOutboundMessageParams) error
}
// replySender posts one reply. Satisfied by *slackSender, so the outbound path
// reuses Send's Markdown->mrkdwn conversion, chunking, and threading.
type replySender interface {
- Send(ctx context.Context, out channel.OutboundMessage) (channel.SendResult, error)
+ SendWithMetadata(ctx context.Context, out channel.OutboundMessage, metadata slack.SlackMetadata) (channel.SendResult, error)
}
// Outbound delivers an agent's chat reply back to Slack — the outbound half of
@@ -86,16 +87,6 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// Issue / autopilot tasks carry no chat_session.
return nil
}
- binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
- ChatSessionID: sessionID,
- ChannelType: string(TypeSlack),
- })
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return nil // not a Slack session (Feishu / web-only)
- }
- return fmt.Errorf("lookup slack chat binding: %w", err)
- }
content := chatDoneContent(e.Payload)
if content == "" {
return nil // nothing to say (empty completion)
@@ -112,6 +103,17 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
if !ok {
return nil
}
+ delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil // direct Chat or another channel
+ }
+ return fmt.Errorf("lookup slack task delivery: %w", err)
+ }
+ if delivery.ChannelType != string(TypeSlack) {
+ return nil
+ }
+ binding := slackBindingFromTaskDelivery(delivery)
task, err := o.q.GetAgentTask(ctx, taskID)
if err != nil {
return fmt.Errorf("load agent task: %w", err)
@@ -138,11 +140,11 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return fmt.Errorf("decode slack credentials: %w", err)
}
channelID, threadTS := outboundTarget(binding)
- result, err := o.newSender(creds).Send(ctx, channel.OutboundMessage{
+ result, err := o.newSender(creds).SendWithMetadata(ctx, channel.OutboundMessage{
ChatID: channelID,
Text: content,
ThreadID: threadTS,
- })
+ }, outboundMetadata(delivery.BindingID, delivery.RouteRevision, "task_reply"))
if err != nil {
return fmt.Errorf("post slack reply: %w", err)
}
@@ -166,9 +168,32 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
if rows != 1 {
return fmt.Errorf("record slack reply provenance: updated %d assistant rows, want 1", rows)
}
+ for _, messageID := range messageIDs {
+ if err := o.q.RecordChannelOutboundMessage(ctx, db.RecordChannelOutboundMessageParams{
+ OutboundInstallationID: delivery.InstallationID,
+ OutboundChannelType: delivery.ChannelType,
+ OutboundMessageID: messageID,
+ OutboundBindingID: delivery.BindingID,
+ OutboundRouteRevision: delivery.RouteRevision,
+ OutboundTaskID: taskID,
+ OutboundKind: "task_reply",
+ }); err != nil {
+ return fmt.Errorf("record slack outbound message: %w", err)
+ }
+ }
return nil
}
+func slackBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {
+ return db.ChannelChatSessionBinding{
+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,
+ ChannelType: delivery.ChannelType, ChannelChatID: delivery.ChannelChatID,
+ ChatType: delivery.ChatType,
+ LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,
+ RouteRevision: delivery.RouteRevision, Config: delivery.Config,
+ }
+}
+
// chatDoneTaskID extracts the task id from the event envelope or the typed/map
// payload emitted by TaskService. Outbound delivery fails closed when the task
// origin cannot be established.
diff --git a/server/internal/integrations/slack/outbound_test.go b/server/internal/integrations/slack/outbound_test.go
index 1d9bf082d3..c1fb83570a 100644
--- a/server/internal/integrations/slack/outbound_test.go
+++ b/server/internal/integrations/slack/outbound_test.go
@@ -8,6 +8,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -33,6 +34,8 @@ type fakeOutboundQueries struct {
provenanceRows int64
provenanceErr error
gotProvenance db.SetChatMessageChannelOutboundProvenanceByTaskParams
+ recordedOutbound []db.RecordChannelOutboundMessageParams
+ recordOutboundErr error
}
func (f *fakeOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
@@ -43,13 +46,25 @@ func (f *fakeOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pg
return f.taskChannelIngested, nil
}
-func (f *fakeOutboundQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
- return f.binding, f.bindingErr
+func (f *fakeOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ if f.bindingErr != nil {
+ return db.ChannelTaskDelivery{}, f.bindingErr
+ }
+ return db.ChannelTaskDelivery{
+ BindingID: f.binding.ID, InstallationID: f.binding.InstallationID,
+ ChannelType: string(TypeSlack), ChannelChatID: f.binding.ChannelChatID,
+ ChannelMessageID: f.binding.LastMessageID, ChannelThreadID: f.binding.LastThreadID,
+ RouteRevision: f.binding.RouteRevision, Config: f.binding.Config,
+ }, nil
}
func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
return f.inst, f.instErr
}
+func (f *fakeOutboundQueries) RecordChannelOutboundMessage(_ context.Context, arg db.RecordChannelOutboundMessageParams) error {
+ f.recordedOutbound = append(f.recordedOutbound, arg)
+ return f.recordOutboundErr
+}
func (f *fakeOutboundQueries) SetChatMessageChannelOutboundProvenanceByTask(_ context.Context, arg db.SetChatMessageChannelOutboundProvenanceByTaskParams) (int64, error) {
f.gotProvenance = arg
@@ -60,14 +75,16 @@ func (f *fakeOutboundQueries) SetChatMessageChannelOutboundProvenanceByTask(_ co
}
type fakeSender struct {
- called int
- got channel.OutboundMessage
- result channel.SendResult
+ called int
+ got channel.OutboundMessage
+ gotMetadata slack.SlackMetadata
+ result channel.SendResult
}
-func (f *fakeSender) Send(_ context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+func (f *fakeSender) SendWithMetadata(_ context.Context, out channel.OutboundMessage, metadata slack.SlackMetadata) (channel.SendResult, error) {
f.called++
f.got = out
+ f.gotMetadata = metadata
if len(f.result.MessageIDs) > 0 || f.result.MessageID != "" {
return f.result, nil
}
diff --git a/server/internal/integrations/slack/replier.go b/server/internal/integrations/slack/replier.go
index 60e85bd0dd..9e7646b2c9 100644
--- a/server/internal/integrations/slack/replier.go
+++ b/server/internal/integrations/slack/replier.go
@@ -34,6 +34,7 @@ const (
agentOfflineText = "⚠️ The agent is offline right now. Your message was received and will be handled once it's back online."
agentArchivedText = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."
freshPendingText = "✅ Fresh start ready. Your next chat message will run without previous context."
+ chatStartedText = "✅ Started a new Multica chat. Your next message will enter it."
issueUsageText = "Please include an issue title. Use:\n\n`/issue <title>`\n`[description]` (optional)"
)
@@ -43,6 +44,10 @@ type bindingMinter interface {
Mint(ctx context.Context, workspaceID, installationID pgtype.UUID, slackUserID string) (BindingToken, error)
}
+type controlAckLedger interface {
+ RecordChannelOutboundMessage(ctx context.Context, arg db.RecordChannelOutboundMessageParams) error
+}
+
// OutboundReplier implements engine.OutboundReplier for Slack.
type OutboundReplier struct {
binding bindingMinter
@@ -51,6 +56,7 @@ type OutboundReplier struct {
appURL string
bindingPath string
logger *slog.Logger
+ ledger controlAckLedger
}
// OutboundReplierConfig configures the replier. Binding + AppURL are required
@@ -69,6 +75,7 @@ type OutboundReplierConfig struct {
AppURL string
BindingPath string // default "/slack/bind"
Logger *slog.Logger
+ Queries *db.Queries
}
var _ engine.OutboundReplier = (*OutboundReplier)(nil)
@@ -93,6 +100,7 @@ func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {
appURL: strings.TrimRight(cfg.AppURL, "/"),
bindingPath: bindingPath,
logger: logger,
+ ledger: cfg.Queries,
}
r.newSender = func(c credentials) replySender {
return newSlackSender(c, slack.New(c.BotToken), logger)
@@ -110,22 +118,26 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
case engine.OutcomeAgentOffline:
- if err := r.post(ctx, inst, msg, agentOfflineText); err != nil {
+ if err := r.postResult(ctx, inst, msg, res, agentOfflineText); err != nil {
r.logger.WarnContext(ctx, "slack 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 {
+ if err := r.postResult(ctx, inst, msg, res, agentArchivedText); err != nil {
r.logger.WarnContext(ctx, "slack replier: archived notice failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
case engine.OutcomeFreshPending:
- if err := r.post(ctx, inst, msg, freshPendingText); err != nil {
+ if err := r.postResult(ctx, inst, msg, res, freshPendingText); err != nil {
r.logger.WarnContext(ctx, "slack replier: fresh-start confirmation failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
+ case engine.OutcomeChatStarted:
+ if err := r.postResult(ctx, inst, msg, res, chatStartedText); err != nil {
+ r.logger.WarnContext(ctx, "slack replier: new-chat confirmation failed", "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
case engine.OutcomeIssueUsage:
- if err := r.post(ctx, inst, msg, issueUsageText); err != nil {
+ if err := r.postResult(ctx, inst, msg, res, issueUsageText); err != nil {
r.logger.WarnContext(ctx, "slack replier: issue usage reply failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
@@ -137,7 +149,7 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
if res.IssueDuplicate {
text = issueDuplicateText(res)
}
- if err := r.post(ctx, inst, msg, text); err != nil {
+ if err := r.postResult(ctx, inst, msg, res, text); err != nil {
r.logger.WarnContext(ctx, "slack replier: issue outcome reply failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
@@ -145,6 +157,44 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
}
}
+func (r *OutboundReplier) postResult(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result, text string) error {
+ row, ok := inst.Platform.(db.ChannelInstallation)
+ if !ok {
+ return errors.New("installation platform row unavailable")
+ }
+ creds, err := decodeCredentials(row.Config, r.decrypt)
+ if err != nil {
+ return fmt.Errorf("decode credentials: %w", err)
+ }
+ kind := "control_ack"
+ if res.Outcome == engine.OutcomeIngested && res.IssueID.Valid {
+ kind = "issue_ack"
+ }
+ sent, err := r.newSender(creds).SendWithMetadata(ctx, channel.OutboundMessage{
+ ChatID: msg.Source.ChatID, Text: text, ThreadID: msg.Source.ThreadID,
+ }, outboundMetadata(res.ChannelBindingID, res.ChannelRouteRevision, kind))
+ if err != nil {
+ return fmt.Errorf("post slack reply: %w", err)
+ }
+ if r.ledger == nil || !res.ChannelBindingID.Valid {
+ return nil
+ }
+ ids := sent.MessageIDs
+ if len(ids) == 0 && sent.MessageID != "" {
+ ids = []string{sent.MessageID}
+ }
+ for _, id := range ids {
+ if err := r.ledger.RecordChannelOutboundMessage(ctx, db.RecordChannelOutboundMessageParams{
+ OutboundInstallationID: inst.ID, OutboundChannelType: string(TypeSlack),
+ OutboundMessageID: id, OutboundBindingID: res.ChannelBindingID,
+ OutboundRouteRevision: res.ChannelRouteRevision, OutboundKind: kind,
+ }); err != nil {
+ return fmt.Errorf("record slack control acknowledgement: %w", err)
+ }
+ }
+ return nil
+}
+
func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) error {
sender := res.Sender
if sender == "" {
@@ -169,28 +219,7 @@ func (r *OutboundReplier) sendBindingPrompt(ctx context.Context, inst engine.Res
// not mangled into italics.
text := "👋 To start chatting with me, link your Slack account to Multica: <" +
bindURL + "|link your account>\n(This link expires in 15 minutes.)"
- return r.post(ctx, inst, msg, text)
-}
-
-// post resolves the installation's bot token from the carried platform row and
-// sends text back into the originating channel / thread.
-func (r *OutboundReplier) post(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {
- row, ok := inst.Platform.(db.ChannelInstallation)
- if !ok {
- return errors.New("installation platform row unavailable")
- }
- creds, err := decodeCredentials(row.Config, r.decrypt)
- if err != nil {
- return fmt.Errorf("decode credentials: %w", err)
- }
- if _, err := r.newSender(creds).Send(ctx, channel.OutboundMessage{
- ChatID: msg.Source.ChatID,
- Text: text,
- ThreadID: msg.Source.ThreadID,
- }); err != nil {
- return fmt.Errorf("post slack reply: %w", err)
- }
- return nil
+ return r.postResult(ctx, inst, msg, res, text)
}
func issueCreatedText(res engine.Result) string {
diff --git a/server/internal/integrations/slack/replier_test.go b/server/internal/integrations/slack/replier_test.go
index 0056a829d8..a584b21c0e 100644
--- a/server/internal/integrations/slack/replier_test.go
+++ b/server/internal/integrations/slack/replier_test.go
@@ -7,6 +7,7 @@ import (
"time"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/slack-go/slack"
"github.com/multica-ai/multica/server/internal/integrations/channel"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
@@ -18,7 +19,7 @@ type fakeReplySender struct {
calls int
}
-func (f *fakeReplySender) Send(_ context.Context, out channel.OutboundMessage) (channel.SendResult, error) {
+func (f *fakeReplySender) SendWithMetadata(_ context.Context, out channel.OutboundMessage, _ slack.SlackMetadata) (channel.SendResult, error) {
f.calls++
cp := out
f.sent = &cp
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index 6a612253ac..915a4ac76b 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -331,6 +331,23 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
})
}
+func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ bindingKey, config, replyThread := slackSessionRouting(p.Message)
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: replyThread,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{SessionID: result.SessionID, BindingID: result.BindingID, RouteRevision: result.RouteRevision, Append: result.Append}, err
+}
+
func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
@@ -355,8 +372,8 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
})
}
-func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ return r.session.BindMediaRefsWithResult(ctx, engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
diff --git a/server/internal/integrations/slack/slack_channel.go b/server/internal/integrations/slack/slack_channel.go
index 1666ae44a3..73d4fa7473 100644
--- a/server/internal/integrations/slack/slack_channel.go
+++ b/server/internal/integrations/slack/slack_channel.go
@@ -36,14 +36,14 @@ type slackChannel struct {
appToken string // decrypted xapp- — authorizes the Socket Mode connection
botAPI *slack.Client // bot-token client for outbound Send
handler channel.InboundHandler
- slash *SlashCommandProcessor // nil disables /issue slash-command handling
+ slash *SlashCommandProcessor // nil disables /issue and /new slash-command handling
logger *slog.Logger
}
-// slashCommandTimeout bounds the detached processing of one `/issue` slash
-// command (installation + identity resolution, issue creation, response_url
-// reply). It runs off the socket receive loop on its own context, so a slow DB
-// or Slack HTTP call cannot wedge event delivery.
+// slashCommandTimeout bounds detached `/issue`, `/new`, and `/clear` processing
+// (installation + identity resolution, mutation, response_url reply). It runs
+// off the socket receive loop on its own context, so a slow DB or Slack HTTP
+// call cannot wedge event delivery.
const slashCommandTimeout = 10 * time.Second
func (c *slackChannel) Type() channel.Type { return TypeSlack }
@@ -155,7 +155,11 @@ func (c *slackChannel) handleSocketEvent(ctx context.Context, sm *socketmode.Cli
}
cmd, ok := evt.Data.(slack.SlashCommand)
if ok {
- c.dispatchSlashCommand(cmd)
+ envelopeID := ""
+ if evt.Request != nil {
+ envelopeID = evt.Request.EnvelopeID
+ }
+ c.dispatchSlashCommand(cmd, envelopeID)
}
return nil
case socketmode.EventTypeConnecting, socketmode.EventTypeConnected, socketmode.EventTypeHello:
@@ -193,11 +197,11 @@ func (c *slackChannel) dispatchEventsAPI(ctx context.Context, e slackevents.Even
return c.handler(ctx, msg)
}
-// dispatchSlashCommand processes an already-ACKed `/issue` slash command on a
-// detached goroutine with its own bounded context, so the issue creation and
+// dispatchSlashCommand processes an already-ACKed `/issue`, `/new`, or `/clear` command
+// on a detached goroutine with its own bounded context, so the mutation and
// response_url reply never block the socket receive loop (mirrors the router's
// detached outbound path). A nil processor (slash handling not wired) drops it.
-func (c *slackChannel) dispatchSlashCommand(cmd slack.SlashCommand) {
+func (c *slackChannel) dispatchSlashCommand(cmd slack.SlashCommand, envelopeID string) {
if c.slash == nil {
c.logger.Warn("slack: slash command received but no processor configured",
"command", cmd.Command, "app_id", c.appID)
@@ -206,7 +210,7 @@ func (c *slackChannel) dispatchSlashCommand(cmd slack.SlashCommand) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), slashCommandTimeout)
defer cancel()
- c.slash.Handle(ctx, cmd)
+ c.slash.HandleEnvelope(ctx, cmd, envelopeID)
}()
}
@@ -216,7 +220,7 @@ func (c *slackChannel) dispatchSlashCommand(cmd slack.SlashCommand) {
type ChannelDeps struct {
Decrypt Decrypter
Logger *slog.Logger
- // Slash handles the `/issue` slash command delivered over Socket Mode. Nil
+ // Slash handles `/issue` and `/new` commands delivered over Socket Mode. Nil
// leaves slash-command handling off (the connection still serves messages
// and @-mentions); tests that only exercise inbound messages pass nil.
Slash *SlashCommandProcessor
diff --git a/server/internal/integrations/slack/slash_command.go b/server/internal/integrations/slack/slash_command.go
index 763b9070be..43cd40a181 100644
--- a/server/internal/integrations/slack/slash_command.go
+++ b/server/internal/integrations/slack/slash_command.go
@@ -15,8 +15,8 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-// This file implements the Slack `/issue` SLASH COMMAND. It is deliberately
-// separate from the message-based `/issue` (engine ParseIssueCommand): on Slack
+// This file implements the Slack `/issue`, `/new`, and `/clear` SLASH COMMANDS. They are
+// deliberately separate from message-prefix commands: on Slack
// a message whose first character is `/` is intercepted by the client as a
// slash command and never delivered to the app, so the message-prefix form of
// `/issue` cannot work here at all (MUL-3908). Registering `/issue` as a real
@@ -41,15 +41,21 @@ import (
// are kept local so the proven inbound pipeline is untouched.
const issueSlashCommand = "/issue"
+const newSlashCommand = "/new"
+const clearSlashCommand = "/clear"
// User-facing ephemeral replies. Kept terse; only the invoker sees them.
const (
- slashUsageText = "Tell me what to file, e.g. `/issue the login button does nothing on Safari`."
- slashQueuedText = "✅ On it — I'm turning that into an issue. You'll get a Multica notification when it's ready."
- slashNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you."
- slashLinkAccountFallback = "Link your Slack account to Multica first, then try `/issue` again."
- slashInternalErrorText = "⚠️ Something went wrong creating the issue. Please try again."
- slashDisabledText = "This Slack app isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."
+ slashUsageText = "Tell me what to file, e.g. `/issue the login button does nothing on Safari`."
+ slashQueuedText = "✅ On it — I'm turning that into an issue. You'll get a Multica notification when it's ready."
+ slashNotMemberText = "You're not a member of this Multica workspace, so I can't file an issue for you."
+ slashLinkAccountFallback = "Link your Slack account to Multica first, then try `/issue` again."
+ slashInternalErrorText = "⚠️ Something went wrong creating the issue. Please try again."
+ slashDisabledText = "This Slack app isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."
+ slashNewStartedText = "✅ Started a new Multica chat."
+ slashNewThreadGuideText = "In a channel, start the new chat from the target thread with `@Multica /new`."
+ slashClearStartedText = "✅ Cleared the agent context in this Multica chat."
+ slashClearThreadGuideText = "In a channel, clear the target thread's context with `@Multica /clear`."
)
// slashQueries is the narrow slice of generated queries the slash-command
@@ -69,10 +75,16 @@ type quickCreateEnqueuer interface {
EnqueueQuickCreateTask(ctx context.Context, workspaceID, requesterID, agentID, squadID pgtype.UUID, prompt, priority, dueDate string, projectID, parentIssueID pgtype.UUID, attachmentIDs []pgtype.UUID) (db.AgentTaskQueue, error)
}
-// SlashCommandProcessor handles the Slack `/issue` slash command end to end.
+type slashControlStarter interface {
+ StartSlackDMChat(ctx context.Context, inst engine.ResolvedInstallation, userID pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error
+ ClearSlackDMContext(ctx context.Context, inst engine.ResolvedInstallation, userID pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error
+}
+
+// SlashCommandProcessor handles Slack `/issue`, `/new`, and `/clear` commands end to end.
type SlashCommandProcessor struct {
q slashQueries
tasks quickCreateEnqueuer
+ control slashControlStarter
binding bindingMinter
appURL string
bindingPath string
@@ -89,6 +101,7 @@ type SlashCommandProcessor struct {
type SlashCommandConfig struct {
Queries *db.Queries
Tasks quickCreateEnqueuer
+ Control slashControlStarter
Binding bindingMinter
AppURL string
BindingPath string // default "/slack/bind"
@@ -113,6 +126,7 @@ func NewSlashCommandProcessor(cfg SlashCommandConfig) *SlashCommandProcessor {
p := &SlashCommandProcessor{
q: cfg.Queries,
tasks: cfg.Tasks,
+ control: cfg.Control,
binding: cfg.Binding,
appURL: strings.TrimRight(cfg.AppURL, "/"),
bindingPath: bindingPath,
@@ -131,11 +145,21 @@ func NewSlashCommandProcessor(cfg SlashCommandConfig) *SlashCommandProcessor {
// called from a detached goroutine (the socket receive loop has already ACKed),
// so it never returns an error — every outcome is a user-facing message.
func (p *SlashCommandProcessor) Handle(ctx context.Context, cmd slack.SlashCommand) {
- // Only /issue is registered in the manifest; ignore anything else defensively.
- if !strings.EqualFold(strings.TrimSpace(cmd.Command), issueSlashCommand) {
+ p.HandleEnvelope(ctx, cmd, "")
+}
+
+// HandleEnvelope preserves Socket Mode's durable envelope id for control-command dedup.
+func (p *SlashCommandProcessor) HandleEnvelope(ctx context.Context, cmd slack.SlashCommand, envelopeID string) {
+ command := strings.TrimSpace(cmd.Command)
+ if !strings.EqualFold(command, issueSlashCommand) && command != newSlashCommand && command != clearSlashCommand {
return
}
- text := p.process(ctx, cmd)
+ var text string
+ if command == newSlashCommand || command == clearSlashCommand {
+ text = p.processControl(ctx, cmd, envelopeID)
+ } else {
+ text = p.process(ctx, cmd)
+ }
if text == "" || cmd.ResponseURL == "" {
return
}
@@ -145,6 +169,67 @@ func (p *SlashCommandProcessor) Handle(ctx context.Context, cmd slack.SlashComma
}
}
+func (p *SlashCommandProcessor) processControl(ctx context.Context, cmd slack.SlashCommand, envelopeID string) string {
+ inst, err := p.resolveInstallation(ctx, cmd.APIAppID, cmd.TeamID)
+ if err != nil {
+ if errors.Is(err, engine.ErrInstallationNotFound) {
+ return slashDisabledText
+ }
+ return slashInternalErrorText
+ }
+ if !inst.Active {
+ return slashDisabledText
+ }
+ userID, err := p.resolveUser(ctx, inst, cmd.UserID)
+ if err != nil {
+ switch {
+ case errors.Is(err, engine.ErrSenderUnbound):
+ return p.bindingText(ctx, inst, cmd.UserID)
+ case errors.Is(err, engine.ErrSenderNotMember):
+ return slashNotMemberText
+ default:
+ return slashInternalErrorText
+ }
+ }
+ // Keep command availability and channel-routing guidance behind the same
+ // installation, account-binding, and workspace-membership checks as every
+ // other Slack entry point.
+ // Slash payloads do not carry thread_ts; rotating a channel-level guess
+ // would move an unrelated conversation. Channel users must use the mention
+ // form, which arrives through the ordinary Router with an exact thread root.
+ if !strings.HasPrefix(cmd.ChannelID, "D") {
+ if cmd.Command == clearSlashCommand {
+ return slashClearThreadGuideText
+ }
+ return slashNewThreadGuideText
+ }
+ if p.control == nil {
+ return slashInternalErrorText
+ }
+ var startErr error
+ if cmd.Command == clearSlashCommand {
+ startErr = p.control.ClearSlackDMContext(ctx, inst, userID, cmd, envelopeID)
+ } else {
+ startErr = p.control.StartSlackDMChat(ctx, inst, userID, cmd, envelopeID)
+ }
+ if startErr != nil {
+ if errors.Is(startErr, engine.ErrDuplicate) {
+ if cmd.Command == clearSlashCommand {
+ return slashClearStartedText
+ }
+ return slashNewStartedText
+ }
+ p.logger.WarnContext(ctx, "slack slash command: session control failed",
+ "outcome", "session_control_failed", "command", cmd.Command,
+ "channel_type", string(TypeSlack), "app_id", cmd.APIAppID, "error", startErr)
+ return slashInternalErrorText
+ }
+ if cmd.Command == clearSlashCommand {
+ return slashClearStartedText
+ }
+ return slashNewStartedText
+}
+
// process runs the command and returns the ephemeral text to reply with.
func (p *SlashCommandProcessor) process(ctx context.Context, cmd slack.SlashCommand) string {
prompt := strings.TrimSpace(cmd.Text)
diff --git a/server/internal/integrations/slack/slash_command_test.go b/server/internal/integrations/slack/slash_command_test.go
index cf98133883..4003acc315 100644
--- a/server/internal/integrations/slack/slash_command_test.go
+++ b/server/internal/integrations/slack/slash_command_test.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/slack-go/slack"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -52,6 +53,28 @@ type fakeQuickCreate struct {
prompt string
}
+type fakeSlashControlStarter struct {
+ newCalls int
+ clearCalls int
+ envelopeID string
+ cmd slack.SlashCommand
+ err error
+}
+
+func (f *fakeSlashControlStarter) StartSlackDMChat(_ context.Context, _ engine.ResolvedInstallation, _ pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error {
+ f.newCalls++
+ f.cmd = cmd
+ f.envelopeID = envelopeID
+ return f.err
+}
+
+func (f *fakeSlashControlStarter) ClearSlackDMContext(_ context.Context, _ engine.ResolvedInstallation, _ pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error {
+ f.clearCalls++
+ f.cmd = cmd
+ f.envelopeID = envelopeID
+ return f.err
+}
+
func (f *fakeQuickCreate) EnqueueQuickCreateTask(_ context.Context, workspaceID, requesterID, agentID, squadID pgtype.UUID, prompt, _, _ string, _, _ pgtype.UUID, _ []pgtype.UUID) (db.AgentTaskQueue, error) {
f.calls++
f.workspaceID = workspaceID
@@ -285,3 +308,74 @@ func TestSlashHandle_IgnoresOtherCommands(t *testing.T) {
t.Fatalf("non-/issue command must be ignored: calls=%d replies=%d", tasks.calls, *count)
}
}
+
+func TestSlashHandle_NewDMUsesSharedStarterAndEnvelopeDedup(t *testing.T) {
+ q := &fakeSlashQueries{inst: activeSlashInstallation(), binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)}}
+ tasks := &fakeQuickCreate{}
+ p, captured, _ := newTestSlashProcessor(q, tasks, &fakeBindingMinter{})
+ starter := &fakeSlashControlStarter{}
+ p.control = starter
+ cmd := issueSlashCmd()
+ cmd.Command, cmd.ChannelID, cmd.Text = "/new", "D1", "new topic"
+ p.HandleEnvelope(context.Background(), cmd, "env-123")
+ if starter.newCalls != 1 || starter.clearCalls != 0 || starter.envelopeID != "env-123" || starter.cmd.Text != "new topic" {
+ t.Fatalf("starter=%+v", starter)
+ }
+ if tasks.calls != 0 {
+ t.Fatalf("/new must not also enqueue /issue quick-create work, got %d calls", tasks.calls)
+ }
+ if *captured != slashNewStartedText {
+ t.Fatalf("reply=%q", *captured)
+ }
+}
+
+func TestSlashHandle_NewChannelGuidesToMentionWithoutGuessingThread(t *testing.T) {
+ q := &fakeSlashQueries{
+ inst: activeSlashInstallation(),
+ binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)},
+ }
+ p, captured, _ := newTestSlashProcessor(q, &fakeQuickCreate{}, &fakeBindingMinter{})
+ starter := &fakeSlashControlStarter{}
+ p.control = starter
+ cmd := issueSlashCmd()
+ cmd.Command, cmd.ChannelID = "/new", "C1"
+ p.HandleEnvelope(context.Background(), cmd, "env-123")
+ if starter.newCalls != 0 || starter.clearCalls != 0 {
+ t.Fatal("channel slash command must not rotate a guessed route")
+ }
+ if *captured != slashNewThreadGuideText {
+ t.Fatalf("reply=%q", *captured)
+ }
+}
+
+func TestSlashHandle_ClearDMUsesSharedStarterAndEnvelopeDedup(t *testing.T) {
+ q := &fakeSlashQueries{inst: activeSlashInstallation(), binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)}}
+ p, captured, _ := newTestSlashProcessor(q, &fakeQuickCreate{}, &fakeBindingMinter{})
+ starter := &fakeSlashControlStarter{}
+ p.control = starter
+ cmd := issueSlashCmd()
+ cmd.Command, cmd.ChannelID, cmd.Text = "/clear", "D1", "start clean"
+ p.HandleEnvelope(context.Background(), cmd, "env-clear-123")
+ if starter.clearCalls != 1 || starter.newCalls != 0 || starter.envelopeID != "env-clear-123" || starter.cmd.Text != "start clean" {
+ t.Fatalf("starter=%+v", starter)
+ }
+ if *captured != slashClearStartedText {
+ t.Fatalf("reply=%q", *captured)
+ }
+}
+
+func TestSlashHandle_ClearChannelGuidesToMentionWithoutGuessingThread(t *testing.T) {
+ q := &fakeSlashQueries{inst: activeSlashInstallation(), binding: db.ChannelUserBinding{MulticaUserID: slashTestUUID(9)}}
+ p, captured, _ := newTestSlashProcessor(q, &fakeQuickCreate{}, &fakeBindingMinter{})
+ starter := &fakeSlashControlStarter{}
+ p.control = starter
+ cmd := issueSlashCmd()
+ cmd.Command, cmd.ChannelID = "/clear", "C1"
+ p.HandleEnvelope(context.Background(), cmd, "env-clear-123")
+ if starter.newCalls != 0 || starter.clearCalls != 0 {
+ t.Fatal("channel slash command must not clear a guessed route")
+ }
+ if *captured != slashClearThreadGuideText {
+ t.Fatalf("reply=%q", *captured)
+ }
+}
diff --git a/server/internal/integrations/slack/slash_control.go b/server/internal/integrations/slack/slash_control.go
new file mode 100644
index 0000000000..c9d628c22c
--- /dev/null
+++ b/server/internal/integrations/slack/slash_control.go
@@ -0,0 +1,191 @@
+package slack
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/slack-go/slack"
+
+ "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/service"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type slashControlTasks interface {
+ PrepareChatTaskEnqueue(ctx context.Context, agentID, initiator pgtype.UUID) (service.PreparedChatTaskEnqueue, error)
+ EnqueuePreparedChannelChatTaskInTx(ctx context.Context, tx pgx.Tx, session db.ChatSession, initiator pgtype.UUID, forceFresh bool, contextRevision int64, prepared service.PreparedChatTaskEnqueue) (db.AgentTaskQueue, error)
+ FinalizeChatTaskEnqueue(ctx context.Context, task db.AgentTaskQueue)
+}
+
+type slackDMControlStarter struct {
+ q *db.Queries
+ session *engine.ChatSession
+ tasks slashControlTasks
+ lifecycle engine.ChannelChatLifecycle
+}
+
+const maxSlackControlRouteRetries = 8
+
+func NewSlackDMControlStarter(q *db.Queries, tx engine.TxStarter, tasks slashControlTasks, lifecycle engine.ChannelChatLifecycle) slashControlStarter {
+ return &slackDMControlStarter{
+ q: q, tasks: tasks, lifecycle: lifecycle,
+ session: engine.NewChatSession(q, tx, TypeSlack, engine.SessionTitles{}),
+ }
+}
+
+func (s *slackDMControlStarter) StartSlackDMChat(ctx context.Context, inst engine.ResolvedInstallation, userID pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error {
+ if envelopeID == "" {
+ return errors.New("slack /new: missing socket envelope id")
+ }
+ d := &deduper{q: s.q}
+ claim, err := d.Claim(ctx, inst.ID, envelopeID)
+ if err != nil {
+ return err
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = d.Release(context.WithoutCancel(ctx), inst.ID, envelopeID, claim)
+ }
+ }()
+
+ body := strings.TrimSpace(cmd.Text)
+ var prepared service.PreparedChatTaskEnqueue
+ if body != "" {
+ prepared, err = s.tasks.PrepareChatTaskEnqueue(ctx, inst.AgentID, userID)
+ if err != nil {
+ return fmt.Errorf("slack /new: prepare task: %w", err)
+ }
+ }
+ var task db.AgentTaskQueue
+ var started engine.StartSessionResult
+ for attempt := 0; ; attempt++ {
+ task = db.AgentTaskQueue{}
+ started, err = s.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: inst.WorkspaceID, AgentID: inst.AgentID, InstallationID: inst.ID,
+ Sender: userID, BindingKey: cmd.ChannelID, ChatType: channel.ChatTypeP2P,
+ },
+ Initiator: userID,
+ Body: body, DedupMessageID: envelopeID, ClaimToken: claim,
+ PersistMessage: body != "", HistoryBoundaryPending: true,
+ BeforeCommit: func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {
+ if body == "" {
+ return nil
+ }
+ var enqueueErr error
+ task, enqueueErr = s.tasks.EnqueuePreparedChannelChatTaskInTx(ctx, tx, session, userID, false, 1, prepared)
+ return enqueueErr
+ },
+ })
+ if !errors.Is(err, engine.ErrRouteChanged) {
+ break
+ }
+ slog.InfoContext(ctx, "slack /new route changed; retrying",
+ "outcome", "chat_route_retry", "channel_type", string(TypeSlack),
+ "installation_id", inst.ID, "attempt", attempt+1,
+ )
+ if attempt+1 >= maxSlackControlRouteRetries {
+ return fmt.Errorf("slack /new route did not stabilize after %d retries: %w", maxSlackControlRouteRetries, err)
+ }
+ }
+ if err != nil {
+ return err
+ }
+ committed = true
+ if s.lifecycle != nil {
+ s.lifecycle.ChannelChatStarted(engine.ChannelChatStartedEvent{
+ WorkspaceID: inst.WorkspaceID, CreatorID: userID, AgentID: inst.AgentID,
+ SessionID: started.SessionID, InstallationID: inst.ID,
+ ChannelType: TypeSlack, RouteRevision: started.RouteRevision,
+ Title: started.Append.InitialTitle,
+ })
+ if started.Append.InitialTitle != "" {
+ s.lifecycle.GenerateChannelChatTitle(inst.WorkspaceID, userID, started.SessionID, started.Append.InitialTitle, body)
+ }
+ }
+ if body == "" {
+ return nil
+ }
+ s.tasks.FinalizeChatTaskEnqueue(ctx, task)
+ return nil
+}
+
+func (s *slackDMControlStarter) ClearSlackDMContext(ctx context.Context, inst engine.ResolvedInstallation, userID pgtype.UUID, cmd slack.SlashCommand, envelopeID string) error {
+ if envelopeID == "" {
+ return errors.New("slack /clear: missing socket envelope id")
+ }
+ d := &deduper{q: s.q}
+ claim, err := d.Claim(ctx, inst.ID, envelopeID)
+ if err != nil {
+ return err
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = d.Release(context.WithoutCancel(ctx), inst.ID, envelopeID, claim)
+ }
+ }()
+
+ body := strings.TrimSpace(cmd.Text)
+ var prepared service.PreparedChatTaskEnqueue
+ if body != "" {
+ prepared, err = s.tasks.PrepareChatTaskEnqueue(ctx, inst.AgentID, userID)
+ if err != nil {
+ return fmt.Errorf("slack /clear: prepare task: %w", err)
+ }
+ }
+
+ var task db.AgentTaskQueue
+ for attempt := 0; ; attempt++ {
+ sessionID, ensureErr := s.session.EnsureSession(ctx, engine.EnsureSessionInput{
+ WorkspaceID: inst.WorkspaceID, AgentID: inst.AgentID, InstallationID: inst.ID,
+ Sender: userID, BindingKey: cmd.ChannelID, ChatType: channel.ChatTypeP2P,
+ })
+ if ensureErr != nil {
+ return ensureErr
+ }
+
+ task = db.AgentTaskQueue{}
+ if body == "" {
+ err = s.session.MarkPendingFreshWithDedup(ctx, sessionID, "", inst.ID, envelopeID, claim)
+ } else {
+ _, err = s.session.AppendUserMessage(ctx, engine.AppendInput{
+ SessionID: sessionID, Sender: userID, InstallationID: inst.ID,
+ Body: body, CommandText: clearSlashCommand,
+ DedupMessageID: envelopeID, ClaimToken: claim, ForceFresh: true,
+ BeforeCommit: func(ctx context.Context, tx pgx.Tx, session db.ChatSession, contextRevision int64, _ pgtype.UUID, _ int64) error {
+ var enqueueErr error
+ task, enqueueErr = s.tasks.EnqueuePreparedChannelChatTaskInTx(
+ ctx, tx, session, userID, true, contextRevision, prepared,
+ )
+ return enqueueErr
+ },
+ })
+ }
+ if !errors.Is(err, engine.ErrRouteChanged) {
+ break
+ }
+ slog.InfoContext(ctx, "slack /clear route changed; retrying",
+ "outcome", "context_clear_route_retry", "channel_type", string(TypeSlack),
+ "installation_id", inst.ID, "attempt", attempt+1,
+ )
+ if attempt+1 >= maxSlackControlRouteRetries {
+ return fmt.Errorf("slack /clear route did not stabilize after %d retries: %w", maxSlackControlRouteRetries, err)
+ }
+ }
+ if err != nil {
+ return err
+ }
+ committed = true
+ if task.ID.Valid {
+ s.tasks.FinalizeChatTaskEnqueue(ctx, task)
+ }
+ return nil
+}
diff --git a/server/internal/integrations/telegram/inbound.go b/server/internal/integrations/telegram/inbound.go
index 430715290f..54dd6b2248 100644
--- a/server/internal/integrations/telegram/inbound.go
+++ b/server/internal/integrations/telegram/inbound.go
@@ -61,9 +61,9 @@ func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.Inbou
cleaned := normalizeText(text, botUsername)
commandText := cleaned
forceFresh := false
- if body, fresh := engine.ParseFreshSessionCommand(cleaned); fresh {
- cleaned = body
- forceFresh = true
+ if control, ok := engine.ParseControlCommand(cleaned); ok {
+ cleaned = control.Body
+ forceFresh = control.Kind == engine.ControlCommandFreshSession
}
agentText := cleaned
quotedHuman := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && !m.ReplyToMessage.From.IsBot
@@ -190,7 +190,7 @@ func mentionsBot(m *Message, botUsername string) bool {
}
// normalizeText strips the bot mention token while retaining shared commands
-// such as /new and /issue for the engine's command parser.
+// such as /clear and /issue for the engine's command parser.
func normalizeText(text, botUsername string) string {
cleaned := text
if botUsername != "" {
diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.go
index 72db89c0bf..118e3c3dee 100644
--- a/server/internal/integrations/telegram/outbound.go
+++ b/server/internal/integrations/telegram/outbound.go
@@ -17,7 +17,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
- "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -67,9 +66,7 @@ type Outbound struct {
// outboundQueries is the slice of generated queries the 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)
+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
}
@@ -968,59 +965,26 @@ type replyTarget struct {
botToken string
}
-// resolveTarget maps an event to its Telegram binding + credentials. Returns
-// (nil, nil) when the session is not Telegram-bound. When viaTask is true the
-// chat session id is recovered from the task row (EventTaskMessage carries
-// only TaskID).
-func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, viaTask bool) (*replyTarget, error) {
- var task *db.AgentTaskQueue
+// resolveTarget maps an event's immutable task delivery snapshot to Telegram
+// credentials. A missing snapshot means the task came from Web/Desktop/Mobile
+// and must not reach an external conversation, even if its Chat once had a
+// Telegram route.
+func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, _ bool) (*replyTarget, error) {
taskID, hasTaskID := eventTaskID(e)
- sessionID, err := util.ParseUUID(e.ChatSessionID)
- if err != nil || !sessionID.Valid {
- if !viaTask || !hasTaskID {
- return nil, nil
- }
- taskRow, terr := o.q.GetAgentTask(ctx, taskID)
- if terr != nil {
- return nil, fmt.Errorf("load agent task: %w", terr)
- }
- if !taskRow.ChatSessionID.Valid {
- return nil, nil
- }
- task = &taskRow
- sessionID = taskRow.ChatSessionID
- }
- binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
- ChatSessionID: sessionID,
- ChannelType: string(TypeTelegram),
- })
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return nil, nil // not a Telegram session
- }
- return nil, fmt.Errorf("lookup telegram chat binding: %w", err)
- }
- // A bound session can be reused by web/mobile tasks. Only a task whose
- // immutable input provenance came from a channel may reply to Telegram;
- // chat_input_task_id alone cannot distinguish direct tasks from channel
- // tasks. Fail closed when the task id or provenance lookup is unavailable.
if !hasTaskID {
return nil, nil
}
- if task == nil {
- taskRow, terr := o.q.GetAgentTask(ctx, taskID)
- if terr != nil {
- return nil, fmt.Errorf("load agent task: %w", terr)
- }
- task = &taskRow
- }
- deliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, *task)
+ delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)
if err != nil {
- return nil, fmt.Errorf("classify task input origin: %w", err)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("lookup telegram task delivery: %w", err)
}
- if !deliver {
+ if delivery.ChannelType != string(TypeTelegram) {
return nil, nil
}
+ binding := telegramBindingFromTaskDelivery(delivery)
inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
ID: binding.InstallationID,
ChannelType: string(TypeTelegram),
@@ -1046,6 +1010,16 @@ func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, viaTask bo
}, nil
}
+func telegramBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {
+ return db.ChannelChatSessionBinding{
+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,
+ ChannelType: delivery.ChannelType, ChannelChatID: delivery.ChannelChatID,
+ ChatType: delivery.ChatType, LastMessageID: delivery.ChannelMessageID,
+ LastThreadID: delivery.ChannelThreadID, RouteRevision: delivery.RouteRevision,
+ Config: delivery.Config,
+ }
+}
+
// outboundTarget recovers the numeric chat id (from the binding config when
// the binding key is a composite "chat:thread") and the reply thread.
func outboundTarget(b db.ChannelChatSessionBinding) (chatID, threadID, replyTo int64) {
diff --git a/server/internal/integrations/telegram/outbound_test.go b/server/internal/integrations/telegram/outbound_test.go
index 553d82bbf7..d46efabbd2 100644
--- a/server/internal/integrations/telegram/outbound_test.go
+++ b/server/internal/integrations/telegram/outbound_test.go
@@ -16,6 +16,7 @@ import (
"testing"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
@@ -24,28 +25,31 @@ import (
)
type fakeTelegramOutboundQueries struct {
- task db.AgentTaskQueue
- taskErr error
+ deliveryErr error
channelOrigin bool
- originErr error
binding db.ChannelChatSessionBinding
bindings map[[16]byte]db.ChannelChatSessionBinding
installation db.ChannelInstallation
}
-func (f *fakeTelegramOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
- return f.task, f.taskErr
-}
-
-func (f *fakeTelegramOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pgtype.UUID) (bool, error) {
- return f.channelOrigin, f.originErr
-}
-
-func (f *fakeTelegramOutboundQueries) GetChannelChatSessionBindingBySession(_ context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
- if binding, ok := f.bindings[arg.ChatSessionID.Bytes]; ok {
- return binding, nil
+func (f *fakeTelegramOutboundQueries) GetChannelTaskDelivery(_ context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ if f.deliveryErr != nil {
+ return db.ChannelTaskDelivery{}, f.deliveryErr
+ }
+ if !f.channelOrigin {
+ return db.ChannelTaskDelivery{}, pgx.ErrNoRows
}
- return f.binding, nil
+ binding := f.binding
+ if mapped, ok := f.bindings[taskID.Bytes]; ok {
+ binding = mapped
+ }
+ return db.ChannelTaskDelivery{
+ TaskID: taskID, BindingID: binding.ID, InstallationID: binding.InstallationID,
+ ChannelType: string(TypeTelegram), ChannelChatID: binding.ChannelChatID,
+ ChatType: binding.ChatType, ChannelMessageID: binding.LastMessageID,
+ ChannelThreadID: binding.LastThreadID, RouteRevision: binding.RouteRevision,
+ Config: binding.Config,
+ }, nil
}
func (f *fakeTelegramOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
@@ -59,13 +63,6 @@ func telegramTestUUID(b byte) pgtype.UUID {
return id
}
-func telegramTestTask() db.AgentTaskQueue {
- return db.AgentTaskQueue{
- ChatSessionID: telegramTestUUID(3),
- ChatInputTaskID: telegramTestUUID(4),
- }
-}
-
func telegramTestEvent() events.Event {
return events.Event{
TaskID: "00000000-0000-0000-0000-000000000002",
@@ -116,7 +113,6 @@ func telegramTestBinding(chatID int64) db.ChannelChatSessionBinding {
func newTelegramOutboundQueries() *fakeTelegramOutboundQueries {
return &fakeTelegramOutboundQueries{
- task: telegramTestTask(),
binding: db.ChannelChatSessionBinding{
InstallationID: telegramTestUUID(1),
ChannelChatID: "42",
@@ -131,9 +127,9 @@ func newTelegramOutboundQueries() *fakeTelegramOutboundQueries {
}
}
-func TestResolveTargetFailsClosedWhenTaskLookupFails(t *testing.T) {
+func TestResolveTargetFailsClosedWhenDeliveryLookupFails(t *testing.T) {
q := newTelegramOutboundQueries()
- q.taskErr = errors.New("database unavailable")
+ q.deliveryErr = errors.New("database unavailable")
o := NewOutbound(q, nil, "", nil, nil)
if _, err := o.resolveTarget(context.Background(), telegramTestEvent(), false); err == nil {
@@ -864,8 +860,8 @@ func TestOutboundLegacyLaneCollisionDoesNotBlockAnotherSession(t *testing.T) {
q := newTelegramOutboundQueries()
q.channelOrigin = true
q.bindings = map[[16]byte]db.ChannelChatSessionBinding{
- {15: 3}: telegramTestBinding(42),
- {15: 7}: telegramTestBinding(43),
+ {15: 2}: telegramTestBinding(42),
+ {15: 5}: telegramTestBinding(43),
}
o := NewOutbound(q, nil, api.URL, api.Client(), nil)
ctx, cancel := context.WithCancel(context.Background())
@@ -971,9 +967,9 @@ func TestOutboundBackoffSessionsDoNotExhaustWorkers(t *testing.T) {
q.channelOrigin = true
q.bindings = make(map[[16]byte]db.ChannelChatSessionBinding)
for i := byte(1); i <= terminalWorkerCount+2; i++ {
- q.bindings[[16]byte{15: i}] = telegramTestBinding(100 + int64(i))
+ q.bindings[[16]byte{15: i + 30}] = telegramTestBinding(100 + int64(i))
}
- q.bindings[[16]byte{15: 20}] = telegramTestBinding(200)
+ q.bindings[[16]byte{15: 60}] = telegramTestBinding(200)
o := NewOutbound(q, nil, api.URL, api.Client(), nil)
ctx, cancel := context.WithCancel(context.Background())
o.Start(ctx)
@@ -1029,8 +1025,9 @@ func TestOutboundShutdownAbandonsQueuedRetryWaitingAndInflightJobs(t *testing.T)
q := newTelegramOutboundQueries()
q.channelOrigin = true
q.bindings = map[[16]byte]db.ChannelChatSessionBinding{
- {15: 3}: telegramTestBinding(42),
- {15: 7}: telegramTestBinding(43),
+ {15: 2}: telegramTestBinding(42),
+ {15: 5}: telegramTestBinding(43),
+ {15: 6}: telegramTestBinding(43),
}
o := NewOutbound(q, nil, api.URL, api.Client(), nil)
ctx, cancel := context.WithCancel(context.Background())
diff --git a/server/internal/integrations/telegram/replier.go b/server/internal/integrations/telegram/replier.go
index 468c2f9161..3b51d6937c 100644
--- a/server/internal/integrations/telegram/replier.go
+++ b/server/internal/integrations/telegram/replier.go
@@ -23,12 +23,13 @@ import (
// - NeedsBinding: mint a single-use binding token, reply with the link to
// the in-product redeem page (/telegram/bind).
// - AgentOffline / AgentArchived: a status notice.
-// - FreshPending / IssueUsage: command confirmation or corrective guidance.
+// - FreshPending / ChatStarted / IssueUsage: command confirmation or corrective guidance.
// - Ingested with an /issue result: creation or duplicate confirmation.
// - Dropped addressed /issue commands: an authorization/status refusal.
const (
msgFreshPending = "✅ Fresh start ready. Your next chat message will run without previous context."
+ msgChatStarted = "✅ Started a new Multica chat. Your next message will enter it."
msgIssueUsage = "Please include an issue title. Use:\n\n/issue <title>\n[description] (optional)"
msgIssueNotMember = "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."
msgIssueDisabled = "This Telegram bot isn't connected to Multica (or was disconnected). Ask a workspace admin to reconnect it."
@@ -116,6 +117,11 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
r.logger.WarnContext(ctx, "telegram replier: fresh-start confirmation failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
+ case engine.OutcomeChatStarted:
+ if err := r.post(ctx, inst, msg, msgChatStarted); err != nil {
+ r.logger.WarnContext(ctx, "telegram replier: new-chat confirmation failed",
+ "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
case engine.OutcomeIssueUsage:
if err := r.post(ctx, inst, msg, msgIssueUsage); err != nil {
r.logger.WarnContext(ctx, "telegram replier: issue usage reply failed",
diff --git a/server/internal/integrations/telegram/replier_test.go b/server/internal/integrations/telegram/replier_test.go
index 2d1f3e11cd..e743705e59 100644
--- a/server/internal/integrations/telegram/replier_test.go
+++ b/server/internal/integrations/telegram/replier_test.go
@@ -127,6 +127,7 @@ func TestReplyCoversCommandAndIssueOutcomes(t *testing.T) {
for _, res := range []engine.Result{
{Outcome: engine.OutcomeFreshPending},
+ {Outcome: engine.OutcomeChatStarted},
{Outcome: engine.OutcomeIssueUsage},
{Outcome: engine.OutcomeIngested, IssueID: issueID, IssueIdentifier: "MUL-7", IssueTitle: "Title", IssueDuplicate: true},
{Outcome: engine.OutcomeDropped, DropReason: engine.DropReasonNonWorkspaceMember},
@@ -135,7 +136,7 @@ func TestReplyCoversCommandAndIssueOutcomes(t *testing.T) {
r.Reply(context.Background(), inst, msg, res)
}
- want := []string{msgFreshPending, msgIssueUsage, issueDuplicateText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-7", IssueTitle: "Title"}), msgIssueNotMember, msgIssueDisabled}
+ want := []string{msgFreshPending, msgChatStarted, msgIssueUsage, issueDuplicateText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-7", IssueTitle: "Title"}), msgIssueNotMember, msgIssueDisabled}
if len(got) != len(want) {
t.Fatalf("got %d replies, want %d: %+v", len(got), len(want), got)
}
diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.go
index d76c864300..a7249a6ffe 100644
--- a/server/internal/integrations/telegram/resolvers.go
+++ b/server/internal/integrations/telegram/resolvers.go
@@ -197,6 +197,7 @@ func (r *deduper) Release(ctx context.Context, installationID pgtype.UUID, messa
// mapping testable without a database.
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
@@ -217,6 +218,26 @@ func (r *sessionBinder) EnsureSession(ctx context.Context, p engine.EnsureSessio
})
}
+func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ bindingKey, config, replyThread := telegramSessionRouting(p.Message)
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: bindingKey, BindingConfig: config, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID, ThreadID: replyThread,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{
+ SessionID: result.SessionID, BindingID: result.BindingID,
+ RouteRevision: result.RouteRevision, Append: result.Append,
+ }, err
+}
+
func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error {
return r.session.MarkPendingFresh(ctx, sessionID, messageID)
}
@@ -241,14 +262,20 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
})
}
-func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ in := engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
Sender: p.Sender,
MediaRefs: p.MediaRefs,
- })
+ }
+ if richer, ok := r.session.(interface {
+ BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
+ }); ok {
+ return richer.BindMediaRefsWithResult(ctx, in)
+ }
+ return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}
// ---- audit ----
diff --git a/server/internal/integrations/telegram/resolvers_test.go b/server/internal/integrations/telegram/resolvers_test.go
index 98e1be16e3..d030913002 100644
--- a/server/internal/integrations/telegram/resolvers_test.go
+++ b/server/internal/integrations/telegram/resolvers_test.go
@@ -11,6 +11,7 @@ import (
)
type captureChatSession struct {
+ startIn engine.StartSessionInput
appendIn engine.AppendInput
}
@@ -18,6 +19,11 @@ func (f *captureChatSession) EnsureSession(context.Context, engine.EnsureSession
return pgtype.UUID{}, nil
}
+func (f *captureChatSession) StartSession(_ context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {
+ f.startIn = in
+ return engine.StartSessionResult{SessionID: pgtype.UUID{Valid: true}}, nil
+}
+
func (f *captureChatSession) MarkPendingFresh(context.Context, pgtype.UUID, string) error {
return nil
}
@@ -51,6 +57,49 @@ func TestTelegramSessionBinder_AppendPreservesFreshContextIntent(t *testing.T) {
}
if !session.appendIn.ForceFresh {
- t.Fatal("AppendUserMessage lost ForceFresh; /new <message> would remain in the previous context generation")
+ t.Fatal("AppendUserMessage lost ForceFresh; /clear <message> would remain in the previous context generation")
+ }
+}
+
+func TestTelegramSessionBinder_StartSessionPreservesRouteAndFirstTurn(t *testing.T) {
+ session := &captureChatSession{}
+ binder := &sessionBinder{session: session}
+
+ result, err := binder.StartSession(context.Background(), engine.StartSessionParams{
+ Creator: telegramTestUUID(6),
+ Sender: telegramTestUUID(7),
+ Message: channel.InboundMessage{
+ MessageID: "-100200:10",
+ Text: "summarize this",
+ Source: channel.Source{
+ ChatID: "-100200",
+ ChatType: channel.ChatTypeGroup,
+ ThreadID: "42",
+ },
+ },
+ PersistMessage: true,
+ HistoryBoundaryPending: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+
+ if !result.SessionID.Valid {
+ t.Fatal("StartSession result lost session id")
+ }
+ if got := session.startIn.BindingKey; got != "-100200:42" {
+ t.Fatalf("BindingKey = %q, want forum-topic route", got)
+ }
+ if got := session.startIn.ThreadID; got != "42" {
+ t.Fatalf("ThreadID = %q, want reply topic", got)
+ }
+ if got := session.startIn.Body; got != "summarize this" {
+ t.Fatalf("Body = %q, want first /new turn", got)
+ }
+ if !session.startIn.PersistMessage || !session.startIn.HistoryBoundaryPending {
+ t.Fatalf("start flags = persist:%t history:%t, want both true", session.startIn.PersistMessage, session.startIn.HistoryBoundaryPending)
+ }
+ if session.startIn.Sender != telegramTestUUID(6) || session.startIn.Initiator != telegramTestUUID(7) {
+ t.Fatalf("creator/initiator mapping wrong: %+v", session.startIn)
}
}
diff --git a/server/internal/integrations/telegram/telegram_test.go b/server/internal/integrations/telegram/telegram_test.go
index 6ee745d69a..4fd3a4c730 100644
--- a/server/internal/integrations/telegram/telegram_test.go
+++ b/server/internal/integrations/telegram/telegram_test.go
@@ -153,16 +153,16 @@ func TestInboundGroupHumanReplyNewCommandPreservesQuotedContext(t *testing.T) {
MessageID: 10,
From: &User{ID: 111, FirstName: "Grace"},
Chat: Chat{ID: -100200, Type: "supergroup"},
- Text: "@my_bot /new summarize this",
+ Text: "@my_bot /clear summarize this",
ReplyToMessage: quoted,
}}, 999, "my_bot")
if !ok || !msg.AddressedToBot {
t.Fatalf("message was not accepted: ok=%v addressed=%v", ok, msg.AddressedToBot)
}
if !msg.ForceFresh {
- t.Fatal("/new human reply must request a fresh session before shared routing")
+ t.Fatal("/clear human reply must request a fresh session before shared routing")
}
- if msg.CommandText != "/new summarize this" {
+ if msg.CommandText != "/clear summarize this" {
t.Fatalf("CommandText = %q, want original cleaned command", msg.CommandText)
}
for _, want := range []string{
@@ -174,8 +174,26 @@ func TestInboundGroupHumanReplyNewCommandPreservesQuotedContext(t *testing.T) {
t.Fatalf("enriched Text = %q, missing %q", msg.Text, want)
}
}
- if strings.Contains(msg.Text, "/new") {
- t.Fatalf("agent-readable Text still contains /new: %q", msg.Text)
+ if strings.Contains(msg.Text, "/clear") {
+ t.Fatalf("agent-readable Text still contains /clear: %q", msg.Text)
+ }
+}
+
+func TestInboundGroupChatCommandUsesSameControlNormalization(t *testing.T) {
+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &Message{
+ MessageID: 10,
+ From: &User{ID: 111, FirstName: "Grace"},
+ Chat: Chat{ID: -100200, Type: "supergroup"},
+ Text: "@my_bot /new inspect this",
+ }}, 999, "my_bot")
+ if !ok || !msg.AddressedToBot {
+ t.Fatalf("message was not accepted: ok=%v addressed=%v", ok, msg.AddressedToBot)
+ }
+ if msg.Text != "inspect this" || msg.CommandText != "/new inspect this" {
+ t.Fatalf("Text/CommandText = %q/%q", msg.Text, msg.CommandText)
+ }
+ if msg.ForceFresh {
+ t.Fatal("/new must not set /clear's ForceFresh semantic")
}
}
@@ -250,7 +268,7 @@ func TestInboundTelegramCommandSuffixes(t *testing.T) {
wantFresh bool
}{
{text: "/fresh@my_bot continue", wantText: "/fresh continue", wantFresh: false},
- {text: "/new@my_bot continue", wantText: "continue", wantFresh: true},
+ {text: "/clear@my_bot continue", wantText: "continue", wantFresh: true},
{text: "/issue@my_bot fix login", wantText: "/issue fix login", wantFresh: false},
} {
u := Update{UpdateID: 1, Message: &Message{
diff --git a/server/internal/integrations/wecom/inbound_media_bind_db_test.go b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
index 70f902729e..2971e81440 100644
--- a/server/internal/integrations/wecom/inbound_media_bind_db_test.go
+++ b/server/internal/integrations/wecom/inbound_media_bind_db_test.go
@@ -30,6 +30,7 @@ import (
"testing"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
@@ -166,9 +167,16 @@ type bindTestTasks struct {
promoted int
}
-func (*bindTestTasks) EnqueueChannelChatTask(context.Context, db.ChatSession, pgtype.UUID, bool, int64) (db.AgentTaskQueue, error) {
+func (*bindTestTasks) EnqueueChannelChatTask(context.Context, db.ChatSession, pgtype.UUID, bool, int64, pgtype.UUID, int64) (db.AgentTaskQueue, error) {
return db.AgentTaskQueue{}, nil
}
+func (*bindTestTasks) PrepareChatTaskEnqueue(context.Context, pgtype.UUID, pgtype.UUID) (service.PreparedChatTaskEnqueue, error) {
+ return service.PreparedChatTaskEnqueue{}, nil
+}
+func (*bindTestTasks) EnqueuePreparedChannelChatTaskInTx(context.Context, pgx.Tx, db.ChatSession, pgtype.UUID, bool, int64, service.PreparedChatTaskEnqueue) (db.AgentTaskQueue, error) {
+ return db.AgentTaskQueue{}, nil
+}
+func (*bindTestTasks) FinalizeChatTaskEnqueue(context.Context, db.AgentTaskQueue) {}
func (b *bindTestTasks) PromoteChannelChatTasksIfMediaReady(context.Context, pgtype.UUID) error {
b.mu.Lock()
defer b.mu.Unlock()
diff --git a/server/internal/integrations/wecom/inbound_media_test.go b/server/internal/integrations/wecom/inbound_media_test.go
index b00fbfc731..5a8abf88a3 100644
--- a/server/internal/integrations/wecom/inbound_media_test.go
+++ b/server/internal/integrations/wecom/inbound_media_test.go
@@ -404,6 +404,50 @@ func TestDispatchFrame_GroupMentionedMixedCommand(t *testing.T) {
}
}
+func TestDispatchFrame_MixedSessionControlsShareNormalization(t *testing.T) {
+ tests := []struct {
+ command string
+ wantFresh bool
+ }{
+ {command: "/clear 点评一下", wantFresh: true},
+ {command: "/new 点评一下", wantFresh: false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.command, func(t *testing.T) {
+ got, called, _ := dispatchOne(t, mixedFrame(t, nil,
+ imageRun("https://cos.example.com/a"),
+ textRun(tc.command),
+ ))
+ if !called {
+ t.Fatal("the mixed control message never reached the handler")
+ }
+ if got.Text != "[Image]\n点评一下" {
+ t.Fatalf("visible body = %q, want media with stripped directive", got.Text)
+ }
+ if got.CommandText != tc.command {
+ t.Fatalf("CommandText = %q, want original control source %q", got.CommandText, tc.command)
+ }
+ if got.ForceFresh != tc.wantFresh {
+ t.Fatalf("ForceFresh = %v, want %v", got.ForceFresh, tc.wantFresh)
+ }
+ })
+ }
+}
+
+func TestDispatchFrame_GroupMentionedMixedChatStripsAddressingAndDirective(t *testing.T) {
+ group := map[string]any{"chattype": "group", "chatid": "GROUP_1"}
+ got, called, _ := dispatchOneAs(t, mixedFrame(t, group,
+ imageRun("https://cos.example.com/a"),
+ textRun("@Multica Bot /new 点评一下"),
+ ), "Multica Bot")
+ if !called {
+ t.Fatal("the group message never reached the handler")
+ }
+ if got.Text != "[Image]\n点评一下" || got.CommandText != "/new 点评一下" {
+ t.Fatalf("Text/CommandText = %q/%q", got.Text, got.CommandText)
+ }
+}
+
// TestDispatchFrame_GroupMentionedSpokenIssueWithAnImage is the intersection
// of all three decisions that meet in this function, and the only test that
// holds them together.
diff --git a/server/internal/integrations/wecom/outbound.go b/server/internal/integrations/wecom/outbound.go
index 966eb5864a..c935fe7c13 100644
--- a/server/internal/integrations/wecom/outbound.go
+++ b/server/internal/integrations/wecom/outbound.go
@@ -44,7 +44,7 @@ import (
// outboundQueries is the slice of generated queries the WeCom outbound
// subscriber needs. *db.Queries satisfies it.
type outboundQueries interface {
- GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
+ GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
@@ -144,16 +144,6 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// Issue / autopilot tasks carry no chat_session.
return nil
}
- binding, err := o.q.GetChannelChatSessionBindingBySession(ctx, db.GetChannelChatSessionBindingBySessionParams{
- ChatSessionID: sessionID,
- ChannelType: channelTypeWecom,
- })
- if err != nil {
- if errors.Is(err, pgx.ErrNoRows) {
- return nil // not a wecom session (Slack / Lark / web-only)
- }
- return fmt.Errorf("wecom: lookup chat binding: %w", err)
- }
// An empty completion normally ends the turn here. It does not when the
// agent produced a file and said nothing about it: the platform writes an
// assistant message for exactly that case, and returning now would throw
@@ -180,6 +170,17 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
if !ok {
return nil
}
+ delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil
+ }
+ return fmt.Errorf("wecom: lookup task delivery: %w", err)
+ }
+ if delivery.ChannelType != channelTypeWecom {
+ return nil
+ }
+ binding := wecomBindingFromTaskDelivery(delivery)
task, err := o.q.GetAgentTask(ctx, taskID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -240,6 +241,16 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
return nil
}
+func wecomBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {
+ return db.ChannelChatSessionBinding{
+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,
+ ChannelType: delivery.ChannelType, ChannelChatID: delivery.ChannelChatID,
+ ChatType: delivery.ChatType,
+ LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,
+ RouteRevision: delivery.RouteRevision, Config: delivery.Config,
+ }
+}
+
// chatDoneTaskID recovers the task id an EventChatDone belongs to. The
// envelope's TaskID is preferred, with the payload as the fallback —
// service.broadcastChatDone sets ChatDonePayload.TaskID and leaves the
diff --git a/server/internal/integrations/wecom/outbound_test.go b/server/internal/integrations/wecom/outbound_test.go
index b676174d26..9325778e56 100644
--- a/server/internal/integrations/wecom/outbound_test.go
+++ b/server/internal/integrations/wecom/outbound_test.go
@@ -83,8 +83,17 @@ type fakeOutboundQueries struct {
func askedOverWecom() *bool { asked := true; return &asked }
func askedInTheWebUI() *bool { asked := false; return &asked }
-func (f *fakeOutboundQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
- return f.sessionBinding, f.sessionErr
+func (f *fakeOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {
+ if f.sessionErr != nil {
+ return db.ChannelTaskDelivery{}, f.sessionErr
+ }
+ return db.ChannelTaskDelivery{
+ BindingID: f.sessionBinding.ID, InstallationID: f.sessionBinding.InstallationID,
+ ChannelType: channelTypeWecom, ChannelChatID: f.sessionBinding.ChannelChatID,
+ ChatType: f.sessionBinding.ChatType,
+ ChannelMessageID: f.sessionBinding.LastMessageID, ChannelThreadID: f.sessionBinding.LastThreadID,
+ RouteRevision: f.sessionBinding.RouteRevision, Config: f.sessionBinding.Config,
+ }, nil
}
func (f *fakeOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {
return f.installation, f.installErr
diff --git a/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go b/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go
index 122a8afbe3..47bbc22a90 100644
--- a/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go
+++ b/server/internal/integrations/wecom/regression_group_mention_swallows_command_test.go
@@ -8,7 +8,7 @@ package wecom
// 失败". The shared command parsers read the first non-empty line and want the
// directive at the start of it, so with the mention still in front they see
// "@Multica" and decide this is ordinary prose. Every slash command in every
-// group was silently dropped: no issue filed, no fresh session, and nothing
+// group was silently dropped: no issue filed, no context clear, and nothing
// said to the person about it.
//
// Slack strips its mention token before classifying (slack/inbound.go
@@ -88,20 +88,20 @@ func TestAnIssueCommandAfterAMentionIsStillACommand(t *testing.T) {
}
}
-// TestAFreshSessionCommandAfterAMentionIsStillACommand: /new is the other
+// TestAFreshSessionCommandAfterAMentionIsStillACommand: /clear is the other
// shared directive. When it is dropped the agent keeps the previous thread and
// answers with a conversation the person was trying to leave behind.
func TestAFreshSessionCommandAfterAMentionIsStillACommand(t *testing.T) {
t.Parallel()
for _, tc := range []struct{ name, body string }{
- {"mention then command", "@Andrew /new 重新分析一下"},
- {"two mentions then command", "@Andrew @Bowen /new 重新分析一下"},
- {"mention, full-width space, command", "@Andrew /new 重新分析一下"},
+ {"mention then command", "@Andrew /clear 重新分析一下"},
+ {"two mentions then command", "@Andrew @Bowen /clear 重新分析一下"},
+ {"mention, full-width space, command", "@Andrew /clear 重新分析一下"},
} {
t.Run(tc.name, func(t *testing.T) {
msg := dispatchGroupMessage(t, "", tc.body)
if _, ok := engine.ParseFreshSessionCommand(msg.CommandText); !ok {
- t.Fatalf("the shared parser did not see /new in %q.\nCommandText = %q — the request for a "+
+ t.Fatalf("the shared parser did not see /clear in %q.\nCommandText = %q — the request for a "+
"fresh session is silently dropped and the agent answers with the old conversation "+
"still in hand.", tc.body, msg.CommandText)
}
diff --git a/server/internal/integrations/wecom/replier.go b/server/internal/integrations/wecom/replier.go
index 3eb5c98f52..31a52c1234 100644
--- a/server/internal/integrations/wecom/replier.go
+++ b/server/internal/integrations/wecom/replier.go
@@ -24,7 +24,8 @@ import (
const (
agentOfflineText = "⚠️ 智能体当前不在线,你的消息已收到,等它上线后会处理。"
agentArchivedText = "⚠️ 该智能体已归档,无法回复。请联系工作区管理员。"
- freshPendingText = "✅ 已准备开始新对话。你的下一条聊天消息将不带之前的上下文运行。"
+ freshPendingText = "✅ 已准备从空上下文运行。你的下一条聊天消息仍会进入当前对话,但不会带上之前的上下文。"
+ chatStartedText = "✅ 已新建 Multica 对话。你的下一条消息会进入该对话。"
issueUsageText = "请填写任务标题,格式如下:\n\n`/issue <标题>`\n`[描述]`(可选)"
)
@@ -121,6 +122,10 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall
r.logger.WarnContext(ctx, "wecom replier: fresh-start confirmation failed",
"installation_id", util.UUIDToString(inst.ID), "error", err)
}
+ case engine.OutcomeChatStarted:
+ if err := r.post(ctx, inst, msg, chatStartedText); err != nil {
+ r.logger.WarnContext(ctx, "wecom replier: new-chat confirmation failed", "installation_id", util.UUIDToString(inst.ID), "error", err)
+ }
case engine.OutcomeIssueUsage:
if err := r.post(ctx, inst, msg, issueUsageText); err != nil {
r.logger.WarnContext(ctx, "wecom replier: issue usage reply failed",
diff --git a/server/internal/integrations/wecom/resolvers_test.go b/server/internal/integrations/wecom/resolvers_test.go
index 5d02b31981..bb11938d62 100644
--- a/server/internal/integrations/wecom/resolvers_test.go
+++ b/server/internal/integrations/wecom/resolvers_test.go
@@ -26,6 +26,7 @@ import (
// param mapping can be asserted without a database.
type fakeSessionBinder struct {
ensureIn engine.EnsureSessionInput
+ startIn engine.StartSessionInput
appendIn engine.AppendInput
bindIn engine.BindMediaInput
binds int
@@ -42,6 +43,10 @@ func (f *fakeSessionBinder) EnsureSession(_ context.Context, in engine.EnsureSes
f.ensureIn = in
return f.sessID, nil
}
+func (f *fakeSessionBinder) StartSession(_ context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {
+ f.startIn = in
+ return engine.StartSessionResult{SessionID: f.sessID}, nil
+}
func (f *fakeSessionBinder) MarkPendingFresh(context.Context, pgtype.UUID, string) error { return nil }
func (f *fakeSessionBinder) AppendUserMessage(_ context.Context, in engine.AppendInput) (engine.AppendResult, error) {
f.appendIn = in
@@ -70,6 +75,41 @@ func TestSessionBinder_EnsureSessionMapsGroupKey(t *testing.T) {
}
}
+func TestSessionBinder_StartSessionMapsWeComRouteAndFirstTurn(t *testing.T) {
+ t.Parallel()
+ fb := &fakeSessionBinder{sessID: mustTestUUID(t)}
+ b := &sessionBinder{session: fb}
+ inst := engine.ResolvedInstallation{ID: mustTestUUID(t), WorkspaceID: mustTestUUID(t), AgentID: mustTestUUID(t)}
+ sender := mustTestUUID(t)
+ creator := mustTestUUID(t)
+ claim := mustTestUUID(t)
+ result, err := b.StartSession(context.Background(), engine.StartSessionParams{
+ Installation: inst,
+ Creator: creator,
+ Sender: sender,
+ ClaimToken: claim,
+ Message: channel.InboundMessage{
+ MessageID: "m1", Text: "first turn",
+ Source: channel.Source{ChatID: "GROUP_1", ChatType: channel.ChatTypeGroup},
+ },
+ MediaPendingSeconds: 45,
+ PersistMessage: true,
+ })
+ if err != nil {
+ t.Fatalf("StartSession: %v", err)
+ }
+ if result.SessionID != fb.sessID {
+ t.Fatal("StartSession lost shared-session result")
+ }
+ got := fb.startIn
+ if got.BindingKey != "GROUP_1" || got.Body != "first turn" || got.MessageID != "m1" || got.ClaimToken != claim || got.MediaPendingSeconds != 45 || !got.PersistMessage {
+ t.Fatalf("start mapping wrong: %+v", got)
+ }
+ if got.Sender != creator || got.Initiator != sender {
+ t.Fatalf("creator/initiator mapping wrong: %+v", got)
+ }
+}
+
func TestSessionBinder_AppendUsesTextAsCommand(t *testing.T) {
t.Parallel()
fb := &fakeSessionBinder{}
@@ -97,7 +137,7 @@ func TestSessionBinder_BindMediaReachesTheSessionStore(t *testing.T) {
refs := []channel.MediaRef{{StorageKey: "k", Filename: "photo.jpg"}}
issue := pgtype.UUID{Bytes: [16]byte{7}, Valid: true}
- if err := b.BindMedia(context.Background(), engine.BindMediaParams{
+ if _, err := b.BindMedia(context.Background(), engine.BindMediaParams{
MediaRefs: refs,
IssueID: issue,
}); err != nil {
diff --git a/server/internal/integrations/wecom/wecom_resolvers.go b/server/internal/integrations/wecom/wecom_resolvers.go
index 77207fbbbf..59b6cbc5b0 100644
--- a/server/internal/integrations/wecom/wecom_resolvers.go
+++ b/server/internal/integrations/wecom/wecom_resolvers.go
@@ -84,11 +84,28 @@ func NewResolverSet(
// production value.
type engineSessionBinder interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
+ StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error)
MarkPendingFresh(ctx context.Context, sessionID pgtype.UUID, messageID string) error
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
+func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {
+ result, err := r.session.StartSession(ctx, engine.StartSessionInput{
+ EnsureSessionInput: engine.EnsureSessionInput{
+ WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,
+ InstallationID: p.Installation.ID, Sender: p.Creator,
+ BindingKey: p.Message.Source.ChatID, ChatType: p.Message.Source.ChatType,
+ },
+ Initiator: p.Sender,
+ Body: p.Message.Text, MessageID: p.Message.MessageID,
+ ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,
+ PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,
+ BeforeCommit: p.BeforeCommit,
+ })
+ return engine.StartSessionResult{SessionID: result.SessionID, BindingID: result.BindingID, RouteRevision: result.RouteRevision, Append: result.Append}, err
+}
+
// ---- installation routing ----
type installationResolver struct{ store *Store }
@@ -267,8 +284,8 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
// rather than to the chat message that created it; the other issue fields are
// what let the description reference them. Feishu passes all of them
// (lark/feishu_resolvers.go:223).
-func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
- return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) (engine.BindMediaResult, error) {
+ in := engine.BindMediaInput{
MessageID: p.MessageID,
SessionID: p.SessionID,
WorkspaceID: p.WorkspaceID,
@@ -278,7 +295,13 @@ func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams)
IssueCommandText: p.IssueCommandText,
Body: p.Body,
MediaRefs: p.MediaRefs,
- })
+ }
+ if richer, ok := r.session.(interface {
+ BindMediaRefsWithResult(context.Context, engine.BindMediaInput) (engine.BindMediaResult, error)
+ }); ok {
+ return richer.BindMediaRefsWithResult(ctx, in)
+ }
+ return engine.BindMediaResult{}, r.session.BindMediaRefs(ctx, in)
}
// ---- audit ----
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
index 47f4d3671f..f5d2c5b9d7 100644
--- a/server/internal/integrations/wecom/ws_frame.go
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -427,7 +427,7 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
// its "/issue …" on the first line the parser reads.
//
// In a group the @-mention IS how you reach the bot, so it arrives glued to
- // whatever was typed after it — "@Andrew /new" is a person asking for a
+ // whatever was typed after it — "@Andrew /clear" is a person asking for a
// fresh session, not prose that happens to contain a word — and the
// addressing comes off the front.
//
@@ -443,6 +443,18 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
if chatType == channel.ChatTypeGroup {
command = stripLeadingMentions(command, botDisplayName)
}
+ media := mc.attachments()
+ normalizedText, control, controlNormalized := normalizeWeComControlLayout(
+ mc, text, command, chatType, botDisplayName, len(media) > 0,
+ )
+ if controlNormalized {
+ text = normalizedText
+ // A media-bearing bare /clear is a real turn, not the shared pending
+ // sentinel. ForceFresh below carries the already-consumed directive.
+ if control.Kind == engine.ControlCommandFreshSession && control.Body == "" {
+ command = text
+ }
+ }
wm := InboundMessage{
BotID: botID,
@@ -453,7 +465,7 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
SenderUserID: senderID,
Content: text,
ReqID: reqID,
- Media: mc.attachments(),
+ Media: media,
}
raw, _ := json.Marshal(wm)
@@ -472,6 +484,7 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
// (feishu_channel.go:139) and Slack from its cleaned text
// (slack/inbound.go:131); WeCom was the one adapter leaving it empty.
CommandText: command,
+ ForceFresh: controlNormalized && control.Kind == engine.ControlCommandFreshSession,
// A pure /issue command in WeCom should NOT trigger the
// agent — the engine already creates the issue and the
// OutboundReplier already sends "✅ 已创建 #N". Letting the agent
@@ -499,6 +512,68 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
}
}
+// normalizeWeComControlLayout removes /clear or /new from the agent-readable
+// body while retaining media placeholders in their original mixed-message
+// positions. CommandText remains the sender-authored, placeholder-free source
+// so Router alone applies the semantic difference between the directives.
+func normalizeWeComControlLayout(
+ mc aibotMsgCallback,
+ visible string,
+ command string,
+ chatType channel.ChatType,
+ botDisplayName string,
+ hasMedia bool,
+) (string, engine.ControlCommand, bool) {
+ control, ok := engine.ParseControlCommand(command)
+ if !ok || (control.Body == "" && !hasMedia) {
+ return visible, engine.ControlCommand{}, false
+ }
+
+ normalizeWords := func(words string) string {
+ if chatType == channel.ChatTypeGroup {
+ return stripLeadingMentions(words, botDisplayName)
+ }
+ return strings.TrimSpace(words)
+ }
+
+ switch strings.ToLower(mc.MsgType) {
+ case "text":
+ itemControl, itemOK := engine.ParseControlCommand(normalizeWords(mc.Text.Content))
+ if !itemOK || itemControl.Kind != control.Kind {
+ return visible, engine.ControlCommand{}, false
+ }
+ return itemControl.Body, control, true
+ case "voice":
+ itemControl, itemOK := engine.ParseControlCommand(normalizeWords(mc.Voice.Content))
+ if !itemOK || itemControl.Kind != control.Kind {
+ return visible, engine.ControlCommand{}, false
+ }
+ return itemControl.Body, control, true
+ case "mixed":
+ var runs []string
+ consumed := false
+ for _, item := range mc.Mixed.MsgItem {
+ rendered := item.render()
+ if !consumed {
+ if words := item.words(); words != "" {
+ itemControl, itemOK := engine.ParseControlCommand(normalizeWords(words))
+ if itemOK && itemControl.Kind == control.Kind {
+ rendered = itemControl.Body
+ consumed = true
+ }
+ }
+ }
+ if rendered != "" {
+ runs = append(runs, rendered)
+ }
+ }
+ if consumed {
+ return strings.Join(runs, "\n"), control, true
+ }
+ }
+ return visible, engine.ControlCommand{}, false
+}
+
// stripLeadingMentions removes the @-mentions a message opens with, which in a
// group chat is how the sender addresses the bot. WeCom puts them in the text
// and sends no mention list alongside it, so there is nothing to match against
@@ -512,8 +587,10 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac
// somebody — "@Andrew ask @李雷 about yesterday" is one instruction naming one
// colleague — and stripping that would quietly rewrite what they said.
//
-// This feeds command classification only. The stored message keeps the text
-// exactly as it arrived, so the transcript still shows who was addressed.
+// This primarily feeds command classification. For a recognized /clear or /new,
+// normalizeWeComControlLayout also applies the same addressing cleanup while
+// rebuilding the agent-visible mixed-media body, so neither the bot mention nor
+// the consumed directive is persisted as prompt text.
//
// Slack does the same thing with a regex over its mention token
// (slack/inbound.go cleanText); Feishu is handed an already-clean command body
@@ -526,7 +603,7 @@ func stripLeadingMentions(s, botName string) string {
}
// Our own name first, matched whole. A display name may contain
// spaces — "Multica Bot" is the obvious one — and cutting at the
- // first space would leave "Bot /new 重新分析", which is not a command,
+ // first space would leave "Bot /clear 重新分析", which is not a command,
// so every slash command in that group would still be dropped.
//
// The name is not guessed. It comes from the installation config, set
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
index 4aa6bcf97a..6edeca2958 100644
--- a/server/internal/integrations/wecom/ws_frame_test.go
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -67,7 +67,7 @@ func TestChannelMessageFromCallback_P2PMentionIsProseNotACommand(t *testing.T) {
t.Parallel()
for _, tc := range []struct{ name, content string }{
{"issue directive after a colleague's name", "@李雷 /issue 帮我问问他"},
- {"fresh-session directive after a colleague's name", "@李雷 /new 的排期你问一下"},
+ {"fresh-session directive after a colleague's name", "@李雷 /clear 的排期你问一下"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
diff --git a/server/internal/migrations/channel_chat_route_rollback_test.go b/server/internal/migrations/channel_chat_route_rollback_test.go
new file mode 100644
index 0000000000..f75e618ac6
--- /dev/null
+++ b/server/internal/migrations/channel_chat_route_rollback_test.go
@@ -0,0 +1,84 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func TestChannelOutboundMessageDownRefusesExplicitChannelChat(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ schema := "channel_route_down_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE chat_session (
+ id UUID PRIMARY KEY,
+ explicitly_created_at TIMESTAMPTZ
+ );
+ CREATE TABLE channel_chat_session_binding (
+ chat_session_id UUID NOT NULL,
+ retired_at TIMESTAMPTZ
+ );
+ CREATE TABLE channel_outbound_message (id UUID);
+ INSERT INTO chat_session (id, explicitly_created_at)
+ VALUES ('22222222-2222-2222-2222-222222222222', now());
+ INSERT INTO channel_chat_session_binding (chat_session_id, retired_at)
+ VALUES ('22222222-2222-2222-2222-222222222222', NULL);
+ `); err != nil {
+ t.Fatalf("create fixture: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "425_channel_outbound_message.down.sql")); err == nil ||
+ !strings.Contains(err.Error(), "cannot roll back channel chat routes") {
+ t.Fatalf("down migration error = %v, want explicit channel Chat refusal", err)
+ }
+ var outboundExists bool
+ if err := conn.QueryRow(ctx, `SELECT to_regclass('channel_outbound_message') IS NOT NULL`).Scan(&outboundExists); err != nil {
+ t.Fatalf("check preserved outbound table: %v", err)
+ }
+ if !outboundExists {
+ t.Fatal("down migration dropped outbound table despite refused rollback")
+ }
+
+ if _, err := conn.Exec(ctx, `UPDATE chat_session SET explicitly_created_at = NULL`); err != nil {
+ t.Fatalf("clear explicit origin: %v", err)
+ }
+ applyMigrationFile(t, ctx, conn.Conn(), "425_channel_outbound_message.down.sql")
+ if err := conn.QueryRow(ctx, `SELECT to_regclass('channel_outbound_message') IS NOT NULL`).Scan(&outboundExists); err != nil {
+ t.Fatalf("check dropped outbound table: %v", err)
+ }
+ if outboundExists {
+ t.Fatal("down migration left outbound table without channel route state")
+ }
+}
diff --git a/server/internal/migrations/channel_task_delivery_backfill_test.go b/server/internal/migrations/channel_task_delivery_backfill_test.go
new file mode 100644
index 0000000000..2660b3cd15
--- /dev/null
+++ b/server/internal/migrations/channel_task_delivery_backfill_test.go
@@ -0,0 +1,332 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/chatoriginbackfill"
+)
+
+func TestChatOriginHookBackfillsOnlyFirstPartySessionsInShortPages(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ schema := "channel_route_generation_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE chat_session (
+ id UUID PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL
+ );
+ CREATE TABLE chat_message (
+ chat_session_id UUID NOT NULL,
+ channel_ingested BOOLEAN NOT NULL
+ );
+ CREATE TABLE channel_chat_session_binding (
+ id UUID PRIMARY KEY,
+ chat_session_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ channel_chat_id TEXT NOT NULL,
+ chat_type TEXT NOT NULL
+ );
+
+ INSERT INTO chat_session (id, created_at) VALUES
+ ('11111111-1111-1111-1111-111111111111', '2026-08-01T00:00:00Z'),
+ ('22222222-2222-2222-2222-222222222222', '2026-08-02T00:00:00Z'),
+ ('33333333-3333-3333-3333-333333333333', '2026-08-03T00:00:00Z');
+ INSERT INTO channel_chat_session_binding (
+ id, chat_session_id, installation_id, channel_chat_id, chat_type
+ ) VALUES (
+ '44444444-4444-4444-4444-444444444444',
+ '22222222-2222-2222-2222-222222222222',
+ '55555555-5555-5555-5555-555555555555',
+ 'channel-1', 'group'
+ );
+ INSERT INTO chat_message (chat_session_id, channel_ingested)
+ VALUES ('33333333-3333-3333-3333-333333333333', TRUE);
+ `); err != nil {
+ t.Fatalf("create legacy fixture: %v", err)
+ }
+
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "420_channel_chat_route_generation.up.sql")); err != nil {
+ t.Fatalf("apply migration: %v", err)
+ }
+ var preHookCount int
+ if err := conn.QueryRow(ctx, `SELECT count(*) FROM chat_session WHERE explicitly_created_at IS NOT NULL`).Scan(&preHookCount); err != nil {
+ t.Fatalf("count pre-hook sessions: %v", err)
+ }
+ if preHookCount != 0 {
+ t.Fatalf("migration 420 rewrote %d chat sessions; backfill must stay in the paged hook", preHookCount)
+ }
+
+ result, err := chatoriginbackfill.Hook(ctx, pool, chatoriginbackfill.HookOptions{
+ BatchSize: 1,
+ SessionTable: pgx.Identifier{schema, "chat_session"}.Sanitize(),
+ BindingTable: pgx.Identifier{schema, "channel_chat_session_binding"}.Sanitize(),
+ MessageTable: pgx.Identifier{schema, "chat_message"}.Sanitize(),
+ })
+ if err != nil {
+ t.Fatalf("run Chat origin hook: %v", err)
+ }
+ if result.RowsVisited != 3 || result.RowsBackfilled != 1 || result.Pages != 3 {
+ t.Fatalf("unexpected hook result: %+v", result)
+ }
+ retry, err := chatoriginbackfill.Hook(ctx, pool, chatoriginbackfill.HookOptions{
+ BatchSize: 1,
+ SessionTable: pgx.Identifier{schema, "chat_session"}.Sanitize(),
+ BindingTable: pgx.Identifier{schema, "channel_chat_session_binding"}.Sanitize(),
+ MessageTable: pgx.Identifier{schema, "chat_message"}.Sanitize(),
+ })
+ if err != nil {
+ t.Fatalf("retry Chat origin hook: %v", err)
+ }
+ if retry.RowsBackfilled != 0 {
+ t.Fatalf("idempotent retry backfilled %d rows", retry.RowsBackfilled)
+ }
+
+ rows, err := conn.Query(ctx, `
+ SELECT id, explicitly_created_at IS NOT NULL
+ FROM chat_session
+ ORDER BY id
+ `)
+ if err != nil {
+ t.Fatalf("query migrated sessions: %v", err)
+ }
+ defer rows.Close()
+
+ want := []bool{true, false, false}
+ i := 0
+ for rows.Next() {
+ var id uuid.UUID
+ var explicit bool
+ if err := rows.Scan(&id, &explicit); err != nil {
+ t.Fatalf("scan migrated session: %v", err)
+ }
+ if i >= len(want) {
+ t.Fatalf("unexpected migrated session %s", id)
+ }
+ if explicit != want[i] {
+ t.Fatalf("session %s explicit = %t, want %t", id, explicit, want[i])
+ }
+ i++
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate migrated sessions: %v", err)
+ }
+ if i != len(want) {
+ t.Fatalf("migrated session rows = %d, want %d", i, len(want))
+ }
+}
+
+func TestChannelTaskDeliveryBackfillSnapshotsOnlyTasksWithLiveRoutingData(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ for _, tc := range []struct {
+ name string
+ withBinding bool
+ wantCount int
+ }{
+ {name: "backfills resolvable task", withBinding: true, wantCount: 1},
+ {name: "skips task whose installation route was removed", wantCount: 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ schema := "channel_delivery_backfill_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE agent_task_queue (
+ id UUID PRIMARY KEY,
+ chat_session_id UUID,
+ chat_input_task_id UUID,
+ status TEXT NOT NULL
+ );
+ CREATE TABLE chat_message (
+ task_id UUID,
+ role TEXT NOT NULL,
+ channel_ingested BOOLEAN NOT NULL
+ );
+ CREATE TABLE channel_chat_session_binding (
+ id UUID PRIMARY KEY,
+ installation_id UUID NOT NULL,
+ channel_type TEXT NOT NULL,
+ channel_chat_id TEXT NOT NULL,
+ chat_type TEXT NOT NULL,
+ last_message_id TEXT,
+ last_thread_id TEXT,
+ route_revision BIGINT NOT NULL,
+ config JSONB NOT NULL,
+ chat_session_id UUID NOT NULL
+ );
+ CREATE TABLE channel_task_delivery (
+ task_id UUID PRIMARY KEY,
+ binding_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ channel_type TEXT NOT NULL,
+ channel_chat_id TEXT NOT NULL,
+ chat_type TEXT NOT NULL,
+ channel_message_id TEXT,
+ channel_thread_id TEXT,
+ route_revision BIGINT NOT NULL,
+ config JSONB NOT NULL
+ );
+ `); err != nil {
+ t.Fatalf("create fixture tables: %v", err)
+ }
+
+ const taskID = "11111111-1111-1111-1111-111111111111"
+ const sessionID = "22222222-2222-2222-2222-222222222222"
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO agent_task_queue (id, chat_session_id, status)
+ VALUES ($1, $2, 'running')
+ `, taskID, sessionID); err != nil {
+ t.Fatalf("seed task: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO chat_message (task_id, role, channel_ingested)
+ VALUES ($1, 'user', TRUE)
+ `, taskID); err != nil {
+ t.Fatalf("seed message: %v", err)
+ }
+ if tc.withBinding {
+ if _, err := conn.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding (
+ id, installation_id, channel_type, channel_chat_id, chat_type,
+ last_message_id, last_thread_id, route_revision, config, chat_session_id
+ ) VALUES (
+ '33333333-3333-3333-3333-333333333333',
+ '44444444-4444-4444-4444-444444444444',
+ 'slack', 'D1', 'p2p', 'm1', 'm1', 1, '{}', $1
+ )
+ `, sessionID); err != nil {
+ t.Fatalf("seed binding: %v", err)
+ }
+ }
+
+ _, err = conn.Exec(ctx, readMigrationFile(t, "427_channel_task_delivery_backfill.up.sql"))
+ if err != nil {
+ t.Fatalf("apply migration: %v", err)
+ }
+ var count int
+ if err := conn.QueryRow(ctx, `SELECT count(*) FROM channel_task_delivery WHERE task_id = $1`, taskID).Scan(&count); err != nil {
+ t.Fatalf("count deliveries: %v", err)
+ }
+ if count != tc.wantCount {
+ t.Fatalf("delivery rows = %d, want %d", count, tc.wantCount)
+ }
+ })
+ }
+}
+
+func TestChannelTaskDeliveryPrimaryKeyReusesConcurrentIndex(t *testing.T) {
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ defer pool.Close()
+
+ schema := "channel_delivery_pkey_" + strings.ReplaceAll(uuid.NewString(), "-", "")
+ quotedSchema := pgx.Identifier{schema}.Sanitize()
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+quotedSchema); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA "+quotedSchema+" CASCADE")
+ })
+
+ conn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire connection: %v", err)
+ }
+ defer conn.Release()
+ if _, err := conn.Exec(ctx, `SELECT set_config('search_path', $1, false)`, schema); err != nil {
+ t.Fatalf("set search path: %v", err)
+ }
+ if _, err := conn.Exec(ctx, `
+ CREATE TABLE channel_task_delivery (
+ task_id UUID NOT NULL,
+ binding_id UUID NOT NULL
+ )
+ `); err != nil {
+ t.Fatalf("create delivery table: %v", err)
+ }
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "423_channel_task_delivery_pkey_index.up.sql")); err != nil {
+ t.Fatalf("build concurrent unique index: %v", err)
+ }
+ if _, err := conn.Exec(ctx, readMigrationFile(t, "424_channel_task_delivery_primary_key.up.sql")); err != nil {
+ t.Fatalf("attach primary key: %v", err)
+ }
+
+ var constraintType string
+ var primary, valid bool
+ if err := conn.QueryRow(ctx, `
+ SELECT constraint_row.contype::text, index_row.indisprimary, index_row.indisvalid
+ FROM pg_constraint AS constraint_row
+ JOIN pg_index AS index_row ON index_row.indexrelid = constraint_row.conindid
+ WHERE constraint_row.conrelid = to_regclass($1)
+ AND constraint_row.conname = 'channel_task_delivery_pkey'
+ `, schema+".channel_task_delivery").Scan(&constraintType, &primary, &valid); err != nil {
+ t.Fatalf("inspect primary key: %v", err)
+ }
+ if constraintType != "p" || !primary || !valid {
+ t.Fatalf("constraint type=%q primary=%t valid=%t", constraintType, primary, valid)
+ }
+}
diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.go
index 5549c7d527..01225c678d 100644
--- a/server/internal/service/attribution_stamp_test.go
+++ b/server/internal/service/attribution_stamp_test.go
@@ -1232,6 +1232,7 @@ func TestEnqueueChatTaskStampsChatEvidence(t *testing.T) {
t.Fatalf("seed chat session: %v", err)
}
t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID) })
+ seedChannelTaskBinding(t, pool, chatSessionID)
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
@@ -1282,6 +1283,7 @@ func TestEnqueueChatTaskDefersForChannelMediaAndPromotesWhenReady(t *testing.T)
t.Cleanup(func() {
_, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
})
+ seedChannelTaskBinding(t, pool, chatSessionID)
if err := pool.QueryRow(ctx, `
INSERT INTO chat_message (chat_session_id, role, content)
VALUES ($1, 'user', 'first') RETURNING id`, chatSessionID).Scan(&priorMessageID); err != nil {
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index 9be369d27e..f07c9df421 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -171,6 +171,102 @@ func TestRuntimeOfflineRetryWaitsForHealthyRuntime(t *testing.T) {
}
}
+func TestMaybeRetryFailedTaskCopiesChannelDelivery(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var runtimeID, sessionID, installationID, bindingID, parentID string
+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("read agent runtime: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, 'channel retry') RETURNING id
+ `, workspaceID, agentID, userID).Scan(&sessionID); err != nil {
+ t.Fatalf("insert chat session: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_installation (workspace_id, agent_id, channel_type, config, status, installer_user_id)
+ VALUES ($1, $2, 'slack', '{}'::jsonb, 'active', $3) RETURNING id
+ `, workspaceID, agentID, userID).Scan(&installationID); err != nil {
+ t.Fatalf("insert channel installation: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type,
+ last_message_id, last_thread_id, route_revision, config
+ ) VALUES ($1, $2, 'slack', 'D123', 'p2p', '171.001', '171.001', 4, '{"channel_id":"D123"}'::jsonb)
+ RETURNING id
+ `, sessionID, installationID).Scan(&bindingID); err != nil {
+ t.Fatalf("insert channel binding: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, chat_session_id, status, priority, attempt,
+ max_attempts, failure_reason, originator_user_id, accountable_user_id, originator_source
+ ) VALUES ($1, $2, $3, 'failed', 0, 1, 3, 'timeout', $4, $4, 'direct_human')
+ RETURNING id
+ `, agentID, runtimeID, sessionID, userID).Scan(&parentID); err != nil {
+ t.Fatalf("insert failed channel task: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+ ) VALUES ($1, $2, $3, 'slack', 'D123', 'p2p', '171.001', '171.001', 4, '{"channel_id":"D123"}'::jsonb)
+ `, parentID, bindingID, installationID); err != nil {
+ t.Fatalf("insert parent delivery: %v", err)
+ }
+
+ parent, err := q.GetAgentTask(ctx, util.MustParseUUID(parentID))
+ if err != nil {
+ t.Fatalf("load parent: %v", err)
+ }
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ child, err := svc.MaybeRetryFailedTask(ctx, parent)
+ if err != nil {
+ t.Fatalf("MaybeRetryFailedTask: %v", err)
+ }
+ if child == nil {
+ t.Fatal("expected retry child")
+ }
+ delivery, err := q.GetChannelTaskDelivery(ctx, child.ID)
+ if err != nil {
+ t.Fatalf("load retry delivery: %v", err)
+ }
+ if util.UUIDToString(delivery.BindingID) != bindingID ||
+ util.UUIDToString(delivery.InstallationID) != installationID ||
+ delivery.ChannelType != "slack" || delivery.ChannelChatID != "D123" ||
+ delivery.RouteRevision != 4 || delivery.ChannelMessageID.String != "171.001" {
+ t.Fatalf("retry delivery drifted from parent: %+v", delivery)
+ }
+
+ // Exercise the independent FailTask retry path as well. It creates the
+ // child inside the same transaction that marks this attempt failed, and its
+ // delivery copy must commit atomically with that child.
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'running' WHERE id = $1`, child.ID); err != nil {
+ t.Fatalf("mark retry running: %v", err)
+ }
+ if _, err := svc.FailTask(ctx, child.ID, "runtime timed out", "", "", "", "timeout", false, "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+ var grandchildID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT id FROM agent_task_queue WHERE parent_task_id = $1 ORDER BY created_at DESC LIMIT 1
+ `, child.ID).Scan(&grandchildID); err != nil {
+ t.Fatalf("load FailTask retry child: %v", err)
+ }
+ grandchildDelivery, err := q.GetChannelTaskDelivery(ctx, grandchildID)
+ if err != nil {
+ t.Fatalf("load FailTask retry delivery: %v", err)
+ }
+ if util.UUIDToString(grandchildDelivery.BindingID) != bindingID || grandchildDelivery.RouteRevision != 4 {
+ t.Fatalf("FailTask retry delivery drifted from parent: %+v", grandchildDelivery)
+ }
+}
+
// TestFailTaskProviderNetworkBudget is the end-to-end guard for Elon's must-fix
// (MUL-4910): FailTask must (1) grant provider_network its raised budget and
// persist a self-consistent child (attempt=3, max_attempts=3), and (2) still
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index e7300ee9c3..408ad0aea4 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -18,6 +18,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/attribution"
+ "github.com/multica-ai/multica/server/internal/chattitle"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/featureflags"
"github.com/multica-ai/multica/server/internal/issuestatus"
@@ -1774,100 +1775,156 @@ var ErrChatQuickActionsBusy = errors.New("chat quick actions: session busy")
// a race with archiving the session and therefore must not persist a new turn.
var ErrChatSessionArchived = errors.New("chat task: session archived")
-// EnqueueChatTask creates a task-owned input batch for a chat session. Channel
-// media makes the task deferred until binding completes or its durable fallback
-// deadline expires; other chat tasks are queued immediately. Unlike issue
-// tasks, chat tasks have no issue_id.
-//
-// Errors split into two layers:
-//
-// - Productizable rejections (agent archived, no runtime, session
-// archived) return the sentinel errors above. Callers (e.g. the Lark
-// dispatcher) can errors.Is them to decide a user-visible outcome.
-//
-// - Infrastructure failures (DB load / insert errors) are wrapped
-// as ordinary errors. The caller should treat them as retryable
-// or page-worthy, NOT as user-facing state.
-//
-// initiatorUserID is the user who actually sent the triggering message — the
-// real requester behind this run. Callers pass it explicitly because
-// chat_session.creator_id is not a reliable source: Lark group sessions set the
-// creator to the installer, not the sender (see the lark dispatcher). Web chat
-// passes the request user; the lark dispatcher passes the inbound sender of the
-// latest message in the silence window. Stored on the task so the daemon brief
-// can attribute the run to the right person. See MUL-2645.
-//
-// forceFreshSession applies only to the task created by this call. Channel
-// callers additionally use EnqueueChannelChatTask to snapshot the durable
-// context revision; its batch seal and history reads cannot cross that boundary.
-// The daemon skips prior provider-session resume for a fresh dispatch without
-// clearing the Chat's stored resume pointer for later generations.
-func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error) {
- return s.enqueueChatTask(ctx, chatSession, initiatorUserID, forceFreshSession, 0)
-}
-
-func (s *TaskService) EnqueueChannelChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error) {
- return s.enqueueChatTask(ctx, chatSession, initiatorUserID, forceFreshSession, contextRevision)
+// PreparedChatTaskEnqueue is an opaque, side-effect-free input snapshot built
+// before a caller opens a task-enqueue transaction.
+type PreparedChatTaskEnqueue struct {
+ accountableUser pgtype.UUID
+ attrSource pgtype.Text
+ attrEvidenceKind pgtype.Text
+ runtimeOverlay runtimeMCPOverlayData
}
-func (s *TaskService) enqueueChatTask(ctx context.Context, chatSession db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool, contextRevision int64) (db.AgentTaskQueue, error) {
- agent, err := s.Queries.GetAgent(ctx, chatSession.AgentID)
+// PrepareChatTaskEnqueue performs reads and optional external integration work
+// before the caller opens a transaction. BuildTaskOverlay may perform network
+// I/O and must never run while /new holds route-rotation locks.
+func (s *TaskService) PrepareChatTaskEnqueue(
+ ctx context.Context,
+ agentID, initiatorUserID pgtype.UUID,
+) (PreparedChatTaskEnqueue, error) {
+ agent, err := s.Queries.GetAgent(ctx, agentID)
if err != nil {
- slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
- return db.AgentTaskQueue{}, fmt.Errorf("load agent: %w", err)
+ slog.Error("chat task preparation failed", "agent_id", util.UUIDToString(agentID), "error", err)
+ return PreparedChatTaskEnqueue{}, fmt.Errorf("load agent: %w", err)
}
if agent.ArchivedAt.Valid {
- return db.AgentTaskQueue{}, ErrChatTaskAgentArchived
+ return PreparedChatTaskEnqueue{}, ErrChatTaskAgentArchived
}
if !agent.RuntimeID.Valid {
- return db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime
+ return PreparedChatTaskEnqueue{}, ErrChatTaskAgentNoRuntime
}
- // The chat sender (initiator) is the direct_human originator and accountable.
- // Evidence uses the uniform pair (kind=chat, ref=chat_session_id) so the
- // attribution UI links to the conversation the same way it does for
- // autopilot_run / issue_assignment — the dedicated chat_session_id column still
- // exists for its own consumers. An unresolved sender (some Lark group messages)
- // degrades to unattributed rather than a NULL-source bypass (MUL-4302 §2).
- attr := attribution.DirectHumanRun(initiatorUserID, attribution.EvidenceChat, chatSession.ID)
- // An unresolved sender degrades to owner_fallback (accountable = agent owner),
- // or is refused if the workspace is fail-closed (MUL-4302 §3.5).
+ attr := attribution.DirectHumanRun(
+ initiatorUserID, attribution.EvidenceChat, pgtype.UUID{},
+ )
attr, err = s.applyAttributionFallback(ctx, attr, agent)
if err != nil {
- slog.Warn("chat task enqueue refused: attribution fail-closed", "chat_session_id", util.UUIDToString(chatSession.ID))
+ slog.Warn("chat task enqueue refused: attribution fail-closed",
+ "agent_id", util.UUIDToString(agentID))
+ return PreparedChatTaskEnqueue{}, err
+ }
+ attrSource, _, attrEvidenceKind, _ := attributionCreateParams(attr)
+ return PreparedChatTaskEnqueue{
+ accountableUser: attr.AccountableUserID,
+ attrSource: attrSource, attrEvidenceKind: attrEvidenceKind,
+ runtimeOverlay: s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent),
+ }, nil
+}
+
+// EnqueueChatTask creates a Direct Chat task. If the Chat also has a channel
+// binding, its context generation is still snapshotted, but no external delivery
+// snapshot is created: first-party sends reply only to first-party clients.
+func (s *TaskService) EnqueueChatTask(
+ ctx context.Context,
+ chatSession db.ChatSession,
+ initiatorUserID pgtype.UUID,
+ forceFreshSession bool,
+) (db.AgentTaskQueue, error) {
+ return s.enqueueChatTask(
+ ctx, chatSession, initiatorUserID, forceFreshSession, 0, false,
+ pgtype.UUID{}, 0,
+ )
+}
+
+// EnqueueChannelChatTask creates a channel-owned task for one durable context
+// generation and freezes its external delivery route in the same transaction.
+func (s *TaskService) EnqueueChannelChatTask(
+ ctx context.Context,
+ chatSession db.ChatSession,
+ initiatorUserID pgtype.UUID,
+ forceFreshSession bool,
+ contextRevision int64,
+ bindingID pgtype.UUID,
+ routeRevision int64,
+) (db.AgentTaskQueue, error) {
+ if contextRevision <= 0 {
+ return db.AgentTaskQueue{}, errors.New("channel chat task requires a context revision")
+ }
+ return s.enqueueChatTask(
+ ctx, chatSession, initiatorUserID, forceFreshSession,
+ contextRevision, true, bindingID, routeRevision,
+ )
+}
+
+func (s *TaskService) enqueueChatTask(
+ ctx context.Context,
+ chatSession db.ChatSession,
+ initiatorUserID pgtype.UUID,
+ forceFreshSession bool,
+ contextRevision int64,
+ requireDelivery bool,
+ expectedBindingID pgtype.UUID,
+ expectedRouteRevision int64,
+) (db.AgentTaskQueue, error) {
+ prepared, err := s.PrepareChatTaskEnqueue(ctx, chatSession.AgentID, initiatorUserID)
+ if err != nil {
return db.AgentTaskQueue{}, err
}
- attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
- runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)
-
+ if s.TxStarter == nil {
+ return db.AgentTaskQueue{}, errors.New("chat task enqueue: transaction starter is required")
+ }
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("begin chat task enqueue: %w", err)
}
defer tx.Rollback(ctx)
- qtx := s.Queries.WithTx(tx)
- // Refuse to enqueue onto a session that has been archived, the same guard
- // the direct-send path takes. This is the one enqueue path with a delay in
- // front of it: the channel run trigger is debounced by
- // DefaultChatRunBatchWindow, so the message is persisted immediately and
- // the task row is only created here, up to a window later. An archive
- // committing inside that window cancels the tasks it can see — there are
- // none yet — and drops the channel binding, and without this check the
- // flush then inserts a fresh task on a conversation the user closed.
- // ClaimAgentTask does not read chat_session.status either, so the daemon
- // would run it: quota and runtime spent on a closed conversation, new
- // assistant turns written into an archived chat, the agent flipped back to
- // 'working', and the brief describing the run as a private web chat
- // because the binding is already gone.
- //
- // The lock is what makes the check hold — the caller's copy of the session
- // was loaded before the transaction opened and can already be stale, the
- // same reason the send path re-reads the agent under its lock. It is
- // deliberately FOR NO KEY UPDATE rather than the send path's FOR UPDATE;
- // see LockChatSessionForEnqueue for why the channel path cannot afford to
- // block the inbound appends FOR UPDATE would. Taken as the transaction's
- // first statement, so the chat_session -> agent_task_queue order is
- // unchanged and no new deadlock edge appears.
+ task, err := s.enqueueChatTaskTx(
+ ctx, s.Queries.WithTx(tx), chatSession, initiatorUserID,
+ forceFreshSession, contextRevision, requireDelivery,
+ expectedBindingID, expectedRouteRevision, prepared,
+ )
+ if err != nil {
+ return db.AgentTaskQueue{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("commit chat task enqueue: %w", err)
+ }
+ s.FinalizeChatTaskEnqueue(ctx, task)
+ return task, nil
+}
+
+// EnqueuePreparedChannelChatTaskInTx adds the first /new turn to a caller-owned
+// route-rotation transaction. Preparation must happen before that transaction;
+// post-commit effects belong to FinalizeChatTaskEnqueue.
+func (s *TaskService) EnqueuePreparedChannelChatTaskInTx(
+ ctx context.Context,
+ tx pgx.Tx,
+ chatSession db.ChatSession,
+ initiatorUserID pgtype.UUID,
+ forceFreshSession bool,
+ contextRevision int64,
+ prepared PreparedChatTaskEnqueue,
+) (db.AgentTaskQueue, error) {
+ if contextRevision <= 0 {
+ return db.AgentTaskQueue{}, errors.New("prepared channel chat task requires a context revision")
+ }
+ return s.enqueueChatTaskTx(
+ ctx, s.Queries.WithTx(tx), chatSession, initiatorUserID,
+ forceFreshSession, contextRevision, true, pgtype.UUID{}, 0, prepared,
+ )
+}
+
+func (s *TaskService) enqueueChatTaskTx(
+ ctx context.Context,
+ qtx *db.Queries,
+ chatSession db.ChatSession,
+ initiatorUserID pgtype.UUID,
+ forceFreshSession bool,
+ contextRevision int64,
+ requireDelivery bool,
+ expectedBindingID pgtype.UUID,
+ expectedRouteRevision int64,
+ prepared PreparedChatTaskEnqueue,
+) (db.AgentTaskQueue, error) {
currentSession, err := qtx.LockChatSessionForEnqueue(ctx, chatSession.ID)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("lock chat session: %w", err)
@@ -1875,85 +1932,115 @@ func (s *TaskService) enqueueChatTask(ctx context.Context, chatSession db.ChatSe
if currentSession.Status != "active" {
return db.AgentTaskQueue{}, ErrChatSessionArchived
}
- // Lock the channel binding only after the chat_session lock above. The
- // append path touches chat_session before binding as well, so this order
- // avoids an ABBA edge while keeping pending fresh in the enqueue transaction.
- binding, err := qtx.LockChannelChatSessionBindingForContext(ctx, chatSession.ID)
- if err != nil && !errors.Is(err, pgx.ErrNoRows) {
- return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", err)
+
+ agent, err := qtx.GetAgentForClaimUpdate(ctx, chatSession.AgentID)
+ if err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("reload chat agent: %w", err)
}
- if errors.Is(err, pgx.ErrNoRows) && contextRevision > 0 {
- return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", err)
+ if agent.ArchivedAt.Valid {
+ return db.AgentTaskQueue{}, ErrChatTaskAgentArchived
}
- pendingFresh := false
- if err == nil {
- if err := qtx.EnsureChannelChatContextGeneration(ctx, chatSession.ID); err != nil {
- return db.AgentTaskQueue{}, fmt.Errorf("ensure channel context generation: %w", err)
+ if !agent.RuntimeID.Valid {
+ return db.AgentTaskQueue{}, ErrChatTaskAgentNoRuntime
+ }
+
+ binding, bindingErr := qtx.LockChannelChatSessionBindingForContext(ctx, chatSession.ID)
+ if bindingErr != nil && !errors.Is(bindingErr, pgx.ErrNoRows) {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", bindingErr)
+ }
+ if requireDelivery {
+ if errors.Is(bindingErr, pgx.ErrNoRows) {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock channel chat binding: %w", pgx.ErrNoRows)
}
+ routeMatches := expectedBindingID.Valid &&
+ binding.ID == expectedBindingID &&
+ binding.RouteRevision == expectedRouteRevision
+ if binding.RetiredAt.Valid && !routeMatches {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock retired channel chat binding: %w", pgx.ErrNoRows)
+ }
+ if expectedBindingID.Valid && !routeMatches {
+ return db.AgentTaskQueue{}, fmt.Errorf("lock expected channel chat route: %w", pgx.ErrNoRows)
+ }
+ }
+
+ pendingFresh := false
+ if bindingErr == nil {
if contextRevision <= 0 {
contextRevision = binding.ContextRevision
}
- generation, err := qtx.LockChannelChatContextGenerationByRevision(ctx, db.LockChannelChatContextGenerationByRevisionParams{
- ChatSessionID: chatSession.ID, Revision: contextRevision,
- })
+ generation, err := qtx.LockChannelChatContextGenerationByRevision(
+ ctx, db.LockChannelChatContextGenerationByRevisionParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ },
+ )
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("lock channel context generation: %w", err)
}
- pendingFresh = generation.PendingFresh || (contextRevision == binding.ContextRevision && binding.PendingFresh)
+ pendingFresh = generation.PendingFresh
}
if pendingFresh {
forceFreshSession = true
}
- mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, db.GetChannelMediaPendingUntilParams{
- ChatSessionID: chatSession.ID,
- ChannelContextRevision: pgtype.Int8{Int64: contextRevision, Valid: contextRevision > 0},
- })
+
+ mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(
+ ctx, db.GetChannelMediaPendingUntilParams{
+ ChatSessionID: chatSession.ID,
+ ChannelContextRevision: pgtype.Int8{
+ Int64: contextRevision, Valid: contextRevision > 0,
+ },
+ },
+ )
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
- slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
return db.AgentTaskQueue{}, fmt.Errorf("load channel media pending deadline: %w", err)
}
if errors.Is(err, pgx.ErrNoRows) {
mediaPendingUntil = pgtype.Timestamptz{}
}
+
task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
- ID: dbid.NewV7(),
- AgentID: chatSession.AgentID,
- RuntimeID: agent.RuntimeID,
- Priority: 2, // medium priority for chat
- ChatSessionID: chatSession.ID,
- InitiatorUserID: initiatorUserID,
- FireAt: mediaPendingUntil,
- OriginatorUserID: initiatorUserID,
- AccountableUserID: attr.AccountableUserID,
- ForceFreshSession: pgtype.Bool{
- Bool: forceFreshSession,
- Valid: true,
+ ID: dbid.NewV7(),
+ AgentID: chatSession.AgentID,
+ RuntimeID: agent.RuntimeID,
+ Priority: 2,
+ ChatSessionID: chatSession.ID,
+ InitiatorUserID: initiatorUserID,
+ FireAt: mediaPendingUntil,
+ OriginatorUserID: initiatorUserID,
+ AccountableUserID: prepared.accountableUser,
+ ForceFreshSession: pgtype.Bool{Bool: forceFreshSession, Valid: true},
+ RuntimeMcpOverlay: prepared.runtimeOverlay.Overlay,
+ RuntimeConnectedApps: prepared.runtimeOverlay.ConnectedApps,
+ OriginatorSource: prepared.attrSource,
+ TriggerEvidenceKind: prepared.attrEvidenceKind,
+ TriggerEvidenceRefID: chatSession.ID,
+ ChannelContextRevision: pgtype.Int8{
+ Int64: contextRevision, Valid: contextRevision > 0,
},
- RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
- RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
- OriginatorSource: attrSource,
- TriggerEvidenceKind: attrEvidenceKind,
- TriggerEvidenceRefID: attrEvidenceRef,
- ChannelContextRevision: pgtype.Int8{Int64: contextRevision, Valid: contextRevision > 0},
})
if err != nil {
- slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
return db.AgentTaskQueue{}, fmt.Errorf("create chat task: %w", err)
}
+ if requireDelivery {
+ if _, err := qtx.CreateChannelTaskDeliveryFromSession(
+ ctx, db.CreateChannelTaskDeliveryFromSessionParams{
+ TaskID: task.ID, ChatSessionID: chatSession.ID,
+ },
+ ); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("snapshot channel task delivery: %w", err)
+ }
+ }
+
task, err = qtx.SetChatTaskInputOwnerSelf(ctx, task.ID)
if err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("set channel chat task input owner: %w", err)
}
- if err := qtx.LinkUnownedChannelChatMessagesToTask(ctx, db.LinkUnownedChannelChatMessagesToTaskParams{
- TaskID: task.ID,
- ChatSessionID: chatSession.ID,
- }); err != nil {
+ if err := qtx.LinkUnownedChannelChatMessagesToTask(
+ ctx, db.LinkUnownedChannelChatMessagesToTaskParams{
+ TaskID: task.ID, ChatSessionID: chatSession.ID,
+ },
+ ); err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("seal channel chat task input: %w", err)
}
- // The deadline read above ran before the seal; under READ COMMITTED a media
- // message committed between the two statements is sealed into this task
- // without deferring it, and the daemon could claim it before its media
- // binds. Re-derive the deferral from the sealed batch itself.
switch corrected, err := qtx.DeferChatTaskForSealedPendingMedia(ctx, task.ID); {
case err == nil:
task = corrected
@@ -1961,49 +2048,50 @@ func (s *TaskService) enqueueChatTask(ctx context.Context, chatSession db.ChatSe
return db.AgentTaskQueue{}, fmt.Errorf("defer chat task for sealed pending media: %w", err)
}
if pendingFresh {
- if err := qtx.ClearChannelChatContextPendingFresh(ctx, db.ClearChannelChatContextPendingFreshParams{
- ChatSessionID: chatSession.ID, Revision: contextRevision,
- }); err != nil {
+ if err := qtx.ClearChannelChatContextPendingFresh(
+ ctx, db.ClearChannelChatContextPendingFreshParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ },
+ ); err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("clear channel context pending fresh: %w", err)
}
- if err := qtx.ClearChannelChatSessionPendingFreshForRevision(ctx, db.ClearChannelChatSessionPendingFreshForRevisionParams{
- ChatSessionID: chatSession.ID, Revision: contextRevision,
- }); err != nil {
+ if err := qtx.ClearChannelChatSessionPendingFreshForRevision(
+ ctx, db.ClearChannelChatSessionPendingFreshForRevisionParams{
+ ChatSessionID: chatSession.ID, Revision: contextRevision,
+ },
+ ); err != nil {
return db.AgentTaskQueue{}, fmt.Errorf("clear channel pending fresh: %w", err)
}
}
- if err := tx.Commit(ctx); err != nil {
- return db.AgentTaskQueue{}, fmt.Errorf("commit chat task enqueue: %w", err)
- }
+ return task, nil
+}
+// FinalizeChatTaskEnqueue performs only post-commit effects.
+func (s *TaskService) FinalizeChatTaskEnqueue(ctx context.Context, task db.AgentTaskQueue) {
if task.Status == "deferred" {
slog.Info("chat task deferred for channel media",
"task_id", util.UUIDToString(task.ID),
- "chat_session_id", util.UUIDToString(chatSession.ID),
- "agent_id", util.UUIDToString(chatSession.AgentID),
+ "chat_session_id", util.UUIDToString(task.ChatSessionID),
+ "agent_id", util.UUIDToString(task.AgentID),
"fire_at", task.FireAt.Time,
)
- // Fence the clear-vs-create race: media completion may have found no
- // committed task after our deadline read. Re-check after commit so the
- // task is promoted immediately when the marker has already cleared.
- // The task is already durably committed, so a fence failure must not
- // surface as an enqueue failure — the router would treat it as "no
- // task" and clear the typing indicator while the run still happens.
- // The claim-path deferred promoter re-queues it at fire_at regardless.
- if err := s.PromoteChannelChatTasksIfMediaReady(ctx, chatSession.ID); err != nil {
+ if err := s.PromoteChannelChatTasksIfMediaReady(ctx, task.ChatSessionID); err != nil {
slog.Warn("chat task media-ready fence failed; deferred task falls back to its deadline",
"task_id", util.UUIDToString(task.ID),
- "chat_session_id", util.UUIDToString(chatSession.ID),
- "error", err)
+ "chat_session_id", util.UUIDToString(task.ChatSessionID),
+ "error", err,
+ )
}
- return task, nil
+ return
}
- slog.Info("chat task enqueued", "task_id", util.UUIDToString(task.ID), "chat_session_id", util.UUIDToString(chatSession.ID), "agent_id", util.UUIDToString(chatSession.AgentID))
- // See EnqueueTaskForIssue for ordering rationale.
+ slog.Info("chat task enqueued",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", util.UUIDToString(task.ChatSessionID),
+ "agent_id", util.UUIDToString(task.AgentID),
+ )
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
s.NotifyTaskEnqueued(ctx, task)
- return task, nil
}
// RegenerateChatQuickActions runs a fresh suggestion pass for the session's
@@ -2129,6 +2217,7 @@ type DirectChatSendResult struct {
Message db.ChatMessage
BoundAttachmentIDs []pgtype.UUID
Queued bool
+ InitialTitle string
}
var ErrChatSessionAlreadyStarted = errors.New("chat session already has a user message")
@@ -2255,6 +2344,17 @@ func (s *TaskService) SendDirectChatMessage(
return fmt.Errorf("adopt onboarding kickoff: %w", err)
}
+ // Initialize an explicitly empty Chat before inserting its first public
+ // user message. The CAS query also protects a manual rename and competing
+ // first send; keeping it in this transaction prevents a title-only commit.
+ if title := chattitle.Derive(content); title != "" {
+ if _, err := qtx.InitializeChatSessionTitle(ctx, db.InitializeChatSessionTitleParams{ID: session.ID, Title: title}); err == nil {
+ out.InitialTitle = title
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("initialize direct chat title: %w", err)
+ }
+ }
+
// Create the user message already owned by this task (task_id = task.id),
// so it belongs to this immutable input batch the instant it exists.
msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
@@ -2283,6 +2383,33 @@ func (s *TaskService) SendDirectChatMessage(
return fmt.Errorf("link chat attachments: %w", err)
}
out.BoundAttachmentIDs = bound
+
+ // An explicitly empty /new Chat can receive its first turn from a
+ // first-party client. For an attachment-only turn, initialize the
+ // title from the first attachment that was actually bound. The media
+ // title CAS runs after the message insert by design and still refuses
+ // to overwrite a manual rename or a competing first message.
+ if out.InitialTitle == "" && strings.TrimSpace(content) == "" && len(bound) > 0 {
+ attachments, err := qtx.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{
+ ChatMessageID: msg.ID,
+ WorkspaceID: session.WorkspaceID,
+ })
+ if err != nil {
+ return fmt.Errorf("list bound chat attachments for title: %w", err)
+ }
+ if len(attachments) > 0 {
+ title := chattitle.Derive(attachments[0].Filename)
+ if title != "" {
+ if _, err := qtx.InitializeChatSessionMediaTitle(ctx, db.InitializeChatSessionMediaTitleParams{
+ ID: session.ID, MessageID: msg.ID, Title: title,
+ }); err == nil {
+ out.InitialTitle = title
+ } else if !errors.Is(err, pgx.ErrNoRows) {
+ return fmt.Errorf("initialize direct attachment chat title: %w", err)
+ }
+ }
+ }
+ }
}
if err := qtx.TouchChatSession(ctx, session.ID); err != nil {
@@ -4652,6 +4779,11 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
} else if transferErr != nil {
return fmt.Errorf("transfer pending source context to retry: %w", transferErr)
} else {
+ if err := qtx.CopyChannelTaskDelivery(ctx, db.CopyChannelTaskDeliveryParams{
+ ChildTaskID: child.ID, ParentTaskID: taskID,
+ }); err != nil {
+ return fmt.Errorf("copy retry channel delivery: %w", err)
+ }
retried = &child
}
case errors.Is(cerr, pgx.ErrNoRows):
@@ -5087,9 +5219,12 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
)
return nil, nil
}
- tx, beginErr := s.TxStarter.Begin(ctx)
- if beginErr != nil {
- return nil, beginErr
+ if s.TxStarter == nil {
+ return nil, errors.New("task auto-retry: transaction starter is required")
+ }
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("task auto-retry: begin transaction: %w", err)
}
defer tx.Rollback(ctx)
qtx := s.Queries.WithTx(tx)
@@ -5129,8 +5264,13 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
}
return nil, err
}
+ if err := qtx.CopyChannelTaskDelivery(ctx, db.CopyChannelTaskDeliveryParams{
+ ChildTaskID: child.ID, ParentTaskID: parent.ID,
+ }); err != nil {
+ return nil, fmt.Errorf("copy auto-retry channel delivery: %w", err)
+ }
if err := tx.Commit(ctx); err != nil {
- return nil, err
+ return nil, fmt.Errorf("task auto-retry: commit: %w", err)
}
slog.Info("task auto-retry enqueued",
"parent_task_id", util.UUIDToString(parent.ID),
diff --git a/server/internal/service/task_channel_command_media_test.go b/server/internal/service/task_channel_command_media_test.go
index 2c458a8478..a3351893ea 100644
--- a/server/internal/service/task_channel_command_media_test.go
+++ b/server/internal/service/task_channel_command_media_test.go
@@ -32,9 +32,39 @@ func seedChannelCommandSession(t *testing.T, pool *pgxpool.Pool, workspaceID, ag
_, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, chatSessionID)
_, _ = pool.Exec(cleanupCtx, `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
})
+ seedChannelTaskBinding(t, pool, chatSessionID)
return chatSessionID
}
+// seedChannelTaskBinding gives EnqueueChatTask the same current route every
+// production caller has. The enqueue path now snapshots that route as a hard
+// delivery invariant, so a channel-ingested fixture without a binding is not a
+// valid channel task fixture.
+func seedChannelTaskBinding(t *testing.T, pool *pgxpool.Pool, chatSessionID string) {
+ t.Helper()
+ ctx := context.Background()
+ var bindingID string
+ if err := pool.QueryRow(ctx, `
+ WITH binding AS (
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type
+ ) VALUES ($1, gen_random_uuid(), 'dingtalk', $2, 'p2p')
+ RETURNING id, chat_session_id, context_revision
+ ), generation AS (
+ INSERT INTO channel_chat_context_generation (chat_session_id, revision)
+ SELECT chat_session_id, context_revision FROM binding
+ )
+ SELECT id FROM binding`, chatSessionID, chatSessionID).Scan(&bindingID); err != nil {
+ t.Fatalf("seed channel task binding: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_task_delivery WHERE binding_id = $1`, bindingID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_context_generation WHERE chat_session_id = $1`, chatSessionID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_chat_session_binding WHERE id = $1`, bindingID)
+ })
+}
+
func TestEnqueueChatTaskConsumesPendingFreshOnlyOnSuccess(t *testing.T) {
pool := newResolveOriginatorPool(t)
ctx := context.Background()
@@ -47,10 +77,14 @@ func TestEnqueueChatTaskConsumesPendingFreshOnlyOnSuccess(t *testing.T) {
}
if _, err := pool.Exec(ctx, `
- INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, pending_fresh
- ) VALUES ($1, gen_random_uuid(), 'dingtalk', 'chat-fresh', 'p2p', TRUE)`, chatSessionID); err != nil {
- t.Fatalf("seed channel binding: %v", err)
+ WITH binding AS (
+ UPDATE channel_chat_session_binding SET pending_fresh = TRUE
+ WHERE chat_session_id = $1
+ RETURNING chat_session_id
+ )
+ UPDATE channel_chat_context_generation SET pending_fresh = TRUE
+ WHERE chat_session_id = $1`, chatSessionID); err != nil {
+ t.Fatalf("seed pending fresh: %v", err)
}
if _, err := pool.Exec(ctx, `
INSERT INTO chat_message (chat_session_id, role, content)
diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.go
index f3b59d8486..3a13970b84 100644
--- a/server/internal/service/task_channel_media_race_test.go
+++ b/server/internal/service/task_channel_media_race_test.go
@@ -83,7 +83,8 @@ func TestEnqueueChannelChatTask_ContextClearFailureRollsBackTaskAndSeal(t *testi
q := db.New(pool)
workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
- var chatSessionID, installationID, messageID string
+ var chatSessionID, installationID, bindingID, messageID string
+ var routeRevision int64
if err := pool.QueryRow(ctx, `
INSERT INTO chat_session (workspace_id, agent_id, creator_id)
VALUES ($1, $2, $3) RETURNING id
@@ -98,12 +99,13 @@ func TestEnqueueChannelChatTask_ContextClearFailureRollsBackTaskAndSeal(t *testi
`, workspaceID, agentID, userID).Scan(&installationID); err != nil {
t.Fatalf("seed channel installation: %v", err)
}
- if _, err := pool.Exec(ctx, `
+ if err := pool.QueryRow(ctx, `
INSERT INTO channel_chat_session_binding (
chat_session_id, installation_id, channel_type, channel_chat_id,
chat_type, pending_fresh, context_revision
) VALUES ($1, $2, 'slack', $3, 'p2p', TRUE, 1)
- `, chatSessionID, installationID, "rollback-"+chatSessionID); err != nil {
+ RETURNING id, route_revision
+ `, chatSessionID, installationID, "rollback-"+chatSessionID).Scan(&bindingID, &routeRevision); err != nil {
t.Fatalf("seed channel binding: %v", err)
}
if _, err := pool.Exec(ctx, `
@@ -143,7 +145,7 @@ func TestEnqueueChannelChatTask_ContextClearFailureRollsBackTaskAndSeal(t *testi
}
_, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
- }, util.MustParseUUID(userID), false, 1)
+ }, util.MustParseUUID(userID), false, 1, util.MustParseUUID(bindingID), routeRevision)
if !errors.Is(err, injectedErr) {
t.Fatalf("EnqueueChannelChatTask error = %v, want injected clear failure", err)
}
@@ -176,11 +178,18 @@ func TestEnqueueChannelChatTask_RejectsRetiredBinding(t *testing.T) {
q := db.New(pool)
workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)
+ if _, err := pool.Exec(ctx, `
+ UPDATE channel_chat_session_binding
+ SET retired_at = now()
+ WHERE chat_session_id = $1
+ `, chatSessionID); err != nil {
+ t.Fatalf("retire channel route: %v", err)
+ }
svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
_, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
- }, util.MustParseUUID(userID), false, 1)
+ }, util.MustParseUUID(userID), false, 1, pgtype.UUID{}, 0)
if !errors.Is(err, pgx.ErrNoRows) {
t.Fatalf("EnqueueChannelChatTask error = %v, want missing binding", err)
}
@@ -194,6 +203,84 @@ func TestEnqueueChannelChatTask_RejectsRetiredBinding(t *testing.T) {
}
}
+func TestEnqueueChannelChatTask_RejectsMismatchedActiveRouteProof(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)
+ appendChannelUserMessage(t, ctx, pool, chatSessionID, "must remain unowned")
+
+ var routeRevision int64
+ if err := pool.QueryRow(ctx, `
+ SELECT route_revision FROM channel_chat_session_binding WHERE chat_session_id = $1
+ `, chatSessionID).Scan(&routeRevision); err != nil {
+ t.Fatalf("load active route revision: %v", err)
+ }
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ _, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false, 1, util.MustParseUUID("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), routeRevision)
+ if !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("EnqueueChannelChatTask error = %v, want route mismatch", err)
+ }
+
+ var taskCount, ownedMessageCount int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE chat_session_id = $1`, chatSessionID).Scan(&taskCount); err != nil {
+ t.Fatalf("count channel tasks: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND task_id IS NOT NULL`, chatSessionID).Scan(&ownedMessageCount); err != nil {
+ t.Fatalf("count owned channel messages: %v", err)
+ }
+ if taskCount != 0 || ownedMessageCount != 0 {
+ t.Fatalf("route mismatch task/owned messages = %d/%d, want 0/0", taskCount, ownedMessageCount)
+ }
+}
+
+func TestEnqueueChannelChatTask_AllowsMatchingRetiredRouteForPendingInput(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ chatSessionID := seedChannelChatSession(t, ctx, pool, workspaceID, agentID, userID)
+ messageID := appendChannelUserMessage(t, ctx, pool, chatSessionID, "queued before /new")
+
+ var bindingID string
+ var routeRevision int64
+ if err := pool.QueryRow(ctx, `
+ UPDATE channel_chat_session_binding
+ SET retired_at = now()
+ WHERE chat_session_id = $1
+ RETURNING id, route_revision
+ `, chatSessionID).Scan(&bindingID, &routeRevision); err != nil {
+ t.Fatalf("retire and load channel route: %v", err)
+ }
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ task, err := svc.EnqueueChannelChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID), AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false, 1, util.MustParseUUID(bindingID), routeRevision)
+ if err != nil {
+ t.Fatalf("EnqueueChannelChatTask: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM channel_task_delivery WHERE task_id = $1`, task.ID)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)
+ })
+
+ var sealedTaskID, deliveryBindingID string
+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, messageID).Scan(&sealedTaskID); err != nil {
+ t.Fatalf("load sealed message owner: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT binding_id FROM channel_task_delivery WHERE task_id = $1`, task.ID).Scan(&deliveryBindingID); err != nil {
+ t.Fatalf("load frozen task delivery: %v", err)
+ }
+ if sealedTaskID != util.UUIDToString(task.ID) || deliveryBindingID != bindingID {
+ t.Fatalf("retired route enqueue sealed/delivery = %s/%s, want %s/%s", sealedTaskID, deliveryBindingID, util.UUIDToString(task.ID), bindingID)
+ }
+}
+
// TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue pins the fix
// for the enqueue-vs-append race: a media-pending message sealed into the task
// after the deadline read must still leave the task deferred (not claimable)
@@ -213,6 +300,7 @@ func TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue(t *testing.T)
t.Cleanup(func() {
_, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
})
+ seedChannelTaskBinding(t, pool, chatSessionID)
// The message that armed this flush: plain text, no media marker.
if _, err := pool.Exec(ctx, `
INSERT INTO chat_message (chat_session_id, role, content)
@@ -316,6 +404,7 @@ func TestEnqueueChatTaskLocksOutAConcurrentArchiveButNotInboundMessages(t *testi
t.Cleanup(func() {
_, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
})
+ seedChannelTaskBinding(t, pool, chatSessionID)
if _, err := pool.Exec(ctx, `
INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
VALUES ($1, 'user', 'first', TRUE)`, chatSessionID); err != nil {
diff --git a/server/internal/service/task_channel_seal_race_test.go b/server/internal/service/task_channel_seal_race_test.go
index 450dd5bb93..d4c6861bcb 100644
--- a/server/internal/service/task_channel_seal_race_test.go
+++ b/server/internal/service/task_channel_seal_race_test.go
@@ -232,6 +232,7 @@ func seedChannelChatSession(t *testing.T, ctx context.Context, pool *pgxpool.Poo
t.Cleanup(func() {
_, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, id)
})
+ seedChannelTaskBinding(t, pool, id)
return id
}
diff --git a/server/migrations/420_channel_chat_route_generation.down.sql b/server/migrations/420_channel_chat_route_generation.down.sql
new file mode 100644
index 0000000000..13faadf0fe
--- /dev/null
+++ b/server/migrations/420_channel_chat_route_generation.down.sql
@@ -0,0 +1,12 @@
+-- Channel Chat route migration.
+DROP TABLE IF EXISTS channel_task_delivery;
+
+ALTER TABLE chat_session
+ DROP COLUMN IF EXISTS explicitly_created_at;
+
+ALTER TABLE channel_chat_session_binding
+ DROP COLUMN IF EXISTS history_boundary_pending,
+ DROP COLUMN IF EXISTS history_end_message_id,
+ DROP COLUMN IF EXISTS history_start_message_id,
+ DROP COLUMN IF EXISTS retired_at,
+ DROP COLUMN IF EXISTS route_revision;
diff --git a/server/migrations/420_channel_chat_route_generation.up.sql b/server/migrations/420_channel_chat_route_generation.up.sql
new file mode 100644
index 0000000000..2a2c81ae39
--- /dev/null
+++ b/server/migrations/420_channel_chat_route_generation.up.sql
@@ -0,0 +1,24 @@
+-- Channel Chat route migration.
+ALTER TABLE channel_chat_session_binding
+ ADD COLUMN route_revision BIGINT NOT NULL DEFAULT 1,
+ ADD COLUMN retired_at TIMESTAMPTZ,
+ ADD COLUMN history_start_message_id TEXT,
+ ADD COLUMN history_end_message_id TEXT,
+ ADD COLUMN history_boundary_pending BOOLEAN NOT NULL DEFAULT FALSE;
+
+ALTER TABLE chat_session
+ ADD COLUMN explicitly_created_at TIMESTAMPTZ;
+
+CREATE TABLE channel_task_delivery (
+ task_id UUID NOT NULL,
+ binding_id UUID NOT NULL,
+ installation_id UUID NOT NULL,
+ channel_type TEXT NOT NULL,
+ channel_chat_id TEXT NOT NULL,
+ chat_type TEXT NOT NULL,
+ channel_message_id TEXT,
+ channel_thread_id TEXT,
+ route_revision BIGINT NOT NULL,
+ config JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/421_channel_chat_active_route_index.down.sql b/server/migrations/421_channel_chat_active_route_index.down.sql
new file mode 100644
index 0000000000..13ceff1497
--- /dev/null
+++ b/server/migrations/421_channel_chat_active_route_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_chat_session_binding_active_route;
diff --git a/server/migrations/421_channel_chat_active_route_index.up.sql b/server/migrations/421_channel_chat_active_route_index.up.sql
new file mode 100644
index 0000000000..3e38f9cf76
--- /dev/null
+++ b/server/migrations/421_channel_chat_active_route_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE UNIQUE INDEX CONCURRENTLY idx_channel_chat_session_binding_active_route ON channel_chat_session_binding (installation_id, channel_chat_id) WHERE retired_at IS NULL;
diff --git a/server/migrations/422_channel_chat_route_history.down.sql b/server/migrations/422_channel_chat_route_history.down.sql
new file mode 100644
index 0000000000..c0f40b3316
--- /dev/null
+++ b/server/migrations/422_channel_chat_route_history.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE UNIQUE INDEX CONCURRENTLY channel_chat_session_binding_installation_id_channel_chat_i_key ON channel_chat_session_binding (installation_id, channel_chat_id);
diff --git a/server/migrations/422_channel_chat_route_history.up.sql b/server/migrations/422_channel_chat_route_history.up.sql
new file mode 100644
index 0000000000..4979343342
--- /dev/null
+++ b/server/migrations/422_channel_chat_route_history.up.sql
@@ -0,0 +1,3 @@
+-- Channel Chat route migration.
+ALTER TABLE channel_chat_session_binding DROP CONSTRAINT IF EXISTS channel_chat_session_binding_installation_id_channel_chat_i_key;
+DROP INDEX IF EXISTS channel_chat_session_binding_installation_id_channel_chat_i_key;
diff --git a/server/migrations/423_channel_task_delivery_pkey_index.down.sql b/server/migrations/423_channel_task_delivery_pkey_index.down.sql
new file mode 100644
index 0000000000..35f520531a
--- /dev/null
+++ b/server/migrations/423_channel_task_delivery_pkey_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS channel_task_delivery_pkey;
diff --git a/server/migrations/423_channel_task_delivery_pkey_index.up.sql b/server/migrations/423_channel_task_delivery_pkey_index.up.sql
new file mode 100644
index 0000000000..7850b5654b
--- /dev/null
+++ b/server/migrations/423_channel_task_delivery_pkey_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE UNIQUE INDEX CONCURRENTLY channel_task_delivery_pkey ON channel_task_delivery (task_id);
diff --git a/server/migrations/424_channel_task_delivery_primary_key.down.sql b/server/migrations/424_channel_task_delivery_primary_key.down.sql
new file mode 100644
index 0000000000..378429e1ae
--- /dev/null
+++ b/server/migrations/424_channel_task_delivery_primary_key.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE channel_task_delivery
+ DROP CONSTRAINT IF EXISTS channel_task_delivery_pkey;
diff --git a/server/migrations/424_channel_task_delivery_primary_key.up.sql b/server/migrations/424_channel_task_delivery_primary_key.up.sql
new file mode 100644
index 0000000000..8aeed4b14f
--- /dev/null
+++ b/server/migrations/424_channel_task_delivery_primary_key.up.sql
@@ -0,0 +1,5 @@
+-- Promote the concurrently-built unique index without rebuilding it or
+-- holding a long index-build lock on channel_task_delivery.
+ALTER TABLE channel_task_delivery
+ ADD CONSTRAINT channel_task_delivery_pkey
+ PRIMARY KEY USING INDEX channel_task_delivery_pkey;
diff --git a/server/migrations/425_channel_outbound_message.down.sql b/server/migrations/425_channel_outbound_message.down.sql
new file mode 100644
index 0000000000..1c2a8b30a3
--- /dev/null
+++ b/server/migrations/425_channel_outbound_message.down.sql
@@ -0,0 +1,15 @@
+-- Channel Chat route migration.
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1
+ FROM channel_chat_session_binding AS binding
+ LEFT JOIN chat_session AS session ON session.id = binding.chat_session_id
+ WHERE binding.retired_at IS NOT NULL
+ OR session.explicitly_created_at IS NOT NULL
+ ) THEN
+ RAISE EXCEPTION 'cannot roll back channel chat routes after /new has created a channel Chat';
+ END IF;
+END $$;
+
+DROP TABLE IF EXISTS channel_outbound_message;
diff --git a/server/migrations/425_channel_outbound_message.up.sql b/server/migrations/425_channel_outbound_message.up.sql
new file mode 100644
index 0000000000..6680acc53a
--- /dev/null
+++ b/server/migrations/425_channel_outbound_message.up.sql
@@ -0,0 +1,11 @@
+-- Channel Chat route migration.
+CREATE TABLE channel_outbound_message (
+ installation_id UUID NOT NULL,
+ channel_type TEXT NOT NULL,
+ channel_message_id TEXT NOT NULL,
+ binding_id UUID NOT NULL,
+ route_revision BIGINT NOT NULL,
+ task_id UUID,
+ outbound_kind TEXT NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/426_channel_outbound_message_id_index.down.sql b/server/migrations/426_channel_outbound_message_id_index.down.sql
new file mode 100644
index 0000000000..3306eeec8c
--- /dev/null
+++ b/server/migrations/426_channel_outbound_message_id_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_outbound_message_id;
diff --git a/server/migrations/426_channel_outbound_message_id_index.up.sql b/server/migrations/426_channel_outbound_message_id_index.up.sql
new file mode 100644
index 0000000000..de44d54ead
--- /dev/null
+++ b/server/migrations/426_channel_outbound_message_id_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE UNIQUE INDEX CONCURRENTLY idx_channel_outbound_message_id ON channel_outbound_message (installation_id, channel_message_id);
diff --git a/server/migrations/427_channel_task_delivery_backfill.down.sql b/server/migrations/427_channel_task_delivery_backfill.down.sql
new file mode 100644
index 0000000000..e6508a3c0b
--- /dev/null
+++ b/server/migrations/427_channel_task_delivery_backfill.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+SELECT 1;
diff --git a/server/migrations/427_channel_task_delivery_backfill.up.sql b/server/migrations/427_channel_task_delivery_backfill.up.sql
new file mode 100644
index 0000000000..40eacf9932
--- /dev/null
+++ b/server/migrations/427_channel_task_delivery_backfill.up.sql
@@ -0,0 +1,20 @@
+-- Channel Chat route migration.
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+)
+SELECT
+ task.id, binding.id, binding.installation_id, binding.channel_type,
+ binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id,
+ binding.route_revision, binding.config
+FROM agent_task_queue AS task
+JOIN channel_chat_session_binding AS binding
+ ON binding.chat_session_id = task.chat_session_id
+WHERE task.status IN ('queued', 'deferred', 'dispatched', 'running', 'waiting_local_directory')
+ AND EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.task_id = COALESCE(task.chat_input_task_id, task.id)
+ AND message.role = 'user'
+ AND message.channel_ingested
+ )
+ON CONFLICT (task_id) DO NOTHING;
diff --git a/server/migrations/428_channel_task_delivery_binding_index.down.sql b/server/migrations/428_channel_task_delivery_binding_index.down.sql
new file mode 100644
index 0000000000..2a809f0e0b
--- /dev/null
+++ b/server/migrations/428_channel_task_delivery_binding_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_task_delivery_binding;
diff --git a/server/migrations/428_channel_task_delivery_binding_index.up.sql b/server/migrations/428_channel_task_delivery_binding_index.up.sql
new file mode 100644
index 0000000000..920356827e
--- /dev/null
+++ b/server/migrations/428_channel_task_delivery_binding_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE INDEX CONCURRENTLY idx_channel_task_delivery_binding ON channel_task_delivery (binding_id);
diff --git a/server/migrations/429_channel_task_delivery_installation_index.down.sql b/server/migrations/429_channel_task_delivery_installation_index.down.sql
new file mode 100644
index 0000000000..6b7c1d6bda
--- /dev/null
+++ b/server/migrations/429_channel_task_delivery_installation_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_task_delivery_installation;
diff --git a/server/migrations/429_channel_task_delivery_installation_index.up.sql b/server/migrations/429_channel_task_delivery_installation_index.up.sql
new file mode 100644
index 0000000000..8b4adf6d80
--- /dev/null
+++ b/server/migrations/429_channel_task_delivery_installation_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE INDEX CONCURRENTLY idx_channel_task_delivery_installation ON channel_task_delivery (installation_id);
diff --git a/server/migrations/430_channel_outbound_message_binding_index.down.sql b/server/migrations/430_channel_outbound_message_binding_index.down.sql
new file mode 100644
index 0000000000..a3bdd8ca07
--- /dev/null
+++ b/server/migrations/430_channel_outbound_message_binding_index.down.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_outbound_message_binding_route;
diff --git a/server/migrations/430_channel_outbound_message_binding_index.up.sql b/server/migrations/430_channel_outbound_message_binding_index.up.sql
new file mode 100644
index 0000000000..d89e8613d9
--- /dev/null
+++ b/server/migrations/430_channel_outbound_message_binding_index.up.sql
@@ -0,0 +1,2 @@
+-- Channel Chat route migration.
+CREATE INDEX CONCURRENTLY idx_channel_outbound_message_binding_route ON channel_outbound_message (binding_id, route_revision);
diff --git a/server/migrations/431_chat_explicit_origin_backfill.down.sql b/server/migrations/431_chat_explicit_origin_backfill.down.sql
new file mode 100644
index 0000000000..a176ec49a3
--- /dev/null
+++ b/server/migrations/431_chat_explicit_origin_backfill.down.sql
@@ -0,0 +1,2 @@
+-- explicitly_created_at is removed with migration 420.
+SELECT 1;
diff --git a/server/migrations/431_chat_explicit_origin_backfill.up.sql b/server/migrations/431_chat_explicit_origin_backfill.up.sql
new file mode 100644
index 0000000000..65dae0281d
--- /dev/null
+++ b/server/migrations/431_chat_explicit_origin_backfill.up.sql
@@ -0,0 +1,3 @@
+-- The idempotent pre-migration hook performs the legacy Chat origin backfill
+-- in short primary-key pages before this marker is recorded.
+SELECT 1;
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 029bc134dc..b79e4896c5 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -66,7 +66,7 @@ WITH closed AS (
pending_fresh = TRUE
WHERE binding.chat_session_id = $2
AND binding.context_revision = $3
- RETURNING binding.id, binding.chat_session_id, binding.installation_id, binding.channel_type, binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id, binding.config, binding.created_at, binding.pending_fresh, binding.context_revision
+ RETURNING binding.id, binding.chat_session_id, binding.installation_id, binding.channel_type, binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id, binding.config, binding.created_at, binding.pending_fresh, binding.context_revision, binding.route_revision, binding.retired_at, binding.history_start_message_id, binding.history_end_message_id, binding.history_boundary_pending
), opened AS (
INSERT INTO channel_chat_context_generation (
chat_session_id, revision, history_start_message_id,
@@ -385,6 +385,28 @@ func (q *Queries) ConsumeChannelBindingToken(ctx context.Context, tokenHash stri
return i, err
}
+const copyChannelTaskDelivery = `-- name: CopyChannelTaskDelivery :exec
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+)
+SELECT
+ $1, delivery.binding_id, delivery.installation_id, delivery.channel_type, delivery.channel_chat_id, delivery.chat_type,
+ delivery.channel_message_id, delivery.channel_thread_id, delivery.route_revision, delivery.config
+FROM channel_task_delivery AS delivery
+WHERE delivery.task_id = $2
+`
+
+type CopyChannelTaskDeliveryParams struct {
+ ChildTaskID pgtype.UUID `json:"child_task_id"`
+ ParentTaskID pgtype.UUID `json:"parent_task_id"`
+}
+
+func (q *Queries) CopyChannelTaskDelivery(ctx context.Context, arg CopyChannelTaskDeliveryParams) error {
+ _, err := q.db.Exec(ctx, copyChannelTaskDelivery, arg.ChildTaskID, arg.ParentTaskID)
+ return err
+}
+
const countChannelMediaPendingObjects = `-- name: CountChannelMediaPendingObjects :one
SELECT
count(*) FILTER (WHERE state <> 'tombstoned') AS pending_objects,
@@ -461,18 +483,23 @@ func (q *Queries) CreateChannelBindingToken(ctx context.Context, arg CreateChann
const createChannelChatSessionBinding = `-- name: CreateChannelChatSessionBinding :one
-WITH binding AS (
+WITH next_route AS (
+ SELECT COALESCE(MAX(route_revision) + 1, 1)::bigint AS route_revision
+ FROM channel_chat_session_binding AS existing
+ WHERE existing.installation_id = $2 AND existing.channel_chat_id = $4
+), binding AS (
INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
-) VALUES (
- $1, $2, $3, $4, $5, $6
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type,
+ config, route_revision
)
-RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision
+SELECT $1, $2, $3, $4, $5, $6, next_route.route_revision
+FROM next_route
+RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending
), generation AS (
INSERT INTO channel_chat_context_generation (chat_session_id, revision)
SELECT chat_session_id, context_revision FROM binding
)
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM binding
`
type CreateChannelChatSessionBindingParams struct {
@@ -485,18 +512,23 @@ type CreateChannelChatSessionBindingParams struct {
}
type CreateChannelChatSessionBindingRow struct {
- ID pgtype.UUID `json:"id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InstallationID pgtype.UUID `json:"installation_id"`
- ChannelType string `json:"channel_type"`
- ChannelChatID string `json:"channel_chat_id"`
- ChatType string `json:"chat_type"`
- LastMessageID pgtype.Text `json:"last_message_id"`
- LastThreadID pgtype.Text `json:"last_thread_id"`
- Config []byte `json:"config"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- PendingFresh bool `json:"pending_fresh"`
- ContextRevision int64 `json:"context_revision"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ PendingFresh bool `json:"pending_fresh"`
+ ContextRevision int64 `json:"context_revision"`
+ RouteRevision int64 `json:"route_revision"`
+ RetiredAt pgtype.Timestamptz `json:"retired_at"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
}
// =====================
@@ -531,6 +563,106 @@ func (q *Queries) CreateChannelChatSessionBinding(ctx context.Context, arg Creat
&i.CreatedAt,
&i.PendingFresh,
&i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ )
+ return i, err
+}
+
+const createChannelChatSessionBindingGeneration = `-- name: CreateChannelChatSessionBindingGeneration :one
+WITH next_route AS (
+ SELECT GREATEST(
+ $1::bigint,
+ COALESCE(MAX(route_revision) + 1, 1)::bigint
+ ) AS route_revision
+ FROM channel_chat_session_binding AS existing
+ WHERE existing.installation_id = $2
+ AND existing.channel_chat_id = $3
+), binding AS (
+INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type,
+ config, route_revision, history_start_message_id, history_boundary_pending
+) SELECT
+ $4, $2, $5, $3, $6,
+ $7, next_route.route_revision, $8, $9
+FROM next_route
+RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending
+), generation AS (
+ INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision, history_start_message_id, history_boundary_pending
+ )
+ SELECT chat_session_id, context_revision, history_start_message_id, history_boundary_pending
+ FROM binding
+)
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM binding
+`
+
+type CreateChannelChatSessionBindingGenerationParams struct {
+ RouteRevision int64 `json:"route_revision"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ ChannelType string `json:"channel_type"`
+ ChatType string `json:"chat_type"`
+ Config []byte `json:"config"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
+}
+
+type CreateChannelChatSessionBindingGenerationRow struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ PendingFresh bool `json:"pending_fresh"`
+ ContextRevision int64 `json:"context_revision"`
+ RouteRevision int64 `json:"route_revision"`
+ RetiredAt pgtype.Timestamptz `json:"retired_at"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
+}
+
+func (q *Queries) CreateChannelChatSessionBindingGeneration(ctx context.Context, arg CreateChannelChatSessionBindingGenerationParams) (CreateChannelChatSessionBindingGenerationRow, error) {
+ row := q.db.QueryRow(ctx, createChannelChatSessionBindingGeneration,
+ arg.RouteRevision,
+ arg.InstallationID,
+ arg.ChannelChatID,
+ arg.ChatSessionID,
+ arg.ChannelType,
+ arg.ChatType,
+ arg.Config,
+ arg.HistoryStartMessageID,
+ arg.HistoryBoundaryPending,
+ )
+ var i CreateChannelChatSessionBindingGenerationRow
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
)
return i, err
}
@@ -582,6 +714,48 @@ func (q *Queries) CreateChannelOutboundCardMessage(ctx context.Context, arg Crea
return i, err
}
+const createChannelTaskDeliveryFromSession = `-- name: CreateChannelTaskDeliveryFromSession :one
+
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+)
+SELECT
+ $1, binding.id, binding.installation_id, binding.channel_type,
+ binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id,
+ binding.route_revision, binding.config
+FROM channel_chat_session_binding AS binding
+WHERE binding.chat_session_id = $2
+RETURNING task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at
+`
+
+type CreateChannelTaskDeliveryFromSessionParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+// =====================
+// channel_task_delivery
+// =====================
+func (q *Queries) CreateChannelTaskDeliveryFromSession(ctx context.Context, arg CreateChannelTaskDeliveryFromSessionParams) (ChannelTaskDelivery, error) {
+ row := q.db.QueryRow(ctx, createChannelTaskDeliveryFromSession, arg.TaskID, arg.ChatSessionID)
+ var i ChannelTaskDelivery
+ err := row.Scan(
+ &i.TaskID,
+ &i.BindingID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.ChannelMessageID,
+ &i.ChannelThreadID,
+ &i.RouteRevision,
+ &i.Config,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const createChannelUserBinding = `-- name: CreateChannelUserBinding :one
INSERT INTO channel_user_binding (
@@ -661,22 +835,38 @@ func (q *Queries) DeleteChannelBindingTokensByInstallation(ctx context.Context,
}
const deleteChannelChatSessionBindingBySession = `-- name: DeleteChannelChatSessionBindingBySession :exec
-WITH deleted_binding AS (
- DELETE FROM channel_chat_session_binding AS binding
+WITH target AS (
+ SELECT binding.id FROM channel_chat_session_binding AS binding
WHERE binding.chat_session_id = $1
+), cleared_deliveries AS (
+ DELETE FROM channel_task_delivery AS delivery WHERE delivery.binding_id IN (SELECT id FROM target)
+), cleared_outbound AS (
+ DELETE FROM channel_outbound_message AS outbound WHERE outbound.binding_id IN (SELECT id FROM target)
+), deleted_binding AS (
+ DELETE FROM channel_chat_session_binding AS binding WHERE binding.id IN (SELECT id FROM target)
)
DELETE FROM channel_chat_context_generation AS generation
WHERE generation.chat_session_id = $1
`
// Application-layer integrity (replaces the old chat_session-FK ON DELETE
-// CASCADE): drop the binding when its chat_session is deleted.
+// CASCADE): drop the binding, its immutable delivery/history dependents,
+// and the Chat's context generations.
func (q *Queries) DeleteChannelChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteChannelChatSessionBindingBySession, chatSessionID)
return err
}
const deleteChannelChatSessionBindingsByInstallation = `-- name: DeleteChannelChatSessionBindingsByInstallation :exec
+WITH cleared_deliveries AS (
+ DELETE FROM channel_task_delivery AS delivery
+ WHERE delivery.installation_id = $1
+ AND delivery.channel_type = $2
+), cleared_outbound AS (
+ DELETE FROM channel_outbound_message AS outbound
+ WHERE outbound.installation_id = $1
+ AND outbound.channel_type = $2
+)
DELETE FROM channel_chat_session_binding AS binding
WHERE binding.installation_id = $1
AND binding.channel_type = $2
@@ -723,6 +913,12 @@ cleared_dingtalk_bot_identity AS (
cleared_dingtalk_group_routes AS (
DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM doomed)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM doomed)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
@@ -849,24 +1045,6 @@ func (q *Queries) DeleteChannelUserBindingsByWorkspaceMember(ctx context.Context
return err
}
-const ensureChannelChatContextGeneration = `-- name: EnsureChannelChatContextGeneration :exec
-INSERT INTO channel_chat_context_generation (
- chat_session_id, revision
-)
-SELECT binding.chat_session_id, binding.context_revision
-FROM channel_chat_session_binding AS binding
-WHERE binding.chat_session_id = $1
-ON CONFLICT (chat_session_id, revision) DO NOTHING
-`
-
-// Rolling-deploy repair: an older server can create a binding after the schema
-// migration but before every process is upgraded. Materialize its generation
-// lazily before a new server attempts to lock it.
-func (q *Queries) EnsureChannelChatContextGeneration(ctx context.Context, chatSessionID pgtype.UUID) error {
- _, err := q.db.Exec(ctx, ensureChannelChatContextGeneration, chatSessionID)
- return err
-}
-
const findChannelBindingForMember = `-- name: FindChannelBindingForMember :one
SELECT b.id, b.workspace_id, b.multica_user_id, b.installation_id, b.channel_type, b.channel_user_id, b.config, b.bound_at FROM channel_user_binding b
JOIN channel_installation ci ON ci.id = b.installation_id
@@ -1050,8 +1228,8 @@ func (q *Queries) GetChannelChatContextGeneration(ctx context.Context, arg GetCh
}
const getChannelChatSessionBinding = `-- name: GetChannelChatSessionBinding :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
-WHERE installation_id = $1 AND channel_chat_id = $2
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
+WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
`
type GetChannelChatSessionBindingParams struct {
@@ -1077,12 +1255,17 @@ func (q *Queries) GetChannelChatSessionBinding(ctx context.Context, arg GetChann
&i.CreatedAt,
&i.PendingFresh,
&i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
)
return i, err
}
const getChannelChatSessionBindingBySession = `-- name: GetChannelChatSessionBindingBySession :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
WHERE chat_session_id = $1
AND channel_type = $2
`
@@ -1112,12 +1295,17 @@ func (q *Queries) GetChannelChatSessionBindingBySession(ctx context.Context, arg
&i.CreatedAt,
&i.PendingFresh,
&i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
)
return i, err
}
const getChannelChatSessionBindingBySessionAny = `-- name: GetChannelChatSessionBindingBySessionAny :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
WHERE chat_session_id = $1
`
@@ -1143,6 +1331,11 @@ func (q *Queries) GetChannelChatSessionBindingBySessionAny(ctx context.Context,
&i.CreatedAt,
&i.PendingFresh,
&i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
)
return i, err
}
@@ -1372,6 +1565,29 @@ func (q *Queries) GetChannelOutboundCardByTask(ctx context.Context, arg GetChann
return i, err
}
+const getChannelTaskDelivery = `-- name: GetChannelTaskDelivery :one
+SELECT task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type, channel_message_id, channel_thread_id, route_revision, config, created_at FROM channel_task_delivery WHERE task_id = $1
+`
+
+func (q *Queries) GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (ChannelTaskDelivery, error) {
+ row := q.db.QueryRow(ctx, getChannelTaskDelivery, taskID)
+ var i ChannelTaskDelivery
+ err := row.Scan(
+ &i.TaskID,
+ &i.BindingID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.ChannelMessageID,
+ &i.ChannelThreadID,
+ &i.RouteRevision,
+ &i.Config,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
const getChannelUserBindingByUserID = `-- name: GetChannelUserBindingByUserID :one
SELECT id, workspace_id, multica_user_id, installation_id, channel_type, channel_user_id, config, bound_at FROM channel_user_binding
WHERE installation_id = $1 AND channel_user_id = $2
@@ -1506,6 +1722,52 @@ func (q *Queries) ListAllActiveChannelInstallations(ctx context.Context) ([]Chan
return items, nil
}
+const listChannelChatSessionBindingsBySessions = `-- name: ListChannelChatSessionBindingsBySessions :many
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
+WHERE chat_session_id = ANY($1::uuid[])
+`
+
+// Batch projection for Chat list responses. Historical bindings are retained,
+// so retired Chats keep their channel source while only the active generation
+// reports itself as the current route.
+func (q *Queries) ListChannelChatSessionBindingsBySessions(ctx context.Context, chatSessionIds []pgtype.UUID) ([]ChannelChatSessionBinding, error) {
+ rows, err := q.db.Query(ctx, listChannelChatSessionBindingsBySessions, chatSessionIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChannelChatSessionBinding{}
+ for rows.Next() {
+ var i ChannelChatSessionBinding
+ if err := rows.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChannelInboundAuditByInstallation = `-- name: ListChannelInboundAuditByInstallation :many
SELECT id, installation_id, channel_type, channel_chat_id, event_type, channel_event_id, channel_message_id, drop_reason, received_at FROM channel_inbound_audit
WHERE installation_id = $1
@@ -1596,6 +1858,72 @@ func (q *Queries) ListChannelInstallationsByWorkspace(ctx context.Context, arg L
return items, nil
}
+const listChannelOutboundMessageIDsForBinding = `-- name: ListChannelOutboundMessageIDsForBinding :many
+SELECT outbound.channel_message_id FROM channel_outbound_message AS outbound
+WHERE outbound.binding_id = $1
+ORDER BY outbound.created_at ASC
+`
+
+func (q *Queries) ListChannelOutboundMessageIDsForBinding(ctx context.Context, bindingID pgtype.UUID) ([]string, error) {
+ rows, err := q.db.Query(ctx, listChannelOutboundMessageIDsForBinding, bindingID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []string{}
+ for rows.Next() {
+ var channel_message_id string
+ if err := rows.Scan(&channel_message_id); err != nil {
+ return nil, err
+ }
+ items = append(items, channel_message_id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listChannelOutboundMessagesByIDs = `-- name: ListChannelOutboundMessagesByIDs :many
+SELECT outbound.installation_id, outbound.channel_type, outbound.channel_message_id, outbound.binding_id, outbound.route_revision, outbound.task_id, outbound.outbound_kind, outbound.created_at FROM channel_outbound_message AS outbound
+WHERE outbound.installation_id = $1
+ AND outbound.channel_message_id = ANY($2::text[])
+`
+
+type ListChannelOutboundMessagesByIDsParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelMessageIds []string `json:"channel_message_ids"`
+}
+
+func (q *Queries) ListChannelOutboundMessagesByIDs(ctx context.Context, arg ListChannelOutboundMessagesByIDsParams) ([]ChannelOutboundMessage, error) {
+ rows, err := q.db.Query(ctx, listChannelOutboundMessagesByIDs, arg.InstallationID, arg.ChannelMessageIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChannelOutboundMessage{}
+ for rows.Next() {
+ var i ChannelOutboundMessage
+ if err := rows.Scan(
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelMessageID,
+ &i.BindingID,
+ &i.RouteRevision,
+ &i.TaskID,
+ &i.OutboundKind,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockChannelChatContextGenerationByRevision = `-- name: LockChannelChatContextGenerationByRevision :one
SELECT chat_session_id, revision, history_start_message_id, history_end_message_id, history_boundary_pending, pending_fresh, initiator_user_id, created_at FROM channel_chat_context_generation
WHERE chat_session_id = $1
@@ -1625,14 +1953,14 @@ func (q *Queries) LockChannelChatContextGenerationByRevision(ctx context.Context
}
const lockChannelChatSessionBindingForContext = `-- name: LockChannelChatSessionBindingForContext :one
-SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision FROM channel_chat_session_binding
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
WHERE chat_session_id = $1
FOR UPDATE
`
// Context mutations acquire this row after chat_session and before any
// channel_chat_context_generation row. Keeping the statements separate makes
-// the lock order explicit and identical for append, /new, and task enqueue.
+// the lock order explicit and identical for append, /clear, and task enqueue.
func (q *Queries) LockChannelChatSessionBindingForContext(ctx context.Context, chatSessionID pgtype.UUID) (ChannelChatSessionBinding, error) {
row := q.db.QueryRow(ctx, lockChannelChatSessionBindingForContext, chatSessionID)
var i ChannelChatSessionBinding
@@ -1649,6 +1977,11 @@ func (q *Queries) LockChannelChatSessionBindingForContext(ctx context.Context, c
&i.CreatedAt,
&i.PendingFresh,
&i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
)
return i, err
}
@@ -1660,7 +1993,7 @@ FOR UPDATE
`
// EnqueueChatTask reads this under the same row lock and transaction that
-// creates the task. A concurrent `/new` therefore lands either before this
+// creates the task. A concurrent `/clear` therefore lands either before this
// task and is consumed by it, or after this task and remains for the next one.
func (q *Queries) LockChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
row := q.db.QueryRow(ctx, lockChannelChatSessionPendingFresh, chatSessionID)
@@ -1698,14 +2031,85 @@ func (q *Queries) LockChannelInstallationAppIDSlot(ctx context.Context, arg Lock
return err
}
+const lockCurrentChannelChatSessionBinding = `-- name: LockCurrentChannelChatSessionBinding :one
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
+WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+FOR UPDATE
+`
+
+type LockCurrentChannelChatSessionBindingParams struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelChatID string `json:"channel_chat_id"`
+}
+
+func (q *Queries) LockCurrentChannelChatSessionBinding(ctx context.Context, arg LockCurrentChannelChatSessionBindingParams) (ChannelChatSessionBinding, error) {
+ row := q.db.QueryRow(ctx, lockCurrentChannelChatSessionBinding, arg.InstallationID, arg.ChannelChatID)
+ var i ChannelChatSessionBinding
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ )
+ return i, err
+}
+
+const lockCurrentChannelChatSessionBindingBySession = `-- name: LockCurrentChannelChatSessionBindingBySession :one
+SELECT id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending FROM channel_chat_session_binding
+WHERE chat_session_id = $1 AND retired_at IS NULL
+FOR UPDATE
+`
+
+// Shared append fence. A message may have resolved a Chat immediately before
+// /new retired it; locking only chat_session would then let the stale append
+// land after the route switch. Requiring the binding to remain current makes
+// every adapter retry against the winning generation.
+func (q *Queries) LockCurrentChannelChatSessionBindingBySession(ctx context.Context, chatSessionID pgtype.UUID) (ChannelChatSessionBinding, error) {
+ row := q.db.QueryRow(ctx, lockCurrentChannelChatSessionBindingBySession, chatSessionID)
+ var i ChannelChatSessionBinding
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ )
+ return i, err
+}
+
const markChannelChatSessionPendingFresh = `-- name: MarkChannelChatSessionPendingFresh :one
UPDATE channel_chat_session_binding
SET pending_fresh = TRUE
-WHERE chat_session_id = $1
+WHERE chat_session_id = $1 AND retired_at IS NULL
RETURNING pending_fresh
`
-// Persists a channel `/new` intent until the next chat task is successfully
+// Persists a channel `/clear` intent until the next chat task is successfully
// created. RETURNING makes a missing binding an error instead of silently
// acknowledging a fresh start that was never stored.
func (q *Queries) MarkChannelChatSessionPendingFresh(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
@@ -1803,6 +2207,12 @@ cleared_dingtalk_bot_identity AS (
cleared_dingtalk_group_routes AS (
DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM dead)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM dead)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM dead)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding
WHERE installation_id IN (SELECT id FROM dead)
@@ -1994,6 +2404,46 @@ func (q *Queries) RecordChannelMediaPendingObject(ctx context.Context, arg Recor
return storage_key, err
}
+const recordChannelOutboundMessage = `-- name: RecordChannelOutboundMessage :exec
+
+INSERT INTO channel_outbound_message (
+ installation_id, channel_type, channel_message_id, binding_id,
+ route_revision, task_id, outbound_kind
+) VALUES (
+ $1, $2,
+ $3, $4,
+ $5, $6,
+ $7
+)
+ON CONFLICT (installation_id, channel_message_id) DO NOTHING
+`
+
+type RecordChannelOutboundMessageParams struct {
+ OutboundInstallationID pgtype.UUID `json:"outbound_installation_id"`
+ OutboundChannelType string `json:"outbound_channel_type"`
+ OutboundMessageID string `json:"outbound_message_id"`
+ OutboundBindingID pgtype.UUID `json:"outbound_binding_id"`
+ OutboundRouteRevision int64 `json:"outbound_route_revision"`
+ OutboundTaskID pgtype.UUID `json:"outbound_task_id"`
+ OutboundKind string `json:"outbound_kind"`
+}
+
+// =====================
+// channel_outbound_message
+// =====================
+func (q *Queries) RecordChannelOutboundMessage(ctx context.Context, arg RecordChannelOutboundMessageParams) error {
+ _, err := q.db.Exec(ctx, recordChannelOutboundMessage,
+ arg.OutboundInstallationID,
+ arg.OutboundChannelType,
+ arg.OutboundMessageID,
+ arg.OutboundBindingID,
+ arg.OutboundRouteRevision,
+ arg.OutboundTaskID,
+ arg.OutboundKind,
+ )
+ return err
+}
+
const releaseChannelInboundDedup = `-- name: ReleaseChannelInboundDedup :execrows
DELETE FROM channel_inbound_message_dedup
WHERE installation_id = $1
@@ -2094,6 +2544,44 @@ func (q *Queries) ResolveChannelChatContextHistoryStart(ctx context.Context, arg
return err
}
+const retireChannelChatSessionBinding = `-- name: RetireChannelChatSessionBinding :one
+UPDATE channel_chat_session_binding
+SET retired_at = now(),
+ history_end_message_id = $1
+WHERE id = $2 AND retired_at IS NULL
+RETURNING id, chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, last_message_id, last_thread_id, config, created_at, pending_fresh, context_revision, route_revision, retired_at, history_start_message_id, history_end_message_id, history_boundary_pending
+`
+
+type RetireChannelChatSessionBindingParams struct {
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ ID pgtype.UUID `json:"id"`
+}
+
+func (q *Queries) RetireChannelChatSessionBinding(ctx context.Context, arg RetireChannelChatSessionBindingParams) (ChannelChatSessionBinding, error) {
+ row := q.db.QueryRow(ctx, retireChannelChatSessionBinding, arg.HistoryEndMessageID, arg.ID)
+ var i ChannelChatSessionBinding
+ err := row.Scan(
+ &i.ID,
+ &i.ChatSessionID,
+ &i.InstallationID,
+ &i.ChannelType,
+ &i.ChannelChatID,
+ &i.ChatType,
+ &i.LastMessageID,
+ &i.LastThreadID,
+ &i.Config,
+ &i.CreatedAt,
+ &i.PendingFresh,
+ &i.ContextRevision,
+ &i.RouteRevision,
+ &i.RetiredAt,
+ &i.HistoryStartMessageID,
+ &i.HistoryEndMessageID,
+ &i.HistoryBoundaryPending,
+ )
+ return i, err
+}
+
const setChannelChatContextInitiator = `-- name: SetChannelChatContextInitiator :one
UPDATE channel_chat_context_generation
SET initiator_user_id = $1
@@ -2203,22 +2691,53 @@ func (q *Queries) TombstoneChannelMediaPendingObject(ctx context.Context, arg To
}
const updateChannelChatSessionBindingReplyTarget = `-- name: UpdateChannelChatSessionBindingReplyTarget :exec
-UPDATE channel_chat_session_binding
-SET last_message_id = $2,
- last_thread_id = $3
-WHERE chat_session_id = $1
+WITH current_route AS (
+ SELECT current_binding.id, current_binding.chat_session_id, current_binding.installation_id, current_binding.channel_type, current_binding.channel_chat_id, current_binding.chat_type, current_binding.last_message_id, current_binding.last_thread_id, current_binding.config, current_binding.created_at, current_binding.pending_fresh, current_binding.context_revision, current_binding.route_revision, current_binding.retired_at, current_binding.history_start_message_id, current_binding.history_end_message_id, current_binding.history_boundary_pending
+ FROM channel_chat_session_binding AS current_binding
+ WHERE current_binding.chat_session_id = $3
+ FOR UPDATE OF current_binding
+), closed_previous AS (
+ UPDATE channel_chat_session_binding AS previous
+ SET history_end_message_id = $1
+ FROM current_route AS current
+ WHERE current.history_boundary_pending
+ AND $1::text IS NOT NULL
+ AND previous.installation_id = current.installation_id
+ AND previous.channel_chat_id = current.channel_chat_id
+ -- Multiple native Slack /new commands can rotate through empty
+ -- generations before another public message supplies a platform cursor.
+ -- That cursor closes every still-open retired generation.
+ AND previous.route_revision < current.route_revision
+ AND previous.retired_at IS NOT NULL
+ AND previous.history_end_message_id IS NULL
+)
+UPDATE channel_chat_session_binding AS binding
+SET last_message_id = $1,
+ last_thread_id = $2,
+ history_start_message_id = CASE
+ WHEN binding.history_boundary_pending
+ AND $1::text IS NOT NULL
+ THEN $1
+ ELSE binding.history_start_message_id
+ END,
+ history_boundary_pending = CASE
+ WHEN $1::text IS NOT NULL THEN FALSE
+ ELSE binding.history_boundary_pending
+ END
+FROM current_route
+WHERE binding.id = current_route.id
`
type UpdateChannelChatSessionBindingReplyTargetParams struct {
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- LastMessageID pgtype.Text `json:"last_message_id"`
- LastThreadID pgtype.Text `json:"last_thread_id"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ ReplyChatSessionID pgtype.UUID `json:"reply_chat_session_id"`
}
// Records the most recent inbound trigger message + thread so the decoupled
// outbound patcher can thread its reply back into the originating topic.
func (q *Queries) UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg UpdateChannelChatSessionBindingReplyTargetParams) error {
- _, err := q.db.Exec(ctx, updateChannelChatSessionBindingReplyTarget, arg.ChatSessionID, arg.LastMessageID, arg.LastThreadID)
+ _, err := q.db.Exec(ctx, updateChannelChatSessionBindingReplyTarget, arg.LastMessageID, arg.LastThreadID, arg.ReplyChatSessionID)
return err
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 881e9ecd67..165895e012 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -90,6 +90,22 @@ func (q *Queries) AdvanceCancelledChatSessionPointer(ctx context.Context, taskID
return err
}
+const chatSessionHasPublicUserMessage = `-- name: ChatSessionHasPublicUserMessage :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE chat_session_id = $1
+ AND role = 'user'
+ AND message_kind != 'channel_command'
+) AS has_public_user_message
+`
+
+func (q *Queries) ChatSessionHasPublicUserMessage(ctx context.Context, chatSessionID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, chatSessionHasPublicUserMessage, chatSessionID)
+ var has_public_user_message bool
+ err := row.Scan(&has_public_user_message)
+ return has_public_user_message, err
+}
+
const chatSessionHasUserMessage = `-- name: ChatSessionHasUserMessage :one
SELECT EXISTS (
SELECT 1 FROM chat_message
@@ -302,7 +318,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
const createChatSession = `-- name: CreateChatSession :one
INSERT INTO chat_session (workspace_id, agent_id, creator_id, title, runtime_id, is_agent_intro, project_id, id)
VALUES ($1, $2, $3, $4, (SELECT runtime_id FROM agent WHERE id = $2), $5, $6, COALESCE($7::uuid, gen_random_uuid()))
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type CreateChatSessionParams struct {
@@ -343,6 +359,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPa
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -845,7 +862,7 @@ func (q *Queries) GetChatMessageByTaskAssistant(ctx context.Context, taskID pgty
}
const getChatSession = `-- name: GetChatSession :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at FROM chat_session
WHERE id = $1
`
@@ -869,12 +886,13 @@ func (q *Queries) GetChatSession(ctx context.Context, id pgtype.UUID) (ChatSessi
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
const getChatSessionInWorkspace = `-- name: GetChatSessionInWorkspace :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at FROM chat_session
WHERE id = $1 AND workspace_id = $2
`
@@ -903,6 +921,7 @@ func (q *Queries) GetChatSessionInWorkspace(ctx context.Context, arg GetChatSess
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -1078,7 +1097,7 @@ func (q *Queries) GetLatestAssistantChatMessageForSession(ctx context.Context, c
}
const getOldestActiveChatSessionForCreatorAgent = `-- name: GetOldestActiveChatSessionForCreatorAgent :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at FROM chat_session
WHERE workspace_id = $1
AND creator_id = $2
AND agent_id = $3
@@ -1118,6 +1137,7 @@ func (q *Queries) GetOldestActiveChatSessionForCreatorAgent(ctx context.Context,
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -1152,26 +1172,17 @@ func (q *Queries) GetPendingChatTask(ctx context.Context, chatSessionID pgtype.U
}
const getPublicChatSessionInWorkspace = `-- name: GetPublicChatSessionInWorkspace :one
-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id FROM chat_session AS cs
+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id, cs.explicitly_created_at FROM chat_session AS cs
WHERE cs.id = $1
AND cs.workspace_id = $2
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
EXISTS (
SELECT 1 FROM chat_message AS public_message
WHERE public_message.chat_session_id = cs.id
AND public_message.message_kind != 'channel_command'
)
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
)
`
@@ -1183,8 +1194,8 @@ type GetPublicChatSessionInWorkspaceParams struct {
// A channel command is a durable control-plane record, not a public chat turn.
// Channel-created sessions therefore become public only after they contain a
// non-command message. Empty first-party sessions stay public so the member can
-// open a newly-created Web Chat and send its first message. channel_ingested is
-// the immutable fallback when a channel binding has since been removed.
+// open a newly-created Web Chat and send its first message. The explicit marker
+// is durable, so removing an installation cannot change list visibility.
func (q *Queries) GetPublicChatSessionInWorkspace(ctx context.Context, arg GetPublicChatSessionInWorkspaceParams) (ChatSession, error) {
row := q.db.QueryRow(ctx, getPublicChatSessionInWorkspace, arg.ID, arg.WorkspaceID)
var i ChatSession
@@ -1205,6 +1216,7 @@ func (q *Queries) GetPublicChatSessionInWorkspace(ctx context.Context, arg GetPu
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -1298,6 +1310,103 @@ func (q *Queries) HasPendingChatTurnForSession(ctx context.Context, chatSessionI
return has_pending, err
}
+const initializeChatSessionMediaTitle = `-- name: InitializeChatSessionMediaTitle :one
+UPDATE chat_session AS session
+SET title = $1
+WHERE session.id = $2
+ AND session.title = ''
+ AND EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.id = $3
+ AND message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS other_message
+ WHERE other_message.chat_session_id = session.id
+ AND other_message.role = 'user'
+ AND other_message.message_kind != 'channel_command'
+ AND other_message.id != $3
+ )
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
+`
+
+type InitializeChatSessionMediaTitleParams struct {
+ Title string `json:"title"`
+ ID pgtype.UUID `json:"id"`
+ MessageID pgtype.UUID `json:"message_id"`
+}
+
+func (q *Queries) InitializeChatSessionMediaTitle(ctx context.Context, arg InitializeChatSessionMediaTitleParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, initializeChatSessionMediaTitle, arg.Title, arg.ID, arg.MessageID)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ &i.ExplicitlyCreatedAt,
+ )
+ return i, err
+}
+
+const initializeChatSessionTitle = `-- name: InitializeChatSessionTitle :one
+UPDATE chat_session AS session
+SET title = $1
+WHERE session.id = $2
+ AND session.title = ''
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
+`
+
+type InitializeChatSessionTitleParams struct {
+ Title string `json:"title"`
+ ID pgtype.UUID `json:"id"`
+}
+
+func (q *Queries) InitializeChatSessionTitle(ctx context.Context, arg InitializeChatSessionTitleParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, initializeChatSessionTitle, arg.Title, arg.ID)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ &i.ExplicitlyCreatedAt,
+ )
+ return i, err
+}
+
const linkChatMessageToTask = `-- name: LinkChatMessageToTask :exec
UPDATE chat_message
SET task_id = $2
@@ -1487,7 +1596,7 @@ func (q *Queries) ListAgentBuilderSessionsByCreator(ctx context.Context, arg Lis
}
const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many
-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id, cs.explicitly_created_at,
CASE WHEN cs.status = 'archived' THEN 0
ELSE (SELECT count(*) FROM chat_message m
WHERE m.chat_session_id = cs.id
@@ -1510,18 +1619,9 @@ LEFT JOIN LATERAL (
) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
lm.created_at IS NOT NULL
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
)
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC
`
@@ -1548,6 +1648,7 @@ type ListAllChatSessionsByCreatorRow struct {
IsAgentIntro bool `json:"is_agent_intro"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
ProjectID pgtype.UUID `json:"project_id"`
+ ExplicitlyCreatedAt pgtype.Timestamptz `json:"explicitly_created_at"`
UnreadCount int32 `json:"unread_count"`
LastMessageContent string `json:"last_message_content"`
LastMessageRole string `json:"last_message_role"`
@@ -1589,6 +1690,7 @@ func (q *Queries) ListAllChatSessionsByCreator(ctx context.Context, arg ListAllC
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
&i.UnreadCount,
&i.LastMessageContent,
&i.LastMessageRole,
@@ -2081,7 +2183,7 @@ func (q *Queries) ListChatMessagesPageForChannelContext(ctx context.Context, arg
}
const listChatSessionsByCreator = `-- name: ListChatSessionsByCreator :many
-SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
+SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id, cs.explicitly_created_at,
(SELECT count(*) FROM chat_message m
WHERE m.chat_session_id = cs.id
AND m.role = 'assistant'
@@ -2102,18 +2204,9 @@ LEFT JOIN LATERAL (
) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
lm.created_at IS NOT NULL
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
)
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC
`
@@ -2140,6 +2233,7 @@ type ListChatSessionsByCreatorRow struct {
IsAgentIntro bool `json:"is_agent_intro"`
PinnedAt pgtype.Timestamptz `json:"pinned_at"`
ProjectID pgtype.UUID `json:"project_id"`
+ ExplicitlyCreatedAt pgtype.Timestamptz `json:"explicitly_created_at"`
UnreadCount int32 `json:"unread_count"`
LastMessageContent string `json:"last_message_content"`
LastMessageRole string `json:"last_message_role"`
@@ -2177,6 +2271,7 @@ func (q *Queries) ListChatSessionsByCreator(ctx context.Context, arg ListChatSes
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
&i.UnreadCount,
&i.LastMessageContent,
&i.LastMessageRole,
@@ -2418,7 +2513,7 @@ func (q *Queries) LockChatSessionForDelete(ctx context.Context, id pgtype.UUID)
}
const lockChatSessionForDraftWrite = `-- name: LockChatSessionForDraftWrite :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at FROM chat_session
WHERE id = $1
FOR UPDATE
`
@@ -2463,12 +2558,13 @@ func (q *Queries) LockChatSessionForDraftWrite(ctx context.Context, id pgtype.UU
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
const lockChatSessionForEnqueue = `-- name: LockChatSessionForEnqueue :one
-SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id FROM chat_session
+SELECT id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at FROM chat_session
WHERE id = $1
FOR NO KEY UPDATE
`
@@ -2529,6 +2625,7 @@ func (q *Queries) LockChatSessionForEnqueue(ctx context.Context, id pgtype.UUID)
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -2661,6 +2758,38 @@ func (q *Queries) LockChatSessionsByWorkspace(ctx context.Context, workspaceID p
return items, nil
}
+const markChatSessionExplicitlyCreated = `-- name: MarkChatSessionExplicitlyCreated :one
+UPDATE chat_session
+SET explicitly_created_at = COALESCE(explicitly_created_at, now())
+WHERE id = $1
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
+`
+
+func (q *Queries) MarkChatSessionExplicitlyCreated(ctx context.Context, id pgtype.UUID) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, markChatSessionExplicitlyCreated, id)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ &i.ExplicitlyCreatedAt,
+ )
+ return i, err
+}
+
const markChatSessionRead = `-- name: MarkChatSessionRead :exec
UPDATE chat_session SET last_read_at = now()
WHERE id = $1
@@ -3039,6 +3168,54 @@ func (q *Queries) ReleaseOnboardingKickoffFromTask(ctx context.Context, id pgtyp
return err
}
+const replaceImplicitChatSessionTitle = `-- name: ReplaceImplicitChatSessionTitle :one
+UPDATE chat_session AS session
+SET title = $1
+WHERE session.id = $2
+ AND session.explicitly_created_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
+`
+
+type ReplaceImplicitChatSessionTitleParams struct {
+ Title string `json:"title"`
+ ID pgtype.UUID `json:"id"`
+}
+
+// Hidden channel sessions were not user-visible or manually renameable before
+// their first ordinary turn. Replace the legacy platform-generic title (or the
+// new empty placeholder) under the append transaction's route fence. An empty
+// title deliberately prepares a media-only first turn for attachment naming.
+func (q *Queries) ReplaceImplicitChatSessionTitle(ctx context.Context, arg ReplaceImplicitChatSessionTitleParams) (ChatSession, error) {
+ row := q.db.QueryRow(ctx, replaceImplicitChatSessionTitle, arg.Title, arg.ID)
+ var i ChatSession
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AgentID,
+ &i.CreatorID,
+ &i.Title,
+ &i.SessionID,
+ &i.WorkDir,
+ &i.Status,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UnreadSince,
+ &i.RuntimeID,
+ &i.LastReadAt,
+ &i.IsAgentIntro,
+ &i.PinnedAt,
+ &i.ProjectID,
+ &i.ExplicitlyCreatedAt,
+ )
+ return i, err
+}
+
const setChatMessageChannelOutboundProvenanceByTask = `-- name: SetChatMessageChannelOutboundProvenanceByTask :execrows
UPDATE chat_message
SET channel_outbound_type = $1,
@@ -3123,7 +3300,7 @@ UPDATE chat_session
SET status = CASE WHEN $2::bool THEN 'archived' ELSE 'active' END,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type SetChatSessionArchivedParams struct {
@@ -3155,6 +3332,7 @@ func (q *Queries) SetChatSessionArchived(ctx context.Context, arg SetChatSession
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -3163,7 +3341,7 @@ const setChatSessionPinned = `-- name: SetChatSessionPinned :one
UPDATE chat_session
SET pinned_at = CASE WHEN $2::bool THEN COALESCE(pinned_at, now()) ELSE NULL END
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type SetChatSessionPinnedParams struct {
@@ -3196,6 +3374,7 @@ func (q *Queries) SetChatSessionPinned(ctx context.Context, arg SetChatSessionPi
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -3384,7 +3563,7 @@ const updateChatSessionProject = `-- name: UpdateChatSessionProject :one
UPDATE chat_session
SET project_id = $1
WHERE id = $2 AND workspace_id = $3
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type UpdateChatSessionProjectParams struct {
@@ -3415,6 +3594,7 @@ func (q *Queries) UpdateChatSessionProject(ctx context.Context, arg UpdateChatSe
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -3453,7 +3633,7 @@ func (q *Queries) UpdateChatSessionSession(ctx context.Context, arg UpdateChatSe
const updateChatSessionTitle = `-- name: UpdateChatSessionTitle :one
UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type UpdateChatSessionTitleParams struct {
@@ -3481,6 +3661,7 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
@@ -3488,7 +3669,7 @@ func (q *Queries) UpdateChatSessionTitle(ctx context.Context, arg UpdateChatSess
const updateChatSessionTitleIfCurrent = `-- name: UpdateChatSessionTitleIfCurrent :one
UPDATE chat_session SET title = $1, updated_at = now()
WHERE id = $2 AND title = $3
-RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id
+RETURNING id, workspace_id, agent_id, creator_id, title, session_id, work_dir, status, created_at, updated_at, unread_since, runtime_id, last_read_at, is_agent_intro, pinned_at, project_id, explicitly_created_at
`
type UpdateChatSessionTitleIfCurrentParams struct {
@@ -3525,6 +3706,7 @@ func (q *Queries) UpdateChatSessionTitleIfCurrent(ctx context.Context, arg Updat
&i.IsAgentIntro,
&i.PinnedAt,
&i.ProjectID,
+ &i.ExplicitlyCreatedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.go
index c4bf342945..39c53de7bd 100644
--- a/server/pkg/db/generated/dingtalk.sql.go
+++ b/server/pkg/db/generated/dingtalk.sql.go
@@ -82,6 +82,14 @@ cleared_group_routes AS (
DELETE FROM dingtalk_group_route
WHERE installation_id IN (SELECT id FROM retired)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message
+ WHERE installation_id IN (SELECT id FROM retired)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding
WHERE installation_id IN (SELECT id FROM retired)
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 1f140a4fbf..31d8613579 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -333,18 +333,23 @@ type ChannelChatContextGeneration struct {
}
type ChannelChatSessionBinding struct {
- ID pgtype.UUID `json:"id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InstallationID pgtype.UUID `json:"installation_id"`
- ChannelType string `json:"channel_type"`
- ChannelChatID string `json:"channel_chat_id"`
- ChatType string `json:"chat_type"`
- LastMessageID pgtype.Text `json:"last_message_id"`
- LastThreadID pgtype.Text `json:"last_thread_id"`
- Config []byte `json:"config"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- PendingFresh bool `json:"pending_fresh"`
- ContextRevision int64 `json:"context_revision"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ LastMessageID pgtype.Text `json:"last_message_id"`
+ LastThreadID pgtype.Text `json:"last_thread_id"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ PendingFresh bool `json:"pending_fresh"`
+ ContextRevision int64 `json:"context_revision"`
+ RouteRevision int64 `json:"route_revision"`
+ RetiredAt pgtype.Timestamptz `json:"retired_at"`
+ HistoryStartMessageID pgtype.Text `json:"history_start_message_id"`
+ HistoryEndMessageID pgtype.Text `json:"history_end_message_id"`
+ HistoryBoundaryPending bool `json:"history_boundary_pending"`
}
type ChannelInboundAudit struct {
@@ -410,6 +415,31 @@ type ChannelOutboundCardMessage struct {
CreatedAt pgtype.Timestamptz `json:"created_at"`
}
+type ChannelOutboundMessage struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelMessageID string `json:"channel_message_id"`
+ BindingID pgtype.UUID `json:"binding_id"`
+ RouteRevision int64 `json:"route_revision"`
+ TaskID pgtype.UUID `json:"task_id"`
+ OutboundKind string `json:"outbound_kind"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+type ChannelTaskDelivery struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ BindingID pgtype.UUID `json:"binding_id"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelType string `json:"channel_type"`
+ ChannelChatID string `json:"channel_chat_id"`
+ ChatType string `json:"chat_type"`
+ ChannelMessageID pgtype.Text `json:"channel_message_id"`
+ ChannelThreadID pgtype.Text `json:"channel_thread_id"`
+ RouteRevision int64 `json:"route_revision"`
+ Config []byte `json:"config"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type ChannelUserBinding struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -460,22 +490,23 @@ type ChatPinnedAgent struct {
}
type ChatSession struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- AgentID pgtype.UUID `json:"agent_id"`
- CreatorID pgtype.UUID `json:"creator_id"`
- Title string `json:"title"`
- SessionID pgtype.Text `json:"session_id"`
- WorkDir pgtype.Text `json:"work_dir"`
- Status string `json:"status"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- UnreadSince pgtype.Timestamptz `json:"unread_since"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- LastReadAt pgtype.Timestamptz `json:"last_read_at"`
- IsAgentIntro bool `json:"is_agent_intro"`
- PinnedAt pgtype.Timestamptz `json:"pinned_at"`
- ProjectID pgtype.UUID `json:"project_id"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ Title string `json:"title"`
+ SessionID pgtype.Text `json:"session_id"`
+ WorkDir pgtype.Text `json:"work_dir"`
+ Status string `json:"status"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ UnreadSince pgtype.Timestamptz `json:"unread_since"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ LastReadAt pgtype.Timestamptz `json:"last_read_at"`
+ IsAgentIntro bool `json:"is_agent_intro"`
+ PinnedAt pgtype.Timestamptz `json:"pinned_at"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ ExplicitlyCreatedAt pgtype.Timestamptz `json:"explicitly_created_at"`
}
type ClientUsageDaily struct {
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index 4ff55f680c..e011c8f882 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -71,6 +71,12 @@ cleared_agent_label_assignments AS (
cleared_skill_label_assignments AS (
DELETE FROM skill_to_label WHERE skill_id IN (SELECT id FROM ws_skills)
),
+cleared_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM ws_installations)
+),
+cleared_channel_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM ws_installations)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index d39617c788..203fcd7d3a 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -31,6 +31,9 @@ deleted_channel_outbound_cards AS (
deleted_lark_outbound_cards AS (
DELETE FROM lark_outbound_card_message WHERE task_id IN (SELECT id FROM batch)
),
+deleted_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE task_id IN (SELECT id FROM batch)
+),
deleted_draft_restores AS (
DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)
)
@@ -407,6 +410,14 @@ deleted_github_check_suites AS (
deleted_pending_github_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),
+deleted_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_outbound_messages AS (
+ DELETE FROM channel_outbound_message
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
deleted_channel_chat_contexts AS (
DELETE FROM channel_chat_context_generation
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index f85a827106..d825ac03a5 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -213,6 +213,12 @@ cleared_dingtalk_bot_identity AS (
cleared_dingtalk_group_routes AS (
DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM dead)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM dead)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM dead)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding
WHERE installation_id IN (SELECT id FROM dead)
@@ -291,6 +297,12 @@ cleared_dingtalk_bot_identity AS (
cleared_dingtalk_group_routes AS (
DELETE FROM dingtalk_group_route WHERE installation_id IN (SELECT id FROM doomed)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM doomed)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM doomed)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM doomed)
RETURNING chat_session_id
@@ -524,12 +536,17 @@ WHERE installation_id = $1;
-- is its own session. config carries any platform-specific outbound routing the
-- key alone does not (e.g. Slack's real channel_id when the key is composite);
-- it is opaque to the shared session service.
-WITH binding AS (
+WITH next_route AS (
+ SELECT COALESCE(MAX(route_revision) + 1, 1)::bigint AS route_revision
+ FROM channel_chat_session_binding AS existing
+ WHERE existing.installation_id = $2 AND existing.channel_chat_id = $4
+), binding AS (
INSERT INTO channel_chat_session_binding (
- chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
-) VALUES (
- $1, $2, $3, $4, $5, $6
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type,
+ config, route_revision
)
+SELECT $1, $2, $3, $4, $5, $6, next_route.route_revision
+FROM next_route
RETURNING *
), generation AS (
INSERT INTO channel_chat_context_generation (chat_session_id, revision)
@@ -537,11 +554,59 @@ RETURNING *
)
SELECT * FROM binding;
+-- name: CreateChannelChatSessionBindingGeneration :one
+WITH next_route AS (
+ SELECT GREATEST(
+ @route_revision::bigint,
+ COALESCE(MAX(route_revision) + 1, 1)::bigint
+ ) AS route_revision
+ FROM channel_chat_session_binding AS existing
+ WHERE existing.installation_id = @installation_id
+ AND existing.channel_chat_id = @channel_chat_id
+), binding AS (
+INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type,
+ config, route_revision, history_start_message_id, history_boundary_pending
+) SELECT
+ @chat_session_id, @installation_id, @channel_type, @channel_chat_id, @chat_type,
+ @config, next_route.route_revision, sqlc.narg('history_start_message_id'), @history_boundary_pending
+FROM next_route
+RETURNING *
+), generation AS (
+ INSERT INTO channel_chat_context_generation (
+ chat_session_id, revision, history_start_message_id, history_boundary_pending
+ )
+ SELECT chat_session_id, context_revision, history_start_message_id, history_boundary_pending
+ FROM binding
+)
+SELECT * FROM binding;
+
-- name: GetChannelChatSessionBinding :one
-- Lookup-by-channel-chat: the inbound dispatcher finds the existing
-- chat_session before deciding whether to create one.
SELECT * FROM channel_chat_session_binding
-WHERE installation_id = $1 AND channel_chat_id = $2;
+WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL;
+
+-- name: LockCurrentChannelChatSessionBinding :one
+SELECT * FROM channel_chat_session_binding
+WHERE installation_id = $1 AND channel_chat_id = $2 AND retired_at IS NULL
+FOR UPDATE;
+
+-- name: LockCurrentChannelChatSessionBindingBySession :one
+-- Shared append fence. A message may have resolved a Chat immediately before
+-- /new retired it; locking only chat_session would then let the stale append
+-- land after the route switch. Requiring the binding to remain current makes
+-- every adapter retry against the winning generation.
+SELECT * FROM channel_chat_session_binding
+WHERE chat_session_id = $1 AND retired_at IS NULL
+FOR UPDATE;
+
+-- name: RetireChannelChatSessionBinding :one
+UPDATE channel_chat_session_binding
+SET retired_at = now(),
+ history_end_message_id = sqlc.narg('history_end_message_id')
+WHERE id = @id AND retired_at IS NULL
+RETURNING *;
-- name: GetChannelChatSessionBindingBySession :one
-- Reverse lookup for the outbound patcher: given a chat_session_id, find
@@ -562,26 +627,64 @@ WHERE chat_session_id = sqlc.arg('chat_session_id')
SELECT * FROM channel_chat_session_binding
WHERE chat_session_id = $1;
+-- name: ListChannelChatSessionBindingsBySessions :many
+-- Batch projection for Chat list responses. Historical bindings are retained,
+-- so retired Chats keep their channel source while only the active generation
+-- reports itself as the current route.
+SELECT * FROM channel_chat_session_binding
+WHERE chat_session_id = ANY(@chat_session_ids::uuid[]);
+
-- name: UpdateChannelChatSessionBindingReplyTarget :exec
-- Records the most recent inbound trigger message + thread so the decoupled
-- outbound patcher can thread its reply back into the originating topic.
-UPDATE channel_chat_session_binding
+WITH current_route AS (
+ SELECT current_binding.*
+ FROM channel_chat_session_binding AS current_binding
+ WHERE current_binding.chat_session_id = sqlc.arg('reply_chat_session_id')
+ FOR UPDATE OF current_binding
+), closed_previous AS (
+ UPDATE channel_chat_session_binding AS previous
+ SET history_end_message_id = sqlc.narg('last_message_id')
+ FROM current_route AS current
+ WHERE current.history_boundary_pending
+ AND sqlc.narg('last_message_id')::text IS NOT NULL
+ AND previous.installation_id = current.installation_id
+ AND previous.channel_chat_id = current.channel_chat_id
+ -- Multiple native Slack /new commands can rotate through empty
+ -- generations before another public message supplies a platform cursor.
+ -- That cursor closes every still-open retired generation.
+ AND previous.route_revision < current.route_revision
+ AND previous.retired_at IS NOT NULL
+ AND previous.history_end_message_id IS NULL
+)
+UPDATE channel_chat_session_binding AS binding
SET last_message_id = sqlc.narg('last_message_id'),
- last_thread_id = sqlc.narg('last_thread_id')
-WHERE chat_session_id = $1;
+ last_thread_id = sqlc.narg('last_thread_id'),
+ history_start_message_id = CASE
+ WHEN binding.history_boundary_pending
+ AND sqlc.narg('last_message_id')::text IS NOT NULL
+ THEN sqlc.narg('last_message_id')
+ ELSE binding.history_start_message_id
+ END,
+ history_boundary_pending = CASE
+ WHEN sqlc.narg('last_message_id')::text IS NOT NULL THEN FALSE
+ ELSE binding.history_boundary_pending
+ END
+FROM current_route
+WHERE binding.id = current_route.id;
-- name: MarkChannelChatSessionPendingFresh :one
--- Persists a channel `/new` intent until the next chat task is successfully
+-- Persists a channel `/clear` intent until the next chat task is successfully
-- created. RETURNING makes a missing binding an error instead of silently
-- acknowledging a fresh start that was never stored.
UPDATE channel_chat_session_binding
SET pending_fresh = TRUE
-WHERE chat_session_id = $1
+WHERE chat_session_id = $1 AND retired_at IS NULL
RETURNING pending_fresh;
-- name: LockChannelChatSessionPendingFresh :one
-- EnqueueChatTask reads this under the same row lock and transaction that
--- creates the task. A concurrent `/new` therefore lands either before this
+-- creates the task. A concurrent `/clear` therefore lands either before this
-- task and is consumed by it, or after this task and remains for the next one.
SELECT pending_fresh FROM channel_chat_session_binding
WHERE chat_session_id = $1
@@ -590,7 +693,7 @@ FOR UPDATE;
-- name: LockChannelChatSessionBindingForContext :one
-- Context mutations acquire this row after chat_session and before any
-- channel_chat_context_generation row. Keeping the statements separate makes
--- the lock order explicit and identical for append, /new, and task enqueue.
+-- the lock order explicit and identical for append, /clear, and task enqueue.
SELECT * FROM channel_chat_session_binding
WHERE chat_session_id = $1
FOR UPDATE;
@@ -606,18 +709,6 @@ SET pending_fresh = FALSE
WHERE chat_session_id = @chat_session_id
AND context_revision = @revision;
--- name: EnsureChannelChatContextGeneration :exec
--- Rolling-deploy repair: an older server can create a binding after the schema
--- migration but before every process is upgraded. Materialize its generation
--- lazily before a new server attempts to lock it.
-INSERT INTO channel_chat_context_generation (
- chat_session_id, revision
-)
-SELECT binding.chat_session_id, binding.context_revision
-FROM channel_chat_session_binding AS binding
-WHERE binding.chat_session_id = $1
-ON CONFLICT (chat_session_id, revision) DO NOTHING;
-
-- name: AdvanceChannelChatContextGeneration :one
-- Opens a new agent-visible context while retaining the same Multica Chat.
-- The triggering platform message is the exclusive end of the old generation
@@ -685,10 +776,17 @@ WHERE chat_session_id = @chat_session_id
-- name: DeleteChannelChatSessionBindingBySession :exec
-- Application-layer integrity (replaces the old chat_session-FK ON DELETE
--- CASCADE): drop the binding when its chat_session is deleted.
-WITH deleted_binding AS (
- DELETE FROM channel_chat_session_binding AS binding
+-- CASCADE): drop the binding, its immutable delivery/history dependents,
+-- and the Chat's context generations.
+WITH target AS (
+ SELECT binding.id FROM channel_chat_session_binding AS binding
WHERE binding.chat_session_id = sqlc.arg('chat_session_id')
+), cleared_deliveries AS (
+ DELETE FROM channel_task_delivery AS delivery WHERE delivery.binding_id IN (SELECT id FROM target)
+), cleared_outbound AS (
+ DELETE FROM channel_outbound_message AS outbound WHERE outbound.binding_id IN (SELECT id FROM target)
+), deleted_binding AS (
+ DELETE FROM channel_chat_session_binding AS binding WHERE binding.id IN (SELECT id FROM target)
)
DELETE FROM channel_chat_context_generation AS generation
WHERE generation.chat_session_id = sqlc.arg('chat_session_id');
@@ -703,10 +801,76 @@ WHERE generation.chat_session_id = sqlc.arg('chat_session_id');
-- channel binding is removed. Context generations belong to the preserved Chat,
-- not to the retired binding: in-flight task history snapshots may still read
-- them after this statement commits.
+WITH cleared_deliveries AS (
+ DELETE FROM channel_task_delivery AS delivery
+ WHERE delivery.installation_id = sqlc.arg('installation_id')
+ AND delivery.channel_type = sqlc.arg('channel_type')
+), cleared_outbound AS (
+ DELETE FROM channel_outbound_message AS outbound
+ WHERE outbound.installation_id = sqlc.arg('installation_id')
+ AND outbound.channel_type = sqlc.arg('channel_type')
+)
DELETE FROM channel_chat_session_binding AS binding
WHERE binding.installation_id = sqlc.arg('installation_id')
AND binding.channel_type = sqlc.arg('channel_type');
+-- =====================
+-- channel_task_delivery
+-- =====================
+
+-- name: CreateChannelTaskDeliveryFromSession :one
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+)
+SELECT
+ @task_id, binding.id, binding.installation_id, binding.channel_type,
+ binding.channel_chat_id, binding.chat_type, binding.last_message_id, binding.last_thread_id,
+ binding.route_revision, binding.config
+FROM channel_chat_session_binding AS binding
+WHERE binding.chat_session_id = @chat_session_id
+RETURNING *;
+
+-- name: GetChannelTaskDelivery :one
+SELECT * FROM channel_task_delivery WHERE task_id = $1;
+
+-- name: CopyChannelTaskDelivery :exec
+INSERT INTO channel_task_delivery (
+ task_id, binding_id, installation_id, channel_type, channel_chat_id, chat_type,
+ channel_message_id, channel_thread_id, route_revision, config
+)
+SELECT
+ @child_task_id, delivery.binding_id, delivery.installation_id, delivery.channel_type, delivery.channel_chat_id, delivery.chat_type,
+ delivery.channel_message_id, delivery.channel_thread_id, delivery.route_revision, delivery.config
+FROM channel_task_delivery AS delivery
+WHERE delivery.task_id = @parent_task_id;
+
+-- =====================
+-- channel_outbound_message
+-- =====================
+
+-- name: RecordChannelOutboundMessage :exec
+INSERT INTO channel_outbound_message (
+ installation_id, channel_type, channel_message_id, binding_id,
+ route_revision, task_id, outbound_kind
+) VALUES (
+ sqlc.arg('outbound_installation_id'), sqlc.arg('outbound_channel_type'),
+ sqlc.arg('outbound_message_id'), sqlc.arg('outbound_binding_id'),
+ sqlc.arg('outbound_route_revision'), sqlc.narg('outbound_task_id'),
+ sqlc.arg('outbound_kind')
+)
+ON CONFLICT (installation_id, channel_message_id) DO NOTHING;
+
+-- name: ListChannelOutboundMessageIDsForBinding :many
+SELECT outbound.channel_message_id FROM channel_outbound_message AS outbound
+WHERE outbound.binding_id = $1
+ORDER BY outbound.created_at ASC;
+
+-- name: ListChannelOutboundMessagesByIDs :many
+SELECT outbound.* FROM channel_outbound_message AS outbound
+WHERE outbound.installation_id = @installation_id
+ AND outbound.channel_message_id = ANY(@channel_message_ids::text[]);
+
-- =====================
-- channel_inbound_message_dedup
-- =====================
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 231d0b6fa6..f53e10c87d 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -23,28 +23,19 @@ WHERE id = $1 AND workspace_id = $2;
-- A channel command is a durable control-plane record, not a public chat turn.
-- Channel-created sessions therefore become public only after they contain a
-- non-command message. Empty first-party sessions stay public so the member can
--- open a newly-created Web Chat and send its first message. channel_ingested is
--- the immutable fallback when a channel binding has since been removed.
+-- open a newly-created Web Chat and send its first message. The explicit marker
+-- is durable, so removing an installation cannot change list visibility.
SELECT cs.* FROM chat_session AS cs
WHERE cs.id = $1
AND cs.workspace_id = $2
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
EXISTS (
SELECT 1 FROM chat_message AS public_message
WHERE public_message.chat_session_id = cs.id
AND public_message.message_kind != 'channel_command'
)
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
);
-- name: ListChatSessionsByCreator :many
@@ -72,18 +63,9 @@ LEFT JOIN LATERAL (
) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
lm.created_at IS NOT NULL
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
)
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
@@ -118,18 +100,9 @@ LEFT JOIN LATERAL (
) lm ON true
WHERE cs.workspace_id = $1 AND cs.creator_id = $2
AND (
+ cs.explicitly_created_at IS NOT NULL
+ OR
lm.created_at IS NOT NULL
- OR (
- NOT EXISTS (
- SELECT 1 FROM channel_chat_session_binding AS binding
- WHERE binding.chat_session_id = cs.id
- )
- AND NOT EXISTS (
- SELECT 1 FROM chat_message AS channel_message
- WHERE channel_message.chat_session_id = cs.id
- AND channel_message.channel_ingested
- )
- )
)
ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;
@@ -198,6 +171,63 @@ UPDATE chat_session SET title = $2, updated_at = now()
WHERE id = $1
RETURNING *;
+-- name: MarkChatSessionExplicitlyCreated :one
+UPDATE chat_session
+SET explicitly_created_at = COALESCE(explicitly_created_at, now())
+WHERE id = $1
+RETURNING *;
+
+-- name: InitializeChatSessionTitle :one
+UPDATE chat_session AS session
+SET title = @title
+WHERE session.id = @id
+ AND session.title = ''
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+RETURNING *;
+
+-- name: ReplaceImplicitChatSessionTitle :one
+-- Hidden channel sessions were not user-visible or manually renameable before
+-- their first ordinary turn. Replace the legacy platform-generic title (or the
+-- new empty placeholder) under the append transaction's route fence. An empty
+-- title deliberately prepares a media-only first turn for attachment naming.
+UPDATE chat_session AS session
+SET title = @title
+WHERE session.id = @id
+ AND session.explicitly_created_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+RETURNING *;
+
+-- name: InitializeChatSessionMediaTitle :one
+UPDATE chat_session AS session
+SET title = @title
+WHERE session.id = @id
+ AND session.title = ''
+ AND EXISTS (
+ SELECT 1 FROM chat_message AS message
+ WHERE message.id = @message_id
+ AND message.chat_session_id = session.id
+ AND message.role = 'user'
+ AND message.message_kind != 'channel_command'
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM chat_message AS other_message
+ WHERE other_message.chat_session_id = session.id
+ AND other_message.role = 'user'
+ AND other_message.message_kind != 'channel_command'
+ AND other_message.id != @message_id
+ )
+RETURNING *;
+
-- name: UpdateChatSessionProject :one
-- Project context is user-editable session metadata. Do not touch updated_at:
-- changing context is not conversation activity and must not reorder history.
@@ -1407,6 +1437,14 @@ SELECT EXISTS (
WHERE chat_session_id = $1 AND role = 'user'
) AS has_user_message;
+-- name: ChatSessionHasPublicUserMessage :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE chat_session_id = $1
+ AND role = 'user'
+ AND message_kind != 'channel_command'
+) AS has_public_user_message;
+
-- name: CreateChatDraftRestore :one
-- Persists the deferred-cancellation draft restore (#5219) in the same tx
-- that deletes the triggering user message: the chat:cancel_finalized
diff --git a/server/pkg/db/queries/dingtalk.sql b/server/pkg/db/queries/dingtalk.sql
index 99fc63c9d9..a2c2b99a16 100644
--- a/server/pkg/db/queries/dingtalk.sql
+++ b/server/pkg/db/queries/dingtalk.sql
@@ -252,6 +252,14 @@ cleared_group_routes AS (
DELETE FROM dingtalk_group_route
WHERE installation_id IN (SELECT id FROM retired)
),
+cleared_task_deliveries AS (
+ DELETE FROM channel_task_delivery
+ WHERE installation_id IN (SELECT id FROM retired)
+),
+cleared_outbound_messages AS (
+ DELETE FROM channel_outbound_message
+ WHERE installation_id IN (SELECT id FROM retired)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding
WHERE installation_id IN (SELECT id FROM retired)
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index bbbac3b491..5922db914e 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -114,6 +114,12 @@ cleared_agent_label_assignments AS (
cleared_skill_label_assignments AS (
DELETE FROM skill_to_label WHERE skill_id IN (SELECT id FROM ws_skills)
),
+cleared_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE installation_id IN (SELECT id FROM ws_installations)
+),
+cleared_channel_outbound_messages AS (
+ DELETE FROM channel_outbound_message WHERE installation_id IN (SELECT id FROM ws_installations)
+),
cleared_chat_sessions AS (
DELETE FROM channel_chat_session_binding WHERE installation_id IN (SELECT id FROM ws_installations)
RETURNING chat_session_id
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index f26a837c03..fad5152cc4 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -218,6 +218,9 @@ deleted_channel_outbound_cards AS (
deleted_lark_outbound_cards AS (
DELETE FROM lark_outbound_card_message WHERE task_id IN (SELECT id FROM batch)
),
+deleted_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery WHERE task_id IN (SELECT id FROM batch)
+),
deleted_draft_restores AS (
DELETE FROM chat_draft_restore WHERE task_id IN (SELECT id FROM batch)
)
@@ -427,6 +430,14 @@ deleted_github_check_suites AS (
deleted_pending_github_suites AS (
DELETE FROM github_pending_check_suite WHERE workspace_id = $1
),
+deleted_channel_task_deliveries AS (
+ DELETE FROM channel_task_delivery
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
+deleted_channel_outbound_messages AS (
+ DELETE FROM channel_outbound_message
+ WHERE installation_id IN (SELECT id FROM ws_channel_installations)
+),
deleted_channel_chat_contexts AS (
DELETE FROM channel_chat_context_generation
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 74f76c9a81..f372f949f1 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -85,6 +85,7 @@ const (
// draft restore (#5219). Channel outbounds (Slack/Lark) deliberately do
// not subscribe to it — cancellation stays silent on external channels.
EventChatCancelFinalized = "chat:cancel_finalized"
+ EventChatSessionCreated = "chat:session_created"
EventChatSessionRead = "chat:session_read"
EventChatSessionDeleted = "chat:session_deleted"
EventChatSessionUpdated = "chat:session_updated"
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 9ab616daf2..df85319e11 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -295,6 +295,22 @@ type ChatSessionReadPayload struct {
ChatSessionID string `json:"chat_session_id"`
}
+type ChatSessionCreatedPayload struct {
+ WorkspaceID string `json:"workspace_id"`
+ ChatSessionID string `json:"chat_session_id"`
+ AgentID string `json:"agent_id"`
+ CreatorID string `json:"creator_id"`
+ Title string `json:"title"`
+ ChannelSource ChatSessionChannelSource `json:"channel_source"`
+ IsCurrentChannelRoute bool `json:"is_current_channel_route"`
+}
+
+type ChatSessionChannelSource struct {
+ ChannelType string `json:"channel_type"`
+ InstallationID string `json:"installation_id"`
+ RouteRevision int64 `json:"route_revision"`
+}
+
// ChatSessionDeletedPayload is broadcast when a chat session is hard-deleted
// so other tabs/devices drop it from their session lists and reset the active
// pointer if it referenced the deleted session.