Skip to content

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

Go

MUL-7019 MUL-7963 fix(wecom): fetch the picture a sender quoted, not just its label (#8832)

Xichang(Seacen) Zhao55e1ebe66698
diff --git a/server/internal/integrations/channel/engine/inline_id_marker_test.go b/server/internal/integrations/channel/engine/inline_id_marker_test.go
new file mode 100644
index 0000000000..33748a6a1c
--- /dev/null
+++ b/server/internal/integrations/channel/engine/inline_id_marker_test.go
@@ -0,0 +1,78 @@
+package engine
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+func testRefID(t *testing.T) pgtype.UUID {
+ t.Helper()
+ id, err := uuid.Parse("019fe1d3-0000-7000-8000-000000000001")
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ return pgtype.UUID{Bytes: id, Valid: true}
+}
+
+// A marker that REFERS to an attachment is rewritten to name it, not to embed
+// it. An adapter asks for this when the thing the marker stands for belongs to
+// somebody else's message — a quoted picture — and embedding it would state
+// this sender attached it.
+func TestAnIDOnlyMarkerNamesTheAttachmentInstead(t *testing.T) {
+ t.Parallel()
+ id := testRefID(t)
+ ref := channel.MediaRef{
+ Type: channel.MsgTypeImage,
+ InlinePlaceholder: "[Image: unavailable]",
+ InlineIDOnly: true,
+ }
+ got := inlineMediaMarkdown(ref, id)
+ want := "[Image: " + uuid.UUID(id.Bytes).String() + "]"
+ if got != want {
+ t.Fatalf("inlineMediaMarkdown = %q, want %q", got, want)
+ }
+ if strings.Contains(got, "/download") || strings.HasPrefix(got, "!") {
+ t.Errorf("the marker was replaced by an embed (%q) — that says this sender attached a "+
+ "picture from somebody else's message", got)
+ }
+}
+
+// The ordinary case is untouched: an attachment the sender made is still
+// embedded, which is what every existing adapter relies on.
+func TestAnOrdinaryMarkerIsStillEmbedded(t *testing.T) {
+ t.Parallel()
+ id := testRefID(t)
+ ref := channel.MediaRef{Type: channel.MsgTypeImage, InlinePlaceholder: "[Image]"}
+ got := inlineMediaMarkdown(ref, id)
+ if !strings.Contains(got, "/download") {
+ t.Fatalf("inlineMediaMarkdown = %q, want the attachment embedded", got)
+ }
+}
+
+// The label ahead of the colon is whatever the adapter called the thing, and
+// only the state word after it is replaced. The two spellings are derived from
+// each other rather than written twice, so a new label needs no change here.
+func TestTheLabelSurvivesTheRewrite(t *testing.T) {
+ t.Parallel()
+ id := testRefID(t)
+ for marker, want := range map[string]string{
+ "[Image: unavailable]": "[Image: ",
+ "[File: unavailable]": "[File: ",
+ "[Video: unavailable]": "[Video: ",
+ "[Image]": "[Image: ",
+ "[]": "[",
+ } {
+ got := inlineAttachmentIDMarker(marker, id)
+ if !strings.HasPrefix(got, want) {
+ t.Errorf("inlineAttachmentIDMarker(%q) = %q, want it to start %q", marker, got, want)
+ }
+ if !strings.Contains(got, uuid.UUID(id.Bytes).String()) {
+ t.Errorf("inlineAttachmentIDMarker(%q) = %q, want it to carry the id", marker, got)
+ }
+ }
+}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index daa7f727db..d914c511f3 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -1066,7 +1066,14 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
media.ref.Type == channel.MsgTypeImage,
)
issueMarkdown = append(issueMarkdown, block)
- if media.ref.InlinePlaceholder != "" {
+ // InlineIDOnly markers are left out on purpose. A marker that only
+ // refers to an attachment sits in the adapter's quoted context,
+ // which composeIssueCommandMediaDescription excludes from the
+ // description by contract; materializing it here would put
+ // somebody else's picture into the issue body as if the reporter
+ // had attached it. The attachment itself is still created and
+ // still listed above.
+ if media.ref.InlinePlaceholder != "" && !media.ref.InlineIDOnly {
replacements = append(replacements, inlineMediaReplacement{
placeholder: media.ref.InlinePlaceholder,
index: media.ref.InlineIndex,
@@ -1123,7 +1130,7 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
replacements = append(replacements, inlineMediaReplacement{
placeholder: media.ref.InlinePlaceholder,
index: media.ref.InlineIndex,
- markdown: inlineAttachmentMarkdown(media.ref, media.id),
+ markdown: inlineMediaMarkdown(media.ref, media.id),
})
}
if body, changed := composeInlineMediaBody(in.Body, replacements); changed {
@@ -1256,6 +1263,39 @@ func nthSubstringIndex(body, marker string, target int) int {
}
}
+// inlineMediaMarkdown is what an adapter's marker is replaced with once the
+// attachment behind it exists — either the object embedded, or the marker
+// naming it. See channel.MediaRef.InlineIDOnly for which an adapter asks for
+// and why.
+func inlineMediaMarkdown(ref channel.MediaRef, id pgtype.UUID) string {
+ if ref.InlineIDOnly {
+ return inlineAttachmentIDMarker(ref.InlinePlaceholder, id)
+ }
+ return inlineAttachmentMarkdown(ref, id)
+}
+
+// inlineAttachmentIDMarker rewrites a bracketed marker so it names the
+// attachment it stands for: "[Image: unavailable]" becomes
+// "[Image: 019fe1d3-…]".
+//
+// Everything up to the first colon is kept, so the label is whatever the
+// adapter called the thing and the engine only replaces the state word after
+// it. That is deliberate — the marker the adapter renders and the marker that
+// replaces it have to stay the same shape for a reader to see them as one
+// thing, and the only way to guarantee that is to derive one from the other
+// rather than spell the vocabulary out twice.
+func inlineAttachmentIDMarker(marker string, id pgtype.UUID) string {
+ label := strings.TrimSuffix(strings.TrimPrefix(marker, "["), "]")
+ if colon := strings.IndexByte(label, ':'); colon >= 0 {
+ label = label[:colon]
+ }
+ label = strings.TrimSpace(label)
+ if label == "" {
+ return "[" + uuid.UUID(id.Bytes).String() + "]"
+ }
+ return "[" + label + ": " + uuid.UUID(id.Bytes).String() + "]"
+}
+
func inlineAttachmentMarkdown(ref channel.MediaRef, id pgtype.UUID) string {
downloadPath := "/api/attachments/" + uuid.UUID(id.Bytes).String() + "/download"
if ref.Type == channel.MsgTypeImage {
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 3830fde362..f4b9e1d052 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -104,6 +104,17 @@ type MediaRef struct {
// partial media failure cannot shift later attachments into the wrong place.
InlinePlaceholder string
InlineIndex int
+ // InlineIDOnly makes that replacement name the attachment instead of
+ // embedding it: the marker becomes itself carrying the attachment's id,
+ // "[Image: 019fe1d3-…]", rather than a Markdown link to the object.
+ //
+ // Set it when the marker REFERS to an attachment rather than carrying
+ // one — a picture the message quotes belongs to a message somebody else
+ // sent, and rendering it inline would state this sender attached it. The
+ // id is the point either way: it is what joins the marker to the entry
+ // the agent sees in the attachment list, and what it passes to
+ // `multica attachment download`.
+ InlineIDOnly bool
}
// ReplyCtx describes the message an inbound message quotes / replies to.
diff --git a/server/internal/integrations/wecom/media_ingest.go b/server/internal/integrations/wecom/media_ingest.go
index 3e2ca4803c..63cef5daef 100644
--- a/server/internal/integrations/wecom/media_ingest.go
+++ b/server/internal/integrations/wecom/media_ingest.go
@@ -209,14 +209,14 @@ func (r *wecomMediaResolver) ingestOne(ctx context.Context, inst engine.Resolved
// reorder with it. The intent row covers the object either way.
return channel.MediaRef{}, fmt.Errorf("upload media: %w", err)
}
- return channel.MediaRef{
+ return m.inline(channel.MediaRef{
Type: m.Kind,
StorageKey: key,
StorageURL: link,
Filename: filename,
MimeType: contentType,
SizeBytes: int64(len(plain)),
- }, nil
+ }), nil
}
// mediaObjectKey names the object. It is derived from the CHAT message rather
@@ -469,12 +469,12 @@ func (r *wecomMediaResolver) ingestStreaming(
if _, err := streamer.UploadStream(ctx, key, plain, size, contentType, filename); err != nil {
return channel.MediaRef{}, fmt.Errorf("upload media: %w", err)
}
- return channel.MediaRef{
+ return m.inline(channel.MediaRef{
Type: m.Kind,
StorageKey: key,
StorageURL: link,
Filename: filename,
MimeType: contentType,
SizeBytes: size,
- }, nil
+ }), nil
}
diff --git a/server/internal/integrations/wecom/quoted_marker_position_test.go b/server/internal/integrations/wecom/quoted_marker_position_test.go
new file mode 100644
index 0000000000..74997ba56a
--- /dev/null
+++ b/server/internal/integrations/wecom/quoted_marker_position_test.go
@@ -0,0 +1,405 @@
+package wecom
+
+// quoted_marker_position_test.go — a quoted attachment is bound to the marker
+// the agent reads, so the number that says WHICH occurrence of the marker it is
+// has to be taken from the text the agent reads.
+//
+// The rule, in one line: every attachment handed over for a quote has its
+// marker in the final body, and its InlineIndex is the position of that marker
+// there — not the attachment's place in the quote's list of attachments.
+//
+// Two ways to break it were found by review of the first version, and they are
+// the same break: that version numbered a quoted attachment by counting the
+// attachments before it and rendered the text separately.
+//
+// - A quoted sentence that spells the marker out ("The UI displays [Image:
+// unavailable]") is an occurrence of it to the engine's search, which looks
+// for the Nth occurrence in the stored body. The picture was numbered 0, the
+// binder rewrote the sentence, and the real marker stayed "unavailable".
+// - The 500-rune cut removed a marker that the attachment list still counted,
+// so the picture was fetched and the quote never named it.
+//
+// Everything here goes through the real callback decoder and
+// channelMessageFromCallback, then asks the one question that matters of the
+// body that comes out: does the Nth occurrence of this attachment's marker sit
+// on the line that stands for it. The same two scenarios run end to end through
+// the real binder in quoted_media_bind_db_test.go.
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+type wire = map[string]any
+
+func qWords(s string) wire { return wire{"msgtype": "text", "text": wire{"content": s}} }
+func qImage(url, key string) wire {
+ return wire{"msgtype": "image", "image": wire{"url": url, "aeskey": key}}
+}
+func qFile(url, key string) wire {
+ return wire{"msgtype": "file", "file": wire{"url": url, "aeskey": key}}
+}
+
+// replyTo decodes a callback that quotes a mixed message made of quoted, through
+// the real JSON decoder, and builds the message the Router would be handed.
+// own is the sender's own 图文混排; an empty own sends the plain words
+// "这个怎么处理".
+func replyTo(t *testing.T, quoted []wire, own []wire) channel.InboundMessage {
+ t.Helper()
+ return replyToAs(t, "wb-1", "T-alex", "MSGID-QPOS", quoted, own)
+}
+
+// replyToAs is replyTo for a bot and sender that exist in a database.
+func replyToAs(t *testing.T, botID, senderID, msgID string, quoted []wire, own []wire) channel.InboundMessage {
+ t.Helper()
+ body := wire{
+ "msgid": msgID,
+ "aibotid": botID,
+ "chattype": "single",
+ "chatid": senderID,
+ "from": wire{"userid": senderID},
+ "quote": wire{"msgtype": "mixed", "mixed": wire{"msg_item": quoted}},
+ }
+ if len(own) == 0 {
+ body["msgtype"] = "text"
+ body["text"] = wire{"content": "这个怎么处理"}
+ } else {
+ body["msgtype"] = "mixed"
+ body["mixed"] = wire{"msg_item": own}
+ }
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatalf("marshal callback: %v", err)
+ }
+ var mc aibotMsgCallback
+ if err := json.Unmarshal(raw, &mc); err != nil {
+ t.Fatalf("decode callback: %v", err)
+ }
+ text, ok := mc.ownText()
+ if !ok {
+ t.Fatal("callback is not routable; the fixture is wrong")
+ }
+ return channelMessageFromCallback(botID, "", mc, text, "req-qpos")
+}
+
+// nthOccurrence is how the engine finds a marker: the Nth non-overlapping
+// occurrence of the marker string anywhere in the stored body (engine
+// nthSubstringIndex). Written out here so the test does not borrow the code
+// whose input it is checking.
+func nthOccurrence(body, marker string, n int) int {
+ offset := 0
+ for i := 0; ; i++ {
+ found := strings.Index(body[offset:], marker)
+ if found < 0 {
+ return -1
+ }
+ found += offset
+ if i == n {
+ return found
+ }
+ offset = found + len(marker)
+ }
+}
+
+// quotedAttachments is what the quote contributed to msg.Media: the entries
+// stamped with a marker. The sender's own attachments carry none.
+func quotedAttachments(msg channel.InboundMessage) []InboundMedia {
+ var out []InboundMedia
+ for _, m := range wecomMedia(msg) {
+ if m.InlinePlaceholder != "" {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+func wecomMedia(msg channel.InboundMessage) []InboundMedia {
+ var raw struct {
+ Media []InboundMedia `json:"media"`
+ }
+ // The wecom envelope rides in Raw; see channelMessageFromCallback.
+ if err := json.Unmarshal(msg.Raw, &raw); err != nil {
+ return nil
+ }
+ return raw.Media
+}
+
+// realMarkerOffsets lists, in order, where a line that IS an attachment's
+// marker sits in body. A real marker is a line of its own inside the quote
+// block; a sentence that merely contains the marker text is not one.
+func realMarkerOffsets(body string) []struct {
+ offset int
+ marker string
+} {
+ var out []struct {
+ offset int
+ marker string
+ }
+ pos := 0
+ for _, line := range strings.SplitAfter(body, "\n") {
+ content := strings.TrimRight(line, "\n")
+ prefix := ""
+ switch {
+ case strings.HasPrefix(content, "> "+quotePrefix+" "):
+ prefix = "> " + quotePrefix + " "
+ case strings.HasPrefix(content, "> "):
+ prefix = "> "
+ }
+ if prefix != "" {
+ rest := strings.TrimSuffix(strings.TrimPrefix(content, prefix), "…")
+ for _, kind := range []channel.MsgType{channel.MsgTypeImage, channel.MsgTypeFile, channel.MsgTypeVideo} {
+ if rest == quotedMediaPlaceholder(kind) {
+ out = append(out, struct {
+ offset int
+ marker string
+ }{pos + len(prefix), rest})
+ }
+ }
+ }
+ pos += len(line)
+ }
+ return out
+}
+
+// assertEachMarkerLandsOnItsOwnLine is the invariant: for every quoted
+// attachment handed over, the Nth occurrence of its marker in the body — the
+// place the binder will rewrite — is the marker line that stands for it, and
+// there is exactly one such line per attachment.
+func assertEachMarkerLandsOnItsOwnLine(t *testing.T, msg channel.InboundMessage, wantAttachments int) {
+ t.Helper()
+ media := quotedAttachments(msg)
+ if len(media) != wantAttachments {
+ t.Fatalf("quoted attachments = %d, want %d", len(media), wantAttachments)
+ }
+ lines := realMarkerOffsets(msg.Text)
+ if len(lines) != len(media) {
+ t.Fatalf("marker lines in the body = %d, quoted attachments handed over = %d — an attachment "+
+ "was fetched whose marker the agent cannot see, or a marker has nothing behind it\nbody: %q",
+ len(lines), len(media), msg.Text)
+ }
+ for i, m := range media {
+ if lines[i].marker != m.InlinePlaceholder {
+ t.Errorf("attachment %d stands for %q but line %d of markers is %q", i, m.InlinePlaceholder, i, lines[i].marker)
+ continue
+ }
+ got := nthOccurrence(msg.Text, m.InlinePlaceholder, m.InlineIndex)
+ if got != lines[i].offset {
+ t.Errorf("attachment %d is marker %q occurrence #%d, which sits at byte %d; its own marker line is at byte %d — "+
+ "the binder would rewrite the wrong text and leave this picture unnamed\nbody: %q",
+ i, m.InlinePlaceholder, m.InlineIndex, got, lines[i].offset, msg.Text)
+ }
+ }
+}
+
+const (
+ imgMarker = "[Image: unavailable]"
+ fileMarker = "[File: unavailable]"
+ urlA = "https://example.invalid/a"
+ urlB = "https://example.invalid/b"
+ urlC = "https://example.invalid/c"
+)
+
+// Review finding 1, as described: the words quoted ahead of the picture spell
+// the marker out.
+func TestAQuotedSentenceThatSpellsTheMarkerDoesNotStealTheIndex(t *testing.T) {
+ t.Parallel()
+ msg := replyTo(t, []wire{
+ qWords("The UI displays " + imgMarker),
+ qImage(urlA, "A"),
+ }, nil)
+
+ media := quotedAttachments(msg)
+ if len(media) != 1 {
+ t.Fatalf("quoted attachments = %d, want 1", len(media))
+ }
+ if media[0].InlineIndex != 1 {
+ t.Errorf("InlineIndex = %d, want 1 — the sentence is occurrence 0 and the picture's own marker is 1; "+
+ "numbering it 0 makes the binder rewrite the sentence", media[0].InlineIndex)
+ }
+ assertEachMarkerLandsOnItsOwnLine(t, msg, 1)
+}
+
+// The index is a position in the rendered text, so it has to hold for every
+// arrangement of words and markers around it.
+func TestQuotedMarkerIndexFollowsTheRenderedText(t *testing.T) {
+ t.Parallel()
+ long := strings.Repeat("字", 600)
+ cases := []struct {
+ name string
+ quoted []wire
+ own []wire
+ indices []int // InlineIndex of each quoted attachment, in order
+ }{
+ {
+ name: "a picture alone",
+ quoted: []wire{qImage(urlA, "A")},
+ indices: []int{0},
+ },
+ {
+ name: "words that do not mention the marker",
+ quoted: []wire{qWords("看这个"), qImage(urlA, "A")},
+ indices: []int{0},
+ },
+ {
+ name: "the literal is spelled twice before the picture",
+ quoted: []wire{qWords(imgMarker + " and again " + imgMarker), qImage(urlA, "A")},
+ indices: []int{2},
+ },
+ {
+ name: "the literal comes after the real marker",
+ quoted: []wire{qImage(urlA, "A"), qWords("shown as " + imgMarker)},
+ indices: []int{0},
+ },
+ {
+ name: "literals between and around two pictures",
+ quoted: []wire{
+ qWords("see " + imgMarker), qImage(urlA, "A"), qWords("see " + imgMarker), qImage(urlB, "B"), qWords("see " + imgMarker),
+ },
+ indices: []int{1, 3},
+ },
+ {
+ name: "a literal of one kind moves only that kind's index",
+ quoted: []wire{qWords("see " + fileMarker), qImage(urlA, "A"), qFile(urlB, "B")},
+ indices: []int{0, 1},
+ },
+ {
+ name: "the sender's own words spell the marker",
+ quoted: []wire{qImage(urlA, "A")},
+ own: []wire{qWords("it says " + imgMarker), qImage(urlC, "C")},
+ indices: []int{0},
+ },
+ {
+ // 490 + the first 10 runes of the literal survive the cut; ten runes
+ // of a marker are not an occurrence of it.
+ name: "the cut splits a literal in half",
+ quoted: []wire{qWords(strings.Repeat("字", 490) + imgMarker), qImage(urlA, "A")},
+ indices: []int{0},
+ },
+ {
+ name: "a literal past the cut is gone from the body and is not counted",
+ quoted: []wire{qWords(long + imgMarker), qImage(urlA, "A")},
+ indices: []int{0},
+ },
+ {
+ name: "a literal inside the kept part is counted",
+ quoted: []wire{qWords(imgMarker + strings.Repeat("字", 600)), qImage(urlA, "A")},
+ indices: []int{1},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ msg := replyTo(t, tc.quoted, tc.own)
+ media := quotedAttachments(msg)
+ if len(media) != len(tc.indices) {
+ t.Fatalf("quoted attachments = %d, want %d", len(media), len(tc.indices))
+ }
+ for i, want := range tc.indices {
+ if media[i].InlineIndex != want {
+ t.Errorf("attachment %d: InlineIndex = %d, want %d\nbody: %q", i, media[i].InlineIndex, want, msg.Text)
+ }
+ }
+ assertEachMarkerLandsOnItsOwnLine(t, msg, len(tc.indices))
+ })
+ }
+}
+
+// Review finding 2, as described: 501 characters, then the picture, and a new
+// picture sent with the reply.
+func TestACutQuoteStillNamesItsPicture(t *testing.T) {
+ t.Parallel()
+ msg := replyTo(t,
+ []wire{qWords(strings.Repeat("字", 501)), qImage(urlA, "Q")},
+ []wire{qImage(urlC, "O"), qWords("还有这个")},
+ )
+
+ if !strings.Contains(msg.Text, "> "+imgMarker) {
+ t.Fatalf("the quoted picture's marker is not in the body:\n%q\n— it was fetched and the agent has "+
+ "nothing that says which attachment it is, next to the one just sent", msg.Text)
+ }
+ if !strings.Contains(msg.Text, strings.Repeat("字", 500)+"…") {
+ t.Errorf("the words were not cut at %d runes and marked", maxQuotedRunes)
+ }
+ if strings.Contains(msg.Text, strings.Repeat("字", 501)) {
+ t.Errorf("the words were not cut")
+ }
+ assertEachMarkerLandsOnItsOwnLine(t, msg, 1)
+
+ all := wecomMedia(msg)
+ if len(all) != 2 || all[0].AESKey != "Q" || all[1].AESKey != "O" {
+ t.Fatalf("media = %+v, want the quoted picture then the sender's own", all)
+ }
+ if all[1].InlinePlaceholder != "" {
+ t.Errorf("the sender's own picture was stamped %q", all[1].InlinePlaceholder)
+ }
+}
+
+// Where the cut falls relative to the markers.
+func TestTheCutNeverRemovesOrSplitsAMarker(t *testing.T) {
+ t.Parallel()
+ words := func(n int) wire { return qWords(strings.Repeat("字", n)) }
+ cases := []struct {
+ name string
+ quoted []wire
+ wantCut bool // is the block marked with an ellipsis
+ wantKept int // quoted attachments that must survive
+ }{
+ {"exactly the budget, then a picture", []wire{words(500), qImage(urlA, "A")}, false, 1},
+ {"one under the budget, then a picture", []wire{words(499), qImage(urlA, "A")}, false, 1},
+ {"one over the budget, then a picture", []wire{words(501), qImage(urlA, "A")}, true, 1},
+ {"the budget is spent, more words, then a picture", []wire{words(500), qWords("更多"), qImage(urlA, "A")}, true, 1},
+ {"a picture first, then a long document", []wire{qImage(urlA, "A"), words(900)}, true, 1},
+ {"the marker starts inside the budget and ends past it", []wire{words(485), qImage(urlA, "A"), words(50)}, true, 1},
+ {
+ "pictures between long passages",
+ []wire{words(300), qImage(urlA, "A"), words(300), qImage(urlB, "B"), words(300), qImage(urlC, "C")},
+ true, 3,
+ },
+ {"a picture and a file", []wire{words(700), qImage(urlA, "A"), qFile(urlB, "B")}, true, 2},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ msg := replyTo(t, tc.quoted, nil)
+ assertEachMarkerLandsOnItsOwnLine(t, msg, tc.wantKept)
+
+ block := strings.SplitN(msg.Text, "\n\n", 2)[0]
+ if got := strings.Contains(block, "…"); got != tc.wantCut {
+ t.Errorf("block marked as cut = %v, want %v\n%q", got, tc.wantCut, block)
+ }
+ // The size bound the code comment promises: the budget, plus the
+ // markers (each on a line of its own), plus the ellipsis, plus the
+ // block's own prefix. The prefix is "> [Quote] " on the first line
+ // and "> " on each later one.
+ markers := tc.wantKept
+ limit := maxQuotedRunes + markers*(utf8.RuneCountInString(imgMarker)+1) + 1
+ limit += utf8.RuneCountInString("> "+quotePrefix+" ") + 2*markers
+ if got := utf8.RuneCountInString(block); got > limit {
+ t.Errorf("block = %d runes, want at most %d (budget %d + %d markers)", got, limit, maxQuotedRunes, markers)
+ }
+ })
+ }
+}
+
+// A quote with no attachment is cut exactly as before: the budget, the
+// ellipsis, nothing else. Pinned beside the new cases because the cut was
+// rewritten around the markers.
+func TestACutQuoteWithoutPicturesIsCutAsItAlwaysWas(t *testing.T) {
+ t.Parallel()
+ msg := replyTo(t, []wire{qWords(strings.Repeat("字", 501))}, nil)
+ want := "> [Quote] " + strings.Repeat("字", 500) + "…\n\n这个怎么处理"
+ if msg.Text != want {
+ t.Errorf("body = %q, want %q", msg.Text, want)
+ }
+
+ // Two runs, the second crossing the budget: the cut lands inside it.
+ msg = replyTo(t, []wire{qWords(strings.Repeat("甲", 300)), qWords(strings.Repeat("乙", 300))}, nil)
+ want = "> [Quote] " + strings.Repeat("甲", 300) + "\n> " + strings.Repeat("乙", 199) + "…\n\n这个怎么处理"
+ if msg.Text != want {
+ t.Errorf("body = %q, want %q", msg.Text, want)
+ }
+}
diff --git a/server/internal/integrations/wecom/quoted_media_bind_db_test.go b/server/internal/integrations/wecom/quoted_media_bind_db_test.go
new file mode 100644
index 0000000000..56a56df400
--- /dev/null
+++ b/server/internal/integrations/wecom/quoted_media_bind_db_test.go
@@ -0,0 +1,315 @@
+package wecom
+
+// quoted_media_bind_db_test.go — the quoted-picture marker, end to end.
+//
+// quoted_marker_position_test.go proves the numbers the adapter stamps are the
+// right ones for the text it renders. This file asks the question the user
+// would: after the real Router, the real wecom resolver (HTTP download of
+// really-encrypted bytes), the real ChatSession binder and a real Postgres, what
+// does the stored message say, and does the id it names belong to the picture
+// that was quoted.
+//
+// Each scenario runs over both download paths. The buffered and the streaming
+// ingest build their MediaRef separately, and a stamp lost in either one leaves
+// the marker "unavailable" while the attachment exists.
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ dbfx "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// quotedBindWorld is what the wecom ResolverSet resolves against: an
+// installation keyed by bot id and a user binding keyed by the anonymized
+// aibot userid, in one workspace.
+type quotedBindWorld struct {
+ workspaceID string
+ botID string
+ senderID string
+}
+
+// seedQuotedBindWorld builds the same rows seedMediaBindFixture does, through
+// the shared testutil fixture so its teardown runs in reverse creation order.
+func seedQuotedBindWorld(t *testing.T, pool *pgxpool.Pool) quotedBindWorld {
+ t.Helper()
+ tag := fmt.Sprintf("%d", time.Now().UnixNano())
+ w := quotedBindWorld{botID: "wb-qbind-" + tag, senderID: "T-qbind-" + tag}
+
+ f := dbfx.New(pool, "", "")
+ f.UserID = f.User(t, "wecom quoted bind", "wecom-quoted-bind-"+tag+"@multica.test")
+ f.WorkspaceID = f.Workspace(t, "wecom quoted bind", "wecom-quoted-bind-"+tag)
+ w.workspaceID = f.WorkspaceID
+ f.Member(t, f.WorkspaceID, f.UserID, "owner")
+ runtimeID := f.Runtime(t, "wecom-qbind-runtime-"+tag, dbfx.Cols{"runtime_mode": "local", "provider": "multica_daemon"})
+ agentID := f.Agent(t, "wecom-qbind-agent-"+tag, runtimeID, dbfx.Cols{"runtime_mode": "local"})
+ installationID := f.Insert(t, "channel_installation", dbfx.Cols{
+ "workspace_id": f.WorkspaceID,
+ "agent_id": agentID,
+ "channel_type": "wecom",
+ "config": fmt.Sprintf(`{"app_id":%q,"bot_id":%q,"app_secret_encrypted":""}`, w.botID, w.botID),
+ "installer_user_id": f.UserID,
+ "status": "active",
+ })
+ f.Insert(t, "channel_user_binding", dbfx.Cols{
+ "workspace_id": f.WorkspaceID,
+ "multica_user_id": f.UserID,
+ "installation_id": installationID,
+ "channel_type": "wecom",
+ "channel_user_id": w.senderID,
+ })
+ // Rows the router and resolver write on their own: they reference the
+ // workspace and the installation, so they go before either.
+ f.Cleanup(t, `DELETE FROM channel_media_pending_object WHERE workspace_id = $1`, f.WorkspaceID)
+ f.Cleanup(t, `DELETE FROM channel_inbound_message_dedup WHERE installation_id = $1`, installationID)
+ return w
+}
+
+// countingStreamStorage is a backend that can stream, and says how often it was
+// asked to. The buffered half is the embedded fake's Upload, which must stay
+// untouched when streaming is available.
+type countingStreamStorage struct {
+ fakeStreamStorage
+ mu2 sync.Mutex
+ streamed int
+}
+
+func (s *countingStreamStorage) UploadStream(ctx context.Context, key string, data io.Reader, size int64, contentType, filename string) (string, error) {
+ s.mu2.Lock()
+ s.streamed++
+ s.mu2.Unlock()
+ return s.fakeStreamStorage.UploadStream(ctx, key, data, size, contentType, filename)
+}
+
+func (s *countingStreamStorage) streams() int {
+ s.mu2.Lock()
+ defer s.mu2.Unlock()
+ return s.streamed
+}
+
+// newPictureServer serves one encrypted picture whose download names itself, so
+// the attachment row it becomes can be told apart from the others.
+func newPictureServer(t *testing.T, filename string) *httptest.Server {
+ t.Helper()
+ srv := cosServer(t, []byte("\xff\xd8\xff\xe0 "+filename), fmt.Sprintf(`attachment; filename=%q`, filename))
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+type quotedBindScenario struct {
+ name string
+ // quoted builds the quoted message's runs; urls are the three pictures'
+ // download addresses, "q1" and "q2" the quoted ones, "own" the sender's.
+ quoted func(q1, q2 string) []wire
+ // own builds the sender's own 图文混排; nil sends plain words.
+ own func(own string) []wire
+ // wantAttachments are the filenames that must exist on the message.
+ wantAttachments []string
+ // wantBody is the stored body once everything has landed. {q1} and {q2}
+ // stand for the ids of the attachments the quote's pictures became.
+ wantBody string
+}
+
+func quotedBindScenarios() []quotedBindScenario {
+ return []quotedBindScenario{
+ {
+ // Review finding 1: the words quoted ahead of the picture spell the
+ // marker out. The sentence must come out as it went in, and the
+ // picture's own marker must carry its id.
+ name: "a quoted sentence that spells the marker",
+ quoted: func(q1, _ string) []wire {
+ return []wire{qWords("The UI displays " + imgMarker), qImage(q1, testAESKey)}
+ },
+ own: func(own string) []wire {
+ return []wire{qImage(own, testAESKey), qWords("看这个")}
+ },
+ wantAttachments: []string{"q1.jpg", "own.jpg"},
+ wantBody: "> [Quote] The UI displays [Image: unavailable]\n> [Image: {q1}]\n\n[Image]\n看这个",
+ },
+ {
+ // Review finding 2: the words run past the budget, and a new picture
+ // is sent with the reply. The quote has to name its picture, and the
+ // id has to be the quoted one's, not the one just sent.
+ name: "a quote cut at 500 runes beside a new picture",
+ quoted: func(q1, _ string) []wire {
+ return []wire{qWords(strings.Repeat("字", 501)), qImage(q1, testAESKey)}
+ },
+ own: func(own string) []wire {
+ return []wire{qImage(own, testAESKey), qWords("还有这个")}
+ },
+ wantAttachments: []string{"q1.jpg", "own.jpg"},
+ wantBody: "> [Quote] " + strings.Repeat("字", 500) + "…\n> [Image: {q1}]\n\n[Image]\n还有这个",
+ },
+ {
+ // Literals after the real marker, several of them, and one in the
+ // sender's own words — none of them is rewritten, both pictures are.
+ name: "literals after, between and in the sender's words",
+ quoted: func(q1, q2 string) []wire {
+ return []wire{
+ qImage(q1, testAESKey),
+ qWords("shown as " + imgMarker + " and " + imgMarker),
+ qImage(q2, testAESKey),
+ }
+ },
+ own: nil,
+ // Plain words reply: the text message is "这个怎么处理".
+ wantAttachments: []string{"q1.jpg", "q2.jpg"},
+ wantBody: "> [Quote] [Image: {q1}]\n> shown as [Image: unavailable] and [Image: unavailable]\n" +
+ "> [Image: {q2}]\n\n这个怎么处理",
+ },
+ {
+ // Two pictures with long passages between them: the cut falls
+ // between the markers and removes words, never a marker.
+ name: "two pictures with the cut between them",
+ quoted: func(q1, q2 string) []wire {
+ return []wire{
+ qWords(strings.Repeat("甲", 300)), qImage(q1, testAESKey),
+ qWords(strings.Repeat("乙", 300)), qImage(q2, testAESKey),
+ }
+ },
+ own: nil,
+ wantAttachments: []string{"q1.jpg", "q2.jpg"},
+ // 300 + (newline, marker) = 321 used; the second passage gets
+ // 500-321 runes less its newline.
+ wantBody: "> [Quote] " + strings.Repeat("甲", 300) + "\n> [Image: {q1}]\n> " +
+ strings.Repeat("乙", 178) + "…\n> [Image: {q2}]\n\n这个怎么处理",
+ },
+ }
+}
+
+func TestAQuotedPictureIsNamedInTheStoredBody(t *testing.T) {
+ storages := []struct {
+ name string
+ make func() (mediaStorage, func() (objects int, streamed int))
+ }{
+ {"buffered download", func() (mediaStorage, func() (int, int)) {
+ s := &fakeMediaStorage{}
+ return s, func() (int, int) { return len(s.stored()), 0 }
+ }},
+ {"streaming download", func() (mediaStorage, func() (int, int)) {
+ s := &countingStreamStorage{}
+ return s, func() (int, int) { return len(s.stored()), s.streams() }
+ }},
+ }
+ for _, sc := range quotedBindScenarios() {
+ for _, st := range storages {
+ t.Run(sc.name+"/"+st.name, func(t *testing.T) {
+ runQuotedBindScenario(t, sc, st.name == "streaming download", st.make)
+ })
+ }
+ }
+}
+
+func runQuotedBindScenario(t *testing.T, sc quotedBindScenario, streaming bool, makeStorage func() (mediaStorage, func() (int, int))) {
+ pool := mediaBindTestDB(t)
+ fixture := seedQuotedBindWorld(t, pool)
+ ctx := context.Background()
+ queries := db.New(pool)
+
+ q1, q2, own := newPictureServer(t, "q1.jpg"), newPictureServer(t, "q2.jpg"), newPictureServer(t, "own.jpg")
+
+ storage, counts := makeStorage()
+ resolver := newTestResolver(storage, engine.NewDBMediaIntentLedger(queries), nil)
+ session := engine.NewChatSession(queries, pool, TypeWecom, engine.SessionTitles{
+ Group: "群聊", Direct: "单聊", Fallback: "会话",
+ })
+ tasks := &bindTestTasks{}
+ router := engine.NewRouter(bindTestIssues{}, tasks, queries, engine.RouterConfig{
+ MediaTimeout: 20 * time.Second,
+ Logger: testLogger(),
+ })
+ router.Register(TypeWecom, NewResolverSet(NewStore(queries), session, nil, resolver))
+
+ var ownItems []wire
+ if sc.own != nil {
+ ownItems = sc.own(own.URL)
+ }
+ msgID := fmt.Sprintf("MSGID-QBIND-%d", time.Now().UnixNano())
+ msg := replyToAs(t, fixture.botID, fixture.senderID, msgID, sc.quoted(q1.URL, q2.URL), ownItems)
+ if err := router.Handle(ctx, msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+
+ // Binding is detached from the ACK path, so poll for the end of it: every
+ // attachment row exists AND the run was released, which is the call after
+ // the bind transaction.
+ var chatMessageID pgtype.UUID
+ var body string
+ var attachments int
+ deadline := time.Now().Add(20 * time.Second)
+ for {
+ err := pool.QueryRow(ctx, `
+ SELECT cm.id, cm.content
+ FROM chat_message cm
+ JOIN chat_session cs ON cs.id = cm.chat_session_id
+ WHERE cs.workspace_id = $1 AND cm.role = 'user'
+ ORDER BY cm.created_at DESC LIMIT 1`, fixture.workspaceID).Scan(&chatMessageID, &body)
+ if err == nil {
+ if err := pool.QueryRow(ctx,
+ `SELECT count(*) FROM attachment WHERE chat_message_id = $1`, chatMessageID).Scan(&attachments); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ if (attachments >= len(sc.wantAttachments) && tasks.promotions() > 0) || time.Now().After(deadline) {
+ break
+ }
+ } else if time.Now().After(deadline) {
+ t.Fatalf("no durable chat_message was ever written: %v", err)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+
+ // The precondition: the download took the path this run is named for.
+ objects, streamed := counts()
+ if objects != len(sc.wantAttachments) {
+ t.Fatalf("objects in storage = %d, want %d — the download did not complete, so the binder was not exercised",
+ objects, len(sc.wantAttachments))
+ }
+ if streaming && streamed != objects {
+ t.Fatalf("UploadStream ran %d times for %d objects — this run was meant to take the streaming path", streamed, objects)
+ }
+ if !streaming && streamed != 0 {
+ t.Fatalf("UploadStream ran on a backend that cannot stream")
+ }
+
+ // Which id is which picture.
+ ids := map[string]string{}
+ rows, err := pool.Query(ctx, `SELECT filename, id::text FROM attachment WHERE chat_message_id = $1`, chatMessageID)
+ if err != nil {
+ t.Fatalf("load attachments: %v", err)
+ }
+ for rows.Next() {
+ var name, id string
+ if err := rows.Scan(&name, &id); err != nil {
+ t.Fatalf("scan attachment: %v", err)
+ }
+ ids[name] = id
+ }
+ rows.Close()
+ for _, name := range sc.wantAttachments {
+ if ids[name] == "" {
+ t.Fatalf("no attachment named %s on the message (have %v)", name, ids)
+ }
+ }
+
+ want := strings.NewReplacer("{q1}", ids["q1.jpg"], "{q2}", ids["q2.jpg"]).Replace(sc.wantBody)
+ if body != want {
+ t.Errorf("stored body after binding:\n got: %q\nwant: %q", body, want)
+ }
+ // The sender's own picture is never named by a quote marker, whatever the
+ // body looks like: a quote that carried its id would be saying the quoted
+ // picture is the one just sent.
+ if id := ids["own.jpg"]; id != "" && strings.Contains(body, id) {
+ t.Errorf("the sender's own attachment id %s appears in the body %q", id, body)
+ }
+}
diff --git a/server/internal/integrations/wecom/quoted_media_test.go b/server/internal/integrations/wecom/quoted_media_test.go
new file mode 100644
index 0000000000..b6d514b243
--- /dev/null
+++ b/server/internal/integrations/wecom/quoted_media_test.go
@@ -0,0 +1,130 @@
+package wecom
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+)
+
+// A quoted picture used to reach the agent as four characters. The common
+// shape of this in a room is somebody quoting a screenshot of an error and
+// typing "这个怎么处理" underneath — the agent got the words and a label where
+// the error was, and answered the label.
+//
+// The callback carries the quoted attachment the same way it carries one the
+// sender just made: a pre-signed url and its aeskey.
+func TestAQuotedPictureIsFetched(t *testing.T) {
+ t.Parallel()
+ var q quotedMessage
+ q.MsgType = "image"
+ q.Image = mediaBody{URL: "https://example.invalid/quoted.png", AESKey: "K1"}
+ mc := aibotMsgCallback{MsgType: "text", Quote: q}
+ mc.Text.Content = "这个怎么处理"
+
+ got := mc.attachments()
+ if len(got) != 1 {
+ t.Fatalf("attachments = %d, want 1 — the quoted picture was not fetched, so the agent "+
+ "answers a label instead of the screenshot", len(got))
+ }
+ if got[0].URL != "https://example.invalid/quoted.png" || got[0].AESKey != "K1" {
+ t.Errorf("attachment = %+v, want the quote's own url and key", got[0])
+ }
+ if got[0].InlinePlaceholder != "[Image: unavailable]" || got[0].InlineIndex != 0 {
+ t.Errorf("marker = %q#%d, want \"[Image: unavailable]\"#0 — without it nothing joins the "+
+ "marker in the body to the entry in the attachment list",
+ got[0].InlinePlaceholder, got[0].InlineIndex)
+ }
+}
+
+// The quote block renders above the sender's own words, so its attachments
+// come first. The engine binds a marker by its occurrence number in the body;
+// the two lists disagreeing puts the wrong id on the wrong picture.
+func TestTheQuotedAttachmentComesBeforeTheSendersOwn(t *testing.T) {
+ t.Parallel()
+ var q quotedMessage
+ q.MsgType = "image"
+ q.Image = mediaBody{URL: "https://example.invalid/quoted.png", AESKey: "Q"}
+ mc := aibotMsgCallback{MsgType: "image", Quote: q}
+ mc.Image = mediaBody{URL: "https://example.invalid/own.png", AESKey: "O"}
+
+ got := mc.attachments()
+ if len(got) != 2 {
+ t.Fatalf("attachments = %d, want 2 (the quoted one and the sender's own)", len(got))
+ }
+ if got[0].AESKey != "Q" || got[1].AESKey != "O" {
+ t.Fatalf("order = %q,%q, want the quoted one first — it renders first",
+ got[0].AESKey, got[1].AESKey)
+ }
+ if got[1].InlinePlaceholder != "" {
+ t.Errorf("the sender's own attachment was stamped %q; its marker is already unambiguous "+
+ "and rewriting it would change what every stored wecom body says", got[1].InlinePlaceholder)
+ }
+}
+
+// Counted per marker, not over the whole list: "[Image: unavailable]" and
+// "[File: unavailable]" are different strings, so a quote carrying one of each
+// gives each its own first occurrence.
+func TestTwoKindsInOneQuoteEachCountFromZero(t *testing.T) {
+ t.Parallel()
+ var q quotedMessage
+ q.MsgType = "mixed"
+ q.Mixed.MsgItem = []mixedItem{
+ {MsgType: "image", Image: mediaBody{URL: "https://example.invalid/a.png", AESKey: "A"}},
+ {MsgType: "file", File: mediaBody{URL: "https://example.invalid/b.pdf", AESKey: "B"}},
+ {MsgType: "image", Image: mediaBody{URL: "https://example.invalid/c.png", AESKey: "C"}},
+ }
+
+ mc := aibotMsgCallback{MsgType: "text", Quote: q}
+ mc.Text.Content = "看这两个"
+ got := mc.attachments()
+ if len(got) != 3 {
+ t.Fatalf("media = %d, want 3", len(got))
+ }
+ want := []struct {
+ marker string
+ index int
+ }{{"[Image: unavailable]", 0}, {"[File: unavailable]", 0}, {"[Image: unavailable]", 1}}
+ for i, w := range want {
+ if got[i].InlinePlaceholder != w.marker || got[i].InlineIndex != w.index {
+ t.Errorf("media[%d] = %q#%d, want %q#%d — counting the markers together sends the "+
+ "binder looking for an occurrence that is not there",
+ i, got[i].InlinePlaceholder, got[i].InlineIndex, w.marker, w.index)
+ }
+ }
+}
+
+// The marker REFERS to the attachment rather than carrying it: the picture
+// belongs to a message somebody else sent, so replacing the marker with an
+// inline image would state this sender attached it again.
+func TestAQuotedAttachmentAsksToBeNamedRatherThanEmbedded(t *testing.T) {
+ t.Parallel()
+ quoted := InboundMedia{Kind: channel.MsgTypeImage, InlinePlaceholder: "[Image: unavailable]", InlineIndex: 2}
+ ref := quoted.inline(channel.MediaRef{Type: channel.MsgTypeImage})
+ if !ref.InlineIDOnly {
+ t.Error("InlineIDOnly is false — the quote's marker would be replaced by an inline image, " +
+ "stating this sender attached somebody else's picture")
+ }
+ if ref.InlinePlaceholder != "[Image: unavailable]" || ref.InlineIndex != 2 {
+ t.Errorf("ref = %q#%d, want the marker carried across", ref.InlinePlaceholder, ref.InlineIndex)
+ }
+
+ own := InboundMedia{Kind: channel.MsgTypeImage}
+ if got := own.inline(channel.MediaRef{Type: channel.MsgTypeImage}); got.InlineIDOnly || got.InlinePlaceholder != "" {
+ t.Errorf("the sender's own ref was changed to %+v; it must stay on the path it was on", got)
+ }
+}
+
+// The two spellings are derived from one another rather than written twice, so
+// they cannot drift: the label ahead of the colon is whatever this adapter
+// called the thing, and the engine only replaces the state word after it.
+func TestTheQuotedMarkerIsTheOrdinaryOneWithRoomInIt(t *testing.T) {
+ t.Parallel()
+ for _, kind := range []channel.MsgType{channel.MsgTypeImage, channel.MsgTypeVideo, channel.MsgTypeFile} {
+ bare := mediaPlaceholder(kind)
+ named := quotedMediaPlaceholder(kind)
+ want := bare[:len(bare)-1] + ": " + mediaUnavailable + "]"
+ if named != want {
+ t.Errorf("quotedMediaPlaceholder(%v) = %q, want %q", kind, named, want)
+ }
+ }
+}
diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.go
index 0706f4fd35..05eb924c13 100644
--- a/server/internal/integrations/wecom/ws_frame.go
+++ b/server/internal/integrations/wecom/ws_frame.go
@@ -130,19 +130,39 @@ type quotedMessage struct {
} `json:"mixed"`
}
-// render turns the quoted message into the lines it contributes. A kind this
-// adapter does not know contributes nothing, the same way a mixed run does.
-func (q quotedMessage) render() string {
+// quoteRun is one line the quoted message contributes: words somebody typed or
+// said, or the marker standing in for an attachment together with the
+// attachment it stands for.
+//
+// The marker and its attachment are one value on purpose. They used to be two
+// lists, rendered by one function and collected by another, and anything that
+// changed the rendered text in between (a sentence that spells the marker out,
+// a cut that removes it) left the second list describing a body the agent never
+// saw. A run that has an attachment cannot be laid out without its marker, and
+// a run that is laid out cannot lose its attachment, so fitQuote below decides
+// what survives once and both follow.
+type quoteRun struct {
+ text string
+ media *InboundMedia
+}
+
+// runs lays the quoted message out as the lines it contributes, in order. A
+// kind this adapter does not know contributes nothing, the same way a mixed
+// run does.
+func (q quotedMessage) runs() []quoteRun {
if !strings.EqualFold(q.MsgType, "mixed") {
- return q.mixedItem.render()
+ if run, ok := q.mixedItem.quoteRun(); ok {
+ return []quoteRun{run}
+ }
+ return nil
}
- var runs []string
+ var out []quoteRun
for _, item := range q.Mixed.MsgItem {
- if s := item.render(); s != "" {
- runs = append(runs, s)
+ if run, ok := item.quoteRun(); ok {
+ out = append(out, run)
}
}
- return strings.Join(runs, "\n")
+ return out
}
// mediaBody is the {url, aeskey} pair every downloadable kind carries. In
@@ -200,6 +220,26 @@ func (item mixedItem) render() string {
return mediaPlaceholder(kind)
}
+// quoteRun is render for a run inside a QUOTED message: an attachment comes
+// back as a marker with room in it to be named (quotedMediaPlaceholder) along
+// with the attachment that marker stands for.
+func (item mixedItem) quoteRun() (quoteRun, bool) {
+ if s := item.words(); s != "" {
+ return quoteRun{text: s}, true
+ }
+ body, kind, ok := mediaFor(item.MsgType, item.Image, item.File, item.Video)
+ if !ok || strings.TrimSpace(body.URL) == "" {
+ return quoteRun{}, false
+ }
+ marker := quotedMediaPlaceholder(kind)
+ return quoteRun{text: marker, media: &InboundMedia{
+ Kind: kind,
+ URL: body.URL,
+ AESKey: body.AESKey,
+ InlinePlaceholder: marker,
+ }}, true
+}
+
// mediaPlaceholder is the marker that stands in for an attachment in the
// stored message body, so the agent can see that something was attached
// before (or instead of) the bytes arriving on the detached media path.
@@ -221,6 +261,38 @@ func mediaPlaceholder(kind channel.MsgType) string {
}
}
+// mediaUnavailable is what a quoted attachment's marker says before anything
+// has been fetched for it, and what it keeps saying if the fetch never
+// succeeds. A marker that is never rewritten still reads as a sentence.
+const mediaUnavailable = "unavailable"
+
+// quotedMediaPlaceholder is the marker a QUOTED attachment renders as. It
+// carries a word inside the brackets where the sender's own "[Image]" carries
+// nothing, because the quote's marker is the one that has to be joined to an
+// attachment.
+//
+// Fetching the quoted picture puts it in the attachment list and stops there.
+// The list is a separate block of text from the body, so with one attachment
+// the reader infers the join and with two it cannot — and a quote is exactly
+// the case where a message carries somebody else's picture beside its own.
+// The marker is what the engine rewrites into the attachment's id.
+//
+// The sender's OWN attachments keep the bare "[Image]" they have always had.
+// It is already unambiguous, being the attachment on the message the reader is
+// looking at, and changing it would change what every existing wecom message
+// body says.
+func quotedMediaPlaceholder(kind channel.MsgType) string {
+ return namedMediaPlaceholder(kind, mediaUnavailable)
+}
+
+// namedMediaPlaceholder writes a name inside the bracketed marker: "[Image]"
+// becomes "[Image: <name>]". engine.inlineAttachmentIDMarker rewrites the same
+// shape and keeps the label ahead of the colon, so the two spellings cannot
+// drift apart.
+func namedMediaPlaceholder(kind channel.MsgType, name string) string {
+ return strings.TrimSuffix(mediaPlaceholder(kind), "]") + ": " + name + "]"
+}
+
// mediaFor returns the body and normalized kind for a raw wecom msgtype, and
// whether that type is one we download at all.
func mediaFor(msgType string, image, file, video mediaBody) (mediaBody, channel.MsgType, bool) {
@@ -240,7 +312,15 @@ func mediaFor(msgType string, image, file, video mediaBody) (mediaBody, channel.
// user sent it. A body with no url is skipped: there is nothing to fetch, and
// carrying it forward would only produce an intent-ledger row for an object
// that can never exist.
+// The quoted message's attachments come FIRST, because the quote block renders
+// above the sender's own words and the two lists have to agree on order — the
+// engine binds a marker by its occurrence number in the body.
func (mc aibotMsgCallback) attachments() []InboundMedia {
+ _, quotedMedia := mc.quotedBlock()
+ return append(quotedMedia, mc.ownAttachments()...)
+}
+
+func (mc aibotMsgCallback) ownAttachments() []InboundMedia {
var out []InboundMedia
add := func(body mediaBody, kind channel.MsgType) {
if strings.TrimSpace(body.URL) == "" {
@@ -335,16 +415,38 @@ const maxQuotedRunes = 500
// here. Prefixing it would let a quote of somebody else's "/issue …" file an
// issue nobody asked for.
func (mc aibotMsgCallback) quotedContext() string {
- rendered := strings.TrimSpace(mc.Quote.render())
+ block, _ := mc.quotedBlock()
+ return block
+}
+
+// quotedBlock is the quote block and the attachments whose markers are in it.
+//
+// FETCHING THE ATTACHMENTS IS THE WHOLE OF THE FIX. "[Image]" is all a quote
+// of a picture could be rendered as — the payload carries no sender, no
+// message id and no timestamp to say WHICH picture — so an agent reading that
+// line cannot tell a screenshot it read a minute ago from one it has never
+// seen, and answers "左下角那块看不清" about a picture it does not have. The
+// url and aeskey on the quote are the only thing that resolves it, and the
+// callback hands them over exactly the way it hands over an attachment the
+// sender just made.
+//
+// The marker closes the other half. Fetching the bytes puts the picture in the
+// attachment list; the marker's occurrence number is what says WHICH entry of
+// that list the quote's marker is, and without it a message carrying two
+// attachments — one quoted, one just sent — hands the agent two markers and
+// two ids with nothing joining them.
+//
+// The rule the pair obeys: an attachment is returned only if its marker is in
+// the block, and its InlineIndex counts occurrences in the block as returned.
+// The engine binds by searching the stored body for the Nth occurrence of the
+// marker string, so the number has to be taken from the text the agent will
+// read — not from how many attachments came before it — and the text is
+// whatever is left after the cut. Both come out of fitQuote in one pass, so
+// neither can describe a block the other did not produce.
+func (mc aibotMsgCallback) quotedBlock() (string, []InboundMedia) {
+ rendered, media := fitQuote(mc.Quote.runs(), maxQuotedRunes)
if rendered == "" {
- return ""
- }
- // A quoted document would otherwise become the body. The sender quoted it
- // to point at it, not to resend it, and the words that carry their question
- // are their own — which follow the block and must not be pushed out of the
- // agent's reach by it.
- if runes := []rune(rendered); len(runes) > maxQuotedRunes {
- rendered = strings.TrimRight(string(runes[:maxQuotedRunes]), " \t\n") + "…"
+ return "", nil
}
var b strings.Builder
for i, line := range strings.Split(rendered, "\n") {
@@ -358,7 +460,85 @@ func (mc aibotMsgCallback) quotedContext() string {
}
b.WriteString(line)
}
- return b.String()
+ return b.String(), media
+}
+
+// fitQuote lays the quote's runs out within maxRunes and returns the text with
+// the attachments that survived in it, each stamped with which occurrence of
+// its marker it is.
+//
+// A quoted document would otherwise become the body. The sender quoted it to
+// point at it, not to resend it, and the words that carry their question are
+// their own — which follow the block and must not be pushed out of the agent's
+// reach by it. So TEXT is cut at maxRunes, markers counting toward that budget
+// while they fall inside it, and the cut is marked with "…".
+//
+// A marker is never cut, and never dropped. Past the budget, runs of words are
+// dropped and runs that carry an attachment are still laid out whole, one line
+// each; a marker that starts inside the budget and ends past it is kept to the
+// end. So the block can run past maxRunes by at most the markers it carries
+// (about twenty runes each), and every attachment the caller will fetch is
+// one the agent can find in the text. #7980 left the same constraint in its
+// discussion: a truncated block must not drop a placeholder it still counts.
+//
+// InlineIndex is counted on the text as laid out, markers and words alike. A
+// quoted sentence that spells "[Image: unavailable]" out is an occurrence of
+// that marker as far as the engine's search is concerned, so it moves the real
+// marker's number up by one.
+func fitQuote(runs []quoteRun, maxRunes int) (string, []InboundMedia) {
+ var (
+ lines []string
+ owners []*InboundMedia // owners[i] is the attachment lines[i] is the marker of, or nil
+ used int
+ cut bool
+ )
+ for _, run := range runs {
+ width := utf8.RuneCountInString(run.text)
+ if len(lines) > 0 {
+ width++ // the newline ahead of it
+ }
+ switch {
+ case run.media != nil:
+ lines = append(lines, run.text)
+ owners = append(owners, run.media)
+ used += width
+ case cut:
+ // The budget ran out earlier; only markers still get through.
+ case used+width <= maxRunes:
+ lines = append(lines, run.text)
+ owners = append(owners, nil)
+ used += width
+ default:
+ cut = true
+ room := maxRunes - used
+ if len(lines) > 0 {
+ room-- // the newline ahead of it
+ }
+ if room > 0 {
+ kept := strings.TrimRight(string([]rune(run.text)[:room]), " \t\n")
+ if kept != "" {
+ lines = append(lines, kept)
+ owners = append(owners, nil)
+ }
+ }
+ if len(lines) == 0 {
+ lines = append(lines, "")
+ owners = append(owners, nil)
+ }
+ lines[len(lines)-1] = strings.TrimRight(lines[len(lines)-1], " \t\n") + "…"
+ }
+ }
+
+ var media []InboundMedia
+ for i, owner := range owners {
+ if owner == nil {
+ continue
+ }
+ m := *owner
+ m.InlineIndex = strings.Count(strings.Join(lines[:i], "\n"), m.InlinePlaceholder)
+ media = append(media, m)
+ }
+ return strings.Join(lines, "\n"), media
}
// ownCommandSource is what the slash-command parsers read: the sender's own
@@ -478,6 +658,31 @@ type InboundMedia struct {
// AESKey unlocks what comes back from URL. Long-connection mode mints one
// per url; see media_crypt.go.
AESKey string `json:"aeskey"`
+ // InlinePlaceholder is the exact marker in the stored body this attachment
+ // stands for, and InlineIndex is which occurrence of that marker it is.
+ // They travel onto channel.MediaRef, and the binder rewrites that one
+ // occurrence to name the attachment once a row exists (engine/session.go).
+ //
+ // Set for a QUOTED attachment only — see quotedMediaPlaceholder for why the
+ // sender's own marker stays bare.
+ InlinePlaceholder string `json:"inline_placeholder,omitempty"`
+ InlineIndex int `json:"inline_index,omitempty"`
+}
+
+// inline copies the marker this attachment stands for onto the ref the binder
+// will rewrite. A ref with no marker is left exactly as it was, which is what
+// keeps the sender's own attachments on the path they were already on.
+func (m InboundMedia) inline(ref channel.MediaRef) channel.MediaRef {
+ if m.InlinePlaceholder == "" {
+ return ref
+ }
+ ref.InlinePlaceholder = m.InlinePlaceholder
+ ref.InlineIndex = m.InlineIndex
+ // The marker REFERS to the attachment, it does not carry it: the picture
+ // belongs to a message somebody else sent, and replacing the marker with an
+ // inline image would state this sender attached it again.
+ ref.InlineIDOnly = true
+ return ref
}
// channelMessageFromCallback converts a wecom-side aibot_msg_callback into
diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.go
index 312134af98..15e6489109 100644
--- a/server/internal/integrations/wecom/ws_frame_test.go
+++ b/server/internal/integrations/wecom/ws_frame_test.go
@@ -196,17 +196,35 @@ func TestQuotedContext(t *testing.T) {
}
})
- t.Run("a quoted attachment shows the same placeholder a sent one does", func(t *testing.T) {
+ // The marker a QUOTED attachment renders carries a word where the sender's
+ // own "[Image]" carries nothing, and that is the change this file makes to
+ // what #7980 established. It is not cosmetic: the bytes behind a quoted
+ // picture are now fetched, so its marker is the one that has to be joined
+ // to an entry in the attachment list, and only a marker with room in it can
+ // be rewritten to name one. The sender's own marker is untouched — see the
+ // case below it.
+ t.Run("a quoted attachment renders a marker that can be named", func(t *testing.T) {
t.Parallel()
var q quotedMessage
q.MsgType = "image"
q.Image = mediaBody{URL: "https://example.invalid/i", AESKey: "k"}
mc := aibotMsgCallback{MsgType: "text", Quote: q}
- if got, want := mc.quotedContext(), "> [Quote] [Image]"; got != want {
+ if got, want := mc.quotedContext(), "> [Quote] [Image: unavailable]"; got != want {
t.Errorf("quotedContext() = %q, want %q", got, want)
}
})
+ t.Run("the sender's own attachment keeps the bare placeholder", func(t *testing.T) {
+ t.Parallel()
+ mc := aibotMsgCallback{MsgType: "image"}
+ mc.Image = mediaBody{URL: "https://example.invalid/own", AESKey: "k"}
+ body, ok := mc.ownText()
+ if !ok || body != "[Image]" {
+ t.Errorf("ownText() = %q,%v, want \"[Image]\" — changing this would change what "+
+ "every wecom message body already stored says", body, ok)
+ }
+ })
+
t.Run("a quoted mixed message renders its runs", func(t *testing.T) {
t.Parallel()
var q quotedMessage
@@ -217,7 +235,7 @@ func TestQuotedContext(t *testing.T) {
shot := mixedItem{MsgType: "image", Image: mediaBody{URL: "https://example.invalid/i", AESKey: "k"}}
q.Mixed.MsgItem = []mixedItem{words, shot}
mc := aibotMsgCallback{MsgType: "text", Quote: q}
- if got, want := mc.quotedContext(), "> [Quote] 看这个\n> [Image]"; got != want {
+ if got, want := mc.quotedContext(), "> [Quote] 看这个\n> [Image: unavailable]"; got != want {
t.Errorf("quotedContext() = %q, want %q", got, want)
}
})