Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7106 feat(dingtalk): add contextual replies and task lifecycle reactions (#8125)
YYClaw8bf525eb2dde
diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdxindex 39c4efd4c0..657991d24f 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx@@ -54,6 +54,18 @@ Bot を DingTalk グループに追加し、`@your-bot <メッセージ>` を送DM とグループチャットのどちらでも、テキストと画像を混在させたメッセージを送れます。PNG、JPEG、GIF、WebP、BMP に対応し、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。ファイルと音声メッセージには現在対応していません。+グループチャットでテキストと画像を混在させたメッセージでは、Bot を @ メンションした部分も、メッセージの一部としてエージェントに送信されます。Bot 名を正確に除去するには、**DingTalk グループ基本情報管理権限**(`qyapi_chat_manage`)を追加してください。++### メッセージを引用して追加質問する++DingTalk の引用機能でメッセージを選び、今回の内容を入力します。グループでは引き続き Bot への @ メンションが必要です。Multica は、DingTalk のコールバックに含まれる対応済みの引用内容を今回のメッセージの前に追加し、エージェントのコンテキストにします。引用内の `/issue`、`/new`、`/clear` は引用内容であり、今回のコマンドとして実行されません。++### メッセージ処理のフィードバック++Multica は DingTalk メッセージを受信すると、元のユーザーメッセージに DingTalk の `收到`(受信)リアクションの追加を試み、エージェントに処理を引き渡したことを示します。エージェントの処理が完了し、DingTalk への返信に成功すると、`收到` は `Done` に置き換わります。処理がキャンセルされると、`收到` は取り消されます。++リアクションは DingTalk API に依存するため、即時に更新されるとは限りません。結果を確認するときは、Bot の返信と Multica の実行記録も参照してください。+### `/issue` で作業を作成する`/issue <タイトル>` または `/issue <タイトル>{改行}<詳細説明>` を送ると、新しい Multica 作業が作成され、Bot に接続されたエージェントに自動的に割り当てられます。同じメッセージの画像も、添付ファイルとして作業に追加されます。通常の会話メッセージとは異なり、`/issue` コマンドは Multica の「[チャット](/chat)」に記録されません。diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdxindex 9b99397b57..4b9c9ef1b0 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx@@ -54,6 +54,18 @@ DingTalk에서 봇에게 DM을 보내거나 그룹에서 @ 멘션해 계정 연DM과 그룹 채팅 모두 텍스트와 이미지가 함께 있는 메시지를 지원합니다. PNG, JPEG, GIF, WebP, BMP 형식을 지원하며 메시지당 최대 4장, 이미지당 최대 10 MB까지 보낼 수 있습니다. 파일과 음성 메시지는 아직 지원하지 않습니다.+그룹 채팅에서 텍스트와 이미지가 함께 있는 메시지는 봇을 @ 멘션한 부분도 메시지의 일부로 에이전트에 전달됩니다. 봇 이름을 정확히 제거하려면 **DingTalk 그룹 기본 정보 관리 권한**(`qyapi_chat_manage`)을 추가하세요.++### 메시지를 인용해 후속 질문하기++DingTalk의 인용 기능으로 메시지를 선택한 뒤 이번 메시지의 내용을 입력하세요. 그룹에서는 여전히 봇을 @ 멘션해야 합니다. Multica는 DingTalk 콜백이 제공하는 지원 가능한 인용 내용을 이번 메시지 앞에 붙여 에이전트 컨텍스트로 전달합니다. 인용 안의 `/issue`, `/new`, `/clear`는 인용 내용일 뿐, 이번 대화의 명령으로 실행되지 않습니다.++### 메시지 처리 피드백++Multica는 DingTalk 메시지를 받으면 사용자의 원래 메시지에 DingTalk의 `收到`(수신) 리액션 추가를 시도해 에이전트에 처리를 맡겼음을 표시합니다. 에이전트가 처리를 마치고 DingTalk에 답장을 성공적으로 보내면 `收到`가 `Done`으로 바뀝니다. 처리가 취소되면 `收到`를 취소합니다.++리액션은 DingTalk API에 의존하므로 즉시 갱신되지 않을 수 있습니다. 결과를 확인할 때는 봇의 답장과 Multica의 실행 기록도 함께 확인하세요.+### `/issue`로 작업 만들기`/issue <제목>` 또는 `/issue <제목>{줄 바꿈}<상세 설명>`을 보내면 새 Multica 작업이 만들어지고 봇에 연결된 에이전트에 자동으로 할당됩니다. 같은 메시지의 이미지도 첨부 파일로 작업에 추가됩니다. 일반 대화 메시지와 달리 `/issue` 명령은 Multica의 “[채팅](/chat)”에 기록을 남기지 않습니다.diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdxindex 77b7560d6b..d9fec01db3 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx@@ -54,6 +54,18 @@ Add the Bot to a DingTalk group, then send `@your-bot <message>`. You must @-menDirect messages and group chats both support messages containing text and images. Supported image formats are PNG, JPEG, GIF, WebP, and BMP. Each message can contain up to 4 images, with a maximum size of 10 MB per image. Files and voice messages are not currently supported.+In group messages containing both text and images, the @-mention of the Bot is also included in the message sent to the agent. To remove the Bot's name precisely, add the **DingTalk Group Basic Information Management** permission (`qyapi_chat_manage`).++### Follow up with a quoted message++Use DingTalk's quote action to select a message, then enter your current input. In groups, you must still @-mention the Bot. Multica prepends supported quoted content supplied by the DingTalk callback to your current message as agent context. An `/issue`, `/new`, or `/clear` inside the quote is quoted content, not a command for the current turn.++### Message processing feedback++After receiving a DingTalk message, Multica attempts to add DingTalk's `RogerThat` reaction to the original user message to indicate that it has been passed to the agent for processing. Once the agent finishes processing and the reply is successfully sent to DingTalk, `RogerThat` is replaced with `Done`. If processing is cancelled, `RogerThat` is removed.++Reactions depend on DingTalk's API and may not update immediately. Check the Bot's reply and the run record in Multica when assessing the outcome.+### Create an issue with `/issue`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).diff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdxindex af1380aa02..41f9e07f09 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx@@ -54,6 +54,18 @@ import { Callout } from "fumadocs-ui/components/callout";私聊和群聊都支持图文混排消息,图片支持 PNG、JPEG、GIF、WebP 和 BMP;每条消息最多 4 张,每张不超过 10 MB。暂不支持文件和语音消息。+注意,群聊中的图文混排消息,@ Bot 产生的内容也会作为消息内容的一部分发送给智能体,如果想精准剔除掉 Bot 名称,需添加“钉群基础信息管理权限”(`qyapi_chat_manage`)。++### 引用消息继续追问++使用钉钉的引用功能选中一条消息,再输入本轮内容;群聊中仍需 @ Bot。Multica 会把钉钉回调提供的、受支持的引用内容放在本轮消息前,作为智能体的上下文。引用中的 `/issue`、`/new` 或 `/clear` 只是引用内容,不会作为本轮指令执行。++### 消息处理反馈++Multica 收到钉钉消息后,会尝试在用户原消息上添加钉钉的`收到`表情,以表示已将消息交由智能体处理;智能体处理完成、并成功将消息发送到钉钉后,`收到`表情会被替换为`Done`;任务被取消后,会撤回`收到`表情。++表情反馈依赖钉钉接口,不保证即时更新。判断结果时请结合 Bot 回复和 Multica 中的运行记录。+### 使用 `/issue` 创建任务发送 `/issue <标题>` 或者 `/issue <标题>{换行}<详细描述>`,就可以创建一个新 Multica 任务,并自动指派给 Bot 连接着的智能体。同一条消息内的图片也会以附件的形式添加到该任务中。跟普通对话消息不一样的是,`/issue` 指令不会在 Multica 的“[对话](/chat)”中留下记录。diff --git a/server/cmd/server/dingtalk_reactions_integration_test.go b/server/cmd/server/dingtalk_reactions_integration_test.gonew file mode 100644index 0000000000..0312c9373f--- /dev/null+++ b/server/cmd/server/dingtalk_reactions_integration_test.go@@ -0,0 +1,150 @@+package main++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "slices"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/dingtalk"+ "github.com/multica-ai/multica/server/internal/realtime"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type dingTalkReactionTransport func(*http.Request) (*http.Response, error)++func (f dingTalkReactionTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++// Exercise the actual server assembly: the inbound notifier and outbound bus+// subscriber must share the same local source cache and reaction lifecycle.+func TestDingTalkReactionsThroughServerRouter(t *testing.T) {+ key := bytes.Repeat([]byte{0x83}, secretbox.KeySize)+ t.Setenv("MULTICA_DINGTALK_SECRET_KEY", base64.StdEncoding.EncodeToString(key))+ box, err := secretbox.New(key)+ if err != nil {+ t.Fatal(err)+ }+ encrypted, err := box.Seal([]byte("fixture-secret"))+ if err != nil {+ t.Fatal(err)+ }+ appID := "reaction-" + dbid.NewV7().String()+ config, err := json.Marshal(map[string]string{"app_id": appID, "robot_code": appID, "app_secret_encrypted": base64.StdEncoding.EncodeToString(encrypted)})+ if err != nil {+ t.Fatal(err)+ }+ fx := dbfx.New(testPool, testWorkspaceID, testUserID)+ agentID := fx.Agent(t, "DingTalk reaction fixture", fx.Runtime(t, "DingTalk fixture runtime"))+ installation := fx.Insert(t, "channel_installation", dbfx.Cols{"workspace_id": testWorkspaceID, "agent_id": agentID, "channel_type": "dingtalk", "config": string(config), "installer_user_id": testUserID, "status": "active"})+ fx.Insert(t, "channel_user_binding", dbfx.Cols{"installation_id": installation, "workspace_id": testWorkspaceID, "channel_type": "dingtalk", "channel_user_id": "sender", "multica_user_id": testUserID})+ fx.Cleanup(t, "DELETE FROM channel_inbound_dedup WHERE installation_id = $1", installation)+ fx.Cleanup(t, "DELETE FROM channel_task_delivery WHERE installation_id = $1", installation)+ var mu sync.Mutex+ var actions []string+ received := make(chan struct{}, 1)+ originalClient := http.DefaultClient+ http.DefaultClient = &http.Client{Transport: dingTalkReactionTransport(func(r *http.Request) (*http.Response, error) {+ if r.URL.Host != "api.dingtalk.com" {+ return nil, fmt.Errorf("unexpected outbound host: %s", r.URL.Host)+ }+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ return nil, err+ }+ response := `{"success":true}`+ action := ""+ switch r.URL.Path {+ case "/v1.0/oauth2/accessToken":+ if body["appKey"] != appID || body["appSecret"] != "fixture-secret" {+ return nil, fmt.Errorf("incorrect installation credentials")+ }+ response = `{"accessToken":"fixture-token","expireIn":7200}`+ case "/v1.0/robot/emotion/reply", "/v1.0/robot/emotion/recall":+ action = r.URL.Path + ":" + fmt.Sprint(body["emotionName"]) + ":" + fmt.Sprint(body["openMsgId"])+ case "/v1.0/robot/oToMessages/batchSend":+ var param struct {+ Text string `json:"text"`+ }+ if err := json.Unmarshal([]byte(fmt.Sprint(body["msgParam"])), ¶m); err != nil {+ return nil, err+ }+ if param.Text != "answer" {+ return nil, fmt.Errorf("unexpected reply: %q", param.Text)+ }+ action = "answer"+ response = `{"processQueryKey":"sent"}`+ default:+ return nil, fmt.Errorf("unexpected provider endpoint: %s", r.URL.Path)+ }+ if action != "" {+ mu.Lock()+ actions = append(actions, action)+ mu.Unlock()+ }+ if action == "/v1.0/robot/emotion/reply:收到:source" {+ received <- struct{}{}+ }+ return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(response))}, nil+ })}+ t.Cleanup(func() { http.DefaultClient = originalClient })+ bus := events.New()+ _, h := NewRouterWithOptions(testPool, realtime.NewHub(), bus, analytics.NoopClient{}, nil, RouterOptions{})+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ raw, err := json.Marshal(map[string]string{"app_id": appID, "current_text": "question"})+ if err != nil {+ t.Fatal(err)+ }+ msg := channel.InboundMessage{EventID: "source", MessageID: "source", Type: channel.MsgTypeText, Text: "question", CommandText: "question", AddressedToBot: true, Raw: raw,+ Source: channel.Source{ChannelType: dingtalk.TypeDingTalk, ChatType: channel.ChatTypeP2P, ChatID: appID, SenderID: "sender"}}+ if err := h.ChannelRouter.Handle(ctx, msg); err != nil {+ t.Fatal(err)+ }+ var sessionID string+ if err := testPool.QueryRow(ctx, "SELECT chat_session_id FROM channel_chat_session_binding WHERE installation_id=$1", installation).Scan(&sessionID); err != nil {+ t.Fatal(err)+ }+ for _, table := range []string{"chat_session", "channel_chat_session_binding", "channel_chat_context_generation", "chat_message", "agent_task_queue"} {+ column := "chat_session_id"+ if table == "chat_session" {+ column = "id"+ }+ fx.Cleanup(t, "DELETE FROM "+table+" WHERE "+column+"=$1", sessionID)+ }+ if !h.ChannelRouter.Drain(ctx) {+ t.Fatal("inbound work did not drain")+ }+ // Drain owns flush/media work, not the detached typing hook. Establish the+ // receipt before testing its terminal transition; terminal-before-ingest is+ // exercised separately and correctly suppresses the receipt altogether.+ select {+ case <-received:+ case <-ctx.Done():+ t.Fatal("receipt did not arrive")+ }+ var taskID string+ if err := testPool.QueryRow(ctx, "SELECT id FROM agent_task_queue WHERE chat_session_id=$1", sessionID).Scan(&taskID); err != nil {+ t.Fatal(err)+ }+ bus.Publish(events.Event{Type: protocol.EventChatDone, TaskID: taskID, ChatSessionID: sessionID, Payload: protocol.ChatDonePayload{Content: "answer"}})+ mu.Lock()+ defer mu.Unlock()+ want := []string{"/v1.0/robot/emotion/reply:收到:source", "answer", "/v1.0/robot/emotion/recall:收到:source", "/v1.0/robot/emotion/reply:Done:source"}+ if !slices.Equal(actions, want) {+ t.Fatalf("assembled reaction lifecycle = %v, want %v", actions, want)+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 26ceba0ed4..2c39794c2a 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -858,7 +858,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusAppURL: appURLFromEnv(),Logger: slog.Default(),})- ack := dingtalk.NewAckNotifier(dingtalkClient, box.Open, slog.Default())+ ack := dingtalk.NewAckNotifier(dingtalkClient, box.Open, slog.Default(), queries)var media engine.MediaResolverif store != nil {media = dingtalk.NewMediaResolver(@@ -871,7 +871,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus}botNames := dingtalk.NewBotNameResolver(dingtalkClient, box.Open)channelRouter.Register(dingtalk.TypeDingTalk, dingtalk.NewDingTalkResolverSet(queries, pool, replier, ack, media, botNames))- dingtalk.NewOutbound(queries, box.Open, dingtalkClient, slog.Default()).Register(bus)+ dingtalk.NewOutbound(queries, box.Open, dingtalkClient, ack, slog.Default()).Register(bus)dingtalk.RegisterDingTalk(channelRegistry, dingtalk.ChannelDeps{Decrypt: box.Open,Client: dingtalkClient,diff --git a/server/internal/integrations/dingtalk/ack.go b/server/internal/integrations/dingtalk/ack.goindex de0be3cb9b..56e23e4fbd 100644--- a/server/internal/integrations/dingtalk/ack.go+++ b/server/internal/integrations/dingtalk/ack.go@@ -2,6 +2,7 @@ package dingtalkimport ("context"+ "errors""log/slog""sync""time"@@ -11,126 +12,209 @@ 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")-// The classic robot API we send through (oToMessages/batchSend) exposes no-// per-message reaction, so a long-running agent turn leaves a mobile user-// staring at silence until the reply lands. (DingTalk's AI-assistant stack does-// offer a reaction capability via ackReactionScope, but the v0.9.1 stream SDK-// does not surface it.) The ack notifier stands in for a typing indicator: on-// ingest it posts a lightweight "working on it" message so the user sees their-// message was received.-//-// It implements engine.TypingNotifier. The engine calls OnIngested after an-// accepted turn has been persisted and scheduled for an agent run. Terminal-// commands such as /issue return their synchronous result without posting this-// non-retractable processing acknowledgement.--// ackProcessingText is the stand-in "typing" message. Kept short: it is a real,-// non-retractable chat message, not an ephemeral indicator.-const ackProcessingText = "👀 On it — I'll reply here when it's ready."--// ackCoalesceWindow suppresses duplicate acks for the same session. It sits just-// above the run debounce window so a burst of messages that flush into one run-// yields a single ack, while a genuinely later turn re-acks.-const ackCoalesceWindow = 5 * time.Second--// ackNotifier posts the processing ack and coalesces bursts per session.+const ackCleanupTimeout = 5 * time.Second++type ackState struct {+ inst engine.ResolvedInstallation+ msg channel.InboundMessage+ settled bool+ attempted bool+ inputID pgtype.UUID+ sessionID pgtype.UUID+}++// ackNotifier keeps a local provider anchor for each input batch. Persisted+// input ownership identifies batches; provider coordinates come only from the+// accepted-ingest cache. A restart, cross-process event, or provider failure can+// still leave a reaction behind. Reaction failures never reject input or prevent+// a reply. Done is separate:+// the outbound sender calls OnReplyDelivered only after every answer chunk lands.type ackNotifier struct {- client *Client- decrypt Decrypter- logger *slog.Logger- window time.Duration- now func() time.Time-- mu sync.Mutex- lastAck map[string]time.Time-- // sendText delivers text into the installation's conversation. Nil uses the- // real Open-API send; tests inject a recorder.- sendText func(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error+ client *Client+ decrypt Decrypter+ logger *slog.Logger+ mu sync.Mutex+ active map[string][]*ackState+ inputs reactionInputQueries+ settledInputs map[pgtype.UUID]bool+ settledOrder []pgtype.UUID+ settledNext int+ sendReaction func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error}var _ engine.TypingNotifier = (*ackNotifier)(nil)-// NewAckNotifier builds the ack notifier over the shared outbound client and the-// credential decrypter.-func NewAckNotifier(client *Client, decrypt Decrypter, logger *slog.Logger) *ackNotifier {+func NewAckNotifier(client *Client, decrypt Decrypter, logger *slog.Logger, inputs reactionInputQueries) *ackNotifier {if logger == nil {logger = slog.Default()}- return &ackNotifier{- client: client,- decrypt: decrypt,- logger: logger,- window: ackCoalesceWindow,- lastAck: make(map[string]time.Time),+ if client == nil {+ client = NewClient(nil, "")}+ return &ackNotifier{client: client, decrypt: decrypt, logger: logger, inputs: inputs, active: make(map[string][]*ackState)}}-// OnIngested posts the processing ack unless a recent ack for the same session-// is still within the coalesce window.func (n *ackNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {- if n.suppress(sessionID) {+ if !sessionID.Valid || msg.MessageID == "" || msg.Source.ChatID == "" {return}- send := n.sendText- if send == nil {- send = n.realSend+ release := n.client.beginReplyInput(sessionID)+ defer release()+ key := util.UUIDToString(sessionID)+ // Keep only reaction coordinates, not callback bodies or session webhooks.+ state := &ackState{inst: inst, msg: channel.InboundMessage{MessageID: msg.MessageID, Source: msg.Source},+ inputID: n.client.replyInputFor(inst.ID, msg), sessionID: sessionID}+ previous, accepted := n.prepareIngest(ctx, key, state)+ if !accepted {+ return+ }+ n.recallStates(ctx, previous)+ n.mu.Lock()+ alreadySettled := state.settled+ if !alreadySettled {+ state.attempted = true+ }+ n.mu.Unlock()+ if alreadySettled {+ return}- if err := send(ctx, inst, msg, ackProcessingText); err != nil {- n.logger.WarnContext(ctx, "dingtalk ack: send failed",- "installation_id", util.UUIDToString(inst.ID), "error", err)+ n.react(ctx, state.inst, state.msg, emotionAcknowledged, false)+ // A clear may win while the add is in flight. Give that completed add one+ // bounded recall; this does not require shared batch/generation identities.+ n.mu.Lock()+ settled := state.settled+ n.mu.Unlock()+ if settled {+ n.recallStates(ctx, []*ackState{state})}}-// OnSettled clears the session's dedup entry so its next turn acks immediately.-func (n *ackNotifier) OnSettled(_ context.Context, sessionID pgtype.UUID) {+// OnSettled is the shared router's failed-flush hook. That hook carries only a+// session ID, so it cannot distinguish overlapping failed/pending generations.+// Task terminal events instead use onInputsSettled with their owned input IDs.+// This hook never marks input Done.+func (n *ackNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {key := util.UUIDToString(sessionID)- if key == "" {+ n.mu.Lock()+ states := n.active[key]+ delete(n.active, key)+ for _, state := range states {+ state.settled = true+ }+ n.mu.Unlock()+ n.recallStates(ctx, states)+}++// Archive does not need a task to retire locally registered receipts. Mark each+// known input settled before recalling it, including adds still in flight. A+// restored agent can immediately accept new inputs; there is no agent-wide timer.+func (n *ackNotifier) onAgentArchived(ctx context.Context, agentID pgtype.UUID) {+ if !agentID.Valid {return}n.mu.Lock()- delete(n.lastAck, key)+ var retired []*ackState+ for key, states := range n.active {+ var remaining []*ackState+ for _, state := range states {+ if state.inst.AgentID == agentID {+ state.settled = true+ n.rememberSettledInput(state.inputID)+ retired = append(retired, state)+ } else {+ remaining = append(remaining, state)+ }+ }+ if len(remaining) == 0 {+ delete(n.active, key)+ } else {+ n.active[key] = remaining+ }+ }n.mu.Unlock()+ n.recallStates(ctx, retired)}-// suppress reports whether an ack for sessionID should be skipped, and otherwise-// records this ack. The check-and-set is atomic so concurrent ingests of one-// burst yield a single ack.-func (n *ackNotifier) suppress(sessionID pgtype.UUID) bool {- key := util.UUIDToString(sessionID)- if key == "" {- return false+func (n *ackNotifier) recallStates(ctx context.Context, states []*ackState) {+ if len(states) == 0 {+ return+ }+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), ackCleanupTimeout)+ defer cancel()+ for _, state := range states {+ n.mu.Lock()+ attempted := state.attempted+ n.mu.Unlock()+ if !attempted || n.react(cleanup, state.inst, state.msg, emotionAcknowledged, true) == nil {+ n.removeRecalledState(state)+ }}- now := n.clock()+}++func (n *ackNotifier) removeRecalledState(state *ackState) {+ key := util.UUIDToString(state.sessionID)n.mu.Lock()defer n.mu.Unlock()- if last, ok := n.lastAck[key]; ok && now.Sub(last) < n.window {- return true- }- // Prune entries past the window before inserting. OnSettled only fires for- // runs that enqueue no task, so task-spawning sessions would otherwise leak- // their entry forever. Stale entries are dead (any later turn re-acks), and- // this runs only on a cache miss, keeping the map bounded by the sessions- // seen within one window.- for k, last := range n.lastAck {- if now.Sub(last) >= n.window {- delete(n.lastAck, k)+ for i, current := range n.active[key] {+ if current == state && state.settled {+ n.active[key] = append(n.active[key][:i], n.active[key][i+1:]...)+ if len(n.active[key]) == 0 {+ delete(n.active, key)+ }+ return}}- n.lastAck[key] = now- return false}-func (n *ackNotifier) clock() time.Time {- if n.now != nil {- return n.now()+// OnReplyDelivered uses only the provider anchor captured during local ingest.+// A restart or cache miss skips Done. Delivery snapshot message IDs are not an+// attribution authority; SRC-001 is a separate shared-core defect.+func (n *ackNotifier) OnReplyDelivered(ctx context.Context, inst engine.ResolvedInstallation, inputMessageID pgtype.UUID) {+ source, ok := n.client.replySourceFor(inst.ID, inputMessageID)+ if !ok {+ return+ }+ n.react(ctx, inst, source.message, emotionDone, false)+}++func (n *ackNotifier) react(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, name string, recall bool) error {+ send := n.sendReaction+ if send == nil {+ send = n.realSendReaction+ }+ if err := send(ctx, inst, msg, name, recall); err != nil {+ n.logger.WarnContext(ctx, "dingtalk reaction failed", "message_id", msg.MessageID, "recall", recall, "error", err)+ return err}- return time.Now()+ return nil}-func (n *ackNotifier) realSend(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, text string) error {- _, err := sendInstallationText(ctx, n.client, n.decrypt, inst, targetFromMessage(msg), text)- return err+func (n *ackNotifier) realSendReaction(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, name string, recall bool) error {+ row, ok := inst.Platform.(db.ChannelInstallation)+ if !ok {+ return errors.New("installation platform row unavailable")+ }+ creds, err := decodeCredentials(row.Config, n.decrypt)+ if err != nil {+ return err+ }+ s := &sender{+ client: n.client, robotCode: creds.RobotCode,+ appKey: creds.AppKey, appSecret: creds.AppSecret,+ }+ return s.setEmojiReaction(ctx, reactionTargetFromMessage(msg), name, recall)+}++// Active receipts can outlive source-cache eviction. Include both owners when+// deciding whether this process has any reaction work for a terminal event.+func (n *ackNotifier) hasSession(sessionID pgtype.UUID) bool {+ if n.client.hasReplySession(sessionID) {+ return true+ }+ n.mu.Lock()+ defer n.mu.Unlock()+ return len(n.active[util.UUIDToString(sessionID)]) != 0}diff --git a/server/internal/integrations/dingtalk/ack_archive_test.go b/server/internal/integrations/dingtalk/ack_archive_test.gonew file mode 100644index 0000000000..afc008c323--- /dev/null+++ b/server/internal/integrations/dingtalk/ack_archive_test.go@@ -0,0 +1,114 @@+package dingtalk++import (+ "context"+ "slices"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "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"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestOutboundArchiveClearsPendingReceiptsOnlyForItsAgent(t *testing.T) {+ n, actions := newTestAckWithMessageIDs(time.Now)+ inst := engine.ResolvedInstallation{ID: sessionUUID(90), AgentID: sessionUUID(80)}+ other := engine.ResolvedInstallation{ID: sessionUUID(91), AgentID: sessionUUID(81)}+ sid := sessionUUID(92)+ add := func(inst engine.ResolvedInstallation, name string, input byte, session byte) {+ n.client.rememberReplySource(inst.ID, sessionUUID(input), sessionUUID(session), groupReactionMessage(name))+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sessionUUID(session))+ }+ add(inst, "pending", 1, 92)+ add(inst, "another-session", 2, 93)+ add(other, "other-agent", 3, 94)+ // There is no task: the subscriber must not query one to clean up archive.+ o := NewOutbound(noDeliveryOutboundQueries{}, nil, n.client, n, nil)+ bus := events.New()+ o.Register(bus)+ e := events.Event{Type: protocol.EventAgentArchived, Payload: map[string]any{"agent": map[string]any{"id": util.UUIDToString(inst.AgentID)}}}+ bus.Publish(e)+ bus.Publish(e)+ // A repeated hook for an archived input stays retired, even after restore.+ bus.Publish(events.Event{Type: protocol.EventAgentRestored, Payload: e.Payload})+ n.OnIngested(context.Background(), inst, groupReactionMessage("pending"), sid)+ add(inst, "after-restore", 4, 92)+ want := []string{"add:pending:" + emotionAcknowledged, "add:another-session:" + emotionAcknowledged, "add:other-agent:" + emotionAcknowledged}+ if !slices.Equal((*actions)[:3], want) {+ t.Fatalf("fixture: %v", *actions)+ }+ recalls := append([]string(nil), (*actions)[3:len(*actions)-1]...)+ slices.Sort(recalls)+ if !slices.Equal(recalls, []string{"recall:another-session:" + emotionAcknowledged, "recall:pending:" + emotionAcknowledged}) || (*actions)[len(*actions)-1] != "add:after-restore:"+emotionAcknowledged {+ t.Fatalf("archive crossed agent/input boundary: %v", *actions)+ }+ if len(n.active) != 2 {+ t.Fatalf("expected other agent and restored input to remain: %v", n.active)+ }+}++func TestOutboundArchiveRecallsAddThatFinishesAfterArchive(t *testing.T) {+ n := NewAckNotifier(nil, nil, nil, nil)+ inst := engine.ResolvedInstallation{ID: sessionUUID(90), AgentID: sessionUUID(80)}+ msg := groupReactionMessage("pending")+ n.client.rememberReplySource(inst.ID, sessionUUID(1), sessionUUID(92), msg)+ started, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})+ var mu sync.Mutex+ visible := false+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, name string, recall bool) error {+ if name != emotionAcknowledged {+ t.Error("archive marked input done")+ }+ if !recall {+ close(started)+ <-release+ }+ mu.Lock()+ visible = !recall+ mu.Unlock()+ return nil+ }+ go func() { defer close(done); n.OnIngested(context.Background(), inst, msg, sessionUUID(92)) }()+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("receipt add never started")+ }+ NewOutbound(nil, nil, n.client, n, nil).handleAgentArchived(events.Event{Payload: map[string]any{"agent": map[string]any{"id": util.UUIDToString(inst.AgentID)}}})+ close(release)+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("receipt add never finished")+ }+ mu.Lock()+ defer mu.Unlock()+ if visible || len(n.active) != 0 {+ t.Fatalf("late provider add survived archive: visible=%v active=%v", visible, n.active)+ }+}++func TestOutboundArchiveIgnoresInvalidPayload(t *testing.T) {+ for _, payload := range []any{nil, make(chan int), map[string]any{"agent": "wrong type"}, map[string]any{"agent": map[string]any{"id": "not-a-uuid"}}} {+ n, actions := newTestAckWithMessageIDs(time.Now)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{AgentID: sessionUUID(80)}, groupReactionMessage("pending"), sessionUUID(92))+ NewOutbound(nil, nil, n.client, n, nil).handleAgentArchived(events.Event{Payload: payload})+ if !slices.Equal(*actions, []string{"add:pending:" + emotionAcknowledged}) {+ t.Fatalf("invalid archive cleared receipt: %v", *actions)+ }+ }+}++func TestOutboundArchiveWithoutNotifierOrAgentIsNoOp(t *testing.T) {+ NewOutbound(nil, nil, nil, nil, nil).handleAgentArchived(events.Event{})+ n, actions := newTestAckWithMessageIDs(time.Now)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("pending"), sessionUUID(92))+ n.onAgentArchived(context.Background(), engine.ResolvedInstallation{}.AgentID)+ if !slices.Equal(*actions, []string{"add:pending:" + emotionAcknowledged}) {+ t.Fatalf("missing archive owner cleared receipt: %v", *actions)+ }+}diff --git a/server/internal/integrations/dingtalk/ack_batch.go b/server/internal/integrations/dingtalk/ack_batch.gonew file mode 100644index 0000000000..83ab115319--- /dev/null+++ b/server/internal/integrations/dingtalk/ack_batch.go@@ -0,0 +1,160 @@+package dingtalk++import (+ "bytes"+ "context"+ "slices"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type reactionInputQueries interface {+ GetChatMessage(context.Context, pgtype.UUID) (db.ChatMessage, error)+}++// Register a receipt against persisted input ownership, not a second debounce+// timer. Unsealed inputs in one context form the pending batch; after sealing,+// task_id separates that batch from the next one in the same conversation.+// Provider requests and database reads run outside the state lock.+func (n *ackNotifier) prepareIngest(ctx context.Context, key string, state *ackState) ([]*ackState, bool) {+ for ctx.Err() == nil {+ n.mu.Lock()+ if n.settledInputs[state.inputID] {+ n.mu.Unlock()+ return nil, false+ }+ previous := append([]*ackState(nil), n.active[key]...)+ candidates := make([]*ackState, 0, len(previous))+ for _, existing := range previous {+ if existing.inst.ID == state.inst.ID && existing.msg.MessageID == state.msg.MessageID {+ n.mu.Unlock()+ return nil, false+ }+ if existing.inst.ID == state.inst.ID {+ candidates = append(candidates, existing)+ }+ }+ n.mu.Unlock()++ var superseded []*ackState+ if n.inputs != nil {+ if !state.inputID.Valid {+ return nil, false+ }+ current, err := n.inputs.GetChatMessage(ctx, state.inputID)+ if err != nil || !current.ChannelIngested || current.Role != "user" || current.ChatSessionID != state.sessionID {+ n.logger.WarnContext(ctx, "dingtalk reaction: accepted input unavailable", "error", err)+ return nil, false+ }+ older := false+ for _, candidate := range candidates {+ input, err := n.inputs.GetChatMessage(ctx, candidate.inputID)+ if err != nil {+ n.logger.WarnContext(ctx, "dingtalk reaction: batch input unavailable", "error", err)+ return nil, false+ }+ if !sameReactionBatch(current, input) {+ continue+ }+ // Match ListChatInputMessages ordering, including its UUID tie-break.+ if input.CreatedAt.Time.After(current.CreatedAt.Time) || (input.CreatedAt.Time.Equal(current.CreatedAt.Time) && bytes.Compare(input.ID.Bytes[:], current.ID.Bytes[:]) > 0) {+ older = true+ }+ superseded = append(superseded, candidate)+ }+ latest, err := n.inputs.GetChatMessage(ctx, state.inputID)+ if err != nil {+ return nil, false+ }+ // Sealing can commit between the reads above. Retry classification+ // before changing any visible anchor when the current owner moved.+ if latest.TaskID != current.TaskID || latest.ChannelContextRevision != current.ChannelContextRevision {+ continue+ }+ if older {+ return nil, false+ }+ }++ n.mu.Lock()+ if n.settledInputs[state.inputID] {+ n.mu.Unlock()+ return nil, false+ }+ if !slices.Equal(n.active[key], previous) {+ n.mu.Unlock()+ continue+ }+ for _, previous := range superseded {+ previous.settled = true+ }+ n.active[key] = append(n.active[key], state)+ n.mu.Unlock()+ return superseded, true+ }+ n.logger.WarnContext(ctx, "dingtalk reaction: input lookup cancelled; receipt skipped", "error", ctx.Err())+ return nil, false+}++func sameReactionBatch(a, b db.ChatMessage) bool {+ if a.ChatSessionID != b.ChatSessionID || !b.ChannelIngested || b.Role != "user" {+ return false+ }+ if a.TaskID.Valid || b.TaskID.Valid {+ return a.TaskID.Valid && a.TaskID == b.TaskID+ }+ return a.ChannelContextRevision == b.ChannelContextRevision+}++// Terminal events retire only their sealed input. Remember a bounded set of+// input IDs so a detached ingest hook that has not begun cannot re-add a receipt.+func (n *ackNotifier) onInputsSettled(ctx context.Context, sessionID pgtype.UUID, inputs []db.ChatMessage) {+ ids := make(map[pgtype.UUID]bool, len(inputs))+ for _, input := range inputs {+ if input.ID.Valid && input.ChannelIngested {+ ids[input.ID] = true+ }+ }+ key := util.UUIDToString(sessionID)+ n.mu.Lock()+ for id := range ids {+ n.rememberSettledInput(id)+ }+ var settled, remaining []*ackState+ for _, state := range n.active[key] {+ if ids[state.inputID] {+ state.settled = true+ settled = append(settled, state)+ } else {+ remaining = append(remaining, state)+ }+ }+ if len(remaining) == 0 {+ delete(n.active, key)+ } else {+ n.active[key] = remaining+ }+ n.mu.Unlock()+ n.recallStates(ctx, settled)+}++// Caller holds n.mu. Both task termination and archive share the same bounded+// input fence so re-delivery of a known hook cannot recreate its receipt.+func (n *ackNotifier) rememberSettledInput(id pgtype.UUID) {+ if !id.Valid || n.settledInputs[id] {+ return+ }+ if n.settledInputs == nil {+ n.settledInputs = make(map[pgtype.UUID]bool)+ }+ if len(n.settledOrder) == maxReplySources {+ delete(n.settledInputs, n.settledOrder[n.settledNext])+ n.settledOrder[n.settledNext] = id+ n.settledNext = (n.settledNext + 1) % maxReplySources+ } else {+ n.settledOrder = append(n.settledOrder, id)+ }+ n.settledInputs[id] = true+}diff --git a/server/internal/integrations/dingtalk/ack_batch_test.go b/server/internal/integrations/dingtalk/ack_batch_test.gonew file mode 100644index 0000000000..ffcdf1b34b--- /dev/null+++ b/server/internal/integrations/dingtalk/ack_batch_test.go@@ -0,0 +1,394 @@+package dingtalk++import (+ "context"+ "errors"+ "slices"+ "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"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++type ackInputQueries struct {+ rows map[pgtype.UUID]db.ChatMessage+ read func(pgtype.UUID)+ err error+}++func (q *ackInputQueries) GetChatMessage(_ context.Context, id pgtype.UUID) (db.ChatMessage, error) {+ if q.read != nil {+ q.read(id)+ }+ if q.err != nil {+ return db.ChatMessage{}, q.err+ }+ row, ok := q.rows[id]+ if !ok {+ return row, pgx.ErrNoRows+ }+ return row, nil+}++func TestAckBatchUsesSealedOwnershipAndInputOrder(t *testing.T) {+ for _, tc := range []struct {+ name string+ sealed, fresh, reversed bool+ want []string+ }{+ {"pending batch", false, false, false, []string{"add:a", "recall:a", "add:b"}},+ {"same sealed batch", true, false, false, []string{"add:a", "recall:a", "add:b"}},+ {"late older hook", false, false, true, []string{"add:b"}},+ {"new context", false, true, false, []string{"add:a", "add:b"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ ctx := context.Background()+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ var actions []string+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ verb := "add:"+ if recall {+ verb = "recall:"+ }+ actions = append(actions, verb+msg.MessageID)+ return nil+ }+ for i, name := range []string{"a", "b"} {+ id := sessionUUID(byte(92 + i))+ row := db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true, ChannelContextRevision: pgtype.Int8{Int64: 1, Valid: true}, CreatedAt: pgtype.Timestamptz{Time: time.Unix(int64(i), 0), Valid: true}}+ if tc.sealed {+ row.TaskID = sessionUUID(94)+ }+ if tc.fresh && i == 1 {+ row.ChannelContextRevision.Int64 = 2+ }+ q.rows[id] = row+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ }+ order := []string{"a", "b"}+ if tc.reversed {+ slices.Reverse(order)+ }+ for _, name := range order {+ n.OnIngested(ctx, inst, groupReactionMessage(name), sid)+ }+ if !slices.Equal(actions, tc.want) {+ t.Fatalf("actions=%v want=%v", actions, tc.want)+ }+ })+ }+}++func TestAckBatchDoesNotMoveAcrossTaskBoundary(t *testing.T) {+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ visible := map[string]bool{}+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ if recall {+ delete(visible, msg.MessageID)+ } else {+ visible[msg.MessageID] = true+ }+ return nil+ }+ for i, name := range []string{"a", "b"} {+ id := sessionUUID(byte(92 + i))+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true, ChannelContextRevision: pgtype.Int8{Int64: 1, Valid: true}}+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ a := q.rows[sessionUUID(92)]+ a.TaskID = sessionUUID(94)+ q.rows[a.ID] = a+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ if len(visible) != 2 {+ t.Fatalf("new batch removed old receipt: %v", visible)+ }+ n.onInputsSettled(context.Background(), sid, []db.ChatMessage{a})+ if len(visible) != 1 || !visible["b"] {+ t.Fatalf("old terminal cleared new batch: %v", visible)+ }+}++func TestAckTerminalBeforeIngestDoesNotRecreateReceipt(t *testing.T) {+ inst, sid, id := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91), sessionUUID(92)+ row := db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ q := &ackInputQueries{rows: map[pgtype.UUID]db.ChatMessage{id: row}}+ n := NewAckNotifier(nil, nil, nil, q)+ calls := 0+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ calls+++ return nil+ }+ // Even the local source capture may follow a fast terminal event.+ n.onInputsSettled(context.Background(), sid, []db.ChatMessage{row})+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage("a"))+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ if calls != 0 || len(n.active) != 0 {+ t.Fatalf("late hook recreated receipt: calls=%d active=%v", calls, n.active)+ }+}++func TestAckBatchRetriesWhenInputSealsDuringLookup(t *testing.T) {+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ visible := map[string]bool{}+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ if recall {+ delete(visible, msg.MessageID)+ } else {+ visible[msg.MessageID] = true+ }+ return nil+ }+ for i, name := range []string{"a", "b"} {+ id := sessionUUID(byte(92 + i))+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ q.read = func(id pgtype.UUID) {+ if id == sessionUUID(92) {+ q.read = nil+ for id, row := range q.rows {+ row.TaskID = sessionUUID(94)+ q.rows[id] = row+ }+ }+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ if len(visible) != 1 || !visible["b"] {+ t.Fatalf("sealing race left wrong receipts: %v", visible)+ }+}++func TestAckBatchRecallsSupersededInFlightAdd(t *testing.T) {+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ for i, name := range []string{"a", "b"} {+ id := sessionUUID(byte(92 + i))+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ }+ started, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})+ var mu sync.Mutex+ visible := map[string]bool{}+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ if msg.MessageID == "a" && !recall {+ close(started)+ <-release+ }+ mu.Lock()+ defer mu.Unlock()+ if recall {+ delete(visible, msg.MessageID)+ } else {+ visible[msg.MessageID] = true+ }+ return nil+ }+ go func() { defer close(done); n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid) }()+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("add did not begin")+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ close(release)+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("late add did not finish")+ }+ mu.Lock()+ defer mu.Unlock()+ if len(visible) != 1 || !visible["b"] {+ t.Fatalf("old add reappeared: %v", visible)+ }+}++func TestAckBatchQueryFailureSkipsReceipt(t *testing.T) {+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{err: errors.New("unavailable")}+ n := NewAckNotifier(nil, nil, nil, q)+ n.client.rememberReplySource(inst.ID, sessionUUID(92), sid, groupReactionMessage("a"))+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ t.Fatal("query failure guessed a batch")+ return nil+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ if len(n.active) != 0 {+ t.Fatal("failed query retained receipt")+ }+}++func TestAckBatchRetriesFailedRecallOnNextMessage(t *testing.T) {+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ visible := map[string]bool{}+ failed := false+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ if recall && msg.MessageID == "a" && !failed {+ failed = true+ return errors.New("temporary recall failure")+ }+ if recall {+ delete(visible, msg.MessageID)+ } else {+ visible[msg.MessageID] = true+ }+ return nil+ }+ for i, name := range []string{"a", "b", "c"} {+ id := sessionUUID(byte(92 + i))+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid)+ if name == "b" && len(visible) != 2 {+ t.Fatalf("fixture did not leave failed recall visible: %v", visible)+ }+ }+ if len(visible) != 1 || !visible["c"] {+ t.Fatalf("failed recall was not retried: %v", visible)+ }+}++func TestAckTerminalDuringBatchLookupDoesNotRecreateReceipt(t *testing.T) {+ inst, sid, id := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91), sessionUUID(92)+ row := db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ q := &ackInputQueries{rows: map[pgtype.UUID]db.ChatMessage{id: row}}+ n := NewAckNotifier(nil, nil, nil, q)+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage("a"))+ q.read = func(pgtype.UUID) {+ q.read = nil+ n.onInputsSettled(context.Background(), sid, []db.ChatMessage{row})+ }+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ t.Fatal("terminal event during lookup recreated receipt")+ return nil+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+}++func TestAckBatchRejectsUnattributableInput(t *testing.T) {+ for _, kind := range []string{"cache miss", "other installation", "other conversation", "other session", "web input", "assistant input"} {+ t.Run(kind, func(t *testing.T) {+ inst, sid, id := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91), sessionUUID(92)+ row := db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ q := &ackInputQueries{rows: map[pgtype.UUID]db.ChatMessage{}}+ n := NewAckNotifier(nil, nil, nil, q)+ msg := groupReactionMessage("a")+ if kind != "cache miss" {+ n.client.rememberReplySource(inst.ID, id, sid, msg)+ }+ switch kind {+ case "other installation":+ inst.ID = sessionUUID(93)+ case "other conversation":+ msg.Source.ChatID = "another-chat"+ case "other session":+ row.ChatSessionID = sessionUUID(94)+ case "web input":+ row.ChannelIngested = false+ case "assistant input":+ row.Role = "assistant"+ }+ q.rows[id] = row+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ t.Fatal("unattributable input received reaction")+ return nil+ }+ n.OnIngested(context.Background(), inst, msg, sid)+ })+ }+}++func TestAckTerminalFenceIsBounded(t *testing.T) {+ n := NewAckNotifier(nil, nil, nil, nil)+ sid := sessionUUID(91)+ var first, last pgtype.UUID+ for i := 0; i <= maxReplySources; i++ {+ last = dbid.NewV7()+ if i == 0 {+ first = last+ }+ n.onInputsSettled(context.Background(), sid, []db.ChatMessage{{ID: last, ChatSessionID: sid, Role: "user", ChannelIngested: true}})+ }+ if len(n.settledInputs) != maxReplySources || n.settledInputs[first] || !n.settledInputs[last] {+ t.Fatalf("terminal fence did not evict oldest entry: count=%d first=%v last=%v", len(n.settledInputs), n.settledInputs[first], n.settledInputs[last])+ }+}++func TestAckConcurrentBatchKeepsLastInput(t *testing.T) {+ const count = 24+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n := NewAckNotifier(nil, nil, nil, q)+ var mu sync.Mutex+ visible := make(map[string]bool)+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, _ string, recall bool) error {+ mu.Lock()+ defer mu.Unlock()+ if recall {+ delete(visible, msg.MessageID)+ } else {+ visible[msg.MessageID] = true+ }+ return nil+ }+ var messages []channel.InboundMessage+ for i := 0; i < count; i++ {+ id := sessionUUID(byte(100 + i))+ msg := groupReactionMessage(string(rune('a' + i)))+ messages = append(messages, msg)+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}+ n.client.rememberReplySource(inst.ID, id, sid, msg)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ // Make every hook begin from the same empty snapshot, then compete to+ // publish. The last persisted input must win regardless of hook order.+ ready := make(chan struct{})+ seen := make(map[pgtype.UUID]bool)+ q.read = func(id pgtype.UUID) {+ mu.Lock()+ if !seen[id] {+ seen[id] = true+ if len(seen) == count {+ close(ready)+ }+ }+ mu.Unlock()+ select {+ case <-ready:+ case <-ctx.Done():+ }+ }+ var hooks sync.WaitGroup+ for _, msg := range messages {+ hooks.Add(1)+ go func() {+ defer hooks.Done()+ n.OnIngested(ctx, inst, msg, sid)+ }()+ }+ hooks.Wait()+ if ctx.Err() != nil {+ t.Fatal("concurrent hooks did not finish")+ }+ if len(visible) != 1 || !visible[messages[count-1].MessageID] {+ t.Fatalf("concurrent batch did not converge to its last input: %v", visible)+ }+}diff --git a/server/internal/integrations/dingtalk/ack_failure_boundaries_test.go b/server/internal/integrations/dingtalk/ack_failure_boundaries_test.gonew file mode 100644index 0000000000..5aec5de483--- /dev/null+++ b/server/internal/integrations/dingtalk/ack_failure_boundaries_test.go@@ -0,0 +1,99 @@+package dingtalk++import (+ "context"+ "errors"+ "slices"+ "testing"+ "time"++ "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"+)++func TestAckBatchLookupFailuresKeepExistingReceipt(t *testing.T) {+ for _, failureRead := range []int{2, 3} {+ name := "candidate lookup"+ if failureRead == 3 {+ name = "current input recheck"+ }+ t.Run(name, func(t *testing.T) {+ n, actions := newTestAckWithMessageIDs(time.Now)+ inst, sid := engine.ResolvedInstallation{ID: sessionUUID(90)}, sessionUUID(91)+ q := &ackInputQueries{rows: make(map[pgtype.UUID]db.ChatMessage)}+ n.inputs = q+ for i, name := range []string{"existing", "new"} {+ id := sessionUUID(byte(92 + i))+ q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, ChannelIngested: true, Role: "user", CreatedAt: pgtype.Timestamptz{Time: time.Unix(int64(i), 0), Valid: true}}+ n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("existing"), sid)+ reads := 0+ q.read = func(pgtype.UUID) {+ reads+++ if reads == failureRead {+ q.err = errors.New("database unavailable")+ }+ }+ n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid)+ if reads != failureRead || !slices.Equal(*actions, []string{"add:existing:" + emotionAcknowledged}) {+ t.Fatalf("failed lookup moved receipt: reads=%d actions=%v", reads, *actions)+ }+ // A failed optional lookup must not poison the next accepted hook.+ q.read, q.err = nil, nil+ n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid)+ want := []string{"add:existing:" + emotionAcknowledged, "recall:existing:" + emotionAcknowledged, "add:new:" + emotionAcknowledged}+ if !slices.Equal(*actions, want) {+ t.Fatalf("recovered lookup: actions=%v want=%v", *actions, want)+ }+ })+ }+}++type terminalOwnerQueries struct {+ noDeliveryOutboundQueries+ task db.AgentTaskQueue+ taskErr error+ taskReads int+}++func (q *terminalOwnerQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {+ q.taskReads+++ return q.task, q.taskErr+}++func TestOutboundTerminalOwnerFailureKeepsReceipts(t *testing.T) {+ sid, taskID := sessionUUID(91), sessionUUID(94)+ for _, tc := range []struct {+ name string+ task db.AgentTaskQueue+ err error+ }{+ {"task lookup failure", db.AgentTaskQueue{}, errors.New("database unavailable")},+ {"missing input owner", db.AgentTaskQueue{ChatSessionID: sid}, nil},+ {"different session", db.AgentTaskQueue{ChatSessionID: sessionUUID(95), ChatInputTaskID: taskID}, nil},+ } {+ t.Run(tc.name, func(t *testing.T) {+ n, actions := newTestAckWithMessageIDs(time.Now)+ inst := engine.ResolvedInstallation{ID: sessionUUID(90)}+ for i, name := range []string{"existing", "new"} {+ n.client.rememberReplySource(inst.ID, sessionUUID(byte(92+i)), sid, groupReactionMessage(name))+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid)+ }+ before := append([]string(nil), (*actions)...)+ q := &terminalOwnerQueries{task: tc.task, taskErr: tc.err}+ o := NewOutbound(q, nil, n.client, n, nil)+ err := o.processEvent(context.Background(), events.Event{Type: protocol.EventTaskCancelled, TaskID: util.UUIDToString(taskID), ChatSessionID: util.UUIDToString(sid)})+ if err != nil || q.taskReads != 1 || !slices.Equal(*actions, before) {+ t.Fatalf("unknown owner changed receipts: err=%v reads=%d actions=%v", err, q.taskReads, *actions)+ }+ if len(n.active[util.UUIDToString(sid)]) != 2 {+ t.Fatal("unknown owner discarded local anchors")+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/ack_test.go b/server/internal/integrations/dingtalk/ack_test.goindex 7dfd8b3f6f..2cfb0b9b07 100644--- a/server/internal/integrations/dingtalk/ack_test.go+++ b/server/internal/integrations/dingtalk/ack_test.go@@ -2,84 +2,148 @@ package dingtalkimport ("context"- "log/slog"+ "errors"+ "slices"+ "sync""testing""time""github.com/jackc/pgx/v5/pgtype"-"github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/integrations/channel/engine")func sessionUUID(b byte) pgtype.UUID {- var u pgtype.UUID- u.Valid = true+ u := pgtype.UUID{Valid: true}u.Bytes[0] = breturn u}--func newTestAck(now func() time.Time) (*ackNotifier, *[]string) {- var sent []string- n := &ackNotifier{- logger: slog.Default(),- window: 5 * time.Second,- now: now,- lastAck: map[string]time.Time{},- sendText: func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, text string) error {- sent = append(sent, text)- return nil- },+func groupReactionMessage(id string) channel.InboundMessage {+ return channel.InboundMessage{MessageID: id, Source: channel.Source{ChatID: "cid-1", ChatType: channel.ChatTypeGroup}}+}+func newTestAck(_ func() time.Time) (*ackNotifier, *[]string) {+ n := NewAckNotifier(nil, nil, nil, nil)+ var actions []string+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, name string, recall bool) error {+ verb := "add:"+ if recall {+ verb = "recall:"+ }+ actions = append(actions, verb+name)+ return nil}- return n, &sent+ return n, &actions}--func TestAckNotifier_CoalescesBurstThenReacksAfterWindow(t *testing.T) {- base := time.Unix(1700000000, 0)- cur := base- n, sent := newTestAck(func() time.Time { return cur })+func newTestAckWithMessageIDs(_ func() time.Time) (*ackNotifier, *[]string) {+ n := NewAckNotifier(nil, nil, nil, nil)+ var actions []string+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, name string, recall bool) error {+ verb := "add:"+ if recall {+ verb = "recall:"+ }+ actions = append(actions, verb+msg.MessageID+":"+name)+ return nil+ }+ return n, &actions+}+func TestAckNotifierClearsSessionWithoutMarkingOtherInputsDone(t *testing.T) {+ n, actions := newTestAckWithMessageIDs(time.Now)+ ctx := context.Background()sid := sessionUUID(1)+ inst := engine.ResolvedInstallation{ID: sessionUUID(9)}+ n.OnIngested(ctx, inst, groupReactionMessage("a"), sid)+ n.OnIngested(ctx, inst, groupReactionMessage("b"), sid)+ n.OnIngested(ctx, inst, groupReactionMessage("other"), sessionUUID(2))+ n.OnSettled(ctx, sid)+ n.client.rememberReplySource(inst.ID, sessionUUID(10), sid, groupReactionMessage("a"))+ n.OnReplyDelivered(ctx, inst, sessionUUID(10))+ want := []string{"add:a:收到", "add:b:收到", "add:other:收到", "recall:a:收到", "recall:b:收到", "add:a:Done"}+ if !slices.Equal(*actions, want) {+ t.Fatalf("actions=%v want=%v", *actions, want)+ }+}+func TestAckNotifierDuplicateIngestDoesNotDuplicateReaction(t *testing.T) {+ n, actions := newTestAck(time.Now)ctx := context.Background()-- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)- if len(*sent) != 1 {- t.Fatalf("a burst within the window must coalesce to one ack, got %d", len(*sent))+ sid := sessionUUID(1)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ if len(*actions) != 1 {+ t.Fatalf("duplicate reactions: %v", *actions)}- if (*sent)[0] != ackProcessingText {- t.Errorf("ack text = %q, want %q", (*sent)[0], ackProcessingText)+}+func TestAckNotifierFailedAddStillAttemptsBoundedRecall(t *testing.T) {+ n := NewAckNotifier(nil, nil, nil, nil)+ var calls int+ n.sendReaction = func(ctx context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, _ string, recall bool) error {+ calls+++ if recall && ctx.Err() != nil {+ t.Error("cleanup inherited cancelled context")+ }+ return errors.New("uncertain provider result")}-- cur = base.Add(6 * time.Second)- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)- if len(*sent) != 2 {- t.Fatalf("a message after the window must re-ack, got %d", len(*sent))+ ctx, cancel := context.WithCancel(context.Background())+ sid := sessionUUID(1)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ cancel()+ n.OnSettled(ctx, sid)+ n.OnSettled(context.Background(), sid)+ if calls != 2 || len(n.active) != 0 {+ t.Fatalf("calls=%d active=%d", calls, len(n.active))}}--func TestAckNotifier_SettleResetsDedup(t *testing.T) {- cur := time.Unix(1700000000, 0)- n, sent := newTestAck(func() time.Time { return cur })- sid := sessionUUID(2)- ctx := context.Background()-- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)- n.OnSettled(ctx, sid)- // Even within the window, a settled session acks its next turn immediately.- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sid)- if len(*sent) != 2 {- t.Fatalf("OnSettled must reset dedup so the next turn re-acks, got %d", len(*sent))+func TestAckNotifierRecallsAddThatFinishesAfterClear(t *testing.T) {+ n := NewAckNotifier(nil, nil, nil, nil)+ started := make(chan struct{})+ release := make(chan struct{})+ done := make(chan struct{})+ var mu sync.Mutex+ var actions []string+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, _ string, recall bool) error {+ if !recall {+ close(started)+ <-release+ }+ mu.Lock()+ defer mu.Unlock()+ if recall {+ actions = append(actions, "recall")+ } else {+ actions = append(actions, "add")+ }+ return nil+ }+ sid := sessionUUID(1)+ go func() {+ defer close(done)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ }()+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("add did not start")+ }+ n.OnSettled(context.Background(), sid)+ close(release)+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("add did not finish")+ }+ mu.Lock()+ defer mu.Unlock()+ if !slices.Equal(actions, []string{"recall", "add", "recall"}) {+ t.Fatalf("actions=%v", actions)}}--func TestAckNotifier_DistinctSessionsAckIndependently(t *testing.T) {- cur := time.Unix(1700000000, 0)- n, sent := newTestAck(func() time.Time { return cur })- ctx := context.Background()-- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sessionUUID(3))- n.OnIngested(ctx, engine.ResolvedInstallation{}, channel.InboundMessage{}, sessionUUID(4))- if len(*sent) != 2 {- t.Fatalf("distinct sessions must each ack, got %d", len(*sent))+func TestAckNotifierInvalidCoordinatesDoNothing(t *testing.T) {+ n, actions := newTestAck(time.Now)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), pgtype.UUID{})+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage(""), sessionUUID(1))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, channel.InboundMessage{MessageID: "a"}, sessionUUID(1))+ n.OnReplyDelivered(context.Background(), engine.ResolvedInstallation{}, pgtype.UUID{})+ if len(*actions) != 0 {+ t.Fatalf("invalid coordinates sent: %v", *actions)}}diff --git a/server/internal/integrations/dingtalk/emotion.go b/server/internal/integrations/dingtalk/emotion.gonew file mode 100644index 0000000000..36b2ebb0a2--- /dev/null+++ b/server/internal/integrations/dingtalk/emotion.go@@ -0,0 +1,67 @@+package dingtalk++import (+ "context"+ "errors"+ "fmt"+)++// DingTalk's built-in emoji reactions are addressed by their platform-defined+// names, not by installation-specific IDs. The Chinese acknowledgement below+// is therefore an OpenAPI enum value (emotion_167), not user-facing copy owned+// by Multica. Done is emotion_193.+const (+ emotionAcknowledged = "收到"+ emotionDone = "Done"++ pathReplyEmotion = "/v1.0/robot/emotion/reply"+ pathRecallEmotion = "/v1.0/robot/emotion/recall"+)++// setEmojiReaction adds or recalls one default emoji reaction on a group or+// direct message. A 401 invalidates the installation token and retries once,+// matching message sends.+func (s *sender) setEmojiReaction(ctx context.Context, target sendTarget, name string, recall bool) error {+ if target.ConversationID == "" || target.SourceMessageID == "" {+ return errors.New("dingtalk: emoji reaction requires conversation id and message id")+ }+ if s.robotCode == "" {+ return errors.New("dingtalk: emoji reaction requires robot code")+ }+ if name != emotionAcknowledged && name != emotionDone {+ return fmt.Errorf("dingtalk: unsupported emoji reaction %q", name)+ }+ path := pathReplyEmotion+ if recall {+ path = pathRecallEmotion+ }+ body := map[string]any{+ "robotCode": s.robotCode,+ "openConversationId": target.ConversationID,+ "openMsgId": target.SourceMessageID,+ "emotionType": 1,+ "emotionName": name,+ }+ for attempt := 0; attempt < 2; attempt++ {+ token, err := s.client.accessToken(ctx, s.appKey, s.appSecret)+ if err != nil {+ return fmt.Errorf("access token: %w", err)+ }+ var resp struct {+ Success bool `json:"success"`+ }+ err = s.client.postJSON(ctx, path, token, body, &resp)+ if err == nil {+ if !resp.Success {+ return fmt.Errorf("dingtalk: %s returned success=false", path)+ }+ return nil+ }+ if errors.Is(err, errUnauthorized) && attempt == 0 {+ s.client.invalidate(s.appKey)+ continue+ }+ return err+ }+ return errUnauthorized+}diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.goindex af576432a9..772ae8bceb 100644--- a/server/internal/integrations/dingtalk/inbound.go+++ b/server/internal/integrations/dingtalk/inbound.go@@ -116,10 +116,18 @@ func (content *botCallbackRepliedContent) UnmarshalJSON(data []byte) error {}content.Text = ""_ = json.Unmarshal(wire.Text, &content.Text)- // Decode only the documented ordered-array shape. Unsupported quote- // variants remain unavailable; never infer a layout from a sibling summary.+ // Reply snapshots use text/content wrappers and msgType aliases that differ+ // from current-message nodes. Keep that decoding scoped to selected context.+ // The ordered array, never a sibling summary, remains the layout authority.content.RichText = nil- _ = json.Unmarshal(wire.RichText, &content.RichText)+ var nodes []json.RawMessage+ if json.Unmarshal(wire.RichText, &nodes) == nil {+ for _, node := range nodes {+ var item richTextItem+ _ = item.unmarshalJSON(node, true)+ content.RichText = append(content.RichText, item)+ }+ }content.DownloadCode = wire.DownloadCodecontent.PictureDownloadCode = wire.PictureDownloadCodecontent.FileName = wire.FileName@@ -155,8 +163,14 @@ type richTextItem struct {// Unknown nested values are not recursively interpreted as prose or commands.// A bad node degrades locally so valid neighboring text and pictures survive.func (item *richTextItem) UnmarshalJSON(data []byte) error {+ return item.unmarshalJSON(data, false)+}++func (item *richTextItem) unmarshalJSON(data []byte, quoted bool) error {type wireItem struct {Text json.RawMessage `json:"text"`+ Content json.RawMessage `json:"content"`+ MsgType json.RawMessage `json:"msgType"`Type string `json:"type"`DownloadCode string `json:"downloadCode"`PictureDownloadCode string `json:"pictureDownloadCode"`@@ -167,6 +181,12 @@ func (item *richTextItem) UnmarshalJSON(data []byte) error {item.Text = "[rich-text content unavailable]"return nil}+ if quoted && wire.Type == "" && len(wire.MsgType) > 0 {+ if json.Unmarshal(wire.MsgType, &wire.Type) != nil {+ item.Text = "[rich-text content unavailable]"+ return nil+ }+ }if wire.Type != "" && wire.Type != "text" && wire.Type != "picture" {item.Text = "[rich-text content unavailable]"return nil@@ -174,6 +194,12 @@ func (item *richTextItem) UnmarshalJSON(data []byte) error {item.Type = wire.Typeitem.DownloadCode = wire.DownloadCodeitem.PictureDownloadCode = wire.PictureDownloadCode+ if quoted && (item.Type == "" || item.Type == "text") {+ if (len(wire.Text) == 0 || string(wire.Text) == "null") && item.Type == "text" {+ wire.Text = wire.Content+ }+ wire.Text = dingTalkQuotedRichTextScalar(wire.Text)+ }if len(wire.Text) > 0 && string(wire.Text) != "null" {if err := json.Unmarshal(wire.Text, &item.Text); err != nil {item.Text = "[rich-text content unavailable]"@@ -184,6 +210,21 @@ func (item *richTextItem) UnmarshalJSON(data []byte) error {return nil}+// Selected text may have one structural text/content wrapper. Read only its+// scalar value: do not traverse arbitrary data, arrays, or JSON inside prose.+// In particular, these quote-only aliases cannot become current commands.+func dingTalkQuotedRichTextScalar(raw json.RawMessage) json.RawMessage {+ var wrapper map[string]json.RawMessage+ if json.Unmarshal(raw, &wrapper) == nil && wrapper != nil {+ for _, key := range []string{"text", "content"} {+ if value, ok := wrapper[key]; ok {+ return value+ }+ }+ }+ return raw+}+// refAlt orders a picture item's two download codes into (primary, fallback),// promoting the secondary code when the primary is missing.func refAlt(downloadCode, pictureDownloadCode string) (ref, alt string) {@@ -197,9 +238,13 @@ func refAlt(downloadCode, pictureDownloadCode string) (ref, alt string) {// envelope does not. AppID is stamped by the receiving connection (it is the// installation's routing key) and read back only inside the resolvers.type dingtalkRawEvent struct {- AppID string `json:"app_id"`- ConversationTitle string `json:"conversation_title,omitempty"`- Media []dingtalkMediaResource `json:"media,omitempty"`+ AppID string `json:"app_id"`+ ConversationTitle string `json:"conversation_title,omitempty"`+ // CurrentText is the normalized current turn before quoted-message context+ // is prepended. It preserves adapter-generated media placeholders in their+ // original order for platform-visible reply rendering.+ CurrentText string `json:"current_text,omitempty"`+ Media []dingtalkMediaResource `json:"media,omitempty"`}type dingtalkMediaResource struct {@@ -269,6 +314,7 @@ func inboundFromCallbackWithBotName(data *botCallbackData, appID, botName stringmsg.Type = channel.MsgTypeTextmsg.Text = strings.TrimSpace(normalizeDingTalkBotMention(data, data.Text.Content, botName))msg.CommandText = msg.Text+ rawEvent.CurrentText = dingtalkCurrentVisibleText(msg)applyDingTalkReplyContext(data, &msg, &rawEvent)return withDingTalkRaw(msg, rawEvent), true@@ -288,6 +334,7 @@ func inboundFromCallbackWithBotName(data *botCallbackData, appID, botName stringmsg.Text = dingtalkImagePlaceholdermsg.CommandText = msg.TextrawEvent.Media = []dingtalkMediaResource{dingtalkMediaResourceAt(ref, alt, 0)}+ rawEvent.CurrentText = dingtalkCurrentVisibleText(msg)applyDingTalkReplyContext(data, &msg, &rawEvent)return withDingTalkRaw(msg, rawEvent), true@@ -331,6 +378,10 @@ func inboundFromCallbackWithBotName(data *botCallbackData, appID, botName string}msg.Text = strings.TrimSpace(text.String())msg.CommandText = strings.TrimSpace(commandText.String())+ // Freeze what the sender actually posted before the adapter consumes a+ // /clear or /new directive for engine routing. Outbound command notices+ // quote this immutable display snapshot, not Router-mutated Text fields.+ rawEvent.CurrentText = msg.TextnormalizeDingTalkRichTextControlLayout(&msg, rc.RichText, len(rawEvent.Media) > 0)applyDingTalkReplyContext(data, &msg, &rawEvent)return withDingTalkRaw(msg, rawEvent), true@@ -349,10 +400,19 @@ func inboundFromCallbackWithBotName(data *botCallbackData, appID, botName stringmsg.Text = "[Unsupported DingTalk message]"}msg.CommandText = msg.Text+ rawEvent.CurrentText = dingtalkCurrentVisibleText(msg)applyDingTalkReplyContext(data, &msg, &rawEvent)return withDingTalkRaw(msg, rawEvent), true}+// dingtalkCurrentVisibleText freezes the current user-visible turn without+// quoted history. It runs after the bot-addressing mention is removed but+// before Router consumes control directives, so command confirmations can+// quote exactly what the sender posted.+func dingtalkCurrentVisibleText(msg channel.InboundMessage) string {+ return strings.TrimSpace(msg.Text)+}+func applyDingTalkReplyContext(data *botCallbackData, msg *channel.InboundMessage, rawEvent *dingtalkRawEvent) {if data == nil || msg == nil || rawEvent == nil {return@@ -740,6 +800,7 @@ func mediaUnreadableMsg(data *botCallbackData, msg channel.InboundMessage, rawEvmsg.Text = "[rich-text content unavailable]"}msg.CommandText = msg.Text+ rawEvent.CurrentText = msg.TextapplyDingTalkReplyContext(data, &msg, &rawEvent)return withDingTalkRaw(msg, rawEvent)}diff --git a/server/internal/integrations/dingtalk/inbound_boundary_test.go b/server/internal/integrations/dingtalk/inbound_boundary_test.goindex a9d97700cf..2fb02a120e 100644--- a/server/internal/integrations/dingtalk/inbound_boundary_test.go+++ b/server/internal/integrations/dingtalk/inbound_boundary_test.go@@ -47,12 +47,12 @@ func TestBotCallbackRepliedContentDoesNotRenderSummaryWhenRichTextMalformed(t *tfunc TestDingTalkReplyOptionalContextBoundaries(t *testing.T) {msg := channel.InboundMessage{Text: "current", CommandText: "current"}- raw := dingtalkRawEvent{}+ raw := dingtalkRawEvent{CurrentText: "current"}data := &botCallbackData{}applyDingTalkReplyContext(nil, &msg, &raw)applyDingTalkReplyContext(data, nil, &raw)applyDingTalkReplyContext(data, &msg, nil)- if msg.Text != "current" || msg.ReplyTo != nil {+ if msg.Text != "current" || msg.ReplyTo != nil || raw.CurrentText != "current" {t.Fatalf("missing context mutated current turn: %+v / %+v", msg, raw)}data.Text.IsReplyMsg = truediff --git a/server/internal/integrations/dingtalk/inbound_contract_test.go b/server/internal/integrations/dingtalk/inbound_contract_test.goindex 775aae9064..6cb8886b77 100644--- a/server/internal/integrations/dingtalk/inbound_contract_test.go+++ b/server/internal/integrations/dingtalk/inbound_contract_test.go@@ -8,8 +8,8 @@ import (// Synthetic boundary fixtures, not captured callbacks. The supported node// schema comes from https://open.dingtalk.com/document/orgapp/receive-message.-// Its public contract does not describe repliedMsg, structured text aliases,-// encoded richText arrays, or template-independent cardContent rendering.+// Current-message nodes follow that schema. Reply snapshots additionally use+// scoped aliases; encoded arrays and card templates stay unsupported.func TestInboundRichTextContractKeepsSupportedNeighbors(t *testing.T) {for _, node := range []string{`{"text":{"content":"/clear hidden"}}`,diff --git a/server/internal/integrations/dingtalk/inbound_matrix_test.go b/server/internal/integrations/dingtalk/inbound_matrix_test.goindex 136afdc869..9567002bc7 100644--- a/server/internal/integrations/dingtalk/inbound_matrix_test.go+++ b/server/internal/integrations/dingtalk/inbound_matrix_test.go@@ -254,6 +254,9 @@ func assertDingTalkMatrixMessage(if err != nil {t.Fatalf("decode raw matrix event: %v", err)}+ if raw.CurrentText != current.body {+ t.Fatalf("current visible text = %q, want %q", raw.CurrentText, current.body)+ }if len(raw.Media) != len(wantRefs) {t.Fatalf("media count = %d, want %d: %+v", len(raw.Media), len(wantRefs), raw.Media)}@@ -270,6 +273,11 @@ func assertDingTalkMatrixMessage(t.Fatalf("message type = %q, want %q", msg.Type, wantType)}+ _, routingJSON := dingtalkSessionRouting(msg)+ if strings.Contains(string(routingJSON), "quote_text") || strings.Contains(string(routingJSON), "source_message_id") || strings.Contains(string(routingJSON), "session_webhook") {+ t.Fatalf("routing retained per-message state: %s", routingJSON)+ }+}func TestInboundFromCallback_MessageShapeMatrix(t *testing.T) {diff --git a/server/internal/integrations/dingtalk/inbound_optional_metadata_test.go b/server/internal/integrations/dingtalk/inbound_optional_metadata_test.gonew file mode 100644index 0000000000..d4cc16c3d8--- /dev/null+++ b/server/internal/integrations/dingtalk/inbound_optional_metadata_test.go@@ -0,0 +1,31 @@+package dingtalk++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestDingTalkCallbackIgnoresUnusedWebhookMetadata(t *testing.T) {+ for _, metadata := range []string{+ `"sessionWebhook":"unused bearer","sessionWebhookExpiredTime":"unknown"`,+ `"sessionWebhook":{"unsupported":"shape"},"sessionWebhookExpiredTime":{}`,+ `"sessionWebhook":"unused bearer","sessionWebhookExpiredTime":2000000000000`,+ `"sessionWebhook":null,"sessionWebhookExpiredTime":null`,+ } {+ t.Run(metadata, func(t *testing.T) {+ wire := `{"msgId":"source","senderStaffId":"sender","conversationId":"group","conversationType":"2","isInAtList":true,"msgtype":"text","text":{"content":"/issue current question"},` + metadata + `}`+ var callback botCallbackData+ if err := json.Unmarshal([]byte(wire), &callback); err != nil {+ t.Fatalf("unused reply capability rejected the current input: %v", err)+ }+ msg, ok := inboundFromCallback(&callback, "app")+ if !ok || msg.Text != "/issue current question" || msg.CommandText != msg.Text || msg.MessageID != "source" {+ t.Fatalf("unused reply capability changed the input: %+v", msg)+ }+ if strings.Contains(string(msg.Raw), "webhook") || strings.Contains(string(msg.Raw), "unused bearer") {+ t.Fatal("unused reply capability survived into the normalized input")+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/inbound_quote_aliases_test.go b/server/internal/integrations/dingtalk/inbound_quote_aliases_test.gonew file mode 100644index 0000000000..9284641127--- /dev/null+++ b/server/internal/integrations/dingtalk/inbound_quote_aliases_test.go@@ -0,0 +1,95 @@+package dingtalk++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestQuotedRichTextWrappersPreserveTextAroundPictures(t *testing.T) {+ for _, node := range []string{+ `{"text":{"text":"111"}}`,+ `{"text":{"content":"111"}}`,+ `{"msgType":"text","content":"111"}`,+ `{"msgType":"text","content":{"text":"111"}}`,+ `{"type":"text","content":{"content":"111"}}`,+ } {+ t.Run(node, func(t *testing.T) {+ wire := `{"senderStaffId":"sender","conversationId":"group","conversationType":"2","isInAtList":true,"msgId":"current","msgtype":"richText","content":{"richText":[{"text":"222"},{"type":"picture","downloadCode":"current-image"},{"text":"333"}],"repliedMsg":{"msgType":"richText","msgId":"selected","content":{"richText":[` + node + `,{"msgType":"picture","downloadCode":"quoted-image"},{"msgType":"text","content":{"text":"/clear historical question"}}]}}}}`+ var cb botCallbackData+ if err := json.Unmarshal([]byte(wire), &cb); err != nil {+ t.Fatal(err)+ }+ msg, ok := inboundFromCallback(&cb, "app")+ const want = "> 111\n> [Image]\n> /clear historical question\n\n222\n[Image]\n333"+ if !ok || msg.Text != want || msg.CommandText != "222333" || msg.ForceFresh {+ t.Fatalf("quoted rich text lost text/order or executed a historical command: %+v, want %q", msg, want)+ }+ raw, err := decodeDingTalkRaw(msg)+ if err != nil || len(raw.Media) != 2 || raw.Media[0].Ref != "quoted-image" || raw.Media[0].InlineIndex != 0 || raw.Media[1].Ref != "current-image" || raw.Media[1].InlineIndex != 1 {+ t.Fatalf("quoted/current image positions changed: %+v, %v", raw, err)+ }+ })+ }+}++func TestQuotedRichTextWrappersDoNotDecodeArbitraryEnvelopes(t *testing.T) {+ for _, node := range []string{+ `{"msgType":"text","content":{"data":{"text":"hidden"}}}`,+ `{"msgType":"text","content":{"text":{"text":"hidden"}}}`,+ `{"msgType":42,"content":"hidden"}`,+ `{"msgType":"audio","content":"hidden"}`,+ `{"msgType":"text","content":["hidden"]}`,+ } {+ t.Run(node, func(t *testing.T) {+ var content botCallbackRepliedContent+ if err := json.Unmarshal([]byte(`{"richText":[`+node+`,{"text":"valid neighbor"}]}`), &content); err != nil {+ t.Fatal(err)+ }+ body, _ := renderDingTalkQuotedMessage(&botCallbackRepliedMessage{MsgType: "richText", Content: content})+ if strings.Contains(body, "hidden") || !strings.Contains(body, "[rich-text content unavailable]") || !strings.Contains(body, "valid neighbor") {+ t.Fatalf("unsupported wrapper changed valid neighbors: %q", body)+ }+ })+ }+}++func TestInboundQuotedRichTextNodeTextBoundaries(t *testing.T) {+ for _, tc := range []struct{ node, want string }{+ {`{"text":{"content":"/clear historical"}}`, "/clear historical"},+ {`{"text":{"text":"/new historical"}}`, "/new historical"},+ {`{"type":"text","content":"/issue historical"}`, "/issue historical"},+ {`{"msgType":"text","content":{"text":"selected [Image]"}}`, "selected [Image]"},+ {`{"msgType":"text","content":{"content":"selected text"}}`, "selected text"},+ {`{"msgType":"text","content":"{\"text\":\"/clear literal JSON\"}"}`, `{"text":"/clear literal JSON"}`},+ {`{"msgType":"text","text":"primary","content":"secondary"}`, "primary"},+ {`{"msgType":"text","text":"","content":"not selected"}`, ""},+ {`{"msgType":"audio","downloadCode":"not-an-image","content":"hidden"}`, "[rich-text content unavailable]"},+ {`{"msgType":42,"text":"hidden"}`, "[rich-text content unavailable]"},+ {`{"msgType":"text","content":{"data":{"text":"hidden"}}}`, "[rich-text content unavailable]"},+ {`{"msgType":"text","content":{"text":{"content":"hidden"}}}`, "[rich-text content unavailable]"},+ {`{"msgType":"text","content":[{"text":"hidden"}]}`, "[rich-text content unavailable]"},+ {`{"msgType":"text","content":42}`, "[rich-text content unavailable]"},+ {`{"data":{"text":"hidden"}}`, "[rich-text content unavailable]"},+ } {+ t.Run(tc.node, func(t *testing.T) {+ var cb botCallbackData+ wire := `{"senderStaffId":"sender","conversationType":"1","msgtype":"text","text":{"content":"explain","repliedMsg":{"msgId":"selected","msgType":"richText","content":{"richText":[` + tc.node + `,{"msgType":"picture","downloadCode":"quoted-image"},{"text":"caption"}]}}}}`+ if err := json.Unmarshal([]byte(wire), &cb); err != nil {+ t.Fatal(err)+ }+ msg, ok := inboundFromCallback(&cb, "app")+ want := "> [Image]\n> caption\n\nexplain"+ if tc.want != "" {+ want = "> " + tc.want + "\n" + want+ }+ if !ok || msg.Text != want || msg.CommandText != "explain" || msg.ForceFresh || !msg.HasSelectedContext || msg.ReplyTo == nil || msg.ReplyTo.MessageID != "selected" {+ t.Fatalf("selected text changed content or command meaning: %+v; want body=%q", msg, want)+ }+ raw, err := decodeDingTalkRaw(msg)+ if err != nil || len(raw.Media) != 1 || raw.Media[0].Ref != "quoted-image" || raw.Media[0].InlineIndex != strings.Count(tc.want, "[Image]") || raw.CurrentText != "explain" {+ t.Fatalf("selected text changed media position or current preview: %+v; err=%v", raw, err)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.goindex bc6bb29692..9f8c5da0a2 100644--- a/server/internal/integrations/dingtalk/inbound_test.go+++ b/server/internal/integrations/dingtalk/inbound_test.go@@ -32,7 +32,7 @@ func TestInboundFromCallback_P2PAddressedAndTrimmed(t *testing.T) {t.Errorf("text/command = %q/%q", msg.Text, msg.CommandText)}raw, err := decodeDingTalkRaw(msg)- if err != nil || raw.AppID != "appkey-A" {+ if err != nil || raw.AppID != "appkey-A" || strings.Contains(string(msg.Raw), "session_webhook") {t.Fatalf("raw routing context = %+v, err=%v", raw, err)}}@@ -72,6 +72,44 @@ func TestInboundFromCallback_BareFreshStaysForSharedPendingPath(t *testing.T) {}}+func TestInboundFromCallback_CommandQuoteSnapshotSurvivesRouterRewrites(t *testing.T) {+ tests := []struct {+ name string+ command string+ rewrite func(*channel.InboundMessage)+ }{+ {name: "issue", command: "/issue calculate 0.1 + 0.2"},+ {name: "clear", command: "/clear", rewrite: func(msg *channel.InboundMessage) {+ msg.Text = ""+ msg.ForceFresh = true+ }},+ {name: "new", command: "/new", rewrite: func(msg *channel.InboundMessage) {+ msg.Text = ""+ msg.CommandText = ""+ }},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ cb := textCallback(convTypeGroup, true)+ cb.Text.Content = tt.command+ msg, ok := inboundFromCallback(cb, "appkey-A")+ if !ok {+ t.Fatal("expected command message")+ }+ raw, err := decodeDingTalkRaw(msg)+ if err != nil || raw.CurrentText != tt.command {+ t.Fatalf("raw current text = %q, want %q, err=%v", raw.CurrentText, tt.command, err)+ }+ if tt.rewrite != nil {+ tt.rewrite(&msg)+ }+ if got := dingtalkVisibleQuoteText(msg); got != tt.command {+ t.Fatalf("visible quote after Router rewrite = %q, want %q", got, tt.command)+ }+ })+ }+}+func TestInboundFromCallback_DoesNotPrivatelyComposeFreshAndIssue(t *testing.T) {cb := textCallback(convTypeP2P, false)cb.Text.Content = "/clear /issue calculate 1+2"@@ -474,7 +512,7 @@ func TestInboundFromCallback_QuotedRichTextDoesNotInferSummaryLayout(t *testing.}}-func TestInboundFromCallback_QuotedRichTextDegradesStructuredTextNodes(t *testing.T) {+func TestInboundFromCallback_QuotedRichTextPreservesStructuredTextNodes(t *testing.T) {var cb botCallbackDataerr := json.Unmarshal([]byte(`{"msgId":"current-message",@@ -510,7 +548,7 @@ func TestInboundFromCallback_QuotedRichTextDegradesStructuredTextNodes(t *testinif !ok || msg.CommandText != "Current text" || msg.Type != channel.MsgTypeImage {t.Fatalf("structured RichText message = %+v, ok=%v", msg, ok)}- want := "> **Alice:**\n>\n> [rich-text content unavailable]\n> [Image]\n\nCurrent text\n[Image]"+ want := "> **Alice:**\n>\n> Quoted text\n> [Image]\n\nCurrent text\n[Image]"if msg.Text != want {t.Fatalf("structured RichText body = %q, want %q", msg.Text, want)}@@ -524,7 +562,7 @@ func TestInboundFromCallback_QuotedRichTextDegradesStructuredTextNodes(t *testin}}-func TestInboundFromCallback_QuotedRichTextDegradesUnknownNodeNames(t *testing.T) {+func TestInboundFromCallback_QuotedRichTextPreservesReplySnapshotNodes(t *testing.T) {var cb botCallbackDataerr := json.Unmarshal([]byte(`{"msgId":"current-message",@@ -535,19 +573,19 @@ func TestInboundFromCallback_QuotedRichTextDegradesUnknownNodeNames(t *testing.T"senderStaffId":"staff-9","content":{"richText":[- {"text":"Current text"},- {"type":"picture","downloadCode":"current-picture"}+ {"text":"222\n"},+ {"type":"picture","downloadCode":"current-picture"},+ {"text":"\n333 @YYClaw"}],"isReplyMsg":true,"repliedMsg":{"msgType":"richText","msgId":"quoted-rich",- "senderNick":"Alice","content":{"richText":[- {"msgType":"text","content":"Quoted heading"},+ {"msgType":"text","content":"111"},{"msgType":"picture","downloadCode":"quoted-picture"},- {"msgType":"text","content":"Quoted caption"}+ {"msgType":"text","content":"结合这两张图,你能联想到什么?"}]}}@@ -558,10 +596,10 @@ func TestInboundFromCallback_QuotedRichTextDegradesUnknownNodeNames(t *testing.T}msg, ok := inboundFromCallback(&cb, "appkey-A")- if !ok || msg.CommandText != "Current text" || msg.Type != channel.MsgTypeImage {+ if !ok || msg.CommandText != "222\n\n333 @YYClaw" || msg.Type != channel.MsgTypeImage || msg.ForceFresh {t.Fatalf("reply snapshot message = %+v, ok=%v", msg, ok)}- want := "> **Alice:**\n>\n> [rich-text content unavailable]\n> [Image]\n> [rich-text content unavailable]\n\nCurrent text\n[Image]"+ want := "> 111\n> [Image]\n> 结合这两张图,你能联想到什么?\n\n222\n\n[Image]\n\n333 @YYClaw"if msg.Text != want {t.Fatalf("reply snapshot body = %q, want %q", msg.Text, want)}@@ -573,6 +611,9 @@ func TestInboundFromCallback_QuotedRichTextDegradesUnknownNodeNames(t *testing.Traw.Media[1].Ref != "current-picture" || raw.Media[1].InlineIndex != 1 {t.Fatalf("reply snapshot media order = %+v", raw.Media)}+ if raw.CurrentText != "222\n\n[Image]\n\n333 @YYClaw" {+ t.Fatalf("reply snapshot changed the current-message preview: %q", raw.CurrentText)+ }}func TestInboundFromCallback_RichTextPicturePrependsQuotedPictureMedia(t *testing.T) {@@ -955,9 +996,9 @@ func TestInboundFromCallback_NonTextReplyKindsKeepQuotedContext(t *testing.T) {if msg.Text != want || msg.CommandText != tt.currentText {t.Fatalf("message text/command = %q / %q, want %q / %q", msg.Text, msg.CommandText, want, tt.currentText)}- _, err := decodeDingTalkRaw(msg)- if err != nil {- t.Fatal(err)+ raw, err := decodeDingTalkRaw(msg)+ if err != nil || raw.CurrentText != tt.currentText {+ t.Fatalf("raw current text = %q, err=%v", raw.CurrentText, err)}})}@@ -997,7 +1038,7 @@ func TestInboundFromCallback_UnreadableCurrentMediaKeepsQuotedContext(t *testingt.Fatalf("unreadable quoted reply text/command = %q / %q", msg.Text, msg.CommandText)}raw, err := decodeDingTalkRaw(msg)- if err != nil || len(raw.Media) != 0 {+ if err != nil || raw.CurrentText != fallback || len(raw.Media) != 0 {t.Fatalf("raw unreadable quoted reply = %+v, err=%v", raw, err)}})diff --git a/server/internal/integrations/dingtalk/markdown.go b/server/internal/integrations/dingtalk/markdown.goindex 67dc35d7f6..2d6a0387a3 100644--- a/server/internal/integrations/dingtalk/markdown.go+++ b/server/internal/integrations/dingtalk/markdown.go@@ -1,20 +1,24 @@package dingtalkimport (+ "regexp""strings"+ "unicode""unicode/utf8")-// DingTalk's robot send APIs (oToMessages.batchSend / groupMessages.send) hard--// reject a sampleMarkdown body over ~20000 bytes and drop the whole message, so-// we chunk well under that. The budget is measured in UTF-8 BYTES, not runes,-// because the limit is on the encoded payload. A code fence open at a chunk-// boundary is closed at the end of the chunk and reopened at the start of the-// next, so neither half renders as broken markdown.+// DingTalk documents a 15000-byte msgParam limit for groupMessages.send:+// https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message+// The send path measures serialized title + text, including JSON escapes.+// Use the same conservative budget for private messages.const (// markdownByteBudget bounds one chunk's body in UTF-8 bytes.- markdownByteBudget = 16000+ markdownByteBudget = 14000+ markdownPayloadByteBudget = 15000+ // Only the source-user preview displayed above a Bot reply is truncated.+ // This is a presentation policy, not a provider title limit.+ quotePreviewByteBudget = 256// A split inside a code block appends "\n```" to make the emitted chunk// self-contained. Keep this space out of the content budget so the final// wire body, not just the pre-rendered slice, stays under the hard limit.@@ -24,9 +28,7 @@ const (// prefix so an adversarially long info string cannot consume the entire// piece budget (or make it negative) when the next code line is split.maxMarkdownFenceInfoBytes = 256- // defaultMarkdownTitle is the chat-list notification preview used when the- // body carries no leading heading. DingTalk shows the title only in the push- // preview, not in the message body.+ // defaultMarkdownTitle is the preview for answers without a leading heading.defaultMarkdownTitle = "Multica has replied.")@@ -49,13 +51,92 @@ func markdownTitle(body string) string {return defaultMarkdownTitle}+// quotePreview is only the source-user excerpt displayed in an outbound reply.+// It never bounds the answer title or the inbound selected context.+func quotePreview(body string) string {+ body = strings.TrimSpace(strings.ReplaceAll(body, "\r\n", "\n"))+ if body == "" {+ return ""+ }+ return boundedPreview(body)+}++func boundedPreview(body string) string {+ const suffix = "\n..."+ if len(body) <= quotePreviewByteBudget {+ return body+ }+ limit := quotePreviewByteBudget - len(suffix)+ for !utf8.RuneStart(body[limit]) {+ limit--+ }+ // A partial web address can link to a different resource. Omit a URL that+ // straddles the preview boundary rather than publishing a truncated target.+ for _, span := range webURLSpans(body) {+ if span[0] < limit && span[1] > limit {+ limit = span[0]+ break+ }+ }+ prefix := strings.TrimRight(body[:limit], " \t\r\n")+ if prefix == "" {+ return "..."+ }+ return prefix + suffix+}++// These are source spans, not parsed/re-serialized URLs. Preserve the original+// spelling, encoding, query and fragment when DingTalk auto-links quote text.+var webURLStart = regexp.MustCompile(`(?i)(?:https?://|www\.)`)++func webURLSpans(body string) [][]int {+ var spans [][]int+ for start := 0; start < len(body); {+ span := webURLStart.FindStringIndex(body[start:])+ if span == nil {+ break+ }+ span[0] += start+ contentStart := start + span[1]+ span[1] = len(body)+ var closing []rune+ urlToken:+ for offset, r := range body[contentStart:] {+ if unicode.IsSpace(r) || unicode.IsControl(r) || strings.ContainsRune("<>\"\\`", r) {+ span[1] = contentStart + offset+ break+ }+ switch r {+ case '(':+ closing = append(closing, ')')+ case '[':+ closing = append(closing, ']')+ case ')', ']':+ if len(closing) == 0 || closing[len(closing)-1] != r {+ span[1] = contentStart + offset+ break urlToken+ }+ closing = closing[:len(closing)-1]+ }+ }+ spans = append(spans, span)+ start = span[1]+ }+ return spans+}+// chunkMarkdown splits body into pieces each at most markdownByteBudget bytes,// preferring line boundaries. A code fence (```) left open at a boundary is// closed at the end of the chunk and reopened at the start of the next so each// chunk is self-contained markdown. A single line longer than the budget is// hard-split on a byte boundary that respects UTF-8 rune edges.func chunkMarkdown(body string) []string {- if len(body) <= markdownByteBudget {+ return chunkMarkdownWithBudget(body, markdownByteBudget)+}++func chunkMarkdownWithBudget(body string, byteBudget int) []string {+ contentByteBudget := byteBudget - markdownSyntheticFenceCloseBytes+ if len(body) <= byteBudget {return []string{body}}@@ -91,11 +172,19 @@ func chunkMarkdown(body string) []string {for _, line := range splitKeepNewline(body) {// A single oversized line cannot fit a chunk; hard-split it.- if len(line) > markdownContentByteBudget {+ if len(line) > contentByteBudget {flush(true)- pieceBudget := markdownContentByteBudget+ pieceBudget := contentByteBudget+ quotePrefix := ""if fenceOpen {- pieceBudget = markdownByteBudget - len(fenceInfo) - len("\n") - len("\n```")+ pieceBudget = byteBudget - len(fenceInfo) - len("\n") - len("\n```")+ } else if strings.HasPrefix(line, "> ") {+ // Each wire message must retain the source attribution of a long+ // quoted line. A prefix on only the first piece makes later pieces+ // appear to be the robot's own answer.+ quotePrefix = "> "+ line = strings.TrimPrefix(line, quotePrefix)+ pieceBudget -= len(quotePrefix)}for _, piece := range hardSplit(line, pieceBudget) {// A piece split out of an oversized line inside a code block must@@ -103,11 +192,12 @@ func chunkMarkdown(body string) []string {if fenceOpen {piece = fenceInfo + "\n" + piece + "\n```"}+ piece = quotePrefix + piecechunks = append(chunks, piece)}continue}- if cur.Len()+len(line) > markdownContentByteBudget {+ if cur.Len()+len(line) > contentByteBudget {flush(true)}if isFenceLine(line) {diff --git a/server/internal/integrations/dingtalk/markdown_test.go b/server/internal/integrations/dingtalk/markdown_test.goindex 2030781446..2323d77185 100644--- a/server/internal/integrations/dingtalk/markdown_test.go+++ b/server/internal/integrations/dingtalk/markdown_test.go@@ -6,17 +6,31 @@ import ("unicode/utf8")-func TestMarkdownTitle(t *testing.T) {- cases := map[string]string{- "# Heading one\nbody": "Heading one",- "\n\n## Second\nmore": "Second",- "no heading here": defaultMarkdownTitle,- "plain line\n# late": defaultMarkdownTitle, // first non-empty line is not a heading- "### spaced \nbody": "spaced",+// Title is selected context on a later DingTalk native quote. It must retain+// source syntax and destinations, including bytes beyond the display preview.++func TestQuotePreview_ByteBudget(t *testing.T) {+ for _, unit := range []string{"x", "界", "🚀"} {+ for _, length := range []int{63, 64, 65, 252, 253, 256, 257, 512, 16001} {+ body := strings.Repeat(unit, length)+ want := body+ if len(body) > 256 {+ want = strings.Repeat(unit, 252/len(unit)) + "\n..."+ }+ if got := quotePreview(body); got != want || !utf8.ValidString(got) {+ t.Errorf("preview for %d runes = %q, want %q", length, got, want)+ }+ }}- for body, want := range cases {- if got := markdownTitle(body); got != want {- t.Errorf("markdownTitle(%q) = %q, want %q", body, got, want)+ // A byte cutoff can land inside a rune when the text mixes ASCII and+ // multibyte characters; repeating a single rune alone misses this boundary.+ for _, prefix := range []string{"a", "ab", "abc"} {+ for _, unit := range []string{"界", "🚀"} {+ body := prefix + strings.Repeat(unit, 300)+ want := prefix + strings.Repeat(unit, (252-len(prefix))/len(unit)) + "\n..."+ if got := quotePreview(body); got != want || len(got) > 256 || !utf8.ValidString(got) {+ t.Errorf("mixed preview for %q + %q = %q, want %q", prefix, unit, got, want)+ }}}}@@ -125,7 +139,7 @@ func TestChunkMarkdown_LongFenceInfoCannotExhaustPieceBudget(t *testing.T) {// following code line through hardSplit. Before the continuation fence was// bounded, this made pieceBudget negative and panicked.fence := "```" + strings.Repeat("x", markdownContentByteBudget-5)- body := fence + "\n" + strings.Repeat("界", markdownByteBudget) + "\n```\n"+ body := fence + "\n" + strings.Repeat("\u754c", markdownByteBudget) + "\n```\n"chunks := chunkMarkdown(body)if len(chunks) < 2 {t.Fatalf("pathological fenced body must split, got %d chunks", len(chunks))@@ -142,8 +156,8 @@ func TestChunkMarkdown_LongFenceInfoCannotExhaustPieceBudget(t *testing.T) {func TestHardSplitDefendsAgainstInvalidBudget(t *testing.T) {for _, budget := range []int{-1, 0, 1} {- pieces := hardSplit("界界", budget)- if got := strings.Join(pieces, ""); got != "界界" {+ pieces := hardSplit("\u754c\u754c", budget)+ if got := strings.Join(pieces, ""); got != "\u754c\u754c" {t.Fatalf("hardSplit budget %d rejoined to %q", budget, got)}for _, piece := range pieces {@@ -153,3 +167,38 @@ func TestHardSplitDefendsAgainstInvalidBudget(t *testing.T) {}}}++func TestQuotePreviewPreservesLiteralParagraphsAndByteBudget(t *testing.T) {+ for _, tc := range []struct{ body, want string }{+ {"", ""}, {" \n\t", ""},+ {"**literal** [link](url)\nsecond line\n\nLater paragraph", "**literal** [link](url)\nsecond line\n\nLater paragraph"},+ {"First\r\n \t\r\nLater", "First\n \t\nLater"},+ {strings.Repeat("界", 86), strings.Repeat("界", 84) + "\n..."},+ {strings.Repeat("x", 256), strings.Repeat("x", 256)},+ {strings.Repeat("x", 256) + "\n\nLater", strings.Repeat("x", 252) + "\n..."},+ {"Already shortened\n...", "Already shortened\n..."},+ } {+ got := quotePreview(tc.body)+ if got != tc.want || len(got) > 256 || !utf8.ValidString(got) {+ t.Fatalf("quote preview=%q, want=%q", got, tc.want)+ }+ if quotePreview(got) != got {+ t.Fatal("rendering an already stored preview changed it")+ }+ }+}++func TestMarkdownTitle(t *testing.T) {+ cases := map[string]string{+ "# Heading one\nbody": "Heading one",+ "\n\n## Second\nmore": "Second",+ "no heading here": defaultMarkdownTitle,+ "plain line\n# late": defaultMarkdownTitle, // first non-empty line is not a heading+ "### spaced \nbody": "spaced",+ }+ for body, want := range cases {+ if got := markdownTitle(body); got != want {+ t.Errorf("markdownTitle(%q) = %q, want %q", body, got, want)+ }+ }+}diff --git a/server/internal/integrations/dingtalk/outbound.go b/server/internal/integrations/dingtalk/outbound.goindex e12c79bac1..140279db08 100644--- a/server/internal/integrations/dingtalk/outbound.go+++ b/server/internal/integrations/dingtalk/outbound.go@@ -2,6 +2,7 @@ package dingtalkimport ("context"+ "encoding/json""errors""fmt""log/slog"@@ -12,6 +13,7 @@ import ("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")@@ -19,6 +21,7 @@ import (// outboundQueries is the slice of generated queries the DingTalk outbound// subscriber needs. *db.Queries satisfies it.type outboundQueries interface {+ ListChatInputMessages(context.Context, pgtype.UUID) ([]db.ChatMessage, error)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)@@ -36,27 +39,55 @@ type Outbound struct {q outboundQueriesdecrypt Decrypterclient *Client+ ack *ackNotifierlogger *slog.Logger}-// NewOutbound builds the DingTalk outbound subscriber over the generated queries,-// the AppSecret decrypter, and the shared token-caching Client.-func NewOutbound(q outboundQueries, decrypt Decrypter, client *Client, logger *slog.Logger) *Outbound {+// NewOutbound builds the DingTalk outbound subscriber over the generated+// queries, the AppSecret decrypter, the shared token-caching Client, and the+// optional processing-reaction lifecycle owner.+func NewOutbound(q outboundQueries, decrypt Decrypter, client *Client, ack *ackNotifier, logger *slog.Logger) *Outbound {if logger == nil {logger = slog.Default()}if client == nil {client = NewClient(nil, "")}- return &Outbound{q: q, decrypt: decrypt, client: client, logger: logger}+ return &Outbound{q: q, decrypt: decrypt, client: client, ack: ack, logger: logger}}-// Register subscribes to chat-done and task-failed. Task-failed keeps the DingTalk-// conversation consistent with the web transcript — without it a failed run-// leaves the user staring at the "👀 On it" ack forever.+// Register subscribes to every chat-task terminal event. Task-cancelled carries+// no reply content, but still has to clear the source-message reaction.func (o *Outbound) Register(bus *events.Bus) {bus.Subscribe(protocol.EventChatDone, o.handleEvent)bus.Subscribe(protocol.EventTaskFailed, o.handleEvent)+ bus.Subscribe(protocol.EventTaskCancelled, o.handleEvent)+ bus.Subscribe(protocol.EventAgentArchived, o.handleAgentArchived)+}++func (o *Outbound) handleAgentArchived(e events.Event) {+ if o.ack == nil {+ return+ }+ raw, err := json.Marshal(e.Payload)+ if err != nil {+ return+ }+ var payload struct {+ Agent struct {+ ID string `json:"id"`+ } `json:"agent"`+ }+ if json.Unmarshal(raw, &payload) != nil {+ return+ }+ id, err := util.ParseUUID(payload.Agent.ID)+ if err != nil || !id.Valid {+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), ackCleanupTimeout)+ defer cancel()+ o.ack.onAgentArchived(ctx, id)}func (o *Outbound) handleEvent(e events.Event) {@@ -77,13 +108,31 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {return nil}content := eventContent(e)+ if content == "" && eventRetryPending(e) {+ return nil+ }+ var loadedTask *db.AgentTaskQueue+ var sealedInputs []db.ChatMessage+ var inputsLoaded bool+ var deliveredInput pgtype.UUID+ var deliveredInstallation engine.ResolvedInstallation+ if o.ack != nil {+ // Reactions are optional: do not spend the reply's network budget on+ // cleanup. Every terminal return attempts to settle its own input batch.+ defer func() {+ o.settleTaskReactions(ctx, taskID, sessionID, loadedTask, sealedInputs, inputsLoaded)+ if deliveredInput.Valid {+ o.ack.OnReplyDelivered(ctx, deliveredInstallation, deliveredInput)+ }+ }()+ }if content == "" {- return nil // nothing to say (empty completion, or a retry-pending failure)+ return nil}delivery, err := o.q.GetChannelTaskDelivery(ctx, taskID)if err != nil {if errors.Is(err, pgx.ErrNoRows) {- return nil // direct Multica task or violated snapshot invariant: fail closed+ return nil}return fmt.Errorf("lookup dingtalk task delivery: %w", err)}@@ -95,6 +144,7 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {if err != nil {return fmt.Errorf("load agent task: %w", err)}+ loadedTask = &taskdeliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, task)if err != nil {return fmt.Errorf("classify task input origin: %w", err)@@ -102,9 +152,26 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {if !deliver {return nil}++ var input db.ChatMessage+ if task.ChatInputTaskID.Valid {+ messages, err := o.q.ListChatInputMessages(ctx, task.ChatInputTaskID)+ if err != nil {+ o.logger.WarnContext(ctx, "dingtalk: sealed input unavailable; sending without attribution", "error", err)+ messages = nil+ }+ if err == nil {+ sealedInputs, inputsLoaded = messages, true+ }+ for i := len(messages) - 1; i >= 0; i-- {+ if messages[i].ChannelIngested {+ input = messages[i]+ break+ }+ }+ }inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{- ID: binding.InstallationID,- ChannelType: string(TypeDingTalk),+ ID: binding.InstallationID, ChannelType: string(TypeDingTalk),})if err != nil {return fmt.Errorf("load dingtalk installation: %w", err)@@ -117,12 +184,65 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {return fmt.Errorf("decode dingtalk credentials: %w", err)}s := &sender{client: o.client, robotCode: creds.RobotCode, appKey: creds.AppKey, appSecret: creds.AppSecret}- if _, err := s.send(ctx, outboundTarget(binding), content); err != nil {+ target := outboundTarget(binding)+ target.QuoteText = sealedInputQuote(input.Content)+ if _, err := s.send(ctx, target, content); err != nil {return fmt.Errorf("post dingtalk reply: %w", err)}+ // A failure notice is terminal, but it is not a successfully completed task.+ // Only chat:done earns the positive Done reaction.+ if o.ack != nil && e.Type == protocol.EventChatDone {+ deliveredInput = input.ID+ deliveredInstallation = engine.ResolvedInstallation{+ ID: inst.ID, WorkspaceID: inst.WorkspaceID, AgentID: inst.AgentID,+ InstallerUserID: inst.InstallerUserID, Active: true, Platform: inst,+ }+ }return nil}+// Task completion owns a sealed input batch, not every pending message in the+// conversation. This also runs for cancellation and empty terminal replies.+func (o *Outbound) settleTaskReactions(ctx context.Context, taskID, sessionID pgtype.UUID, task *db.AgentTaskQueue, inputs []db.ChatMessage, inputsLoaded bool) {+ if !o.ack.hasSession(sessionID) {+ return+ }+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), ackCleanupTimeout)+ defer cancel()+ if task == nil {+ loaded, err := o.q.GetAgentTask(cleanup, taskID)+ if err != nil {+ o.logger.WarnContext(cleanup, "dingtalk reaction: terminal task unavailable", "error", err)+ return+ }+ task = &loaded+ }+ if !task.ChatInputTaskID.Valid || (task.ChatSessionID.Valid && task.ChatSessionID != sessionID) {+ return+ }+ if !inputsLoaded {+ var err error+ inputs, err = o.q.ListChatInputMessages(cleanup, task.ChatInputTaskID)+ if err != nil {+ o.logger.WarnContext(cleanup, "dingtalk reaction: terminal input unavailable", "error", err)+ return+ }+ }+ o.ack.onInputsSettled(cleanup, sessionID, inputs)+}++func eventRetryPending(e events.Event) bool {+ if e.Type != protocol.EventTaskFailed {+ return false+ }+ p, ok := e.Payload.(map[string]any)+ if !ok {+ return false+ }+ retryPending, _ := p["retry_pending"].(bool)+ return retryPending+}+func bindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {return db.ChannelChatSessionBinding{ID: delivery.BindingID, InstallationID: delivery.InstallationID,diff --git a/server/internal/integrations/dingtalk/outbound_boundary_test.go b/server/internal/integrations/dingtalk/outbound_boundary_test.gonew file mode 100644index 0000000000..48fbaeda42--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_boundary_test.go@@ -0,0 +1,44 @@+package dingtalk++import (+ "context"+ "io"+ "net/http"+ "strings"+ "testing"+)++func TestSender_EmojiReactionCredentialAndTerminalFailures(t *testing.T) {+ for _, tc := range []struct {+ name string+ robot string+ tokenStatus, reactionStatus int+ wantToken, wantReaction int+ }{+ {"missing robot", "", 200, 200, 0, 0},+ {"token failure", "robot", 500, 200, 1, 0},+ {"retry exhausted", "robot", 200, 401, 2, 2},+ {"forbidden", "robot", 200, 403, 1, 1},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var tokenCalls, reactionCalls int+ client := NewClient(&http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ status, body := tc.reactionStatus, `{"success":true}`+ if r.URL.Path == accessTokenPath {+ tokenCalls+++ status = tc.tokenStatus+ body = `{"accessToken":"token","expireIn":7200}`+ } else {+ reactionCalls+++ }+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil+ })}, "https://dingtalk.test")+ s := newTestSender(client)+ s.robotCode = tc.robot+ err := s.setEmojiReaction(context.Background(), sendTarget{ConversationID: "cid", SourceMessageID: "source"}, emotionAcknowledged, false)+ if err == nil || tokenCalls != tc.wantToken || reactionCalls != tc.wantReaction {+ t.Fatalf("error=%v token=%d reaction=%d", err, tokenCalls, reactionCalls)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_db_test.go b/server/internal/integrations/dingtalk/outbound_db_test.gonew file mode 100644index 0000000000..9ffc070d4f--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_db_test.go@@ -0,0 +1,227 @@+package dingtalk++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "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"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/internal/util/secretbox"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestOutboundDB_SealedQuoteAndMemoryAnchor(t *testing.T) {+ for _, scenario := range []string{"after_seal", "merged", "cross_generation"} {+ for _, restart := range []bool{false, true} {+ name := scenario + "/warm"+ if restart {+ name = scenario + "/restart"+ }+ t.Run(name, func(t *testing.T) { testOutboundSealedInput(t, scenario, restart) })+ }+ }+}++func testOutboundSealedInput(t *testing.T, scenario string, restart bool) {+ pool := dingtalkInstallTestDB(t)+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ fx := dbfx.New(pool, "", "")+ suffix := util.UUIDToString(dbid.NewV7())+ fx.UserID = fx.User(t, "Sender", "dingtalk-sealed-"+suffix+"@multica.test")+ fx.WorkspaceID = fx.Workspace(t, "DingTalk sealed input", "dingtalk-sealed-"+suffix)+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")+ runtimeID := fx.Runtime(t, "Runtime")+ agentID := fx.Agent(t, "Agent", runtimeID)+ box, err := secretbox.New(bytes.Repeat([]byte{0xA7}, secretbox.KeySize))+ if err != nil {+ t.Fatal(err)+ }+ sealed, err := box.Seal([]byte("test-app-secret"))+ if err != nil {+ t.Fatal(err)+ }+ config, err := json.Marshal(installConfig{AppID: "delivery-" + suffix, RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString(sealed)})+ if err != nil {+ t.Fatal(err)+ }+ installationID := fx.Insert(t, "channel_installation", dbfx.Cols{"workspace_id": fx.WorkspaceID, "agent_id": agentID, "channel_type": "dingtalk", "config": string(config), "installer_user_id": fx.UserID, "status": "active"})+ fx.Cleanup(t, "DELETE FROM dingtalk_bot_identity WHERE installation_id = $1", installationID)+ fx.Cleanup(t, "DELETE FROM dingtalk_group_presence WHERE installation_id = $1", installationID)+ q := db.New(pool)+ httpServer := newDingtalkSendServer(t)+ client := NewClient(nil, httpServer.srv.URL)+ var done []string+ receipts := make(map[string]bool)+ newAck := func(c *Client) *ackNotifier {+ ack := NewAckNotifier(c, box.Open, nil, q)+ ack.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, name string, recall bool) error {+ if name == emotionDone && !recall {+ done = append(done, msg.MessageID)+ }+ if name == emotionAcknowledged {+ if recall {+ delete(receipts, msg.MessageID)+ } else {+ receipts[msg.MessageID] = true+ }+ }+ return nil+ }+ return ack+ }+ ack := newAck(client)+ set := NewDingTalkResolverSet(q, pool, nil, ack, nil, nil)+ cb := textCallback(convTypeGroup, true)+ cb.ConversationId = "group-" + suffix+ cb.MsgId = "first-message"+ cb.SenderStaffId = "first-sender"+ cb.Text.Content = "first question"+ cb.Text.IsReplyMsg = true+ cb.Text.RepliedMsg = &botCallbackRepliedMessage{MsgType: "text", MsgId: "historical-message", SenderNick: "Quoted author", Content: botCallbackRepliedContent{Text: "historical <tag> || context"}}+ first, ok := inboundFromCallback(cb, "delivery-"+suffix)+ if !ok {+ t.Fatal("first callback rejected")+ }+ inst, err := set.Installation.ResolveInstallation(ctx, first)+ if err != nil {+ t.Fatal(err)+ }+ userID := util.MustParseUUID(fx.UserID)+ sid, err := set.Session.EnsureSession(ctx, engine.EnsureSessionParams{Installation: inst, Sender: userID, Message: first})+ if err != nil {+ t.Fatal(err)+ }+ for _, table := range []string{"chat_session", "channel_chat_session_binding", "channel_chat_context_generation", "chat_message", "agent_task_queue"} {+ key := "chat_session_id"+ if table == "chat_session" {+ key = "id"+ }+ fx.Cleanup(t, "DELETE FROM "+table+" WHERE "+key+" = $1", sid)+ }+ fx.Cleanup(t, "DELETE FROM channel_task_delivery WHERE installation_id = $1", installationID)+ appended, err := set.Session.AppendMessage(ctx, engine.AppendParams{SessionID: sid, Sender: userID, InstallationID: inst.ID, Message: first})+ if err != nil {+ t.Fatal(err)+ }+ ack.OnIngested(ctx, inst, first, sid)+ const firstBody = "> **Quoted author:**\n>\n> [quoted content unavailable]\n\nfirst question"+ var persisted string+ if err := pool.QueryRow(ctx, "SELECT content FROM chat_message WHERE id = $1", appended.MessageID).Scan(&persisted); err != nil || persisted != firstBody {+ t.Fatalf("canonical input=%q error=%v", persisted, err)+ }+ session, err := q.GetChatSession(ctx, sid)+ if err != nil {+ t.Fatal(err)+ }+ tasks := service.NewTaskService(q, pool, nil, events.New())+ var task db.AgentTaskQueue+ enqueue := func() {+ task, err = tasks.EnqueueChannelChatTask(ctx, session, userID, false, appended.ContextRevision, appended.BindingID, appended.RouteRevision)+ if err != nil {+ t.Fatal(err)+ }+ }+ if scenario == "after_seal" {+ enqueue()+ }+ cb.MsgId = "second-message"+ cb.SenderStaffId = "second-sender"+ cb.Text = botCallbackText{Content: "second question"}+ second, ok := inboundFromCallback(cb, "delivery-"+suffix)+ if !ok {+ t.Fatal("second callback rejected")+ }+ second.ForceFresh = scenario == "cross_generation"+ if _, err := set.Session.AppendMessage(ctx, engine.AppendParams{SessionID: sid, Sender: userID, InstallationID: inst.ID, Message: second}); err != nil {+ t.Fatal(err)+ }+ ack.OnIngested(ctx, inst, second, sid)+ wantReceipts := 2+ if scenario == "merged" {+ wantReceipts = 1+ }+ if len(receipts) != wantReceipts || !receipts["second-message"] {+ t.Fatalf("batch receipts=%v want last message in each pending/sealed batch", receipts)+ }+ if scenario != "after_seal" {+ enqueue()+ }+ input, err := q.ListChatInputMessages(ctx, task.ChatInputTaskID)+ if err != nil || len(input) == 0 || input[0].Content != firstBody {+ t.Fatalf("sealed input changed: %+v %v", input, err)+ }+ delivery, err := q.GetChannelTaskDelivery(ctx, task.ID)+ if err != nil {+ t.Fatal(err)+ }+ if scenario == "cross_generation" && len(input) != 1 {+ t.Fatal("new generation changed the original task input")+ }+ // The shared core may already snapshot the right provider message. Quote+ // and Done attribution must remain correct with either core version.+ current, err := q.LockChannelChatSessionBindingForContext(ctx, sid)+ if err != nil {+ t.Fatal(err)+ }+ for _, raw := range [][]byte{current.Config, delivery.Config} {+ for _, forbidden := range []string{"quote_text", "source_message_id", "session_webhook", "token="} {+ if bytes.Contains(raw, []byte(forbidden)) {+ t.Fatalf("per-message data persisted in routing: %s", raw)+ }+ }+ }+ if restart {+ client = NewClient(nil, httpServer.srv.URL)+ ack = newAck(client)+ }+ if err := NewOutbound(q, box.Open, client, ack, nil).processEvent(ctx, events.Event{Type: protocol.EventChatDone, TaskID: util.UUIDToString(task.ID), ChatSessionID: util.UUIDToString(sid), Payload: protocol.ChatDonePayload{Content: "first answer"}}); err != nil {+ t.Fatal(err)+ }+ if httpServer.lastPath != pathSendGroup || len(httpServer.sendBodies) != 1 {+ t.Fatal("expected one proactive reply")+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(httpServer.lastBody["msgParam"].(string)), ¶m); err != nil {+ t.Fatal(err)+ }+ wantQuote := "> \\> \\*\\*Quoted author:\\*\\* \n> \\> \n> \\> \\[quoted content unavailable\\] \n> \n> first question\n\n---\n\n"+ wantSource := "first-message"+ if scenario == "merged" {+ wantQuote = "> second question\n\n---\n\n"+ wantSource = "second-message"+ }+ if param.Title != defaultMarkdownTitle || param.Text != wantQuote+"first answer" {+ t.Fatalf("wrong sealed quote: %q", param.Text)+ }+ if restart {+ if len(done) != 0 {+ t.Fatalf("restart reconstructed Done from delivery: %v", done)+ }+ if len(receipts) != wantReceipts {+ t.Fatalf("restart guessed receipt anchors: %v", receipts)+ }+ } else if strings.Join(done, ",") != wantSource {+ t.Fatalf("Done anchor=%v want %s", done, wantSource)+ }+ if !restart {+ if scenario == "merged" {+ if len(receipts) != 0 {+ t.Fatalf("completed batch left receipts: %v", receipts)+ }+ } else if len(receipts) != 1 || !receipts["second-message"] {+ t.Fatalf("older terminal changed next batch receipt: %v", receipts)+ }+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_image_quote_test.go b/server/internal/integrations/dingtalk/outbound_image_quote_test.gonew file mode 100644index 0000000000..488e336e3b--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_image_quote_test.go@@ -0,0 +1,78 @@+package dingtalk++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "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"+)++// Use the sealed-input reader and the real outbound transport. The expected+// wire text deliberately retains history: current-turn boundaries are not+// available in the sealed Markdown, and must not be guessed from quote syntax.+func TestOutboundSealedImagesUseVisiblePlaceholders(t *testing.T) {+ const attachment = ""+ const screenshot = "> 111\n> \n> 结合这两张图,你能联想到什么?\n\n@YYClaw\n\n" + attachment + "\n\n222"+ for _, tc := range []struct{ name, input, wantPrefix string }{+ {"screenshot", screenshot, "> \\> 111 \n> \\> \\[Image\\] \n> \\> 结合这两张图,你能联想到什么? \n> \n> @YYClaw \n> \n> \\[Image\\] \n> \n> 222\n\n---\n\n"},+ {"image only", attachment, "> \\[Image\\]\n\n---\n\n"},+ {"images before preview cutoff", strings.Repeat(attachment+"\n", 4) + "current question", "> \\[Image\\] \n> \\[Image\\] \n> \\[Image\\] \n> \\[Image\\] \n> current question\n\n---\n\n"},+ } {+ for _, private := range []bool{false, true} {+ name := tc.name + "/group"+ if private {+ name = tc.name + "/private"+ }+ t.Run(name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ config, err := json.Marshal(installConfig{AppID: "app", RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ taskID, sid := sessionUUID(46), sessionUUID(45)+ q := deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: string(TypeDingTalk), ChannelChatID: "conversation", ChatType: string(channel.ChatTypeGroup)},+ installation: db.ChannelInstallation{ID: sessionUUID(47), Status: "active", Config: config},+ task: db.AgentTaskQueue{ChatInputTaskID: taskID}, channelIngested: true,+ input: []db.ChatMessage{{ID: sessionUUID(48), ChannelIngested: true, Content: tc.input}},+ }+ if private {+ q.delivery.ChatType = string(channel.ChatTypeP2P)+ q.delivery.Config = []byte(`{"conversation_type":"1","staff_id":"staff"}`)+ }+ const answer = "answer with its own image: " + attachment+ err = NewOutbound(q, nil, NewClient(nil, d.srv.URL), nil, nil).processEvent(context.Background(), events.Event{+ Type: protocol.EventChatDone, TaskID: util.UUIDToString(taskID), ChatSessionID: util.UUIDToString(sid),+ Payload: protocol.ChatDonePayload{Content: answer},+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(d.sendBodies) != 1 {+ t.Fatalf("sent %d messages, want one", len(d.sendBodies))+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(d.sendBodies[0]["msgParam"].(string)), ¶m); err != nil {+ t.Fatal(err)+ }+ want := tc.wantPrefix + answer+ if private {+ want = answer+ }+ if param.Text != want {+ t.Fatalf("wire text = %q, want %q", param.Text, want)+ }+ if q.input[0].Content != tc.input {+ t.Fatal("source display changed sealed model input")+ }+ })+ }+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_layout_test.go b/server/internal/integrations/dingtalk/outbound_layout_test.gonew file mode 100644index 0000000000..b3b8e6ef11--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_layout_test.go@@ -0,0 +1,48 @@+package dingtalk++import (+ "bytes"+ "context"+ "encoding/json"+ "strings"+ "testing"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/extension"+)++// Inspect rendered quotes from real outgoing requests. GFM checks link and+// line-break boundaries; it does not certify DingTalk client rendering.+func TestSender_SourceQuotePreservesLinksAndLineBreaks(t *testing.T) {+ for _, tc := range []struct{ name, quote, want string }{+ {"link parentheses", "[标签](https://example.com)\n普通 (括号)\n\n省略段落", "<blockquote>\n<p>[标签](<a href=\"https://example.com\">https://example.com</a>)<br>\n普通 (括号)</p>\n<p>省略段落</p>\n</blockquote>"},+ {"literal multiline", "第一行 a-b C:\\tmp\\a\n第二行 *literal*\n\nOmitted paragraph", "<blockquote>\n<p>第一行 a-b C:\\tmp\\a<br>\n第二行 *literal*</p>\n<p>Omitted paragraph</p>\n</blockquote>"},+ {"single line", "question", "<blockquote>\n<p>question</p>\n</blockquote>"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group", QuoteText: tc.quote}+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, "**answer**"); err != nil {+ t.Fatal(err)+ }+ if len(d.sendBodies) != 1 {+ t.Fatalf("sent %d messages", len(d.sendBodies))+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(d.sendBodies[0]["msgParam"].(string)), ¶m); err != nil {+ t.Fatal(err)+ }+ if strings.Contains(param.Text, `\(`) || strings.Contains(param.Text, `\)`) {+ t.Fatalf("unnecessary URL escapes: %q", param.Text)+ }+ var rendered bytes.Buffer+ if err := goldmark.New(goldmark.WithExtensions(extension.GFM)).Convert([]byte(param.Text), &rendered); err != nil {+ t.Fatal(err)+ }+ parts := strings.SplitN(rendered.String(), "\n<hr>\n", 2)+ if len(parts) != 2 || parts[0] != tc.want || !strings.Contains(parts[1], "<strong>answer</strong>") {+ t.Fatalf("quote or answer changed:\n%s", rendered.String())+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_payload_test.go b/server/internal/integrations/dingtalk/outbound_payload_test.gonew file mode 100644index 0000000000..ebca396f5b--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_payload_test.go@@ -0,0 +1,81 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "strings"+ "testing"+ "unicode/utf8"+)++// Assert the serialized request and reconstructed body, including escape+// expansion that is invisible to a raw UTF-8 body-length check.+func TestSenderProactivePayloadBudgetPreservesBody(t *testing.T) {+ for _, answer := range []string{+ strings.Repeat("<&>\"\\", 6000),+ strings.Repeat("界🚀", 6000),+ "# " + strings.Repeat("heading", 2200),+ strings.Repeat("\x01", 16000),+ } {+ for _, kind := range []string{convTypeGroup, convTypeP2P} {+ d := newDingtalkSendServer(t)+ target := sendTarget{ConversationType: kind, ConversationID: "group", StaffID: "staff"}+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, answer); err != nil {+ t.Fatal(err)+ }+ var reconstructed strings.Builder+ for _, body := range d.sendBodies {+ raw := body["msgParam"].(string)+ var param markdownParam+ if err := json.Unmarshal([]byte(raw), ¶m); err != nil {+ t.Fatal(err)+ }+ if len(raw) > 15000 || !utf8.ValidString(param.Text) || !utf8.ValidString(param.Title) {+ t.Fatalf("invalid serialized payload: %d bytes", len(raw))+ }+ reconstructed.WriteString(param.Text)+ }+ if reconstructed.String() != answer {+ t.Fatal("chunking lost or duplicated answer bytes")+ }+ }+ }+}++func TestSenderQuotedChunksPreserveOneSourceAndWholeAnswer(t *testing.T) {+ const prefix = "> question\n\n---\n\n"+ for _, tc := range []struct {+ name string+ answer string+ standalone bool+ }{+ {name: "combined", answer: "short answer"},+ {name: "standalone source", answer: strings.Repeat("a", 30000), standalone: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group", QuoteText: "question"}+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, tc.answer); err != nil {+ t.Fatal(err)+ }+ var body strings.Builder+ for i, request := range d.sendBodies {+ raw := request["msgParam"].(string)+ var param markdownParam+ if err := json.Unmarshal([]byte(raw), ¶m); err != nil {+ t.Fatal(err)+ }+ if len(raw) > 15000 || !utf8.ValidString(param.Text) {+ t.Fatalf("invalid serialized quoted payload: %d bytes", len(raw))+ }+ if i == 0 && tc.standalone && param.Text != prefix {+ t.Fatalf("expected standalone source chunk, got %q", param.Text)+ }+ body.WriteString(param.Text)+ }+ if body.String() != prefix+tc.answer {+ t.Fatal("quoted delivery lost or duplicated source/answer bytes")+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_quote.go b/server/internal/integrations/dingtalk/outbound_quote.gonew file mode 100644index 0000000000..568718f1a8--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_quote.go@@ -0,0 +1,51 @@+package dingtalk++import (+ "strings"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/extension"+ "github.com/yuin/goldmark/text"++ "github.com/multica-ai/multica/server/internal/util"+)++// sealedInputQuote keeps the owned input as the source of attribution, including+// quoted history. Materialized channel images use authenticated internal URLs+// that cannot render in DingTalk; display their original placeholder instead.+// Only the exact image form emitted by channel ingestion is replaced. Parsing+// preserves literal Markdown in code, escaped images and ordinary links.+func sealedInputQuote(body string) string {+ if !strings.Contains(body, "/api/attachments/") {+ return body+ }+ source := []byte(body)+ doc := goldmark.New(goldmark.WithExtensions(extension.GFM)).Parser().Parse(text.NewReader(source))+ var quote strings.Builder+ position := 0+ _ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {+ img, ok := node.(*ast.Image)+ if !entering || !ok {+ return ast.WalkContinue, nil+ }+ destination := string(img.Destination)+ if !strings.HasPrefix(destination, "/api/attachments/") {+ return ast.WalkContinue, nil+ }+ if _, ok := util.AttachmentIDFromDownloadURL(destination); !ok {+ return ast.WalkContinue, nil+ }+ literal := ""+ start := img.Pos()+ if !strings.HasPrefix(body[start:], literal) {+ return ast.WalkContinue, nil+ }+ quote.WriteString(body[position:start])+ quote.WriteString(dingtalkImagePlaceholder)+ position = start + len(literal)+ return ast.WalkSkipChildren, nil+ })+ quote.WriteString(body[position:])+ return quote.String()+}diff --git a/server/internal/integrations/dingtalk/outbound_quote_regression_test.go b/server/internal/integrations/dingtalk/outbound_quote_regression_test.gonew file mode 100644index 0000000000..b34e59bd13--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_quote_regression_test.go@@ -0,0 +1,122 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "strings"+ "testing"+)++// Expected wire text is literal: do not build it with the escaping or preview+// helpers under test. A local HTTP receiver cannot certify DingTalk rendering.+func TestSender_QuotedURLsPreserveSourceBytes(t *testing.T) {+ for _, tc := range []struct{ name, quote, want string }{+ {"client screenshot", "原文引用测试:hello-world a_b *literal* [label](https://example.com/a_(b)) \\ test\n只回复“符号测试完成”。", "> 原文引用测试:hello-world a\\_b \\*literal\\* \\[label\\](https://example.com/a_(b)) \\\\ test \n> 只回复“符号测试完成”。\n\n---\n\nanswer"},+ {"reserved characters", "https://example.com/a_b-c+d!e*f?x=a_b+c&y=%28v%29#part_2", "> https://example.com/a_b-c+d!e*f?x=a_b+c&y=%28v%29#part_2\n\n---\n\nanswer"},+ {"multiple URLs and prose", "a_b https://example.com/a_b *literal* http://example.org/c_d end_x", "> a\\_b https://example.com/a_b \\*literal\\* http://example.org/c_d end\\_x\n\n---\n\nanswer"},+ {"scheme casing and www", "HTTPS://EXAMPLE.COM/A_B www.example.com/a_b", "> HTTPS://EXAMPLE.COM/A_B www.example.com/a_b\n\n---\n\nanswer"},+ {"IPv6 and query brackets", "http://[::1]:8080/a_b?keys[]=x_y", "> http://[::1]:8080/a_b?keys[]=x_y\n\n---\n\nanswer"},+ {"closing delimiters", "(https://example.com/a_(b)) [x_y]", "> (https://example.com/a_(b)) \\[x\\_y\\]\n\n---\n\nanswer"},+ {"adjacent literal link", "https://example.com/a_(b))[x_y](elsewhere)", "> https://example.com/a_(b))\\[x\\_y\\](elsewhere)\n\n---\n\nanswer"},+ {"adjacent URLs", "https://example.com/a_(b))[x_y](https://example.org/c_d)", "> https://example.com/a_(b))\\[x\\_y\\](https://example.org/c_d)\n\n---\n\nanswer"},+ {"unicode and line boundaries", "https://example.com/路径_a\u3000x_y\nhttp://example.org/b_c", "> https://example.com/路径_a\u3000x\\_y \n> http://example.org/b_c\n\n---\n\nanswer"},+ {"backslash boundary", "https://example.com/a_b\\ *literal*", "> https://example.com/a_b\\\\ \\*literal\\*\n\n---\n\nanswer"},+ {"ordinary punctuation", "hello-world issue #8125 C++ done! a > b | c", "> hello-world issue #8125 C++ done! a > b | c\n\n---\n\nanswer"},+ {"line-leading syntax", "# heading\n- item\n + item\n> nested\nhttps://example.com/a#b - tail", "> \\# heading \n> \\- item \n> \\+ item \n> \\> nested \n> https://example.com/a#b - tail\n\n---\n\nanswer"},+ {"plain text", "hello-world a_b *literal* [label](relative) \\ test", "> hello-world a\\_b \\*literal\\* \\[label\\](relative) \\\\ test\n\n---\n\nanswer"},+ {"paragraphs", "第一段。\n\n第二段:https://example.com/a_b", "> 第一段。 \n> \n> 第二段:https://example.com/a_b\n\n---\n\nanswer"},+ } {+ for _, transport := range []string{"group", "private"} {+ t.Run(tc.name+"/"+transport, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ d.failFirstSendAuth = transport == "rejected webhook"+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group", QuoteText: tc.quote}+ if transport == "private" {+ target.ConversationType = convTypeP2P+ target.StaffID = "staff"+ }+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, "answer"); err != nil {+ t.Fatal(err)+ }+ if len(d.sendBodies) != 1 {+ t.Fatalf("accepted %d messages, want one", len(d.sendBodies))+ }+ body := d.sendBodies[0]+ var param markdownParam+ if raw, ok := body["msgParam"].(string); ok {+ if err := json.Unmarshal([]byte(raw), ¶m); err != nil {+ t.Fatal(err)+ }+ } else {+ markdown := body["markdown"].(map[string]any)+ param = markdownParam{Title: markdown["title"].(string), Text: markdown["text"].(string)}+ }+ want := tc.want+ if transport == "private" {+ want = "answer"+ }+ if param.Text != want || param.Title != defaultMarkdownTitle {+ t.Fatalf("wire Markdown = %#v; want title=answer, text=%q", param, want)+ }+ })+ }+ }+}++func FuzzQuotedURLPreservesReservedCharacters(f *testing.F) {+ for _, seed := range []string{"a_b", "-+!*#", "?x=a_b+c&y=%28v%29#part_2", "a/b:c;d,e@f$g=h~i"} {+ f.Add(seed)+ }+ f.Fuzz(func(t *testing.T, tail string) {+ if len(tail) == 0 || len(tail) > 180 {+ t.Skip()+ }+ // These are URL characters, independent of Markdown or the production+ // span finder. Delimiter nesting and Unicode have explicit wire cases.+ const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~:/?#@!$&'*+,;=%"+ if strings.ContainsFunc(tail, func(r rune) bool { return !strings.ContainsRune(alphabet, r) }) {+ t.Skip()+ }+ address := "https://example.com/" + tail+ want := "a\\_b " + address + " \\*literal\\*"+ if got := escapeMarkdownQuoteText("a_b " + address + " *literal*"); got != want {+ t.Fatalf("URL or surrounding literal text changed: got=%q want=%q", got, want)+ }+ })+}++func TestQuotePreview_DoesNotPublishPartialURL(t *testing.T) {+ for _, tc := range []struct{ name, body, want string }{+ {"exact budget", "https://example.com/" + strings.Repeat("a", 236), "https://example.com/" + strings.Repeat("a", 236)},+ {"URL alone exceeds budget", "https://example.com/" + strings.Repeat("a", 237), "..."},+ {"URL crosses cutoff", strings.Repeat("x", 230) + " https://example.com/a_long_path_here", strings.Repeat("x", 230) + "\n..."},+ {"URL starts at cutoff", strings.Repeat("x", 251) + " https://example.com/a_b", strings.Repeat("x", 251) + "\n..."},+ {"complete URL before cutoff", "https://example.com/a_b " + strings.Repeat("x", 240), "https://example.com/a_b " + strings.Repeat("x", 228) + "\n..."},+ {"literal CRLF paragraphs", "First\r\n \t\r\nLater", "First\n \t\nLater"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := quotePreview(tc.body)+ if got != tc.want || quotePreview(got) != got {+ t.Fatalf("preview=%q, want=%q (idempotent)", got, tc.want)+ }+ })+ }+}++func TestQuotedWebURLBoundaries(t *testing.T) {+ for _, tc := range []struct{ source, want string }{+ {"", ""},+ {"https://", "https://"},+ {"prefix_https://example.com/a_b", "prefix\\_https://example.com/a_b"},+ {"https://example.com/a_b\tplain_x", "https://example.com/a_b\tplain\\_x"},+ {"https://example.com/a_b\x01plain_x", "https://example.com/a_b\x01plain\\_x"},+ {"https://example.com/a_b\"plain_x", "https://example.com/a_b\"plain\\_x"},+ {"https://example.com/a_b`plain_x`", "https://example.com/a_b\\`plain\\_x\\`"},+ {"<https://example.com/a_b>plain_x", "<https://example.com/a_b>plain\\_x"},+ {"https://example.com/a_(b]plain_x", "https://example.com/a_(b\\]plain\\_x"},+ } {+ if got := escapeMarkdownQuoteText(tc.source); got != tc.want {+ t.Errorf("quote=%q got=%q want=%q", tc.source, got, tc.want)+ }+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_quote_test.go b/server/internal/integrations/dingtalk/outbound_quote_test.gonew file mode 100644index 0000000000..769e993b87--- /dev/null+++ b/server/internal/integrations/dingtalk/outbound_quote_test.go@@ -0,0 +1,33 @@+package dingtalk++import "testing"++func TestSealedInputQuotePreservesSourceSyntax(t *testing.T) {+ const path = "/api/attachments/01a08f95-e516-7c96-8164-5856dbee3a47/download"+ const img = ""+ for _, tc := range []struct{ name, input, want string }{+ {"empty", "", ""},+ {"plain text", "hello **world**", "hello **world**"},+ {"inline image", "前" + img + "后", "前[Image]后"},+ {"quoted image", "> old\n> " + img + "\n\ncurrent", "> old\n> [Image]\n\ncurrent"},+ {"inline code", "`" + img + "` " + img, "`" + img + "` [Image]"},+ {"fenced code", "```md\n" + img + "\n```\n\n" + img, "```md\n" + img + "\n```\n\n[Image]"},+ {"indented code", " " + img + "\n\n" + img, " " + img + "\n\n[Image]"},+ {"escaped image", `\` + img + " " + img, `\` + img + " [Image]"},+ {"ordinary link", "[download](" + path + ")", "[download](" + path + ")"},+ {"external image", "", ""},+ {"invalid attachment", "", ""},+ {"different route", "", ""},+ {"authored alt", "", ""},+ {"authored title", "`, "`},+ {"reference image", "![][ref]\n\n[ref]: " + path, "![][ref]\n\n[ref]: " + path},+ {"HTML code", "<pre>\n" + img + "\n</pre>\n\n" + img, "<pre>\n" + img + "\n</pre>\n\n[Image]"},+ {"image inside link", "[" + img + "](https://example.test)", "[[Image]](https://example.test)"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := sealedInputQuote(tc.input); got != tc.want {+ t.Fatalf("quote = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_send.go b/server/internal/integrations/dingtalk/outbound_send.goindex 6b53fd3bb7..80aa3c04d1 100644--- a/server/internal/integrations/dingtalk/outbound_send.go+++ b/server/internal/integrations/dingtalk/outbound_send.go@@ -5,15 +5,17 @@ import ("encoding/json""errors""fmt"+ "strings")// This file is the OUTBOUND send path shared by the EventChatDone subscriber// (outbound.go) and the OutboundReplier (replier.go). It turns a reply body into-// one or more DingTalk sampleMarkdown messages and posts them with the-// installation's access_token, routing 1:1 vs group to the right robot endpoint.+// one or more DingTalk Markdown messages using the installation's robot endpoints.const (- // msgKeyMarkdown renders a {title, text} sampleMarkdown card.+ // sampleMarkdown is the documented Markdown template for both robot send+ // endpoints. Keep this aligned with DingTalk's endpoint contract instead of+ // inferring a template migration from received interactive-card payloads.msgKeyMarkdown = "sampleMarkdown"// p2p (1:1) proactive send; group send.@@ -23,11 +25,14 @@ const (// sendTarget is the resolved DingTalk destination for a reply. ConversationType// selects the endpoint; StaffID is the recipient for a 1:1 send; ConversationID-// is the group's openConversationId for a group send.+// is the group's+// openConversationId for a group send.type sendTarget struct {ConversationType stringConversationID stringStaffID string+ SourceMessageID string+ QuoteText string}// sender posts replies for one installation. The robotCode + credentials come@@ -45,30 +50,144 @@ type markdownParam struct {Text string `json:"text"`}-// send delivers text to target as one or more sampleMarkdown messages (chunked-// under DingTalk's per-message byte cap). It returns the last message's send-// key. A 401 triggers one token refresh + retry, covering a server-side token-// revocation between cache fill and use.+// send delivers one or more bounded Markdown messages. A proactive-send 401+// triggers one token refresh and retry.func (s *sender) send(ctx context.Context, target sendTarget, text string) (string, error) {if text == "" {return "", nil}- title := markdownTitle(text)+ quote := ""+ if target.ConversationType != convTypeP2P {+ quote = target.QuoteText+ }+ chunks, err := replyMarkdownChunks(text, quote)+ if err != nil {+ return "", err+ }var lastKey string- for _, chunk := range chunkMarkdown(text) {- param, err := json.Marshal(markdownParam{Title: title, Text: chunk})+ for _, chunk := range chunks {+ param, err := json.Marshal(markdownParam{Title: chunk.title, Text: chunk.text})if err != nil {return "", fmt.Errorf("marshal msgParam: %w", err)}- key, err := s.sendOne(ctx, target, string(param))+ lastKey, err = s.sendOne(ctx, target, string(param))if err != nil {return "", err}- lastKey = key}return lastKey, nil}+type replyMarkdownChunk struct{ text, title string }++// Budget serialized JSON before any provider call. Escapes can expand a body+// substantially; re-render smaller chunks to keep Markdown fences intact.+func replyMarkdownChunks(text, quote string) ([]replyMarkdownChunk, error) {+ for budget := markdownByteBudget; budget >= 512; budget /= 2 {+ chunks := replyMarkdownChunksWithBudget(text, quote, budget)+ fits := true+ for _, chunk := range chunks {+ payload, err := json.Marshal(markdownParam{Title: chunk.title, Text: chunk.text})+ if err != nil {+ return nil, fmt.Errorf("marshal Markdown payload: %w", err)+ }+ if len(payload) > markdownPayloadByteBudget {+ fits = false+ break+ }+ }+ if fits {+ return chunks, nil+ }+ }+ return nil, errors.New("dingtalk: Markdown metadata exceeds payload byte budget")+}++func replyMarkdownChunksWithBudget(text, quote string, byteBudget int) []replyMarkdownChunk {+ var chunks []replyMarkdownChunk+ if prefix := prependMarkdownQuote("", quote); prefix != "" {+ for _, chunk := range chunkMarkdownWithBudget(prefix, byteBudget) {+ chunks = append(chunks, replyMarkdownChunk{text: chunk, title: defaultMarkdownTitle})+ }+ }+ for i, body := range chunkMarkdownWithBudget(text, byteBudget) {+ // Derive the title from the answer, independently of the source quote.+ chunk := replyMarkdownChunk{text: body, title: markdownTitle(body)}+ if i == 0 {+ if last := len(chunks) - 1; last >= 0 && len(chunks[last].text)+len(body) <= byteBudget {+ chunk.text = chunks[last].text + body+ chunks[last] = chunk+ continue+ }+ }+ chunks = append(chunks, chunk)+ }+ return chunks+}++// prependMarkdownQuote renders the triggering message as the visual quote+// block supported by DingTalk Markdown. DingTalk's outbound robot message+// contract has no native reply/quote field, so the horizontal rule is part of+// the Markdown as well. Task replies supply the sealed input; immediate command+// feedback supplies the current callback text. Neither persists a quote copy.+func prependMarkdownQuote(text, quote string) string {+ quote = quotePreview(quote)+ if quote == "" {+ return text+ }+ var b strings.Builder+ b.WriteString("> ")+ // Plain newlines are Markdown soft breaks. Preserve source line breaks and+ // the separate ellipsis line with hard breaks in the outbound quote only.+ b.WriteString(strings.ReplaceAll(escapeMarkdownQuoteText(quote), "\n", " \n> "))+ b.WriteString("\n\n---\n\n")+ b.WriteString(text)+ return b.String()+}++func escapeMarkdownQuoteText(text string) string {+ var b strings.Builder+ start := 0+ for _, span := range webURLSpans(text) {+ b.WriteString(escapeMarkdownQuoteInlineText(text[start:span[0]]))+ b.WriteString(text[span[0]:span[1]])+ start = span[1]+ }+ b.WriteString(escapeMarkdownQuoteInlineText(text[start:]))+ // Block markers need protection only at the start of a source line.+ // Avoid adding visible backslashes to ordinary punctuation on clients+ // whose restricted Markdown renderer does not consume those escapes.+ lines := strings.Split(b.String(), "\n")+ for i, line := range lines {+ trimmed := strings.TrimLeft(line, " \t")+ if trimmed != "" && strings.ContainsRune("#+->", rune(trimmed[0])) {+ indent := len(line) - len(trimmed)+ lines[i] = line[:indent] + `\` + trimmed+ }+ }+ return strings.Join(lines, "\n")+}++func escapeMarkdownQuoteInlineText(text string) string {+ // Escaping brackets already prevents Markdown links. Leave parentheses+ // literal: DingTalk can include a trailing escape in its automatic URL link.+ return strings.NewReplacer(+ `\`, `\\`, "`", "\\`", "*", "\\*", "_", "\\_",+ "[", "\\[", "]", "\\]",+ ).Replace(text)+}++func escapeMarkdownText(text string) string {+ // Escaping brackets already prevents Markdown links. Leave parentheses+ // literal: DingTalk can include a trailing escape in its automatic URL link.+ return strings.NewReplacer(+ `\`, `\\`, "`", "\\`", "*", "\\*", "_", "\\_",+ "[", "\\[", "]", "\\]",+ "#", "\\#", "+", "\\+", "-", "\\-", "!", "\\!",+ ">", "\\>", "|", "\\|",+ ).Replace(text)+}+// sendOne posts a single rendered message, refreshing the token once on 401.func (s *sender) sendOne(ctx context.Context, target sendTarget, msgParam string) (string, error) {path, body, err := s.request(target, msgParam)@@ -113,10 +232,11 @@ func (s *sender) request(target sendTarget, msgParam string) (string, map[stringif target.ConversationID == "" {return "", nil, errors.New("dingtalk: group send missing conversation id")}- return pathSendGroup, map[string]any{+ body := map[string]any{"robotCode": s.robotCode,"openConversationId": target.ConversationID,"msgKey": msgKeyMarkdown,"msgParam": msgParam,- }, nil+ }+ return pathSendGroup, body, nil}diff --git a/server/internal/integrations/dingtalk/outbound_send_test.go b/server/internal/integrations/dingtalk/outbound_send_test.goindex 3a8cabc559..c50f0d33dd 100644--- a/server/internal/integrations/dingtalk/outbound_send_test.go+++ b/server/internal/integrations/dingtalk/outbound_send_test.go@@ -7,6 +7,7 @@ import ("io""net/http""net/http/httptest"+ "strings""sync""sync/atomic""testing"@@ -20,10 +21,12 @@ type dingtalkSendServer struct {tokenCalls int32lastPath stringlastBody map[string]any+ sendBodies []map[string]any// failFirstSendAuth makes the first send return 401 so the token-refresh// retry path is exercised.- failFirstSendAuth bool- sendCalls int32+ failFirstSendAuth bool+ emotionSuccessFalse bool+ sendCalls int32}func newDingtalkSendServer(t *testing.T) *dingtalkSendServer {@@ -35,7 +38,7 @@ func newDingtalkSendServer(t *testing.T) *dingtalkSendServer {case accessTokenPath:atomic.AddInt32(&d.tokenCalls, 1)_, _ = w.Write([]byte(`{"accessToken":"tok","expireIn":7200}`))- case pathSendP2P, pathSendGroup:+ case pathSendP2P, pathSendGroup, pathReplyEmotion, pathRecallEmotion:n := atomic.AddInt32(&d.sendCalls, 1)if d.failFirstSendAuth && n == 1 {w.WriteHeader(http.StatusUnauthorized)@@ -46,7 +49,16 @@ func newDingtalkSendServer(t *testing.T) *dingtalkSendServer {d.lastPath = r.URL.Pathd.lastBody = map[string]any{}_ = json.Unmarshal(body, &d.lastBody)- _, _ = w.Write([]byte(`{"processQueryKey":"pqk-1"}`))+ d.sendBodies = append(d.sendBodies, d.lastBody)+ if r.URL.Path == pathReplyEmotion || r.URL.Path == pathRecallEmotion {+ if d.emotionSuccessFalse {+ _, _ = w.Write([]byte(`{"success":false}`))+ } else {+ _, _ = w.Write([]byte(`{"success":true}`))+ }+ } else {+ _, _ = w.Write([]byte(`{"processQueryKey":"pqk-1"}`))+ }default:w.WriteHeader(http.StatusNotFound)}@@ -79,6 +91,23 @@ func TestSender_P2PSendHitsBatchSend(t *testing.T) {if ids, ok := d.lastBody["userIds"].([]any); !ok || len(ids) != 1 || ids[0] != "staff-1" {t.Errorf("userIds = %v", d.lastBody["userIds"])}+ if got := d.lastBody["msgKey"]; got != "sampleMarkdown" {+ t.Fatalf("msgKey = %v, want documented sampleMarkdown", got)+ }+ if _, ok := d.lastBody["atUserIds"]; ok {+ t.Fatalf("1:1 send must not contain atUserIds: %v", d.lastBody)+ }+ paramRaw, ok := d.lastBody["msgParam"].(string)+ if !ok {+ t.Fatalf("msgParam = %T", d.lastBody["msgParam"])+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(paramRaw), ¶m); err != nil {+ t.Fatalf("decode msgParam: %v", err)+ }+ if param.Text != "hi" {+ t.Fatalf("1:1 Markdown = %q, want no sender mention", param.Text)+ }}func TestSender_GroupSendHitsGroupMessages(t *testing.T) {@@ -94,6 +123,116 @@ func TestSender_GroupSendHitsGroupMessages(t *testing.T) {if d.lastBody["openConversationId"] != "cid-g" {t.Errorf("openConversationId = %v", d.lastBody["openConversationId"])}+ if got := d.lastBody["msgKey"]; got != "sampleMarkdown" {+ t.Fatalf("msgKey = %v, want upstream sampleMarkdown", got)+ }+ if _, ok := d.lastBody["atUserIds"]; ok {+ t.Fatalf("group send without a sender target must not contain atUserIds: %v", d.lastBody)+ }+}++func TestPrependMarkdownQuoteSkipsEmptyQuote(t *testing.T) {+ if got := prependMarkdownQuote("answer", " \n "); got != "answer" {+ t.Fatalf("empty quote changed answer: %q", got)+ }+}++func TestPrependMarkdownQuoteSeparatesQuoteFromReply(t *testing.T) {+ if got := prependMarkdownQuote("answer", "question"); got != "> question\n\n---\n\nanswer" {+ t.Fatalf("quoted reply = %q", got)+ }+}++func TestSender_EmojiReactionUsesDefaultRobotReaction(t *testing.T) {+ if emotionAcknowledged != "收到" || emotionDone != "Done" {+ t.Fatalf("emoji reaction names = %q / %q", emotionAcknowledged, emotionDone)+ }+ d := newDingtalkSendServer(t)+ s := newTestSender(NewClient(nil, d.srv.URL))+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "cid-g", SourceMessageID: "msg-original"}++ if err := s.setEmojiReaction(context.Background(), target, emotionAcknowledged, false); err != nil {+ t.Fatalf("add emotion: %v", err)+ }+ if d.lastPath != pathReplyEmotion || d.lastBody["emotionType"] != float64(1) || d.lastBody["emotionName"] != emotionAcknowledged {+ t.Fatalf("reaction request path/body = %q / %v", d.lastPath, d.lastBody)+ }+ if _, exists := d.lastBody["textEmotion"]; exists {+ t.Fatalf("default emoji request contains textEmotion: %v", d.lastBody)+ }+ if err := s.setEmojiReaction(context.Background(), target, emotionDone, false); err != nil {+ t.Fatalf("add done emotion: %v", err)+ }+ if d.lastPath != pathReplyEmotion || d.lastBody["emotionType"] != float64(1) || d.lastBody["emotionName"] != emotionDone {+ t.Fatalf("done request path/body = %q / %v", d.lastPath, d.lastBody)+ }+ if err := s.setEmojiReaction(context.Background(), target, emotionAcknowledged, true); err != nil {+ t.Fatalf("recall emotion: %v", err)+ }+ if d.lastPath != pathRecallEmotion || d.lastBody["emotionType"] != float64(1) || d.lastBody["emotionName"] != emotionAcknowledged {+ t.Fatalf("recall request path/body = %q / %v", d.lastPath, d.lastBody)+ }+}++func TestSender_EmojiReactionRejectsUnknownName(t *testing.T) {+ s := newTestSender(NewClient(nil, "https://api.dingtalk.test"))+ target := sendTarget{ConversationID: "cid", SourceMessageID: "msg"}+ if err := s.setEmojiReaction(context.Background(), target, "未注册名称", false); err == nil {+ t.Fatal("unknown default emoji name must be rejected")+ }+}++func TestSender_EmojiReactionSupportsP2P(t *testing.T) {+ d := newDingtalkSendServer(t)+ s := newTestSender(NewClient(nil, d.srv.URL))+ target := sendTarget{+ ConversationType: convTypeP2P,+ ConversationID: "cid-p2p",+ SourceMessageID: "msg-p2p",+ }++ if err := s.setEmojiReaction(context.Background(), target, emotionAcknowledged, false); err != nil {+ t.Fatalf("add p2p emotion: %v", err)+ }+ if d.lastPath != pathReplyEmotion || d.lastBody["openConversationId"] != "cid-p2p" || d.lastBody["openMsgId"] != "msg-p2p" {+ t.Fatalf("p2p emotion request path/body = %q / %v", d.lastPath, d.lastBody)+ }+}++func TestSender_EmojiReactionRequiresConversationAndMessageIDs(t *testing.T) {+ s := newTestSender(NewClient(nil, "https://api.dingtalk.test"))+ if err := s.setEmojiReaction(context.Background(), sendTarget{ConversationID: "cid"}, emotionAcknowledged, false); err == nil {+ t.Fatal("missing source message id must fail before an API call")+ }+ if err := s.setEmojiReaction(context.Background(), sendTarget{SourceMessageID: "msg"}, emotionAcknowledged, false); err == nil {+ t.Fatal("missing conversation id must fail before an API call")+ }+}++func TestSender_EmojiReactionRefreshesTokenOn401(t *testing.T) {+ d := newDingtalkSendServer(t)+ d.failFirstSendAuth = true+ s := newTestSender(NewClient(nil, d.srv.URL))+ target := sendTarget{ConversationID: "cid", SourceMessageID: "msg"}+ if err := s.setEmojiReaction(context.Background(), target, emotionAcknowledged, false); err != nil {+ t.Fatalf("emotion should succeed after token refresh: %v", err)+ }+ if got := atomic.LoadInt32(&d.tokenCalls); got != 2 {+ t.Fatalf("token calls = %d, want 2", got)+ }+ if got := atomic.LoadInt32(&d.sendCalls); got != 2 {+ t.Fatalf("emotion calls = %d, want 2", got)+ }+}++func TestSender_EmojiReactionRejectsSuccessFalse(t *testing.T) {+ d := newDingtalkSendServer(t)+ d.emotionSuccessFalse = true+ s := newTestSender(NewClient(nil, d.srv.URL))+ target := sendTarget{ConversationID: "cid", SourceMessageID: "msg"}+ if err := s.setEmojiReaction(context.Background(), target, emotionAcknowledged, false); err == nil {+ t.Fatal("success=false must fail")+ }}func TestSender_P2PWithoutStaffIDFails(t *testing.T) {@@ -264,3 +403,34 @@ func TestClient_AccessToken_CancelledCallerDoesNotCancelSharedMint(t *testing.T)t.Fatalf("cancelled first caller caused %d token mints, want 1", got)}}++func TestSender_LongSingleLineAnswerBlockquotePreservesEveryChunk(t *testing.T) {+ // Use an answer blockquote: source QuoteText is capped before chunking.+ source := strings.Repeat("界", 15000)+ d := newDingtalkSendServer(t)+ _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), sendTarget{+ ConversationType: convTypeGroup,+ ConversationID: "group",+ }, "> "+source)+ if err != nil {+ t.Fatal(err)+ }+ if len(d.sendBodies) < 2 {+ t.Fatal("long answer must exercise chunking")+ }+ var joined strings.Builder+ for i, body := range d.sendBodies {+ raw := body["msgParam"].(string)+ var param markdownParam+ if err := json.Unmarshal([]byte(raw), ¶m); err != nil {+ t.Fatal(err)+ }+ if len(raw) > 15000 || !strings.HasPrefix(param.Text, "> ") || param.Title != defaultMarkdownTitle {+ t.Fatalf("chunk %d lost its blockquote/title or exceeded the payload budget: %q", i, raw)+ }+ joined.WriteString(strings.TrimPrefix(param.Text, "> "))+ }+ if joined.String() != source {+ t.Fatal("answer blockquote content was lost or duplicated across chunks")+ }+}diff --git a/server/internal/integrations/dingtalk/outbound_test.go b/server/internal/integrations/dingtalk/outbound_test.goindex fbe11bd0e1..7691abf590 100644--- a/server/internal/integrations/dingtalk/outbound_test.go+++ b/server/internal/integrations/dingtalk/outbound_test.go@@ -2,17 +2,32 @@ package dingtalkimport ("context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "slices"+ "strings""testing"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "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")type noDeliveryOutboundQueries struct{}+func (noDeliveryOutboundQueries) ListChatInputMessages(context.Context, pgtype.UUID) ([]db.ChatMessage, error) {+ panic("must not read input without delivery")+}+func (noDeliveryOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {return db.ChannelTaskDelivery{}, pgx.ErrNoRows}@@ -26,8 +41,44 @@ func (noDeliveryOutboundQueries) GetChannelInstallation(context.Context, db.GetCpanic("GetChannelInstallation must not run without a task delivery snapshot")}+type deliveryOnlyOutboundQueries struct {+ noDeliveryOutboundQueries+ delivery db.ChannelTaskDelivery+ installation db.ChannelInstallation+ task db.AgentTaskQueue+ channelIngested bool+ input []db.ChatMessage+ inputErr error+}++type missingDeliveryInputQueries struct{ deliveryOnlyOutboundQueries }++func (missingDeliveryInputQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {+ return db.ChannelTaskDelivery{}, pgx.ErrNoRows+}++func (q deliveryOnlyOutboundQueries) ListChatInputMessages(context.Context, pgtype.UUID) ([]db.ChatMessage, error) {+ return q.input, q.inputErr+}++func (q deliveryOnlyOutboundQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {+ return q.delivery, nil+}++func (q deliveryOnlyOutboundQueries) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ return q.installation, nil+}++func (q deliveryOnlyOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {+ return q.task, nil+}++func (q deliveryOnlyOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pgtype.UUID) (bool, error) {+ return q.channelIngested, nil+}+func TestOutboundFailsClosedWithoutTaskDeliverySnapshot(t *testing.T) {- o := NewOutbound(noDeliveryOutboundQueries{}, nil, nil, nil)+ o := NewOutbound(noDeliveryOutboundQueries{}, nil, nil, nil, nil)event := events.Event{Type: protocol.EventChatDone,TaskID: "11111111-1111-1111-1111-111111111111",@@ -84,3 +135,176 @@ func TestEventContent(t *testing.T) {})}}++func TestEventRetryPending(t *testing.T) {+ if eventRetryPending(events.Event{Type: protocol.EventTaskFailed}) {+ t.Fatal("missing payload marked retry pending")+ }+ if !eventRetryPending(events.Event{Type: protocol.EventTaskFailed, Payload: map[string]any{"retry_pending": true}}) {+ t.Fatal("retry-pending failure must keep the processing reaction")+ }+ if eventRetryPending(events.Event{Type: protocol.EventChatDone, Payload: map[string]any{"retry_pending": true}}) {+ t.Fatal("chat-done must be terminal")+ }+}++func TestOutboundTerminalReactionLifecycle(t *testing.T) {+ tests := []struct {+ name string+ eventType string+ payload any+ sendFails bool+ wantReply bool+ wantDone bool+ keepActive bool+ inputUnavailable bool+ cancelOnRecall bool+ }{+ {name: "completion", eventType: protocol.EventChatDone, payload: protocol.ChatDonePayload{Content: "answer"}, wantReply: true, wantDone: true},+ {name: "failed task", eventType: protocol.EventTaskFailed, payload: map[string]any{"error": "safe failure", "retry_pending": false}, wantReply: true},+ {name: "cleanup after reply budget", eventType: protocol.EventChatDone, payload: protocol.ChatDonePayload{Content: "answer"}, cancelOnRecall: true, wantReply: true},+ {name: "input lookup failure", eventType: protocol.EventChatDone, payload: protocol.ChatDonePayload{Content: "answer"}, inputUnavailable: true, wantReply: true, keepActive: true},+ {name: "failed delivery", eventType: protocol.EventChatDone, payload: protocol.ChatDonePayload{Content: "answer"}, sendFails: true, wantReply: true},+ {name: "cancelled", eventType: protocol.EventTaskCancelled},+ {name: "empty completion", eventType: protocol.EventChatDone, payload: protocol.ChatDonePayload{}},+ {name: "empty failure", eventType: protocol.EventTaskFailed, payload: map[string]any{"retry_pending": false}},+ {name: "retry pending", eventType: protocol.EventTaskFailed, payload: map[string]any{"error": "must remain private", "retry_pending": true}, keepActive: true},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ var actions []string+ client := NewClient(&http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ body, status := `{"accessToken":"token","expireIn":7200}`, http.StatusOK+ if r.URL.Path == pathSendGroup {+ actions = append(actions, "reply")+ body = `{"processQueryKey":"sent"}`+ if tc.sendFails {+ status = http.StatusInternalServerError+ body = `{"code":"failed","message":"test failure"}`+ }+ }+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil+ })}, "https://dingtalk.test")+ config, err := json.Marshal(installConfig{AppID: "app", RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ sid, taskID := sessionUUID(45), sessionUUID(46)+ q := deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: string(TypeDingTalk), ChannelChatID: "conversation", ChatType: string(channel.ChatTypeGroup), ChannelMessageID: pgtype.Text{String: "source", Valid: true}},+ installation: db.ChannelInstallation{ID: sessionUUID(47), Status: "active", Config: config},+ input: []db.ChatMessage{{ID: sessionUUID(48), ChannelIngested: true, Content: "question"}},+ task: db.AgentTaskQueue{ChatInputTaskID: taskID}, channelIngested: true,+ }+ if tc.inputUnavailable {+ q.inputErr = errors.New("input lookup unavailable")+ }+ ack := NewAckNotifier(client, nil, nil, nil)+ client.rememberReplySource(q.installation.ID, sessionUUID(48), sid, groupReactionMessage("source"))+ ack.sendReaction = func(reactionCtx context.Context, _ engine.ResolvedInstallation, msg channel.InboundMessage, name string, recall bool) error {+ if tc.cancelOnRecall && recall {+ cancel()+ }+ if name == emotionDone && reactionCtx.Err() != nil {+ return reactionCtx.Err()+ }+ verb := "add:"+ if recall {+ verb = "recall:"+ }+ actions = append(actions, verb+msg.MessageID+":"+name)+ return nil+ }+ ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid)+ o := NewOutbound(q, nil, client, ack, nil)+ err = o.processEvent(ctx, events.Event{Type: tc.eventType, TaskID: util.UUIDToString(taskID), ChatSessionID: util.UUIDToString(sid), Payload: tc.payload})+ if (err != nil) != tc.sendFails {+ t.Fatalf("processEvent error = %v, want send failure=%v", err, tc.sendFails)+ }+ want := []string{"add:source:" + emotionAcknowledged}+ if tc.wantReply {+ want = append(want, "reply")+ }+ if !tc.keepActive {+ want = append(want, "recall:source:"+emotionAcknowledged)+ }+ if tc.wantDone {+ want = append(want, "add:source:"+emotionDone)+ }+ if !slices.Equal(actions, want) {+ t.Fatalf("lifecycle actions = %v, want %v", actions, want)+ }+ if (len(ack.active) != 0) != tc.keepActive {+ t.Fatalf("active reactions = %d, keep=%v", len(ack.active), tc.keepActive)+ }+ })+ }+}++func TestOutboundTerminalWithoutDeliverySettlesOnlyOwnedInput(t *testing.T) {+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskFailed, protocol.EventTaskCancelled} {+ t.Run(eventType, func(t *testing.T) {+ ack, actions := newTestAckWithMessageIDs(time.Now)+ sid := sessionUUID(61)+ inst := engine.ResolvedInstallation{ID: sessionUUID(9)}+ for i, name := range []string{"a", "b", "other"} {+ ack.client.rememberReplySource(inst.ID, sessionUUID(byte(70+i)), sid, groupReactionMessage(name))+ }+ ack.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ ack.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ ack.OnIngested(context.Background(), inst, groupReactionMessage("other"), sessionUUID(62))+ q := missingDeliveryInputQueries{deliveryOnlyOutboundQueries{+ task: db.AgentTaskQueue{ChatInputTaskID: sessionUUID(63)},+ input: []db.ChatMessage{{ID: sessionUUID(70), ChannelIngested: true}},+ }}+ o := NewOutbound(q, nil, nil, ack, nil)+ bus := events.New()+ o.Register(bus)+ bus.Publish(events.Event{Type: eventType, TaskID: util.UUIDToString(sessionUUID(63)), ChatSessionID: util.UUIDToString(sid)})+ want := []string{"add:a:" + emotionAcknowledged, "add:b:" + emotionAcknowledged, "add:other:" + emotionAcknowledged, "recall:a:" + emotionAcknowledged}+ if !slices.Equal(*actions, want) {+ t.Fatalf("actions=%v want=%v", *actions, want)+ }+ })+ }+}++func TestOutboundPartialReplyFailureDoesNotMarkDone(t *testing.T) {+ var sends int+ client := NewClient(&http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {+ body, status := `{"accessToken":"token","expireIn":7200}`, http.StatusOK+ if r.URL.Path == pathSendGroup {+ sends+++ body = `{"processQueryKey":"sent"}`+ if sends == 2 {+ status = http.StatusInternalServerError+ body = `{}`+ }+ }+ return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil+ })}, "https://dingtalk.test")+ config, err := json.Marshal(installConfig{AppID: "app", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ sid, tid := sessionUUID(64), sessionUUID(65)+ q := deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: string(TypeDingTalk), ChannelChatID: "group", ChannelMessageID: nullText("source")},+ installation: db.ChannelInstallation{ID: sessionUUID(66), Status: "active", Config: config}, task: db.AgentTaskQueue{ChatInputTaskID: tid}, channelIngested: true,+ input: []db.ChatMessage{{ID: sessionUUID(67), ChannelIngested: true, Content: "question"}},+ }+ ack, actions := newTestAckWithMessageIDs(time.Now)+ ack.client.rememberReplySource(q.installation.ID, q.input[0].ID, sid, groupReactionMessage("source"))+ ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid)+ err = NewOutbound(q, nil, client, ack, nil).processEvent(context.Background(), events.Event{+ Type: protocol.EventChatDone, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid), Payload: protocol.ChatDonePayload{Content: strings.Repeat("answer\n", 6000)},+ })+ if err == nil || sends != 2 {+ t.Fatalf("sends=%d error=%v", sends, err)+ }+ if !slices.Equal(*actions, []string{"add:source:" + emotionAcknowledged, "recall:source:" + emotionAcknowledged}) {+ t.Fatalf("partial reply marked complete: %v", *actions)+ }+}diff --git a/server/internal/integrations/dingtalk/reaction_interest_test.go b/server/internal/integrations/dingtalk/reaction_interest_test.gonew file mode 100644index 0000000000..ff43561edf--- /dev/null+++ b/server/internal/integrations/dingtalk/reaction_interest_test.go@@ -0,0 +1,348 @@+package dingtalk++import (+ "context"+ "errors"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type countedTerminalQueries struct {+ deliveryOnlyOutboundQueries+ deliveryReads, taskReads, inputReads int+ deliveryErr error+}++func (q *countedTerminalQueries) GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error) {+ q.deliveryReads+++ return q.delivery, q.deliveryErr+}+func (q *countedTerminalQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {+ q.taskReads+++ return q.task, nil+}+func (q *countedTerminalQueries) ListChatInputMessages(context.Context, pgtype.UUID) ([]db.ChatMessage, error) {+ q.inputReads+++ return q.input, q.inputErr+}++func TestOutboundUnrelatedSessionsDoNotReadReactionInputs(t *testing.T) {+ for _, kind := range []string{"slack", "lark", "wecom", "telegram", "web"} {+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskFailed, protocol.EventTaskCancelled} {+ t.Run(kind+"/"+eventType, func(t *testing.T) {+ q := &countedTerminalQueries{deliveryOnlyOutboundQueries: deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: kind},+ task: db.AgentTaskQueue{ChatInputTaskID: sessionUUID(3)},+ }}+ if kind == "web" {+ q.deliveryErr = pgx.ErrNoRows+ }+ n := NewAckNotifier(nil, nil, nil, nil)+ // Another DingTalk session must not make the gate process-wide.+ n.client.rememberReplySource(sessionUUID(5), sessionUUID(6), sessionUUID(7), groupReactionMessage("other"))+ event := events.Event{Type: eventType, TaskID: util.UUIDToString(sessionUUID(1)), ChatSessionID: util.UUIDToString(sessionUUID(2)), Payload: map[string]any{"content": "answer", "error": "failed"}}+ if eventType == protocol.EventTaskCancelled {+ event.Payload = nil+ }+ if err := NewOutbound(q, nil, n.client, n, nil).processEvent(context.Background(), event); err != nil {+ t.Fatal(err)+ }+ wantDelivery := 1+ if eventType == protocol.EventTaskCancelled {+ wantDelivery = 0+ }+ if q.deliveryReads != wantDelivery || q.taskReads != 0 || q.inputReads != 0 {+ t.Fatalf("unrelated channel paid reaction queries: delivery=%d task=%d input=%d", q.deliveryReads, q.taskReads, q.inputReads)+ }+ })+ }+ }+}++type interestChatSession struct {+ captureChatSession+ duringCommit func()+}++func (c *interestChatSession) AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error) {+ c.duringCommit()+ return c.captureChatSession.AppendUserMessage(ctx, in)+}+func (c *interestChatSession) StartSession(ctx context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {+ if in.BeforeCommit != nil {+ if err := in.BeforeCommit(ctx, nil, db.ChatSession{ID: c.startResult.SessionID}); err != nil {+ return engine.StartSessionResult{}, err+ }+ }+ c.duringCommit()+ return c.startResult, c.ensureErr+}++func TestTerminalBeforeSourceCaptureFencesLateReaction(t *testing.T) {+ for _, entry := range []string{"append", "start"} {+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskFailed, protocol.EventTaskCancelled} {+ t.Run(entry+"/"+eventType, func(t *testing.T) {+ sid, tid, inputID := sessionUUID(10), sessionUUID(11), sessionUUID(12)+ inst := engine.ResolvedInstallation{ID: sessionUUID(13)}+ msg := groupReactionMessage("source")+ row := db.ChatMessage{ID: inputID, ChatSessionID: sid, TaskID: tid, Role: "user", ChannelIngested: true}+ n := NewAckNotifier(nil, nil, nil, &ackInputQueries{rows: map[pgtype.UUID]db.ChatMessage{inputID: row}})+ q := &countedTerminalQueries{deliveryOnlyOutboundQueries: deliveryOnlyOutboundQueries{+ task: db.AgentTaskQueue{ChatInputTaskID: tid, ChatSessionID: sid}, input: []db.ChatMessage{row},+ }}+ o := NewOutbound(q, nil, n.client, n, nil)+ capture := &interestChatSession{captureChatSession: captureChatSession{+ appendResult: engine.AppendResult{MessageID: inputID},+ startResult: engine.StartSessionResult{SessionID: sid, Append: engine.AppendResult{MessageID: inputID}},+ }}+ capture.duringCommit = func() {+ if _, ok := n.client.replySourceFor(inst.ID, inputID); ok {+ t.Fatal("source captured before simulated commit")+ }+ if !n.client.hasReplySession(sid) {+ t.Fatal("input visible without local interest")+ }+ if err := o.processEvent(context.Background(), events.Event{Type: eventType, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid)}); err != nil {+ t.Fatal(err)+ }+ }+ binder := &sessionBinder{session: capture, replies: n.client}+ if entry == "append" {+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{SessionID: sid, InstallationID: inst.ID, Message: msg}); err != nil {+ t.Fatal(err)+ }+ } else {+ callbackRan := false+ _, err := binder.StartSession(context.Background(), engine.StartSessionParams{Installation: inst, Message: msg, PersistMessage: true, BeforeCommit: func(context.Context, pgx.Tx, db.ChatSession) error { callbackRan = true; return nil }})+ if err != nil || !callbackRan {+ t.Fatalf("start callback: ran=%v err=%v", callbackRan, err)+ }+ }+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ t.Fatal("late callback recreated terminal reaction")+ return nil+ }+ n.OnIngested(context.Background(), inst, msg, sid)+ if q.taskReads != 1 || q.inputReads != 1 || len(n.active) != 0 {+ t.Fatalf("terminal fence not exercised: task=%d input=%d active=%v", q.taskReads, q.inputReads, n.active)+ }+ })+ }+ }+}++func TestReplySessionReferencesReleaseOnFailureAndEviction(t *testing.T) {+ client := NewClient(nil, "")+ sid, inst := sessionUUID(20), sessionUUID(21)+ first := client.beginReplyInput(sid)+ second := client.beginReplyInput(sid)+ first()+ if !client.hasReplySession(sid) {+ t.Fatal("one failed append hid overlapping input")+ }+ second()+ if client.hasReplySession(sid) {+ t.Fatal("failed appends leaked interest")+ }+ client.rememberReplySource(inst, sessionUUID(22), sid, groupReactionMessage("accepted"))+ release := client.beginReplyInput(sid)+ for i := 0; i < maxReplySources; i++ {+ client.rememberReplySource(inst, dbid.NewV7(), sessionUUID(23), groupReactionMessage("other"))+ }+ if !client.hasReplySession(sid) {+ t.Fatal("eviction hid in-flight input")+ }+ release()+ if client.hasReplySession(sid) || len(client.sources.sessions) != 1 {+ t.Fatal("evicted sources leaked session index")+ }+}++func TestReplyInputFailureReleasesInterest(t *testing.T) {+ for _, entry := range []string{"append", "start", "start callback"} {+ t.Run(entry, func(t *testing.T) {+ client := NewClient(nil, "")+ sid := sessionUUID(30)+ wantErr := errors.New("transaction failed")+ capture := &interestChatSession{captureChatSession: captureChatSession{appendErr: wantErr, ensureErr: wantErr, startResult: engine.StartSessionResult{SessionID: sid}}, duringCommit: func() {+ if !client.hasReplySession(sid) {+ t.Fatal("missing pending interest")+ }+ }}+ binder := &sessionBinder{session: capture, replies: client}+ var err error+ if entry == "append" {+ _, err = binder.AppendMessage(context.Background(), engine.AppendParams{SessionID: sid})+ } else {+ p := engine.StartSessionParams{PersistMessage: true}+ if entry == "start callback" {+ p.BeforeCommit = func(context.Context, pgx.Tx, db.ChatSession) error { return wantErr }+ }+ _, err = binder.StartSession(context.Background(), p)+ }+ if !errors.Is(err, wantErr) || client.hasReplySession(sid) {+ t.Fatalf("failed transaction leaked interest: %v", err)+ }+ })+ }+}++func TestOutboundReusesSuccessfulInputReadsForSettlement(t *testing.T) {+ for _, tc := range []struct {+ name string+ empty, failed bool+ wantReads int+ }{+ {name: "owned input", wantReads: 1}, {name: "empty sealed batch", empty: true, wantReads: 1}, {name: "failed read retried for cleanup", failed: true, wantReads: 2},+ } {+ t.Run(tc.name, func(t *testing.T) {+ sid, tid, id := sessionUUID(40), sessionUUID(41), sessionUUID(42)+ q := &countedTerminalQueries{deliveryOnlyOutboundQueries: deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: string(TypeDingTalk)},+ task: db.AgentTaskQueue{ChatSessionID: sid, ChatInputTaskID: tid}, channelIngested: true,+ input: []db.ChatMessage{{ID: id, ChannelIngested: true}},+ }}+ if tc.empty {+ q.input = nil+ }+ if tc.failed {+ q.inputErr = errors.New("input unavailable")+ }+ n := NewAckNotifier(nil, nil, nil, nil)+ n.client.rememberReplySource(sessionUUID(43), id, sid, groupReactionMessage("source"))+ o := NewOutbound(q, nil, n.client, n, nil)+ err := o.processEvent(context.Background(), events.Event{Type: protocol.EventChatDone, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid), Payload: protocol.ChatDonePayload{Content: "answer"}})+ if err != nil || q.taskReads != 1 || q.inputReads != tc.wantReads {+ t.Fatalf("reads: task=%d input=%d err=%v", q.taskReads, q.inputReads, err)+ }+ if n.settledInputs[id] == (tc.empty || tc.failed) {+ t.Fatal("successful sealed batch was not fenced, or failed/empty input invented a fence")+ }+ })+ }+}++func TestActiveReceiptRemainsDiscoverableAfterSourceEviction(t *testing.T) {+ n := NewAckNotifier(nil, nil, nil, nil)+ sid, tid, id := sessionUUID(50), sessionUUID(51), sessionUUID(52)+ inst := engine.ResolvedInstallation{ID: sessionUUID(53)}+ msg := groupReactionMessage("source")+ adds, recalls := 0, 0+ n.sendReaction = func(_ context.Context, _ engine.ResolvedInstallation, _ channel.InboundMessage, _ string, recall bool) error {+ if recall {+ recalls+++ } else {+ adds+++ }+ return nil+ }+ n.client.rememberReplySource(inst.ID, id, sid, msg)+ n.OnIngested(context.Background(), inst, msg, sid)+ for i := 0; i < maxReplySources; i++ {+ n.client.rememberReplySource(inst.ID, dbid.NewV7(), sessionUUID(54), groupReactionMessage("other"))+ }+ if n.client.hasReplySession(sid) {+ t.Fatal("test did not evict source session")+ }+ q := &countedTerminalQueries{deliveryOnlyOutboundQueries: deliveryOnlyOutboundQueries{task: db.AgentTaskQueue{ChatSessionID: sid, ChatInputTaskID: tid}, input: []db.ChatMessage{{ID: id, ChannelIngested: true}}}}+ err := NewOutbound(q, nil, n.client, n, nil).processEvent(context.Background(), events.Event{Type: protocol.EventTaskCancelled, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid)})+ if err != nil || adds != 1 || recalls != 1 || len(n.active) != 0 {+ t.Fatalf("evicted source hid active cleanup: adds=%d recalls=%d err=%v", adds, recalls, err)+ }+}++func TestIngestKeepsTerminalInterestAcrossSourceEviction(t *testing.T) {+ sid, tid, id := sessionUUID(60), sessionUUID(61), sessionUUID(62)+ inst := engine.ResolvedInstallation{ID: sessionUUID(63)}+ row := db.ChatMessage{ID: id, ChatSessionID: sid, TaskID: tid, Role: "user", ChannelIngested: true}+ iq := &ackInputQueries{rows: map[pgtype.UUID]db.ChatMessage{id: row}}+ n := NewAckNotifier(nil, nil, nil, iq)+ msg := groupReactionMessage("source")+ n.client.rememberReplySource(inst.ID, id, sid, msg)+ q := &countedTerminalQueries{deliveryOnlyOutboundQueries: deliveryOnlyOutboundQueries{task: db.AgentTaskQueue{ChatSessionID: sid, ChatInputTaskID: tid}, input: []db.ChatMessage{row}}}+ reads := 0+ iq.read = func(pgtype.UUID) {+ reads+++ if reads != 1 {+ return+ }+ for i := 0; i < maxReplySources; i++ {+ n.client.rememberReplySource(inst.ID, dbid.NewV7(), sessionUUID(64), groupReactionMessage("other"))+ }+ if _, ok := n.client.replySourceFor(inst.ID, id); ok {+ t.Fatal("test did not evict source")+ }+ err := NewOutbound(q, nil, n.client, n, nil).processEvent(context.Background(), events.Event{Type: protocol.EventTaskCancelled, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid)})+ if err != nil {+ t.Fatal(err)+ }+ }+ n.sendReaction = func(context.Context, engine.ResolvedInstallation, channel.InboundMessage, string, bool) error {+ t.Fatal("eviction allowed terminal reaction to reappear")+ return nil+ }+ n.OnIngested(context.Background(), inst, msg, sid)+ if q.inputReads != 1 || len(n.active) != 0 || n.client.hasReplySession(sid) {+ t.Fatal("in-flight interest was lost or leaked")+ }+}++func TestReplyInterestDuplicateCaptureReleasesOnEviction(t *testing.T) {+ client := NewClient(nil, "")+ inst, input, sid := sessionUUID(70), sessionUUID(71), sessionUUID(72)+ msg := groupReactionMessage("source")+ client.rememberReplySource(inst, input, sid, msg)+ client.rememberReplySource(inst, input, sid, msg)+ for i := 0; i < maxReplySources; i++ {+ client.rememberReplySource(inst, dbid.NewV7(), sessionUUID(73), groupReactionMessage("other"))+ }+ if client.hasReplySession(sid) {+ t.Fatal("duplicate capture leaked session interest after source eviction")+ }+}++func TestReplyInterestAbsentClientAndSessionAreNoOps(t *testing.T) {+ var absent *Client+ absent.beginReplyInput(sessionUUID(74))()+ if absent.hasReplySession(sessionUUID(74)) {+ t.Fatal("absent client has reaction interest")+ }+ client := NewClient(nil, "")+ client.beginReplyInput(pgtype.UUID{})()+ client.rememberReplySource(sessionUUID(75), sessionUUID(76), pgtype.UUID{}, groupReactionMessage("source"))+ if client.hasReplySession(pgtype.UUID{}) || len(client.sources.sessions) != 0 {+ t.Fatal("invalid session created reaction interest")+ }+}++func TestStartWithoutInputPreservesCallbackWithoutInterest(t *testing.T) {+ client := NewClient(nil, "")+ sid := sessionUUID(77)+ capture := &interestChatSession{captureChatSession: captureChatSession{+ startResult: engine.StartSessionResult{SessionID: sid},+ }, duringCommit: func() {+ if client.hasReplySession(sid) {+ t.Fatal("empty start registered reaction interest")+ }+ }}+ callbackRan := false+ binder := &sessionBinder{session: capture, replies: client}+ _, err := binder.StartSession(context.Background(), engine.StartSessionParams{+ BeforeCommit: func(context.Context, pgx.Tx, db.ChatSession) error {+ callbackRan = true+ return nil+ },+ })+ if err != nil || !callbackRan || client.hasReplySession(sid) || len(client.sources.entries) != 0 {+ t.Fatalf("empty start changed callback or retained reaction state: callback=%v err=%v", callbackRan, err)+ }+}diff --git a/server/internal/integrations/dingtalk/replier.go b/server/internal/integrations/dingtalk/replier.goindex c648fa99e9..e7b467913e 100644--- a/server/internal/integrations/dingtalk/replier.go+++ b/server/internal/integrations/dingtalk/replier.go@@ -108,6 +108,14 @@ func NewOutboundReplier(cfg OutboundReplierConfig) *OutboundReplier {// Reply routes each outcome to its user-visible message. Errors are logged, not// propagated: the replier runs detached from the inbound ACK path.func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, res engine.Result) {+ // These notices may refer to recovered pending input. The live callback can+ // belong to another generation, so use only its stable conversation route.+ if res.Outcome == engine.OutcomeAgentOffline || res.Outcome == engine.OutcomeAgentArchived {+ msg = channel.InboundMessage{Source: msg.Source}+ if msg.Source.ChatType == channel.ChatTypeGroup {+ msg.Source.SenderID = ""+ }+ }switch res.Outcome {case engine.OutcomeNeedsBinding:if err := r.sendBindingPrompt(ctx, inst, msg, res); err != nil {@@ -144,9 +152,9 @@ func (r *OutboundReplier) Reply(ctx context.Context, inst engine.ResolvedInstall}case engine.OutcomeIngested:if res.IssueID.Valid {- text := issueCreatedText(res)+ text := issueCreatedText(res, r.appURL)if res.IssueDuplicate {- text = issueDuplicateText(res)+ text = issueDuplicateText(res, r.appURL)}if err := r.post(ctx, inst, msg, text); err != nil {r.logger.WarnContext(ctx, "dingtalk replier: issue outcome reply failed",@@ -227,7 +235,28 @@ func sendInstallationText(ctx context.Context, client *Client, decrypt Decrypter// routing identity (used for the immediate binding/status replies, before any// chat binding exists).func targetFromMessage(msg channel.InboundMessage) sendTarget {- t := sendTarget{ConversationType: convTypeGroup, ConversationID: msg.Source.ChatID}+ t := sendTarget{+ ConversationType: convTypeGroup,+ ConversationID: msg.Source.ChatID,+ QuoteText: dingtalkVisibleQuoteText(msg),+ }+ if msg.Source.ChatType == channel.ChatTypeP2P {+ t.ConversationType = convTypeP2P+ t.StaffID = msg.Source.SenderID+ t.QuoteText = ""+ }+ return t+}++// reactionTargetFromMessage addresses the source message itself. DingTalk's+// built-in emoji reactions support both group and 1:1 messages and only need+// the callback's conversation and message IDs.+func reactionTargetFromMessage(msg channel.InboundMessage) sendTarget {+ t := sendTarget{+ ConversationType: convTypeGroup,+ ConversationID: msg.Source.ChatID,+ SourceMessageID: msg.MessageID,+ }if msg.Source.ChatType == channel.ChatTypeP2P {t.ConversationType = convTypeP2Pt.StaffID = msg.Source.SenderID@@ -266,22 +295,42 @@ func droppedReplyText(res engine.Result, msg channel.InboundMessage) string {}}-func issueCreatedText(res engine.Result) string {- identifier := issueResultIdentifier(res)+func issueCreatedText(res engine.Result, appURL string) string {+ identifier := issueMarkdownIdentifier(res, appURL)if res.IssueTitle == "" {return "✅ Created " + identifier}return "✅ Created " + identifier + " — " + res.IssueTitle}-func issueDuplicateText(res engine.Result) string {- identifier := issueResultIdentifier(res)+func issueDuplicateText(res engine.Result, appURL string) string {+ identifier := issueMarkdownIdentifier(res, appURL)if res.IssueTitle == "" {return "⚠️ Not created — active issue " + identifier + " already exists."}return "⚠️ Not created — active issue " + identifier + " already exists: " + res.IssueTitle}+// Link the displayed issue key to its stable UUID within the installation's+// workspace. Legacy /issues/{key} URLs depend on the reader's last workspace,+// and a bare #number is not a routable issue identifier.+func issueMarkdownIdentifier(res engine.Result, appURL string) string {+ identifier := issueResultIdentifier(res)+ workspaceSlug := strings.TrimSpace(res.IssueWorkspaceSlug)+ if !res.IssueID.Valid || workspaceSlug == "" {+ return identifier+ }+ base, err := url.Parse(strings.TrimSpace(appURL))+ if err != nil || (base.Scheme != "https" && base.Scheme != "http") || base.Hostname() == "" || base.User != nil || base.RawQuery != "" || base.Fragment != "" {+ return identifier+ }+ href := channel.IssueWebLink(base.String(), workspaceSlug, util.UUIDToString(res.IssueID))+ // Parentheses in an application's base path must not terminate the Markdown+ // link destination, even when they are valid URL path characters.+ href = strings.NewReplacer("(", "%28", ")", "%29").Replace(href)+ return "[" + escapeMarkdownText(identifier) + "](" + href + ")"+}+func issueResultIdentifier(res engine.Result) string {if res.IssueIdentifier != "" {return res.IssueIdentifierdiff --git a/server/internal/integrations/dingtalk/replier_links_test.go b/server/internal/integrations/dingtalk/replier_links_test.gonew file mode 100644index 0000000000..d078ff4561--- /dev/null+++ b/server/internal/integrations/dingtalk/replier_links_test.go@@ -0,0 +1,85 @@+package dingtalk++import (+ "context"+ "encoding/base64"+ "encoding/json"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestIssueMarkdownIdentifierUsesWorkspaceAndStableID(t *testing.T) {+ const id = "11111111-2222-4333-8444-555555555555"+ issueID, err := util.ParseUUID(id)+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ name, base, slug, key string+ number int32+ missingID bool+ want string+ }{+ {name: "identifier", base: "https://multica.example/", slug: "team-b", key: "ALHE-6", want: "[ALHE\\-6](https://multica.example/team-b/issues/" + id + ")"},+ {name: "number uses UUID target", base: "https://multica.example", slug: "team-b", number: 6, want: "[\\#6](https://multica.example/team-b/issues/" + id + ")"},+ {name: "UUID display fallback", base: "https://multica.example", slug: "team-b", want: "[11111111\\-2222\\-4333\\-8444\\-555555555555](https://multica.example/team-b/issues/" + id + ")"},+ {name: "local app", base: "http://localhost:3000", slug: "team-b", key: "ALHE-6", want: "[ALHE\\-6](http://localhost:3000/team-b/issues/" + id + ")"},+ {name: "base path", base: " https://multica.example/apps/multica/ ", slug: "team-b", key: "ALHE-6", want: "[ALHE\\-6](https://multica.example/apps/multica/team-b/issues/" + id + ")"},+ {name: "parentheses in base path", base: "https://multica.example/apps/(dev)", slug: "team-b", key: "ALHE-6", want: "[ALHE\\-6](https://multica.example/apps/%28dev%29/team-b/issues/" + id + ")"},+ {name: "missing base", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "invalid base", base: "https://[", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "missing scheme", base: "multica.example", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "unsupported scheme", base: "javascript:alert(1)", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "missing host", base: "https:///app", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "credentials", base: "https://user:[email protected]", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "query", base: "https://multica.example?token=private", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "fragment", base: "https://multica.example#other", slug: "team-b", key: "ALHE-6", want: "ALHE-6"},+ {name: "missing workspace", base: "https://multica.example", key: "ALHE-6", want: "ALHE-6"},+ {name: "missing issue ID", base: "https://multica.example", slug: "team-b", key: "ALHE-6", missingID: true, want: "ALHE-6"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ res := engine.Result{IssueID: issueID, IssueIdentifier: tc.key, IssueWorkspaceSlug: tc.slug, IssueNumber: tc.number}+ if tc.missingID {+ res.IssueID = pgtype.UUID{}+ }+ if got := issueMarkdownIdentifier(res, tc.base); got != tc.want {+ t.Fatalf("identifier = %q, want %q", got, tc.want)+ }+ })+ }+}++func TestReplierMissingIssueLinkConfigStillConfirms(t *testing.T) {+ for _, tc := range []struct{ name, appURL, slug string }{+ {"missing app URL", "", "team-b"},+ {"missing result workspace slug", "https://multica.example", ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ config, err := json.Marshal(installConfig{AppID: "app", RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ inst := engine.ResolvedInstallation{Platform: db.ChannelInstallation{Config: config}}+ r := NewOutboundReplier(OutboundReplierConfig{Client: NewClient(nil, d.srv.URL), AppURL: tc.appURL})+ msg := channel.InboundMessage{Source: channel.Source{ChannelType: TypeDingTalk, ChatType: channel.ChatTypeGroup, ChatID: "conversation"}}+ r.Reply(context.Background(), inst, msg, engine.Result{Outcome: engine.OutcomeIngested, IssueID: pgtype.UUID{Valid: true}, IssueIdentifier: "ALHE-6", IssueTitle: "1+1=?", IssueWorkspaceSlug: tc.slug})+ if len(d.sendBodies) != 1 || d.lastPath != pathSendGroup {+ t.Fatalf("sends=%d path=%q", len(d.sendBodies), d.lastPath)+ }+ var got markdownParam+ if err := json.Unmarshal([]byte(d.lastBody["msgParam"].(string)), &got); err != nil {+ t.Fatal(err)+ }+ if got.Text != "✅ Created ALHE-6 — 1+1=?" {+ t.Fatalf("confirmation = %q", got.Text)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/replier_test.go b/server/internal/integrations/dingtalk/replier_test.goindex eb39f903f0..0cdccfccc8 100644--- a/server/internal/integrations/dingtalk/replier_test.go+++ b/server/internal/integrations/dingtalk/replier_test.go@@ -1,20 +1,25 @@package dingtalkimport (+ "context"+ "encoding/base64"+ "encoding/json"+ "strings""testing""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ db "github.com/multica-ai/multica/server/pkg/db/generated")func TestIssueCreatedText(t *testing.T) {issueID := pgtype.UUID{Valid: true}- if got := issueCreatedText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-42", IssueTitle: "Fix login"}); got != "✅ Created MUL-42 — Fix login" {+ if got := issueCreatedText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-42", IssueTitle: "Fix login"}, ""); got != "✅ Created MUL-42 — Fix login" {t.Fatalf("got %q", got)}- if got := issueCreatedText(engine.Result{IssueID: issueID, IssueNumber: 7}); got != "✅ Created #7" {+ if got := issueCreatedText(engine.Result{IssueID: issueID, IssueNumber: 7}, ""); got != "✅ Created #7" {t.Fatalf("fallback got %q", got)}}@@ -23,7 +28,7 @@ func TestIssueDuplicateText(t *testing.T) {issueID := pgtype.UUID{Bytes: [16]byte{9}, Valid: true}got := issueDuplicateText(engine.Result{IssueID: issueID, IssueIdentifier: "MUL-42", IssueTitle: "Fix login", IssueDuplicate: true,- })+ }, "")if got != "⚠️ Not created — active issue MUL-42 already exists: Fix login" {t.Fatalf("duplicate text = %q", got)}@@ -61,3 +66,115 @@ func TestDroppedReplyText(t *testing.T) {})}}++func TestReplierCommandConfirmationsKeepSuccessMarker(t *testing.T) {+ config, err := json.Marshal(installConfig{AppID: "app", RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ inst := engine.ResolvedInstallation{WorkspaceID: pgtype.UUID{Bytes: [16]byte{42}, Valid: true}, Platform: db.ChannelInstallation{Config: config}}+ for _, tc := range []struct {+ name, text string+ result engine.Result+ success bool+ plainReply bool+ }{+ {name: "clear", result: engine.Result{Outcome: engine.OutcomeFreshPending}, text: "Fresh start ready. Your next chat message will run without previous context.", success: true},+ {name: "new", result: engine.Result{Outcome: engine.OutcomeChatStarted}, text: "Started a new Multica chat. Your next message will enter it.", success: true},+ {name: "issue", result: engine.Result{Outcome: engine.OutcomeIngested, IssueID: pgtype.UUID{Valid: true}, IssueWorkspaceSlug: "team-b", IssueIdentifier: "MUL-42", IssueTitle: "✅ Keep this title"}, text: "Created [MUL\\-42](https://multica.example/team-b/issues/00000000-0000-0000-0000-000000000000) — ✅ Keep this title", success: true},+ {name: "issue without title", result: engine.Result{Outcome: engine.OutcomeIngested, IssueID: pgtype.UUID{Valid: true}, IssueWorkspaceSlug: "team-b", IssueNumber: 7}, text: "Created [\\#7](https://multica.example/team-b/issues/00000000-0000-0000-0000-000000000000)", success: true},+ {name: "duplicate issue", result: engine.Result{Outcome: engine.OutcomeIngested, IssueID: pgtype.UUID{Valid: true}, IssueWorkspaceSlug: "team-b", IssueIdentifier: "MUL-42", IssueTitle: "✅ Keep this title", IssueDuplicate: true}, text: "⚠️ Not created — active issue [MUL\\-42](https://multica.example/team-b/issues/00000000-0000-0000-0000-000000000000) already exists: ✅ Keep this title"},+ {name: "offline", result: engine.Result{Outcome: engine.OutcomeAgentOffline}, text: "⚠️ The agent is offline, so this message won't be processed automatically."},+ {name: "ordinary reply", text: "✅ Keep this reply", plainReply: true},+ } {+ for _, route := range []struct {+ name string+ chatType channel.ChatType+ path string+ }{+ {name: "group proactive", chatType: channel.ChatTypeGroup, path: pathSendGroup},+ {name: "private", chatType: channel.ChatTypeP2P, path: pathSendP2P},+ } {+ t.Run(tc.name+"/"+route.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ msg := channel.InboundMessage{+ Source: channel.Source{ChannelType: TypeDingTalk, ChatType: route.chatType, ChatID: "conversation", SenderID: "staff"},+ Text: "✅ Keep this quote",+ }+ r := NewOutboundReplier(OutboundReplierConfig{+ Client: NewClient(nil, d.srv.URL), AppURL: "https://multica.example",+ })+ if tc.plainReply {+ if err := r.post(context.Background(), inst, msg, tc.text); err != nil {+ t.Fatal(err)+ }+ } else {+ r.Reply(context.Background(), inst, msg, tc.result)+ }+ if len(d.sendBodies) != 1 || d.lastPath != route.path {+ t.Fatalf("sent %d messages to %q, want one to %q", len(d.sendBodies), d.lastPath, route.path)+ }+ var got markdownParam+ if err := json.Unmarshal([]byte(d.lastBody["msgParam"].(string)), &got); err != nil {+ t.Fatal(err)+ }+ want := tc.text+ if tc.success {+ want = "✅ " + want+ }+ if route.chatType != channel.ChatTypeP2P {+ if tc.result.Outcome != engine.OutcomeAgentOffline && tc.result.Outcome != engine.OutcomeAgentArchived {+ want = "> ✅ Keep this quote\n\n---\n\n" + want+ }+ }+ if got.Text != want {+ t.Fatalf("reply = %q, want %q", got.Text, want)+ }+ })+ }+ }+}++func TestReplierRecoveredGenerationUsesOnlyStableRoute(t *testing.T) {+ for _, tc := range []struct {+ name string+ chatType channel.ChatType+ outcome engine.Outcome+ path string+ }{+ {"group offline", channel.ChatTypeGroup, engine.OutcomeAgentOffline, pathSendGroup},+ {"direct archived", channel.ChatTypeP2P, engine.OutcomeAgentArchived, pathSendP2P},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ config, err := json.Marshal(installConfig{AppID: "app", RobotCode: "robot", AppSecretEncrypted: base64.StdEncoding.EncodeToString([]byte("secret"))})+ if err != nil {+ t.Fatal(err)+ }+ msg := channel.InboundMessage{Source: channel.Source{ChannelType: TypeDingTalk, ChatType: tc.chatType, ChatID: "stable-conversation"}}+ if tc.chatType == channel.ChatTypeP2P {+ msg.Source.SenderID = "stable-recipient"+ }+ r := NewOutboundReplier(OutboundReplierConfig{Client: NewClient(nil, d.srv.URL)})+ r.Reply(context.Background(), engine.ResolvedInstallation{Platform: db.ChannelInstallation{Config: config}}, msg, engine.Result{Outcome: tc.outcome})+ if d.lastPath != tc.path {+ t.Fatalf("path=%q, want %q", d.lastPath, tc.path)+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(d.lastBody["msgParam"].(string)), ¶m); err != nil {+ t.Fatal(err)+ }+ if strings.Contains(param.Text, "> ") || strings.Contains(param.Text, "@") || d.lastBody["at"] != nil {+ t.Fatalf("recovered notice gained live-message targeting: %v", d.lastBody)+ }+ if tc.chatType == channel.ChatTypeP2P {+ ids, _ := d.lastBody["userIds"].([]any)+ if len(ids) != 1 || ids[0] != "stable-recipient" {+ t.Fatalf("recipient=%v", ids)+ }+ } else if d.lastBody["openConversationId"] != "stable-conversation" {+ t.Fatalf("conversation=%v", d.lastBody["openConversationId"])+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/reply_boundaries_test.go b/server/internal/integrations/dingtalk/reply_boundaries_test.gonew file mode 100644index 0000000000..695ccdbb02--- /dev/null+++ b/server/internal/integrations/dingtalk/reply_boundaries_test.go@@ -0,0 +1,102 @@+package dingtalk++import (+ "context"+ "encoding/json"+ "errors"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "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"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestAckNotifierCredentialFailuresAreOptional(t *testing.T) {+ for _, tc := range []struct {+ name string+ platform any+ decrypt Decrypter+ }{+ {name: "missing installation"},+ {name: "malformed config", platform: db.ChannelInstallation{Config: []byte(`{`)}},+ {name: "decryption failure", platform: db.ChannelInstallation{Config: []byte(`{"app_id":"app","app_secret_encrypted":"eA=="}`)}, decrypt: func([]byte) ([]byte, error) { return nil, errors.New("unavailable key") }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ d := newDingtalkSendServer(t)+ n := NewAckNotifier(NewClient(nil, d.srv.URL), tc.decrypt, nil, nil)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{Platform: tc.platform}, groupReactionMessage("source"), sessionUUID(91))+ n.OnSettled(context.Background(), sessionUUID(91))+ if len(d.sendBodies) != 0 || len(n.active) != 0 {+ t.Fatal("unusable credentials sent a reaction or prevented local cleanup")+ }+ })+ }+}++func TestCommandReplyFailuresStayOptional(t *testing.T) {+ for _, outcome := range []engine.Outcome{engine.OutcomeFreshPending, engine.OutcomeChatStarted} {+ t.Run(string(outcome), func(t *testing.T) {+ d := newDingtalkSendServer(t)+ r := NewOutboundReplier(OutboundReplierConfig{Client: NewClient(nil, d.srv.URL)})+ r.Reply(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("source"), engine.Result{Outcome: outcome})+ if len(d.sendBodies) != 0 {+ t.Fatal("missing credentials sent a command reply")+ }+ })+ }+}++func TestImmediateQuoteWithoutSnapshotDoesNotInventHistory(t *testing.T) {+ for _, msg := range []channel.InboundMessage{+ {Text: "history", ReplyTo: &channel.ReplyCtx{MessageID: "parent"}},+ {Text: "[Image]", Type: channel.MsgTypeImage},+ } {+ if got := dingtalkVisibleQuoteText(msg); got != "" {+ t.Fatalf("missing current text quoted unrelated content: %q", got)+ }+ }+ set := NewDingTalkResolverSet(nil, nil, nil, nil, nil, nil)+ if set.Session == nil {+ t.Fatal("optional notifier disabled session routing")+ }+}++func TestSenderEmptyReplyDoesNotSendQuoteAlone(t *testing.T) {+ d := newDingtalkSendServer(t)+ key, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), sendTarget{ConversationID: "group", QuoteText: "question"}, "")+ if err != nil || key != "" || len(d.sendBodies) != 0 {+ t.Fatalf("empty reply gained a provider side effect: key=%q error=%v", key, err)+ }+}++func TestLegacyAndMixedInputAttribution(t *testing.T) {+ for _, legacy := range []bool{false, true} {+ d := newDingtalkSendServer(t)+ q := deliveryOnlyOutboundQueries{+ delivery: db.ChannelTaskDelivery{ChannelType: string(TypeDingTalk), ChannelChatID: "group"},+ installation: db.ChannelInstallation{Status: "active", Config: []byte(`{"app_id":"app","app_secret_encrypted":"eA=="}`)},+ task: db.AgentTaskQueue{ChatInputTaskID: sessionUUID(94)}, channelIngested: true,+ input: []db.ChatMessage{{ID: sessionUUID(95), ChannelIngested: true, Content: "owned question"}, {Content: "local-only message"}},+ }+ if legacy {+ q.task.ChatInputTaskID.Valid = false+ }+ o := NewOutbound(q, nil, NewClient(nil, d.srv.URL), nil, nil)+ if err := o.processEvent(context.Background(), events.Event{Type: protocol.EventChatDone, TaskID: "11111111-1111-1111-1111-111111111111", ChatSessionID: "22222222-2222-2222-2222-222222222222", Payload: protocol.ChatDonePayload{Content: "answer"}}); err != nil {+ t.Fatal(err)+ }+ var param markdownParam+ if err := json.Unmarshal([]byte(d.lastBody["msgParam"].(string)), ¶m); err != nil {+ t.Fatal(err)+ }+ want := "> owned question\n\n---\n\nanswer"+ if legacy {+ want = "answer"+ }+ if param.Text != want {+ t.Fatalf("wrong input attribution: %q", param.Text)+ }+ }+}diff --git a/server/internal/integrations/dingtalk/reply_source.go b/server/internal/integrations/dingtalk/reply_source.gonew file mode 100644index 0000000000..df9a66769b--- /dev/null+++ b/server/internal/integrations/dingtalk/reply_source.go@@ -0,0 +1,127 @@+package dingtalk++import (+ "sync"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+)++const maxReplySources = 1024++type replySource struct {+ installationID pgtype.UUID+ sessionID pgtype.UUID+ message channel.InboundMessage+}++// This bounded cache associates accepted input with its in-process provider+// anchor. It never repairs shared routing, persists callback data, or recovers+// after restart. Losing an entry suppresses optional reactions for that input.+type replySourceCache struct {+ mu sync.Mutex+ entries map[pgtype.UUID]replySource+ order []pgtype.UUID+ next int+ sessions map[pgtype.UUID]int+}++func (c *Client) rememberReplySource(installationID, inputID, sessionID pgtype.UUID, msg channel.InboundMessage) {+ if c == nil || !installationID.Valid || !inputID.Valid || msg.MessageID == "" || msg.Source.ChatID == "" {+ return+ }+ source := replySource{installationID: installationID, sessionID: sessionID, message: channel.InboundMessage{MessageID: msg.MessageID, Source: msg.Source}}+ cache := &c.sources+ cache.mu.Lock()+ defer cache.mu.Unlock()+ if cache.entries == nil {+ cache.entries = make(map[pgtype.UUID]replySource)+ }+ if _, exists := cache.entries[inputID]; exists {+ return+ }+ if len(cache.order) < maxReplySources {+ cache.order = append(cache.order, inputID)+ } else {+ cache.releaseSession(cache.entries[cache.order[cache.next]].sessionID)+ delete(cache.entries, cache.order[cache.next])+ cache.order[cache.next] = inputID+ cache.next = (cache.next + 1) % maxReplySources+ }+ cache.entries[inputID] = source+ cache.retainSession(sessionID)+}++func (c *Client) replySourceFor(installationID, inputID pgtype.UUID) (replySource, bool) {+ if c == nil || !installationID.Valid || !inputID.Valid {+ return replySource{}, false+ }+ cache := &c.sources+ cache.mu.Lock()+ source, ok := cache.entries[inputID]+ cache.mu.Unlock()+ return source, ok && source.installationID == installationID+}++// Resolve only a locally accepted provider anchor. The cache is bounded, and+// installation plus conversation identity must match before reading its input.+func (c *Client) replyInputFor(installationID pgtype.UUID, msg channel.InboundMessage) pgtype.UUID {+ if c == nil || !installationID.Valid {+ return pgtype.UUID{}+ }+ c.sources.mu.Lock()+ defer c.sources.mu.Unlock()+ for id, source := range c.sources.entries {+ if source.installationID == installationID && source.message.MessageID == msg.MessageID && source.message.Source == msg.Source {+ return id+ }+ }+ return pgtype.UUID{}+}++// Register interest before the input can become visible to a task. The caller+// releases its in-flight reference after commit/source capture or on failure.+// Retained references belong to the bounded source cache; concurrent calls own+// separate references so one failed append cannot hide another accepted input.+func (c *Client) beginReplyInput(sessionID pgtype.UUID) func() {+ if c == nil || !sessionID.Valid {+ return func() {}+ }+ cache := &c.sources+ cache.mu.Lock()+ cache.retainSession(sessionID)+ cache.mu.Unlock()+ return func() {+ cache.mu.Lock()+ cache.releaseSession(sessionID)+ cache.mu.Unlock()+ }+}++func (c *Client) hasReplySession(sessionID pgtype.UUID) bool {+ if c == nil {+ return false+ }+ c.sources.mu.Lock()+ defer c.sources.mu.Unlock()+ return c.sources.sessions[sessionID] > 0+}++// Caller holds cache.mu.+func (cache *replySourceCache) retainSession(sessionID pgtype.UUID) {+ if !sessionID.Valid {+ return+ }+ if cache.sessions == nil {+ cache.sessions = make(map[pgtype.UUID]int)+ }+ cache.sessions[sessionID]+++}++func (cache *replySourceCache) releaseSession(sessionID pgtype.UUID) {+ if cache.sessions[sessionID] <= 1 {+ delete(cache.sessions, sessionID)+ } else {+ cache.sessions[sessionID]--+ }+}diff --git a/server/internal/integrations/dingtalk/reply_source_test.go b/server/internal/integrations/dingtalk/reply_source_test.gonew file mode 100644index 0000000000..dd3580f5a4--- /dev/null+++ b/server/internal/integrations/dingtalk/reply_source_test.go@@ -0,0 +1,117 @@+package dingtalk++import (+ "context"+ "errors"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++func TestReplySourceRequiresLocalAcceptedInput(t *testing.T) {+ client := NewClient(nil, "")+ inst, inputID := sessionUUID(80), sessionUUID(81)+ msg := groupReactionMessage("source")+ msg.Text = "private question"+ msg.Raw = []byte(`{"session_webhook":"private bearer"}`)+ capture := &captureChatSession{appendErr: errors.New("append failed"), appendResult: engine.AppendResult{MessageID: inputID}}+ binder := &sessionBinder{session: capture, replies: client}+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{InstallationID: inst, Message: msg}); err == nil {+ t.Fatal("expected append failure")+ }+ if _, ok := client.replySourceFor(inst, inputID); ok {+ t.Fatal("failed input retained an anchor")+ }+ capture.appendErr = nil+ if _, err := binder.AppendMessage(context.Background(), engine.AppendParams{InstallationID: inst, Message: msg}); err != nil {+ t.Fatal(err)+ }+ source, ok := client.replySourceFor(inst, inputID)+ if !ok || source.message.MessageID != "source" || source.message.Text != "" || len(source.message.Raw) != 0 {+ t.Fatal("source cache lost its anchor or retained callback content")+ }+ if _, ok := client.replySourceFor(sessionUUID(82), inputID); ok {+ t.Fatal("anchor crossed installation")+ }+ if _, ok := NewClient(nil, "").replySourceFor(inst, inputID); ok {+ t.Fatal("restart recovered memory attribution")+ }+ // /new with a first message enters through StartSession instead of AppendMessage.+ freshID := sessionUUID(83)+ capture.startResult = engine.StartSessionResult{Append: engine.AppendResult{MessageID: freshID}}+ if _, err := binder.StartSession(context.Background(), engine.StartSessionParams{Installation: engine.ResolvedInstallation{ID: inst}, Message: msg, PersistMessage: true}); err != nil {+ t.Fatal(err)+ }+ if _, ok := client.replySourceFor(inst, freshID); !ok {+ t.Fatal("new-session input lost its anchor")+ }+}++func TestReplySourceMemoryIsBounded(t *testing.T) {+ client := NewClient(nil, "")+ inst, first := sessionUUID(84), sessionUUID(85)+ client.rememberReplySource(inst, first, sessionUUID(91), groupReactionMessage("first"))+ client.rememberReplySource(inst, first, sessionUUID(91), groupReactionMessage("duplicate"))+ if source, _ := client.replySourceFor(inst, first); source.message.MessageID != "first" {+ t.Fatal("duplicate input replaced accepted source")+ }+ for i := 0; i < maxReplySources; i++ {+ client.rememberReplySource(inst, dbid.NewV7(), sessionUUID(91), groupReactionMessage("other"))+ }+ if len(client.sources.entries) != maxReplySources || len(client.sources.order) != maxReplySources {+ t.Fatal("memory cache exceeded its bound")+ }+ if _, ok := client.replySourceFor(inst, first); ok {+ t.Fatal("oldest anchor was not evicted")+ }+}++func TestReplySourceConcurrentCaptureAndLookup(t *testing.T) {+ client := NewClient(nil, "")+ inst, input := sessionUUID(86), sessionUUID(87)+ msg := groupReactionMessage("source")+ var wg sync.WaitGroup+ for i := 0; i < 32; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ client.rememberReplySource(inst, input, sessionUUID(91), msg)+ client.replySourceFor(inst, input)+ }()+ }+ wg.Wait()+ if len(client.sources.entries) != 1 || len(client.sources.order) != 1 {+ t.Fatal("concurrent duplicate created multiple entries")+ }+}++func TestReplySourceRequiresCompleteCoordinates(t *testing.T) {+ inst, input := sessionUUID(88), sessionUUID(89)+ for _, missing := range []string{"client", "installation", "input", "message", "conversation"} {+ t.Run(missing, func(t *testing.T) {+ client := NewClient(nil, "")+ installationID, inputID, msg := inst, input, groupReactionMessage("source")+ switch missing {+ case "client":+ client = nil+ case "installation":+ installationID.Valid = false+ case "input":+ inputID.Valid = false+ case "message":+ msg.MessageID = ""+ case "conversation":+ msg.Source.ChatID = ""+ }+ client.rememberReplySource(installationID, inputID, sessionUUID(91), msg)+ if _, ok := client.replySourceFor(inst, input); ok {+ t.Fatal("incomplete coordinates created a usable reply anchor")+ }+ if client != nil && len(client.sources.entries) != 0 {+ t.Fatal("incomplete coordinates consumed cache capacity")+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.goindex e9ce7db43a..d8cf152f46 100644--- a/server/internal/integrations/dingtalk/resolvers.go+++ b/server/internal/integrations/dingtalk/resolvers.go@@ -6,6 +6,7 @@ import ("errors""fmt""log/slog"+ "strings""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"@@ -47,7 +48,7 @@ func NewDingTalkResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OGroup: "DingTalk group",Direct: "DingTalk direct message",Fallback: "DingTalk chat",- }), groupPresence: groupPresence},+ }), groupPresence: groupPresence, replies: replyClient(ack)},Audit: &auditor{q: q},Replier: replier,OriginType: originDingTalkChat,@@ -100,6 +101,28 @@ func dingtalkSessionRouting(msg channel.InboundMessage) (bindingKey string, confreturn chatID, raw}+// dingtalkVisibleQuoteText returns only the current user-authored turn for the+// Markdown quote shown in a group reply. The adapter's raw CurrentText keeps+// media placeholders in order without the quoted history.+// CommandText remains the fallback for older/internal callers.+func dingtalkVisibleQuoteText(msg channel.InboundMessage) string {+ if raw, err := decodeDingTalkRaw(msg); err == nil {+ if quote := strings.TrimSpace(raw.CurrentText); quote != "" {+ return quote+ }+ }+ quote := strings.TrimSpace(msg.CommandText)+ if quote == "" {+ // Older/internal callers may not populate CommandText. Falling back is+ // safe only when Text has not been reply-enriched and is not media.+ if msg.ReplyTo != nil || msg.Type == channel.MsgTypeImage {+ return ""+ }+ quote = strings.TrimSpace(msg.Text)+ }+ return quote+}+// outboundTarget recovers the send target from a chat binding's config, falling// back to the channel_chat_id when the config is missing or unparsable.func outboundTarget(b db.ChannelChatSessionBinding) sendTarget {@@ -322,6 +345,22 @@ func (o *groupPresenceObserver) RecordActivity(ctx context.Context, installationfunc (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionParams) (engine.StartSessionResult, error) {bindingKey, config := dingtalkSessionRouting(p.Message)+ var release func()+ defer func() {+ if release != nil {+ release()+ }+ }()+ beforeCommit := p.BeforeCommit+ if p.PersistMessage {+ beforeCommit = func(ctx context.Context, tx pgx.Tx, session db.ChatSession) error {+ release = r.replies.beginReplyInput(session.ID)+ if p.BeforeCommit != nil {+ return p.BeforeCommit(ctx, tx, session)+ }+ return nil+ }+ }result, err := r.session.StartSession(ctx, engine.StartSessionInput{EnsureSessionInput: engine.EnsureSessionInput{WorkspaceID: p.Installation.WorkspaceID, AgentID: p.Installation.AgentID,@@ -332,7 +371,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionPBody: p.Message.Text, CommandText: p.Message.CommandText, MessageID: p.Message.MessageID, ThreadID: p.Message.Source.ThreadID,ClaimToken: p.ClaimToken, MediaPendingSeconds: p.MediaPendingSeconds,PersistMessage: p.PersistMessage, HistoryBoundaryPending: p.HistoryBoundaryPending,- BeforeCommit: p.BeforeCommit,+ BeforeCommit: beforeCommit,})if err != nil {return engine.StartSessionResult{}, err@@ -349,6 +388,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionP)}if p.PersistMessage {+ r.replies.rememberReplySource(p.Installation.ID, result.Append.MessageID, result.SessionID, p.Message)if err := r.groupPresence.RecordActivity(ctx, p.Installation.ID, p.Message); err != nil {logger := slog.Default()if r.groupPresence != nil && r.groupPresence.logger != nil {@@ -368,6 +408,7 @@ func (r *sessionBinder) StartSession(ctx context.Context, p engine.StartSessionP}type sessionBinder struct {+ replies *Clientsession chatSessiongroupPresence *groupPresenceObserver}@@ -407,6 +448,8 @@ func (r *sessionBinder) MarkPendingFresh(ctx context.Context, sessionID pgtype.U}func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams) (engine.AppendResult, error) {+ release := r.replies.beginReplyInput(p.SessionID)+ defer release()commandText := p.Message.CommandTextif commandText == "" {commandText = p.Message.Text@@ -440,6 +483,7 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams"error", err,)}+ r.replies.rememberReplySource(p.InstallationID, result.MessageID, p.SessionID, p.Message)return result, nil}@@ -479,3 +523,11 @@ func (r *auditor) RecordDrop(ctx context.Context, instID pgtype.UUID, msg channeChannelMessageID: nullText(msg.MessageID),})}++// replyClient keeps notifier attribution local to the DingTalk adapter.+func replyClient(ack *ackNotifier) *Client {+ if ack == nil {+ return nil+ }+ return ack.client+}diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.goindex be458fd587..b1b272f2e6 100644--- a/server/internal/integrations/dingtalk/resolvers_test.go+++ b/server/internal/integrations/dingtalk/resolvers_test.go@@ -46,13 +46,15 @@ func (f *fakeGroupPresenceQueries) RecordDingTalkGroupActivity(_ context.Context}type captureChatSession struct {- ensure engine.EnsureSessionInput- ensureCalls int- ensureErr error- start engine.StartSessionInput- append engine.AppendInput- appendErr error- media engine.BindMediaInput+ ensure engine.EnsureSessionInput+ ensureCalls int+ ensureErr error+ start engine.StartSessionInput+ append engine.AppendInput+ appendErr error+ appendResult engine.AppendResult+ startResult engine.StartSessionResult+ media engine.BindMediaInput}func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {@@ -62,12 +64,12 @@ func (c *captureChatSession) EnsureSession(_ context.Context, in engine.EnsureSe}func (c *captureChatSession) StartSession(_ context.Context, in engine.StartSessionInput) (engine.StartSessionResult, error) {c.start = in- return engine.StartSessionResult{}, c.ensureErr+ return c.startResult, 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- return engine.AppendResult{}, c.appendErr+ return c.appendResult, c.appendErr}func TestSessionBinder_RecordsActivityOnlyAfterSuccessfulGroupAppend(t *testing.T) {@@ -409,3 +411,53 @@ func TestOutboundTarget_FallsBackToChatID(t *testing.T) {t.Errorf("missing config must fall back to a group send on chat id: %+v", target)}}++func TestDingTalkVisibleQuoteTextPreservesCurrentImagePlaceholders(t *testing.T) {+ tests := []struct {+ name string+ msg channel.InboundMessage+ currentText string+ want string+ }{+ {+ name: "multi-level reply",+ msg: channel.InboundMessage{+ Text: channel.FormatQuotedMessage("", "internal card JSON") + "\n\nVerify this information",+ CommandText: "Verify this information",+ ReplyTo: &channel.ReplyCtx{MessageID: "parent"},+ },+ currentText: "Verify this information",+ want: "Verify this information",+ },+ {+ name: "images with instruction",+ msg: channel.InboundMessage{+ Type: channel.MsgTypeImage, Text: "[Image]\n[Image]\nReview these", CommandText: "Review these",+ },+ currentText: "[Image]\n[Image]\nReview these",+ want: "[Image]\n[Image]\nReview these",+ },+ {+ name: "image only",+ msg: channel.InboundMessage{+ Type: channel.MsgTypeImage, Text: dingtalkImagePlaceholder, CommandText: dingtalkImagePlaceholder,+ },+ currentText: dingtalkImagePlaceholder,+ want: dingtalkImagePlaceholder,+ },+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ tc.msg.Source = channel.Source{ChatID: "group", ChatType: channel.ChatTypeGroup, SenderID: "staff-7"}+ tc.msg.Raw, _ = json.Marshal(dingtalkRawEvent{+ CurrentText: tc.currentText,+ })+ if got := dingtalkVisibleQuoteText(tc.msg); got != tc.want {+ t.Fatalf("visible quote = %q, want %q", got, tc.want)+ }+ if target := targetFromMessage(tc.msg); target.QuoteText != tc.want || target.StaffID != "" {+ t.Fatalf("immediate-reply target = %+v, want quote %q without a group mention recipient", target, tc.want)+ }+ })+ }+}diff --git a/server/internal/integrations/dingtalk/token.go b/server/internal/integrations/dingtalk/token.goindex f47cb40ebb..46ce5cf0dc 100644--- a/server/internal/integrations/dingtalk/token.go+++ b/server/internal/integrations/dingtalk/token.go@@ -43,6 +43,7 @@ type Client struct {// minting collapses concurrent cache misses for the same AppKey into a// single in-flight token request.minting singleflight.Group+ sources replySourceCache}type cachedToken struct {