Skip to content

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

Go

MUL-7372 fix(dingtalk): preserve quoted answer context and first-chunk attribution (#8412)

YYClawee2793f03136
diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.go
index 772ae8bceb..356007b982 100644
--- a/server/internal/integrations/dingtalk/inbound.go
+++ b/server/internal/integrations/dingtalk/inbound.go
@@ -93,18 +93,20 @@ func (m *botCallbackRepliedMessage) UnmarshalJSON(data []byte) error {
}
type botCallbackRepliedContent struct {
- Text string `json:"text"`
- RichText richTextItems `json:"richText"`
- DownloadCode string `json:"downloadCode"`
- PictureDownloadCode string `json:"pictureDownloadCode"`
- FileName string `json:"fileName"`
- Recognition string `json:"recognition"`
+ Text string `json:"text"`
+ RichText richTextItems `json:"richText"`
+ CardContent json.RawMessage `json:"cardContent"`
+ DownloadCode string `json:"downloadCode"`
+ PictureDownloadCode string `json:"pictureDownloadCode"`
+ FileName string `json:"fileName"`
+ Recognition string `json:"recognition"`
}
func (content *botCallbackRepliedContent) UnmarshalJSON(data []byte) error {
type wireContent struct {
Text json.RawMessage `json:"text"`
RichText json.RawMessage `json:"richText"`
+ CardContent json.RawMessage `json:"cardContent"`
DownloadCode string `json:"downloadCode"`
PictureDownloadCode string `json:"pictureDownloadCode"`
FileName string `json:"fileName"`
@@ -114,6 +116,7 @@ func (content *botCallbackRepliedContent) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &wire); err != nil {
return err
}
+ content.CardContent = append(json.RawMessage(nil), wire.CardContent...)
content.Text = ""
_ = json.Unmarshal(wire.Text, &content.Text)
// Reply snapshots use text/content wrappers and msgType aliases that differ
@@ -539,9 +542,8 @@ func renderDingTalkQuotedMessage(replied *botCallbackRepliedMessage) (string, []
case "text":
appendText(dingTalkReadableQuotedText(replied.Content.Text))
case "interactiveCard":
- // cardParamMap belongs to a template, not a universal body schema.
- // https://open.dingtalk.com/document/orgapp/create-and-deliver-cards
- appendText("[quoted content unavailable]")
+ quotedBody := renderDingTalkQuotedCard(replied.Content.CardContent)
+ appendText(quotedBody)
case "picture", "image":
appendPicture(replied.Content.DownloadCode, replied.Content.PictureDownloadCode)
// The snapshot's text field has no documented caption meaning.
@@ -679,6 +681,8 @@ func normalizeDingTalkRichTextControlLayout(msg *channel.InboundMessage, items [
// including legitimate quoted code/prose containing ||. Current input is never
// filtered. Apply this only to provider text values, not rendered quote blocks,
// so a fallback cannot discard generated image markers and their media slots.
+// This tradeoff was accepted in the review of PR #8061:
+// https://github.com/multica-ai/multica/pull/8061#pullrequestreview-5130718174
func dingTalkReadableQuotedText(value string) string {
if strings.Contains(value, "||") {
return "[quoted content unavailable]"
diff --git a/server/internal/integrations/dingtalk/inbound_card.go b/server/internal/integrations/dingtalk/inbound_card.go
new file mode 100644
index 0000000000..fe4310e315
--- /dev/null
+++ b/server/internal/integrations/dingtalk/inbound_card.go
@@ -0,0 +1,108 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "strings"
+ "unicode"
+)
+
+// Project the observed rendered-card snapshot, not a template's cardParamMap.
+// UNKNOWN children are excluded from selected answer context: the captured
+// group snapshots put source attribution and layout there. We deliberately do
+// not decode their serialized values. Unsupported non-UNKNOWN nodes still mark
+// missing content. TEXT nodes are inline runs, not necessarily paragraphs.
+// The public robot message-type list is not a card-node schema. This projection
+// covers observed RICHTEXT children: TEXT prose, LINK destination strings, IMAGE
+// placeholders, and UNKNOWN layout/source data. Do not infer other node shapes.
+func renderDingTalkQuotedCard(data json.RawMessage) string {
+ const unavailable = "[quoted content unavailable]"
+ var blocks []json.RawMessage
+ if json.Unmarshal(data, &blocks) != nil || len(blocks) == 0 {
+ return unavailable
+ }
+ var body strings.Builder
+ appendText := func(s string) { body.WriteString(s) }
+ missing := func() {
+ if !strings.HasSuffix(body.String(), unavailable+"\n") {
+ if body.Len() > 0 && !strings.HasSuffix(body.String(), "\n") {
+ appendText("\n")
+ }
+ appendText(unavailable + "\n")
+ }
+ }
+ for _, raw := range blocks {
+ var block struct {
+ ElementType string `json:"elementType"`
+ Children []json.RawMessage `json:"children"`
+ }
+ if json.Unmarshal(raw, &block) != nil || block.ElementType != "RICHTEXT" || len(block.Children) == 0 {
+ missing()
+ continue
+ }
+ blockStarted := false
+ for _, rawChild := range block.Children {
+ var node struct {
+ ElementType string `json:"elementType"`
+ Value json.RawMessage `json:"value"`
+ }
+ if json.Unmarshal(rawChild, &node) != nil {
+ missing()
+ continue
+ }
+ if node.ElementType == "UNKNOWN" {
+ continue
+ }
+ if !blockStarted && body.Len() > 0 {
+ appendText("\n\n")
+ }
+ blockStarted = true
+ switch node.ElementType {
+ case "TEXT", "LINK":
+ var value string
+ if len(node.Value) == 0 || string(node.Value) == "null" || json.Unmarshal(node.Value, &value) != nil {
+ missing()
+ continue
+ }
+ // Apply the existing conservative policy to raw provider values,
+ // preserving neighboring nodes and generated image placeholders.
+ if dingTalkReadableQuotedText(value) != value {
+ missing()
+ continue
+ }
+ if node.ElementType == "LINK" {
+ if strings.TrimSpace(value) == "" {
+ missing()
+ continue
+ }
+ // Keep the observed destination verbatim, separate from an
+ // adjacent run. A link label/URL object is not a known shape.
+ if body.Len() > 0 && len(strings.TrimRightFunc(body.String(), unicode.IsSpace)) == body.Len() {
+ appendText("\n")
+ }
+ }
+ // A URL at a run boundary must not absorb the following run into its
+ // destination. Other runs concatenate, preserving inline emphasis splits.
+ spans := webURLSpans(body.String())
+ if value != "" && len(spans) > 0 && spans[len(spans)-1][1] == body.Len() {
+ appendText("\n")
+ }
+ appendText(value)
+ case "IMAGE":
+ // Rendered card snapshots expose an opaque code, not the original
+ // Markdown URL. Observed codes fail the robot file-download API;
+ // retain position without treating them as uploaded-message media.
+ if body.Len() > 0 && !strings.HasSuffix(body.String(), "\n") {
+ appendText("\n")
+ }
+ appendText(dingtalkImagePlaceholder + "\n")
+ default:
+ missing()
+ }
+ }
+ }
+ result := strings.TrimSpace(body.String())
+ if result == "" {
+ result = unavailable
+ }
+ return result
+}
diff --git a/server/internal/integrations/dingtalk/inbound_card_test.go b/server/internal/integrations/dingtalk/inbound_card_test.go
new file mode 100644
index 0000000000..eb1a35054c
--- /dev/null
+++ b/server/internal/integrations/dingtalk/inbound_card_test.go
@@ -0,0 +1,162 @@
+package dingtalk
+
+import (
+ "encoding/json"
+ "os"
+ "strings"
+ "testing"
+)
+
+// Sanitized real community DingTalk callback captured on 2026-09-14. UNKNOWN
+// nodes include serialized layout data; the readable answer is carried by RICHTEXT children.
+func TestInboundQuotedCardObservedSnapshot(t *testing.T) {
+ wire, err := os.ReadFile("testdata/quoted_interactive_card.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cb botCallbackData
+ if err := json.Unmarshal(wire, &cb); err != nil {
+ t.Fatal(err)
+ }
+ msg, ok := inboundFromCallback(&cb, "app")
+ want := "> Bananas. Literal text: . Link: https://example.com/a_(b)?x=a_b+c&y=2#part_2\n> [quoted content unavailable]\n\nexplain"
+ if !ok || msg.Text != want {
+ t.Fatalf("quoted body = %q, want %q (ok=%v)", msg.Text, want, ok)
+ }
+ if msg.CommandText != "explain" || msg.ForceFresh || !msg.HasSelectedContext || msg.ReplyTo == nil || msg.ReplyTo.MessageID != "selected-bot-message" {
+ t.Fatalf("quote changed current instruction or routing: %+v", msg)
+ }
+}
+
+func TestInboundQuotedCardSnapshotBoundaries(t *testing.T) {
+ for _, tc := range []struct{ name, card, want string }{
+ {"preview", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"Multica has replied."}]}]`, "Multica has replied."},
+ {"literal text", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"/clear a || b "},{"elementType":"TEXT","value":"{\"text\":\"literal\"}"}]}]`, "[quoted content unavailable]\n{\"text\":\"literal\"}"},
+ {"blocks", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"one"}]},{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"two"}]}]`, "one\n\ntwo"},
+ {"bad neighbor", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"before"},42,{"elementType":"TEXT","value":{}},{"elementType":"TEXT","value":"after"}]}]`, "before\n[quoted content unavailable]\nafter"},
+ {"unknown wrapper", `[{"elementType":"UNKNOWN","children":[{"elementType":"TEXT","value":"not verified"}]}]`, "[quoted content unavailable]"},
+ {"wrong children", `[{"elementType":"RICHTEXT","children":{}}]`, "[quoted content unavailable]"},
+ {"skip source and layout", `[{"elementType":"RICHTEXT","children":[{"elementType":"UNKNOWN","value":"source /clear"},{"elementType":"UNKNOWN","value":"{}"},{"elementType":"TEXT","value":"answer"}]}]`, "answer"},
+ {"missing image", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT","value":"before"},{"elementType":"IMAGE","downloadCode":42},{"elementType":"TEXT","value":"after"}]}]`, "before\n[Image]\nafter"},
+ {"unknown-only", `[{"elementType":"RICHTEXT","children":[{"elementType":"UNKNOWN","value":"{}"}]}]`, "[quoted content unavailable]"},
+ {"empty", `[]`, "[quoted content unavailable]"},
+ {"null", `null`, "[quoted content unavailable]"},
+ {"invalid blocks", `[42,{"elementType":"RICHTEXT","children":[]}]`, "[quoted content unavailable]"},
+ {"missing text values", `[{"elementType":"RICHTEXT","children":[{"elementType":"TEXT"},{"elementType":"TEXT","value":null},{"elementType":"TEXT","value":""}]}]`, "[quoted content unavailable]"},
+ {"unsupported child", `[{"elementType":"RICHTEXT","children":[{"elementType":"VIDEO","value":"opaque"},{"elementType":"TEXT","value":"after"}]}]`, "[quoted content unavailable]\nafter"},
+ {"leading images", `[{"elementType":"RICHTEXT","children":[{"elementType":"IMAGE"},{"elementType":"IMAGE"},{"elementType":"TEXT","value":"after"}]}]`, "[Image]\n[Image]\nafter"},
+ {"template map", `{"cardData":{"cardParamMap":{"text":"not verified"}}}`, "[quoted content unavailable]"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var cb botCallbackData
+ wire := `{"senderStaffId":"sender","conversationType":"1","msgtype":"text","text":{"content":"explain","repliedMsg":{"msgType":"interactiveCard","content":{"cardContent":` + tc.card + `}}}}`
+ if err := json.Unmarshal([]byte(wire), &cb); err != nil {
+ t.Fatal(err)
+ }
+ msg, ok := inboundFromCallback(&cb, "app")
+ want := "> " + strings.ReplaceAll(tc.want, "\n", "\n> ") + "\n\nexplain"
+ want = strings.ReplaceAll(want, "\n> \n", "\n>\n")
+ if !ok || msg.Text != want || msg.CommandText != "explain" || msg.ForceFresh {
+ t.Fatalf("got %+v, want %q", msg, want)
+ }
+ })
+ }
+}
+
+// Shapes from the four paired probe traces supplied on 2026-09-14. Repeat the
+// selection under content for current richText messages, as the later captures
+// demonstrate; the selected message kind is independent of its container.
+func TestInboundQuotedBotChannelFixtures(t *testing.T) {
+ data, err := os.ReadFile("testdata/quoted_bot_channels.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cases []struct {
+ Name string `json:"name"`
+ Callback botCallbackData `json:"callback"`
+ }
+ if err := json.Unmarshal(data, &cases); err != nil {
+ t.Fatal(err)
+ }
+ for _, tc := range cases {
+ for _, currentKind := range []string{"text", "richText"} {
+ t.Run(tc.Name+"/"+currentKind, func(t *testing.T) {
+ cb := tc.Callback
+ if currentKind == "richText" {
+ cb.Msgtype = currentKind
+ cb.Content, _ = json.Marshal(map[string]any{"richText": []any{map[string]string{"text": "引用测试"}}, "isReplyMsg": true, "repliedMsg": cb.Text.RepliedMsg})
+ cb.Text = botCallbackText{}
+ }
+ msg, ok := inboundFromCallback(&cb, "app")
+ if !ok || msg.Text != "> DingTalk source probe 001.\n\n引用测试" || msg.CommandText != "引用测试" || msg.ReplyTo == nil || msg.ReplyTo.MessageID != "selected" {
+ t.Fatalf("channel projection differs: %+v", msg)
+ }
+ })
+ }
+ }
+}
+
+func TestInboundCardInlineAndMediaOrder(t *testing.T) {
+ var cb botCallbackData
+ wire := `{"senderStaffId":"sender","conversationType":"1","msgtype":"richText","content":{"richText":[{"text":"current"},{"type":"picture","downloadCode":"current-code"}],"repliedMsg":{"msgType":"interactiveCard","content":{"cardContent":[{"elementType":"RICHTEXT","children":[{"elementType":"UNKNOWN","value":"source"},{"elementType":"TEXT","value":"一只"},{"elementType":"TEXT","value":"木质调色板"},{"elementType":"TEXT","value":",literal [Image]"},{"elementType":"IMAGE","downloadCode":"selected-code"},{"elementType":"TEXT","value":"after"}]}]}}}}`
+ if err := json.Unmarshal([]byte(wire), &cb); err != nil {
+ t.Fatal(err)
+ }
+ msg, ok := inboundFromCallback(&cb, "app")
+ if !ok || !strings.Contains(msg.Text, "一只木质调色板,literal [Image]\n> [Image]\n> after") || strings.Contains(msg.Text, "unavailable") {
+ t.Fatalf("card inline/media ordering: %q", msg.Text)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) != 1 || raw.Media[0].Ref != "current-code" || raw.Media[0].InlineIndex != 2 {
+ t.Fatalf("media association lost: %+v (%v)", raw, err)
+ }
+}
+
+// Captured community callbacks retain LINK values even when the visible quote
+// preview is truncated. Source/layout values and sender identity are sanitized.
+func TestInboundQuotedCardCapturedLinks(t *testing.T) {
+ for _, kind := range []string{"private", "group"} {
+ t.Run(kind, func(t *testing.T) {
+ wire, err := os.ReadFile("testdata/quoted_card_link_" + kind + ".json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cb botCallbackData
+ if err := json.Unmarshal(wire, &cb); err != nil {
+ t.Fatal(err)
+ }
+ msg, ok := inboundFromCallback(&cb, "app")
+ want := "> DingTalk quote testParagraph one: Apples are red.Paragraph two: Bananas are yellow. Marker: QUOTE-CONTEXT-7429.Literal HTML: keep this visible\n> [quoted content unavailable]\n> Link: https://example.com/a_(b)?x=a_b+c&y=2#part_2\n> [quoted content unavailable]\n> Paragraph three: Cherries are sweet.\n\nQUOTE-CAPTURE-7429"
+ if !ok || msg.Text != want {
+ t.Fatalf("got %q (ok=%v), want %q", msg.Text, ok, want)
+ }
+ if msg.CommandText != "QUOTE-CAPTURE-7429" || msg.ForceFresh || !msg.HasSelectedContext {
+ t.Fatalf("routing changed: %+v", msg)
+ }
+ })
+ }
+}
+
+func TestQuotedCardNodeContract(t *testing.T) {
+ for _, tc := range []struct{ name, children, want string }{
+ {"link", `{"elementType":"LINK","value":"https://example.com/a_(b)?x=a_b+c&y=2#part_2"}`, "https://example.com/a_(b)?x=a_b+c&y=2#part_2"},
+ {"mixed order", `{"elementType":"TEXT","value":"before"},{"elementType":"LINK","value":"https://example.com/one"},{"elementType":"LINK","value":"https://example.com/two"},{"elementType":"IMAGE"},{"elementType":"UNKNOWN","value":"layout"},{"elementType":"TEXT","value":"after"}`, "before\nhttps://example.com/one\nhttps://example.com/two\n[Image]\nafter"},
+ {"label and suffix", `{"elementType":"TEXT","value":"Link: "},{"elementType":"LINK","value":"https://example.com/a"},{"elementType":"TEXT","value":"suffix"}`, "Link: https://example.com/a\nsuffix"},
+ {"filtered text keeps neighbors", `{"elementType":"TEXT","value":"before"},{"elementType":"TEXT","value":"primary || fallback"},{"elementType":"LINK","value":"https://example.com/ok"},{"elementType":"IMAGE"},{"elementType":"TEXT","value":"after"}`, "before\n[quoted content unavailable]\nhttps://example.com/ok\n[Image]\nafter"},
+ {"filtered link keeps neighbors", `{"elementType":"TEXT","value":"before"},{"elementType":"LINK","value":"https://example.com/a||b"},{"elementType":"LINK","value":"https://example.com/ok"},{"elementType":"IMAGE"},{"elementType":"TEXT","value":"after"}`, "before\n[quoted content unavailable]\nhttps://example.com/ok\n[Image]\nafter"},
+ {"missing link", `{"elementType":"LINK"}`, "[quoted content unavailable]"},
+ {"null link", `{"elementType":"LINK","value":null}`, "[quoted content unavailable]"},
+ {"object link", `{"elementType":"LINK","value":{"url":"https://example.com"}}`, "[quoted content unavailable]"},
+ {"numeric link", `{"elementType":"LINK","value":42}`, "[quoted content unavailable]"},
+ {"empty link", `{"elementType":"LINK","value":""}`, "[quoted content unavailable]"},
+ {"blank link", `{"elementType":"LINK","value":" "}`, "[quoted content unavailable]"},
+ {"future node", `{"elementType":"FUTURE_NODE","value":"do not guess"},{"elementType":"TEXT","value":"after"}`, "[quoted content unavailable]\nafter"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ card := json.RawMessage(`[{"elementType":"RICHTEXT","children":[` + tc.children + `]}]`)
+ if got := renderDingTalkQuotedCard(card); got != tc.want {
+ t.Fatalf("got %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/dingtalk/markdown.go b/server/internal/integrations/dingtalk/markdown.go
index 2d6a0387a3..c3fa6a72c7 100644
--- a/server/internal/integrations/dingtalk/markdown.go
+++ b/server/internal/integrations/dingtalk/markdown.go
@@ -28,27 +28,17 @@ 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 preview for answers without a leading heading.
+ // defaultMarkdownTitle is used when an answer chunk contains only whitespace.
defaultMarkdownTitle = "Multica has replied."
)
-// markdownTitle derives the sampleMarkdown title (the notification preview) from
-// the body's first ATX heading, falling back to a default. The heading is left
-// in the body; only its leading hashes are stripped for the preview.
+// DingTalk's text quote callback carries the selected message's title.
+// Preserve the entire answer chunk. The sender budgets serialized title + text.
func markdownTitle(body string) string {
- for _, line := range strings.Split(body, "\n") {
- trimmed := strings.TrimSpace(line)
- if strings.HasPrefix(trimmed, "#") {
- heading := strings.TrimSpace(strings.TrimLeft(trimmed, "#"))
- if heading != "" {
- return heading
- }
- }
- if trimmed != "" {
- break
- }
+ if strings.TrimSpace(body) == "" {
+ return defaultMarkdownTitle
}
- return defaultMarkdownTitle
+ return body
}
// quotePreview is only the source-user excerpt displayed in an outbound reply.
@@ -135,7 +125,15 @@ func chunkMarkdown(body string) []string {
}
func chunkMarkdownWithBudget(body string, byteBudget int) []string {
+ return chunkMarkdownWithFirstBudget(body, byteBudget, byteBudget)
+}
+
+// Reserve attribution space only in the first emitted answer chunk. Later
+// chunks use the full budget, including when an oversized line is split.
+func chunkMarkdownWithFirstBudget(body string, firstBudget, laterBudget int) []string {
+ byteBudget := firstBudget
contentByteBudget := byteBudget - markdownSyntheticFenceCloseBytes
+ resetBudget := func() { byteBudget = laterBudget; contentByteBudget = byteBudget - markdownSyntheticFenceCloseBytes }
if len(body) <= byteBudget {
return []string{body}
}
@@ -163,6 +161,7 @@ func chunkMarkdownWithBudget(body string, byteBudget int) []string {
// after it — so it never renders as an empty code block.
if !isBlankChunk(text) {
chunks = append(chunks, text)
+ resetBudget()
}
cur.Reset()
if reopen && fenceOpen {
@@ -174,26 +173,33 @@ func chunkMarkdownWithBudget(body string, byteBudget int) []string {
// A single oversized line cannot fit a chunk; hard-split it.
if len(line) > contentByteBudget {
flush(true)
- pieceBudget := contentByteBudget
quotePrefix := ""
- if fenceOpen {
- 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.
+ if !fenceOpen && strings.HasPrefix(line, "> ") {
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
- // carry its own fences, or it would render as plain text.
+ for line != "" {
+ pieceBudget := contentByteBudget - len(quotePrefix)
+ if fenceOpen {
+ pieceBudget = byteBudget - len(fenceInfo) - len("\n") - len("\n```")
+ }
+ // Production budgets reserve room for the longest continuation fence.
+ if pieceBudget < utf8.UTFMax {
+ pieceBudget = utf8.UTFMax
+ }
+ cut := min(len(line), pieceBudget)
+ if cut < len(line) {
+ for cut > 0 && !utf8.RuneStart(line[cut]) {
+ cut--
+ }
+ }
+ piece := line[:cut]
+ line = line[cut:]
if fenceOpen {
piece = fenceInfo + "\n" + piece + "\n```"
}
- piece = quotePrefix + piece
- chunks = append(chunks, piece)
+ chunks = append(chunks, quotePrefix+piece)
+ resetBudget()
}
continue
}
diff --git a/server/internal/integrations/dingtalk/markdown_test.go b/server/internal/integrations/dingtalk/markdown_test.go
index 2323d77185..6eb2c48c5b 100644
--- a/server/internal/integrations/dingtalk/markdown_test.go
+++ b/server/internal/integrations/dingtalk/markdown_test.go
@@ -188,17 +188,43 @@ func TestQuotePreviewPreservesLiteralParagraphsAndByteBudget(t *testing.T) {
}
}
-func TestMarkdownTitle(t *testing.T) {
- cases := map[string]string{
- "# Heading one\nbody": "Heading one",
- "\n\n## Second\nmore": "Second",
- "no heading here": defaultMarkdownTitle,
- "plain line\n# late": defaultMarkdownTitle, // first non-empty line is not a heading
- "### spaced \nbody": "spaced",
- }
- for body, want := range cases {
- if got := markdownTitle(body); got != want {
- t.Errorf("markdownTitle(%q) = %q, want %q", body, got, want)
+func TestMarkdownTitlePreservesSource(t *testing.T) {
+ for _, body := range []string{
+ "# PR8125 标题\n\n第一段:苹果。\n\n第二段:香蕉。",
+ "\n## **Status** `ready` ##\nbody ",
+ "Read [the **result**](https://example.test/result?token=private).",
+ "Read [the result][report].\n\n[report]: https://example.test/result",
+ "![](https://example.test/private.png)",
+ "```go\nfmt.Println(\"# **hello** &amp;\")\n```",
+ "~~~sh\necho ready\n~~~",
+ " value := \"[keep](literal)\"\n",
+ "`**literal** &amp; \\*` and <https://example.test/result>",
+ "\\*literal\\* &amp; &#35; <tag>",
+ "- **First answer**\n- Second answer\n\n> Quoted answer",
+ "| Result | State |\n| --- | --- |\n| One | Done |",
+ "#\n\n---\n\n***\n\n>\n<!-- hidden -->",
+ strings.Repeat("界🚀", 2000) + "\n\nFinal conclusion.",
+ } {
+ if got := markdownTitle(body); got != body {
+ t.Errorf("title lost source: got=%q, want=%q", got, body)
+ }
+ }
+ for _, blank := range []string{"", " \n\t"} {
+ if got := markdownTitle(blank); got != defaultMarkdownTitle {
+ t.Errorf("blank title=%q, want fallback", got)
+ }
+ }
+}
+
+func TestChunkMarkdownWithFirstBudgetPreservesUTF8AtTinyBudgets(t *testing.T) {
+ const body = "界🚀界🚀"
+ chunks := chunkMarkdownWithFirstBudget(body, 1, 2)
+ if strings.Join(chunks, "") != body {
+ t.Fatal("small budgets lost or duplicated source bytes")
+ }
+ for _, chunk := range chunks {
+ if !utf8.ValidString(chunk) {
+ t.Fatal("small budgets split a UTF-8 rune")
}
}
}
diff --git a/server/internal/integrations/dingtalk/media_test.go b/server/internal/integrations/dingtalk/media_test.go
index cd0d777f1a..c656d5e9cb 100644
--- a/server/internal/integrations/dingtalk/media_test.go
+++ b/server/internal/integrations/dingtalk/media_test.go
@@ -480,3 +480,21 @@ func TestMediaResolver_RejectsHTTPSDowngradeRedirect(t *testing.T) {
t.Fatalf("downgrade redirect error = %v", err)
}
}
+
+func TestMediaResolver_SkipsObservedQuotedCardImage(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"card-image": pngBytes})
+ var cb botCallbackData
+ wire := `{"senderStaffId":"sender","conversationType":"1","msgtype":"text","text":{"content":"inspect","repliedMsg":{"msgType":"interactiveCard","content":{"cardContent":[{"elementType":"RICHTEXT","children":[{"elementType":"UNKNOWN","value":"{}"},{"elementType":"TEXT","value":"before"},{"elementType":"IMAGE","downloadCode":"card-image"},{"elementType":"TEXT","value":"after"}]}]}}}}`
+ if err := json.Unmarshal([]byte(wire), &cb); err != nil {
+ t.Fatal(err)
+ }
+ msg, ok := inboundFromCallback(&cb, "app-key")
+ if !ok {
+ t.Fatal("card rejected")
+ }
+ inst, id, _ := mediaFixture()
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, id, msg)
+ if len(got.MediaRefs) != 0 || env.resolves.Load() != 0 || len(env.store.uploads) != 0 || !strings.Contains(got.Text, "> before\n> [Image]\n> after") {
+ t.Fatalf("card image must remain a placeholder without downloading: %+v", got.MediaRefs)
+ }
+}
diff --git a/server/internal/integrations/dingtalk/outbound_db_test.go b/server/internal/integrations/dingtalk/outbound_db_test.go
index 9ffc070d4f..d76ef4ba11 100644
--- a/server/internal/integrations/dingtalk/outbound_db_test.go
+++ b/server/internal/integrations/dingtalk/outbound_db_test.go
@@ -202,7 +202,7 @@ func testOutboundSealedInput(t *testing.T, scenario string, restart bool) {
wantQuote = "> second question\n\n---\n\n"
wantSource = "second-message"
}
- if param.Title != defaultMarkdownTitle || param.Text != wantQuote+"first answer" {
+ if param.Title != "first answer" || param.Text != wantQuote+"first answer" {
t.Fatalf("wrong sealed quote: %q", param.Text)
}
if restart {
diff --git a/server/internal/integrations/dingtalk/outbound_payload_test.go b/server/internal/integrations/dingtalk/outbound_payload_test.go
index ebca396f5b..038156e85b 100644
--- a/server/internal/integrations/dingtalk/outbound_payload_test.go
+++ b/server/internal/integrations/dingtalk/outbound_payload_test.go
@@ -45,12 +45,13 @@ func TestSenderProactivePayloadBudgetPreservesBody(t *testing.T) {
func TestSenderQuotedChunksPreserveOneSourceAndWholeAnswer(t *testing.T) {
const prefix = "> question\n\n---\n\n"
for _, tc := range []struct {
- name string
- answer string
- standalone bool
+ name string
+ answer string
}{
{name: "combined", answer: "short answer"},
- {name: "standalone source", answer: strings.Repeat("a", 30000), standalone: true},
+ {name: "long single line", answer: strings.Repeat("a", 30000)},
+ {name: "14000 multi-line", answer: strings.Repeat("answer line\n", 1273)},
+ {name: "30000 multi-line", answer: strings.Repeat("answer line\n", 2728)},
} {
t.Run(tc.name, func(t *testing.T) {
d := newDingtalkSendServer(t)
@@ -68,8 +69,8 @@ func TestSenderQuotedChunksPreserveOneSourceAndWholeAnswer(t *testing.T) {
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)
+ if i == 0 && (!strings.HasPrefix(param.Text, prefix) || strings.TrimSpace(strings.TrimPrefix(param.Text, prefix)) == "") {
+ t.Fatalf("expected source with nonempty answer, got %q", param.Text)
}
body.WriteString(param.Text)
}
@@ -79,3 +80,77 @@ func TestSenderQuotedChunksPreserveOneSourceAndWholeAnswer(t *testing.T) {
})
}
}
+
+func TestQuotedFirstChunkReservesPrefixForFencedAnswer(t *testing.T) {
+ for _, line := range []string{strings.Repeat("界", 100) + "\n", strings.Repeat("界", 6000) + "\n"} {
+ code := strings.Repeat(line, 30)
+ chunks, err := replyMarkdownChunks("```go\n"+code+"```\n", "source")
+ if err != nil || len(chunks) < 2 {
+ t.Fatalf("chunking: %d %v", len(chunks), err)
+ }
+ prefix := prependMarkdownQuote("", "source")
+ var recovered strings.Builder
+ for i, chunk := range chunks {
+ body := chunk.text
+ if i == 0 {
+ if !strings.HasPrefix(body, prefix) {
+ t.Fatal("first answer has no source")
+ }
+ body = strings.TrimPrefix(body, prefix)
+ }
+ if chunk.title != body || !strings.HasPrefix(body, "```go\n") || isBlankChunk(body) {
+ t.Fatalf("first/title/fence invariant lost: %q", body)
+ }
+ raw, _ := json.Marshal(markdownParam{Title: chunk.title, Text: chunk.text})
+ if len(raw) > markdownPayloadByteBudget {
+ t.Fatal("payload exceeds limit")
+ }
+ body = strings.TrimPrefix(body, "```go\n")
+ if strings.HasSuffix(body, "```\n") {
+ body = strings.TrimSuffix(body, "```\n")
+ } else {
+ body = strings.TrimSuffix(body, "\n```")
+ }
+ recovered.WriteString(body)
+ }
+ if recovered.String() != code {
+ t.Fatal("fenced answer changed")
+ }
+ }
+}
+
+func TestSenderEscapedAnswerWithMultilineQuote(t *testing.T) {
+ for _, quote := range []string{strings.Repeat("a\n", 128), strings.Repeat("*\n", 128)} {
+ t.Run(quote[:1], func(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ answer := strings.Repeat("\x01", 16000)
+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group", QuoteText: quote}
+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, answer); err != nil {
+ t.Fatal(err)
+ }
+ prefix := prependMarkdownQuote("", quote)
+ var recovered strings.Builder
+ for i, sent := range d.sendBodies {
+ raw := sent["msgParam"].(string)
+ var param markdownParam
+ if err := json.Unmarshal([]byte(raw), &param); err != nil {
+ t.Fatal(err)
+ }
+ body := param.Text
+ if i == 0 {
+ if !strings.HasPrefix(body, prefix) {
+ t.Fatal("first answer lost source attribution")
+ }
+ body = strings.TrimPrefix(body, prefix)
+ }
+ if len(raw) > markdownPayloadByteBudget || body == "" || param.Title != body {
+ t.Fatal("wire budget, nonempty answer, or full title invariant violated")
+ }
+ recovered.WriteString(body)
+ }
+ if recovered.String() != answer {
+ t.Fatal("answer bytes were lost or duplicated")
+ }
+ })
+ }
+}
diff --git a/server/internal/integrations/dingtalk/outbound_preview_test.go b/server/internal/integrations/dingtalk/outbound_preview_test.go
new file mode 100644
index 0000000000..ae9af707e7
--- /dev/null
+++ b/server/internal/integrations/dingtalk/outbound_preview_test.go
@@ -0,0 +1,158 @@
+package dingtalk
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+ "unicode/utf8"
+)
+
+// The oracle is the request accepted by the transport, not the chunker's raw
+// string lengths. This catches both a large title and JSON escape expansion.
+func TestSender_SerializedMarkdownBudgetPreservesAnswer(t *testing.T) {
+ for _, transport := range []string{"group", "private"} {
+ for _, tc := range []struct{ name, answer, quote string }{
+ {"short answer", "**Result**: see [details](https://example.test/result?x=1&y=2).\n\nSecond paragraph.", "# Original question"},
+ {"reviewer example", strings.Repeat("a", 12000), ""},
+ {"paragraph boundary", strings.Repeat("a", 6000) + "\n\n" + strings.Repeat("b", 6000), ""},
+ {"old body boundary", strings.Repeat("b", 16000), ""},
+ {"documented limit", strings.Repeat("c", 15000), ""},
+ {"multibyte", strings.Repeat("界🚀", 6000), ""},
+ {"JSON escaping", strings.Repeat("<&>\"\\", 6000), ""},
+ {"control bytes", strings.Repeat("\x01", 16000), ""},
+ {"source quote", strings.Repeat("answer\n", 3000), strings.Repeat("Question <>&\"\n", 1200)},
+ } {
+ t.Run(transport+"/"+tc.name, func(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group", StaffID: "staff", QuoteText: tc.quote}
+ if transport == "private" {
+ target.ConversationType = convTypeP2P
+ }
+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, tc.answer); err != nil {
+ t.Fatal(err)
+ }
+ var delivered strings.Builder
+ prefix := ""
+ if transport != "private" {
+ prefix = prependMarkdownQuote("", tc.quote)
+ }
+ for i, body := range d.sendBodies {
+ var param markdownParam
+ raw := body["msgParam"].(string)
+ if len(raw) > 15000 {
+ t.Fatalf("chunk %d msgParam exceeds payload budget: %d", i, len(raw))
+ }
+ if err := json.Unmarshal([]byte(raw), &param); err != nil {
+ t.Fatal(err)
+ }
+ if !utf8.ValidString(param.Title) || !utf8.ValidString(param.Text) {
+ t.Fatalf("chunk %d has invalid UTF-8", i)
+ }
+
+ answerPart := param.Text
+ if i == 0 {
+ if !strings.HasPrefix(answerPart, prefix) {
+ t.Fatal("first chunk lost source attribution")
+ }
+ answerPart = strings.TrimPrefix(answerPart, prefix)
+ }
+ if strings.TrimSpace(answerPart) == "" {
+ t.Fatal("chunk has no answer")
+ }
+ if param.Title != answerPart {
+ t.Fatalf("chunk %d title lost answer bytes or included presentation metadata", i)
+ }
+ delivered.WriteString(param.Text)
+ }
+ want := tc.answer
+ if transport != "private" {
+ want = prependMarkdownQuote(want, tc.quote)
+ }
+ if delivered.String() != want {
+ t.Fatalf("answer or quote was lost, duplicated or changed: received %d bytes, want %d", delivered.Len(), len(want))
+ }
+ })
+ }
+ }
+}
+
+func TestSender_FullCodeTitlesPreserveSourceAndApplyQuotePolicy(t *testing.T) {
+ code := strings.Repeat("const available = primary || fallback;\n", 700)
+ for _, transport := range []string{"group", "private"} {
+ t.Run(transport, func(t *testing.T) {
+ d := newDingtalkSendServer(t)
+ target := sendTarget{ConversationType: convTypeGroup, ConversationID: "group"}
+ if transport == "private" {
+ target.ConversationType = convTypeP2P
+ target.StaffID = "staff"
+ }
+ if _, err := newTestSender(NewClient(nil, d.srv.URL)).send(context.Background(), target, "```js\n"+code+"```\n"); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.sendBodies) < 2 {
+ t.Fatal("long fenced answer did not split")
+ }
+ var recovered strings.Builder
+ for i, body := range d.sendBodies {
+ var param markdownParam
+ wire := []byte(body["msgParam"].(string))
+ if err := json.Unmarshal(wire, &param); err != nil {
+ t.Fatal(err)
+ }
+ if len(wire) > 15000 || param.Title != param.Text || !strings.HasPrefix(param.Title, "```js\n") {
+ t.Fatalf("chunk %d has an incomplete code title or exceeds wire budget", i)
+ }
+ closing := "\n```" // Synthetic close on all non-final chunks.
+ if i == len(d.sendBodies)-1 {
+ closing = "```\n" // Original closing line.
+ }
+ if !strings.HasSuffix(param.Title, closing) {
+ t.Fatalf("chunk %d lost its closing fence", i)
+ }
+ recovered.WriteString(strings.TrimSuffix(strings.TrimPrefix(param.Title, "```js\n"), closing))
+ cb := textCallback(target.ConversationType, true)
+ cb.Text.Content = "explain"
+ cb.Text.RepliedMsg = &botCallbackRepliedMessage{MsgType: "text", Content: botCallbackRepliedContent{Text: param.Title}}
+ msg, ok := inboundFromCallback(cb, "app")
+ want := "> [quoted content unavailable]\n\nexplain"
+ if !ok || msg.Text != want || msg.CommandText != "explain" {
+ t.Fatalf("chunk %d did not retain the upstream quote policy", i)
+ }
+ }
+ if recovered.String() != code {
+ t.Fatal("splitting lost, duplicated or altered source code")
+ }
+ })
+ }
+}
+
+// Simulate a provider callback carrying the sent title. This proves local
+// round-trip handling, not provider acceptance or actual client callback bytes.
+func TestSender_TitleQuoteRoundTripPreservesCompleteMarkdown(t *testing.T) {
+ const answer = "第一段判断。\n\n第二段有 <tag> 和 [资料](https://example.test/a?x=1&y=2)。\n\n```js\nconst available = primary;\n```\n\n第三段结论。"
+ const instruction = "请解释第二段"
+ for _, conversationType := range []string{convTypeGroup, convTypeP2P} {
+ d := newDingtalkSendServer(t)
+ target := sendTarget{ConversationType: conversationType, ConversationID: "group", 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("short answer split into %d messages", len(d.sendBodies))
+ }
+ var param markdownParam
+ if err := json.Unmarshal([]byte(d.sendBodies[0]["msgParam"].(string)), &param); err != nil {
+ t.Fatal(err)
+ }
+ cb := textCallback(conversationType, true)
+ cb.Text.Content = instruction
+ cb.Text.IsReplyMsg = true
+ cb.Text.RepliedMsg = &botCallbackRepliedMessage{MsgType: "text", MsgId: "quoted-answer", Content: botCallbackRepliedContent{Text: param.Title}}
+ msg, ok := inboundFromCallback(cb, "test-app")
+ want := "> 第一段判断。\n>\n> 第二段有 <tag> 和 [资料](https://example.test/a?x=1&y=2)。\n>\n> ```js\n> const available = primary;\n> ```\n>\n> 第三段结论。\n\n" + instruction
+ if !ok || msg.Text != want || msg.CommandText != instruction {
+ t.Fatalf("unexpected selected context or instruction: ok=%v, text=%q, command=%q", ok, msg.Text, msg.CommandText)
+ }
+ }
+}
diff --git a/server/internal/integrations/dingtalk/outbound_quote_regression_test.go b/server/internal/integrations/dingtalk/outbound_quote_regression_test.go
index b34e59bd13..9c49ee88d8 100644
--- a/server/internal/integrations/dingtalk/outbound_quote_regression_test.go
+++ b/server/internal/integrations/dingtalk/outbound_quote_regression_test.go
@@ -55,7 +55,7 @@ func TestSender_QuotedURLsPreserveSourceBytes(t *testing.T) {
if transport == "private" {
want = "answer"
}
- if param.Text != want || param.Title != defaultMarkdownTitle {
+ if param.Text != want || param.Title != "answer" {
t.Fatalf("wire Markdown = %#v; want title=answer, text=%q", param, want)
}
})
diff --git a/server/internal/integrations/dingtalk/outbound_send.go b/server/internal/integrations/dingtalk/outbound_send.go
index 80aa3c04d1..5792be8a99 100644
--- a/server/internal/integrations/dingtalk/outbound_send.go
+++ b/server/internal/integrations/dingtalk/outbound_send.go
@@ -104,21 +104,17 @@ func replyMarkdownChunks(text, quote string) ([]replyMarkdownChunk, error) {
}
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.
+ prefix := prependMarkdownQuote("", quote)
+ // A multiline quote can outgrow the shrinking body budget while its wire
+ // payload still fits. Keep room for an answer and continuation fence; the
+ // caller validates the combined serialized prefix, title and body.
+ firstBudget := max(byteBudget-len(prefix), maxMarkdownFenceInfoBytes+32)
+ bodies := chunkMarkdownWithFirstBudget(text, firstBudget, byteBudget)
+ chunks := make([]replyMarkdownChunk, 0, len(bodies))
+ for i, body := range bodies {
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
- }
+ chunk.text = prefix + body
}
chunks = append(chunks, chunk)
}
diff --git a/server/internal/integrations/dingtalk/outbound_send_test.go b/server/internal/integrations/dingtalk/outbound_send_test.go
index c50f0d33dd..9e5d6cbec5 100644
--- a/server/internal/integrations/dingtalk/outbound_send_test.go
+++ b/server/internal/integrations/dingtalk/outbound_send_test.go
@@ -425,7 +425,7 @@ func TestSender_LongSingleLineAnswerBlockquotePreservesEveryChunk(t *testing.T)
if err := json.Unmarshal([]byte(raw), &param); err != nil {
t.Fatal(err)
}
- if len(raw) > 15000 || !strings.HasPrefix(param.Text, "> ") || param.Title != defaultMarkdownTitle {
+ if len(raw) > 15000 || !strings.HasPrefix(param.Text, "> ") || param.Title != param.Text {
t.Fatalf("chunk %d lost its blockquote/title or exceeded the payload budget: %q", i, raw)
}
joined.WriteString(strings.TrimPrefix(param.Text, "> "))
diff --git a/server/internal/integrations/dingtalk/testdata/quoted_bot_channels.json b/server/internal/integrations/dingtalk/testdata/quoted_bot_channels.json
new file mode 100644
index 0000000000..a8d471a9cb
--- /dev/null
+++ b/server/internal/integrations/dingtalk/testdata/quoted_bot_channels.json
@@ -0,0 +1,122 @@
+[
+ {
+ "name": "ant/1",
+ "callback": {
+ "senderStaffId": "sender",
+ "conversationId": "chat",
+ "conversationType": "1",
+ "isInAtList": true,
+ "msgId": "current",
+ "originalMsgId": "selected",
+ "msgtype": "text",
+ "text": {
+ "content": "引用测试",
+ "isReplyMsg": true,
+ "repliedMsg": {
+ "msgType": "text",
+ "content": {
+ "text": "DingTalk source probe 001."
+ },
+ "msgId": "selected"
+ }
+ }
+ }
+ },
+ {
+ "name": "ant/2",
+ "callback": {
+ "senderStaffId": "sender",
+ "conversationId": "chat",
+ "conversationType": "2",
+ "isInAtList": true,
+ "msgId": "current",
+ "originalMsgId": "selected",
+ "msgtype": "text",
+ "text": {
+ "content": "引用测试",
+ "isReplyMsg": true,
+ "repliedMsg": {
+ "msgType": "text",
+ "content": {
+ "text": "DingTalk source probe 001."
+ },
+ "msgId": "selected"
+ }
+ }
+ }
+ },
+ {
+ "name": "community/1",
+ "callback": {
+ "senderStaffId": "sender",
+ "conversationId": "chat",
+ "conversationType": "1",
+ "isInAtList": true,
+ "msgId": "current",
+ "originalMsgId": "selected",
+ "msgtype": "text",
+ "text": {
+ "content": "引用测试",
+ "isReplyMsg": true,
+ "repliedMsg": {
+ "msgType": "interactiveCard",
+ "content": {
+ "cardContent": [
+ {
+ "elementType": "RICHTEXT",
+ "children": [
+ {
+ "elementType": "TEXT",
+ "value": "DingTalk source probe 001."
+ }
+ ]
+ }
+ ]
+ },
+ "msgId": "selected"
+ }
+ }
+ }
+ },
+ {
+ "name": "community/2",
+ "callback": {
+ "senderStaffId": "sender",
+ "conversationId": "chat",
+ "conversationType": "2",
+ "isInAtList": true,
+ "msgId": "current",
+ "originalMsgId": "selected",
+ "msgtype": "text",
+ "text": {
+ "content": "引用测试",
+ "isReplyMsg": true,
+ "repliedMsg": {
+ "msgType": "interactiveCard",
+ "content": {
+ "cardContent": [
+ {
+ "elementType": "RICHTEXT",
+ "children": [
+ {
+ "elementType": "UNKNOWN",
+ "value": "{\"content\": [{\"type\": \"text\", \"data\": {\"text\": \"直接回复“DingTalk source probe 001.”\"}}]}"
+ },
+ {
+ "elementType": "UNKNOWN",
+ "value": "{}"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "DingTalk source probe 001."
+ }
+ ]
+ }
+ ]
+ },
+ "msgId": "selected"
+ }
+ }
+ }
+ }
+]
diff --git a/server/internal/integrations/dingtalk/testdata/quoted_card_link_group.json b/server/internal/integrations/dingtalk/testdata/quoted_card_link_group.json
new file mode 100644
index 0000000000..a4f9b79604
--- /dev/null
+++ b/server/internal/integrations/dingtalk/testdata/quoted_card_link_group.json
@@ -0,0 +1,68 @@
+{
+ "conversationType": "2",
+ "msgtype": "text",
+ "senderStaffId": "test-sender",
+ "text": {
+ "content": "QUOTE-CAPTURE-7429",
+ "repliedMsg": {
+ "msgType": "interactiveCard",
+ "content": {
+ "cardContent": [
+ {
+ "children": [
+ {
+ "elementType": "UNKNOWN",
+ "value": "sanitized source attribution"
+ },
+ {
+ "elementType": "UNKNOWN",
+ "value": "sanitized layout"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "DingTalk quote test"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph one: Apples are red."
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph two: Bananas are yellow. Marker: QUOTE-CONTEXT-7429."
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Literal HTML: "
+ },
+ {
+ "elementType": "TEXT",
+ "value": "keep this visible"
+ },
+ {
+ "elementType": "TEXT",
+ "value": " Literal operators: primary || fallback Escaped entity: <already-escaped>"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Link: "
+ },
+ {
+ "elementType": "LINK",
+ "value": "https://example.com/a_(b)?x=a_b+c&y=2#part_2"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "const selected = primary || fallback;\nconst html = \"<span>keep me</span>\";\nconsole.log(selected, html);\n"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph three: Cherries are sweet."
+ }
+ ],
+ "elementType": "RICHTEXT"
+ }
+ ]
+ }
+ }
+ }
+}
diff --git a/server/internal/integrations/dingtalk/testdata/quoted_card_link_private.json b/server/internal/integrations/dingtalk/testdata/quoted_card_link_private.json
new file mode 100644
index 0000000000..c2977c7327
--- /dev/null
+++ b/server/internal/integrations/dingtalk/testdata/quoted_card_link_private.json
@@ -0,0 +1,60 @@
+{
+ "conversationType": "1",
+ "msgtype": "text",
+ "senderStaffId": "test-sender",
+ "text": {
+ "content": "QUOTE-CAPTURE-7429",
+ "repliedMsg": {
+ "msgType": "interactiveCard",
+ "content": {
+ "cardContent": [
+ {
+ "children": [
+ {
+ "elementType": "TEXT",
+ "value": "DingTalk quote test"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph one: Apples are red."
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph two: Bananas are yellow. Marker: QUOTE-CONTEXT-7429."
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Literal HTML: "
+ },
+ {
+ "elementType": "TEXT",
+ "value": "keep this visible"
+ },
+ {
+ "elementType": "TEXT",
+ "value": " Literal operators: primary || fallback Escaped entity: <already-escaped>"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Link: "
+ },
+ {
+ "elementType": "LINK",
+ "value": "https://example.com/a_(b)?x=a_b+c&y=2#part_2"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "const selected = primary || fallback;\nconst html = \"<span>keep me</span>\";\nconsole.log(selected, html);\n"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Paragraph three: Cherries are sweet."
+ }
+ ],
+ "elementType": "RICHTEXT"
+ }
+ ]
+ }
+ }
+ }
+}
diff --git a/server/internal/integrations/dingtalk/testdata/quoted_interactive_card.json b/server/internal/integrations/dingtalk/testdata/quoted_interactive_card.json
new file mode 100644
index 0000000000..0a98a42d49
--- /dev/null
+++ b/server/internal/integrations/dingtalk/testdata/quoted_interactive_card.json
@@ -0,0 +1,45 @@
+{
+ "msgId": "current-message",
+ "originalMsgId": "selected-bot-message",
+ "conversationId": "test-chat",
+ "conversationType": "1",
+ "senderStaffId": "test-sender",
+ "msgtype": "text",
+ "text": {
+ "content": "explain",
+ "isReplyMsg": true,
+ "repliedMsg": {
+ "msgType": "interactiveCard",
+ "msgId": "selected-bot-message",
+ "content": {
+ "cardContent": [
+ {
+ "children": [
+ {
+ "elementType": "UNKNOWN",
+ "value": "{\"content\":[{\"data\":{\"text\":\"> [quoted content unavailable]\"},\"style\":{\"colorTokenV2\":\"common_level1_base_color\",\"sizeToken\":\"common_body_text_style__font_size\",\"lineHeightToken\":\"common_body_text_style__line_height\"},\"type\":\"text\"},{\"data\":{},\"style\":{\"gap\":14},\"type\":\"paragraphSpace\"},{\"data\":{\"text\":\"Repeat paragraph two from the quoted message, then reproduce the JavaScript code exactly.\"},\"style\":{\"colorTokenV2\":\"common_level1_base_color\",\"sizeToken\":\"common_body_text_style__font_size\",\"lineHeightToken\":\"common_body_text_style__line_height\"},\"type\":\"text\"}]}"
+ },
+ {
+ "elementType": "UNKNOWN",
+ "value": "{}"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "Bananas. Literal text: "
+ },
+ {
+ "elementType": "TEXT",
+ "value": ". Link: https://example.com/a_(b)?x=a_b+c&y=2#part_2"
+ },
+ {
+ "elementType": "TEXT",
+ "value": "const available = primary || fallback;\n"
+ }
+ ],
+ "elementType": "RICHTEXT"
+ }
+ ]
+ }
+ }
+ }
+}