Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7019 fix(wecom): show the agent the message a sender quoted (#7980)
Raymundo Arbogust7e8174631749
diff --git a/server/internal/integrations/channel/engine/regression_quoted_body_swallows_directive_test.go b/server/internal/integrations/channel/engine/regression_quoted_body_swallows_directive_test.gonew file mode 100644index 0000000000..513a4e8839--- /dev/null+++ b/server/internal/integrations/channel/engine/regression_quoted_body_swallows_directive_test.go@@ -0,0 +1,153 @@+package engine++// regression_quoted_body_swallows_directive_test.go — a bare /new or /clear+// sent as a reply to another message must still be only a directive.+//+// Router strips a directive from the agent-readable body along one of two+// routes: it re-parses Text itself, or it falls back to Text == CommandText.+// An adapter that renders quoted context ahead of the sender's words breaks+// both — the first line is now the quote, and Text no longer equals the+// command source — so a bare directive behind a quote survives into the body.+//+// The two failures are not symmetric, which is why both are pinned here:+//+// - /new: neither route fires, "/new" is persisted as the first turn of the+// session it just opened, and every later turn inherits it as context.+// - /clear: the FreshSession branch rewrites Text to the (empty) command+// body unless the adapter already stripped it, so the quote — the only+// thing the person actually sent — is dropped without a word.+//+// The wecom adapter is the one that renders quotes today+// (wecom/ws_frame.go quotedContext); the messages below are the exact shape it+// emits, pinned from the other side in+// wecom/regression_quoted_directive_test.go. Router is what has to be driven,+// because neither failure is visible in the adapter's own output.+//+// Router already distinguishes context the sender chose from history it added+// itself (HasSelectedContext, message.go:149). A quote is the former, so the+// adapter sets it and these tests send it — the directive-behind-a-quote case+// needs no rule of its own on the Router side.++import (+ "context"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+)++// TestAnEnrichedWeComBodyDoesNotBecomeTheChatTitle is the title half of the+// enrichment invariant in Handle (router.go:200-208), driven with the exact+// strings the wecom adapter emits.+//+// It exists because CI was green through three rounds of review with the bug+// present: the invariant's own comment predicts that, since no title test+// drove an enriching WeCom message. A quoted screenshot must name the Chat the+// way the same screenshot does without a quote — off the media path — and not+// after the message the sender was replying to.+func TestAnEnrichedWeComBodyDoesNotBecomeTheChatTitle(t *testing.T) {+ const enriched = "> [Quote] 生产库连接数打满了\n\n[Image]"++ // What the adapter sends now: CommandText is the body as it stood before+ // the quote went on.+ withQuote := deriveFirstMessageTitle(chatTitleSource(enriched, "[Image]", false), true)+ // The same screenshot, no quote, straight off main's path.+ withoutQuote := deriveFirstMessageTitle(chatTitleSource("[Image]", "", false), true)+ if withQuote != withoutQuote {+ t.Fatalf("quoted screenshot titles the Chat %q, the same screenshot alone titles it %q; "++ "replying to a message must not rename the conversation after it", withQuote, withoutQuote)+ }++ // And the shape this guards against: an enriching adapter that leaves+ // CommandText empty gets the fallback, which assigns the enriched Text.+ if leaked := deriveFirstMessageTitle(chatTitleSource(enriched, "", false), true); !strings.Contains(leaked, "[Quote]") {+ t.Fatalf("the empty-CommandText fallback no longer leaks the quote (title %q); this test "++ "guards nothing and the invariant it pins has moved", leaked)+ }+}++// quotedDirectiveMessage is what an adapter hands Router for a bare directive+// sent as a reply: the quote is the whole visible body, and the directive+// survives only as the command source.+func quotedDirectiveMessage(t *testing.T, directive string, forceFresh bool) channel.InboundMessage {+ t.Helper()+ msg := p2pMessage(t)+ msg.Text = "> [Quote] Q3 毛利率 42.1%"+ msg.CommandText = directive+ // The sender selected this context by replying to it, so Router must count+ // it as the turn's input even when the directive has no body of its own.+ msg.HasSelectedContext = true+ msg.ForceFresh = forceFresh+ return msg+}++// TestBareNewBehindAQuoteDoesNotPersistTheDirective: what a person experiences+// when this regresses is an agent that answers every later turn as if they had+// opened with the word "/new".+func TestBareNewBehindAQuoteDoesNotPersistTheDirective(t *testing.T) {+ h := newHarness(t)+ h.media.noMedia = true++ if err := h.router.Handle(context.Background(), quotedDirectiveMessage(t, "/new", false)); err != nil {+ t.Fatalf("Handle: %v", err)+ }++ if h.binder.startCalls != 1 {+ t.Fatalf("start calls=%d, want 1 — a bare /new opens a session", h.binder.startCalls)+ }+ if !h.binder.lastStart.PersistMessage {+ t.Fatal("the quote is the only thing the person sent; it has to be the session's first turn, " ++ "not discarded as if the message were empty")+ }+ got := h.binder.lastStart.Message.Text+ if strings.Contains(got, "/new") {+ t.Fatalf("first turn = %q — the directive was persisted as prompt text and every later turn "++ "in this session inherits it", got)+ }+ if got != "> [Quote] Q3 毛利率 42.1%" {+ t.Fatalf("first turn = %q, want the quoted context intact", got)+ }+}++// TestBareClearBehindAQuoteKeepsTheQuote: the other direction. /clear must+// still force a fresh session, but the quote is the turn — dropping it leaves+// the person watching the bot answer a question it was never given.+func TestBareClearBehindAQuoteKeepsTheQuote(t *testing.T) {+ h := newHarness(t)+ h.media.noMedia = true++ // ForceFresh is set by the adapter: it consumed the directive itself+ // because the message carried content besides it.+ if err := h.router.Handle(context.Background(), quotedDirectiveMessage(t, "", true)); err != nil {+ t.Fatalf("Handle: %v", err)+ }++ if !waitFor(time.Second, h.tasks.wasCalled) || !h.tasks.freshArg() {+ t.Fatal("/clear behind a quote must still enqueue a fresh provider session")+ }+ got := h.binder.lastAppend.Message.Text+ if got != "> [Quote] Q3 毛利率 42.1%" {+ t.Fatalf("appended text = %q, want the quoted context intact — an empty body here is the quote "++ "being dropped silently", got)+ }+}++// TestABareDirectiveWithNothingElseIsStillTheSentinel guards the other side of+// the same gate: the fix must not make every bare directive look like a turn.+// With no quote and no media there is nothing to say, and Router's pending+// sentinel is what keeps the session from opening with an empty message.+func TestABareDirectiveWithNothingElseIsStillTheSentinel(t *testing.T) {+ h := newHarness(t)+ h.media.noMedia = true+ msg := p2pMessage(t)+ msg.Text = "/new"++ if err := h.router.Handle(context.Background(), msg); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if h.binder.startCalls != 1 || h.binder.lastStart.PersistMessage {+ t.Fatalf("start calls=%d persist=%v — a bare /new with nothing else must open the session "++ "without persisting an empty first turn", h.binder.startCalls, h.binder.lastStart.PersistMessage)+ }+}diff --git a/server/internal/integrations/wecom/regression_quoted_directive_test.go b/server/internal/integrations/wecom/regression_quoted_directive_test.gonew file mode 100644index 0000000000..f36c6f219f--- /dev/null+++ b/server/internal/integrations/wecom/regression_quoted_directive_test.go@@ -0,0 +1,219 @@+package wecom++// regression_quoted_directive_test.go — a bare /new or /clear sent as a reply+// must reach Router already stripped.+//+// normalizeWeComControlLayout declines a directive with an empty body and no+// media, on purpose: that is the shared pending sentinel, and rewriting it+// would open a session with an empty first turn. A quote changes the premise.+// "/new" replying to an alert is not an empty message — the alert is the whole+// of what the person sent — but the gate could not see the quote, so the+// directive stayed in the body and Router could no longer strip it either: its+// two routes are re-parsing Text (now led by "> [Quote] …") and Text ==+// CommandText (now broken by the same prefix).+//+// What the person experiences: "/new" persisted as the first turn of the+// session they just opened, inherited as context by every later turn. And for+// /clear the mirror image — Router rewrites Text to the empty command body and+// the quote, the only thing they sent, disappears without a word.+//+// Pinned from the other side, on the Router, in+// engine/regression_quoted_body_swallows_directive_test.go. Both are needed:+// this file proves the adapter hands over a stripped body, that one proves+// Router keeps it.++import (+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++func quotedDirectiveCallback(directive string) aibotMsgCallback {+ mc := aibotMsgCallback{MsgID: "m-quoted-directive", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = directive+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "Q3 毛利率 42.1%"+ return mc+}++// TestABareNewBehindAQuoteLeavesOnlyTheQuote: the directive is consumed here,+// so the session's first turn is the thing the person replied to.+func TestABareNewBehindAQuoteLeavesOnlyTheQuote(t *testing.T) {+ t.Parallel()+ mc := quotedDirectiveCallback("/new")+ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-qn")++ if strings.Contains(msg.Text, "/new") {+ t.Fatalf("Text = %q — the directive survived into the body Router will persist as the "++ "session's first turn", msg.Text)+ }+ if msg.Text != "> [Quote] Q3 毛利率 42.1%" {+ t.Fatalf("Text = %q, want the quote alone", msg.Text)+ }+ // Router still has to see /new, or nothing opens a session.+ if _, ok := engine.ParseNewChatCommand(msg.CommandText); !ok {+ t.Fatalf("CommandText = %q — /new is no longer parseable, so no new session is opened", msg.CommandText)+ }+ // And it has to see that the quote is input the sender chose: without this+ // the directive is bare as far as Router is concerned, so it opens the+ // route and persists nothing — the quote is silently dropped again, one+ // layer further down than before.+ if !msg.HasSelectedContext {+ t.Fatal("HasSelectedContext = false — Router reads a quote-only body as an empty message")+ }+}++// TestABareClearBehindAQuoteKeepsTheQuoteAndForcesFresh: /clear carries no body+// of its own, so the adapter must consume it and say so through ForceFresh —+// otherwise Router rewrites Text to the empty command body and the quote goes+// with it.+func TestABareClearBehindAQuoteKeepsTheQuoteAndForcesFresh(t *testing.T) {+ t.Parallel()+ mc := quotedDirectiveCallback("/clear")+ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-qc")++ if msg.Text != "> [Quote] Q3 毛利率 42.1%" {+ t.Fatalf("Text = %q, want the quote alone", msg.Text)+ }+ if !msg.ForceFresh {+ t.Fatal("ForceFresh = false — the adapter consumed /clear without saying so, so the fresh " ++ "session the person asked for never happens")+ }+ // The directive must not survive as a command source either: Router would+ // rewrite Text to its empty body and drop the quote.+ if _, ok := engine.ParseFreshSessionCommand(msg.CommandText); ok {+ t.Fatalf("CommandText = %q still parses as /clear; Router would strip Text to the empty "++ "command body and the quote would be lost", msg.CommandText)+ }+}++// TestAQuotedScreenshotHandsRouterTheSendersOwnBody is the enrichment+// invariant at engine/router.go:200-208, from the adapter's side: once this+// adapter puts content in Text that the member did not type, it owes Router a+// CommandText, because Router's fallback assigns the ALREADY enriched Text.+//+// The trigger is ordinary in WeCom: quote a message, then reply with only a+// screenshot. ownCommandSource answers "" for a standalone photo on purpose —+// a placeholder is not words anybody typed — so before this fix the message+// arrived with an enriched Text and an empty command source, and the Chat was+// named after the message the sender had quoted: "[Quote] 生产库连接数打满了".+//+// The body before enrichment is the honest answer. It is still only what the+// sender sent, and the placeholder in it is dropped downstream by+// deriveFirstMessageTitle, which lands the title on the same media path the+// identical screenshot takes when it arrives with no quote.+func TestAQuotedScreenshotHandsRouterTheSendersOwnBody(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m-quoted-image", ChatID: "TUSER", ChatType: "single", MsgType: "image"}+ mc.From.UserID = "TUSER"+ mc.Image.URL = "https://example.com/screenshot.png"+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "生产库连接数打满了"++ own, _ := mc.ownText()+ msg := channelMessageFromCallback("bot-1", "", mc, own, "req-qimg")++ if msg.Text != "> [Quote] 生产库连接数打满了\n\n[Image]" {+ t.Fatalf("Text = %q, want the quote above the placeholder", msg.Text)+ }+ if msg.CommandText == "" {+ t.Fatal("CommandText is empty behind an enriched Text: Router fills it from Text, and the " ++ "quoted message becomes the Chat title")+ }+ if strings.Contains(msg.CommandText, "[Quote]") {+ t.Fatalf("CommandText = %q — the quote is content the sender did not type; it must not reach "++ "the command source", msg.CommandText)+ }+ if msg.CommandText != "[Image]" {+ t.Fatalf("CommandText = %q, want the body as it stood before enrichment", msg.CommandText)+ }+}++// TestAQuotedScreenshotWithWordsKeepsTheTypedCommand guards the other side:+// the snapshot must not overwrite a command source the sender really did type.+// A screenshot with "/issue …" under it, sent as a reply, still files that+// issue — the case ownCommandSource exists for.+func TestAQuotedScreenshotWithWordsKeepsTheTypedCommand(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m-quoted-mixed", ChatID: "TUSER", ChatType: "single", MsgType: "mixed"}+ mc.From.UserID = "TUSER"+ shot := mixedItem{MsgType: "image"}+ shot.Image.URL = "https://example.com/screenshot.png"+ words := mixedItem{MsgType: "text"}+ words.Text.Content = "/issue 登录坏了"+ mc.Mixed.MsgItem = []mixedItem{shot, words}+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "生产库连接数打满了"++ own, _ := mc.ownText()+ msg := channelMessageFromCallback("bot-1", "", mc, own, "req-qmixed")++ if msg.CommandText != "/issue 登录坏了" {+ t.Fatalf("CommandText = %q, want the sender's own typed command", msg.CommandText)+ }+ if !msg.SkipAgentRun {+ t.Fatal("a pure /issue must still skip the agent run")+ }+}++// TestABareDirectiveWithNoQuoteIsStillTheSentinel is the gate's other side: no+// quote, no media, nothing to say. Consuming the directive here would open a+// session with an empty turn — a worse bug than the one being fixed.+func TestABareDirectiveWithNoQuoteIsStillTheSentinel(t *testing.T) {+ t.Parallel()+ for _, directive := range []string{"/new", "/clear"} {+ t.Run(directive, func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m-bare", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = directive++ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-bare")++ if msg.Text != directive {+ t.Fatalf("Text = %q, want %q left intact for Router's sentinel path", msg.Text, directive)+ }+ if msg.ForceFresh {+ t.Fatal("ForceFresh set for a bare directive with nothing else; the adapter consumed " ++ "a directive it was supposed to pass through")+ }+ if msg.HasSelectedContext {+ t.Fatal("HasSelectedContext set with nothing quoted; Router would take the bare " ++ "directive for a turn and start a run on an empty prompt")+ }+ })+ }+}++// TestAQuotedDocumentDoesNotBecomeTheBody: the quote is a pointer, not a+// resend. Unbounded, a quoted document pushes the sender's own words — which+// follow it — out of anything reading the front of the body.+func TestAQuotedDocumentDoesNotBecomeTheBody(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m-long", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = "这个怎么处理"+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = strings.Repeat("很长的报告内容", 400) // 2800 runes++ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-long")++ if !strings.HasSuffix(msg.Text, "…\n\n这个怎么处理") {+ t.Fatalf("Text does not end with an elided quote followed by the sender's words; got tail %q",+ lastRunes(msg.Text, 24))+ }+ quoteLine := strings.SplitN(msg.Text, "\n\n", 2)[0]+ if got := len([]rune(quoteLine)); got > maxQuotedRunes+len([]rune("> [Quote] …")) {+ t.Fatalf("quoted block = %d runes, want it bounded near %d", got, maxQuotedRunes)+ }+}++func lastRunes(s string, n int) string {+ r := []rune(s)+ if len(r) <= n {+ return s+ }+ return string(r[len(r)-n:])+}diff --git a/server/internal/integrations/wecom/ws_frame.go b/server/internal/integrations/wecom/ws_frame.goindex bffcb941e3..e4bfbec382 100644--- a/server/internal/integrations/wecom/ws_frame.go+++ b/server/internal/integrations/wecom/ws_frame.go@@ -104,6 +104,40 @@ type aibotMsgCallback struct {Mixed struct {MsgItem []mixedItem `json:"msg_item"`} `json:"mixed"`+ // Quote is the message the sender was replying to (引用), present only+ // when they replied to one.+ Quote quotedMessage `json:"quote"`+}++// quotedMessage is the message a sender replied to. WeCom mirrors only its+// CONTENT — a msgtype and that type's body, the same shape a 图文混排 run+// has — so the fields come off mixedItem. What it does NOT carry is any+// identity: no msgid, no userid of whoever wrote it. That is the whole reason+// the quote is rendered into the body rather than resolved: there is nothing+// to resolve it against, on our side or WeCom's.+//+// A quoted 图文混排 nests one more level than a run does, hence the extra+// Mixed field and the render override below.+type quotedMessage struct {+ mixedItem+ Mixed struct {+ MsgItem []mixedItem `json:"msg_item"`+ } `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 {+ if !strings.EqualFold(q.MsgType, "mixed") {+ return q.mixedItem.render()+ }+ var runs []string+ for _, item := range q.Mixed.MsgItem {+ if s := item.render(); s != "" {+ runs = append(runs, s)+ }+ }+ return strings.Join(runs, "\n")}// mediaBody is the {url, aeskey} pair every downloadable kind carries. In@@ -269,6 +303,59 @@ func (mc aibotMsgCallback) ownText() (string, bool) {}}+// quotePrefix labels the quoted block so an agent reading the body as plain+// text can tell it apart from the sender's own words. It sits inside a+// markdown blockquote rather than replacing it: the quote can be several+// lines, and only the blockquote keeps the later ones attached to it.+//+// Spelled like the media placeholders (mediaPlaceholder above) so an agent+// reading every channel through one prompt meets one vocabulary.+const quotePrefix = "[Quote]"++// maxQuotedRunes bounds the quoted block. Runes, not bytes: the quoted text is+// usually Chinese, where a byte bound would cut roughly a third as many+// characters and could split one in half.+const maxQuotedRunes = 500++// quotedContext renders the message the sender was replying to, to be shown+// AHEAD of their own words.+//+// Without it a reply is unanswerable: "这个怎么处理" quoting an alert is a+// complete question in the chat and an empty one to the agent, which sees the+// three words and none of what they point at. WeCom sends the quoted content+// on every such message and this adapter was dropping it.+//+// It is deliberately kept out of ownCommandSource: the command parsers read+// the first non-empty line, and a quoted line is not one the sender typed+// 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())+ 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") + "…"+ }+ var b strings.Builder+ for i, line := range strings.Split(rendered, "\n") {+ if i > 0 {+ b.WriteString("\n")+ }+ b.WriteString("> ")+ if i == 0 {+ b.WriteString(quotePrefix)+ b.WriteString(" ")+ }+ b.WriteString(line)+ }+ return b.String()+}+// ownCommandSource is what the slash-command parsers read: the sender's own// words, and nothing this adapter wrote.//@@ -444,18 +531,59 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbaccommand = stripLeadingMentions(command, botDisplayName)}media := mc.attachments()+ // A quote counts as content here for the same reason media does: it is why+ // the directive-only layouts below are not the empty pending sentinel.+ // Rendering it happens further down — this only needs to know it exists.+ quoted := mc.quotedContext()normalizedText, control, controlNormalized := normalizeWeComControlLayout(- mc, text, command, chatType, botDisplayName, len(media) > 0,+ mc, text, command, chatType, botDisplayName, len(media) > 0 || quoted != "",)if controlNormalized {text = normalizedText- // A media-bearing bare /clear is a real turn, not the shared pending- // sentinel. ForceFresh below carries the already-consumed directive.- if control.Kind == engine.ControlCommandFreshSession && control.Body == "" {- command = text+ }++ // The quoted message goes on last, so everything above — the control-layout+ // rewrite and the command source it may hand back — still reads the body+ // the sender actually composed. Only the stored, agent-visible text grows.+ ownBody := text+ if quoted != "" {+ if text == "" {+ text = quoted+ } else {+ text = quoted + "\n\n" + text}}+ // A bare /clear that still carries content — media, a quote, or both — is a+ // real turn, not the shared pending sentinel, so it must not reach Router+ // with the directive still in the command source. ForceFresh below carries+ // the already-consumed directive; the command source becomes whatever body+ // is left, which is never a command (a quote opens with "> ", a placeholder+ // with "["), so nothing downstream re-parses it.+ //+ // This runs after the quote is prepended, not before: leaving it above would+ // hand Router an empty CommandText, which it fills from Text — reaching the+ // same place by a route that only works while the quote happens not to parse+ // as a command.+ if controlNormalized && control.Kind == engine.ControlCommandFreshSession && control.Body == "" {+ command = text+ }++ // An enriching adapter owes Router a command source (router.go:200-208).+ // ownCommandSource answers "" for a standalone photo, file or video on+ // purpose — a placeholder is not words the sender typed — but once a quote+ // is prepended, Router's empty-CommandText fallback assigns the ALREADY+ // enriched Text, and the quote becomes the Chat title (#8058's shape).+ //+ // So hand over the body as it stood before enrichment: still no words the+ // sender did not type, and the placeholder is dropped again downstream by+ // deriveFirstMessageTitle, which lands the title back on the media path it+ // takes when the same screenshot arrives without a quote. lark snapshots+ // its own body for this reason (ws_frame_decoder.go:113).+ if command == "" && quoted != "" {+ command = ownBody+ }+wm := InboundMessage{BotID: botID,MsgID: mc.MsgID,@@ -484,7 +612,13 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac// (feishu_channel.go:139) and Slack from its cleaned text// (slack/inbound.go:131); WeCom was the one adapter leaving it empty.CommandText: command,- ForceFresh: controlNormalized && control.Kind == engine.ControlCommandFreshSession,+ // The quote is context the sender picked by replying to it, which is+ // what channel.InboundMessage.HasSelectedContext names: it is input+ // even when a control command has no body of its own. Without it a+ // bare directive behind a quote reads as an empty message to Router,+ // which persists nothing and answers nobody.+ HasSelectedContext: quoted != "",+ ForceFresh: controlNormalized && control.Kind == engine.ControlCommandFreshSession,// A pure /issue command in WeCom should NOT trigger the// agent — the engine already creates the issue and the// OutboundReplier already sends "✅ 已创建 #N". Letting the agent@@ -516,16 +650,22 @@ func channelMessageFromCallback(botID, botDisplayName string, mc aibotMsgCallbac// body while retaining media placeholders in their original mixed-message// positions. CommandText remains the sender-authored, placeholder-free source// so Router alone applies the semantic difference between the directives.+//+// hasOtherContent says the message carries something besides the directive —+// an attachment, a quoted message, or both. A directive with nothing else is+// the shared pending sentinel and is left intact for Router to recognise; one+// that arrives alongside content is a real turn, and leaving the directive in+// the body would persist it as prompt text.func normalizeWeComControlLayout(mc aibotMsgCallback,visible string,command string,chatType channel.ChatType,botDisplayName string,- hasMedia bool,+ hasOtherContent bool,) (string, engine.ControlCommand, bool) {control, ok := engine.ParseControlCommand(command)- if !ok || (control.Body == "" && !hasMedia) {+ if !ok || (control.Body == "" && !hasOtherContent) {return visible, engine.ControlCommand{}, false}diff --git a/server/internal/integrations/wecom/ws_frame_test.go b/server/internal/integrations/wecom/ws_frame_test.goindex c72ec51bed..312134af98 100644--- a/server/internal/integrations/wecom/ws_frame_test.go+++ b/server/internal/integrations/wecom/ws_frame_test.go@@ -166,3 +166,142 @@ func TestSendMsgTextBody_ShapeAndChatTypeValidation(t *testing.T) {t.Error("chat_type 3 should be rejected (must be 1 or 2)")}}++// TestQuotedContext pins how the message a sender replied to is rendered into+// the body: labelled, blockquoted on every line, and empty when there is+// nothing to show.+func TestQuotedContext(t *testing.T) {+ t.Parallel()++ textQuote := func(content string) quotedMessage {+ var q quotedMessage+ q.MsgType = "text"+ q.Text.Content = content+ return q+ }++ t.Run("a quoted line is labelled and blockquoted", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgType: "text", Quote: textQuote("这是今日的测试情况")}+ if got, want := mc.quotedContext(), "> [Quote] 这是今日的测试情况"; got != want {+ t.Errorf("quotedContext() = %q, want %q", got, want)+ }+ })++ t.Run("every line of a multi-line quote stays inside the block", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgType: "text", Quote: textQuote("第一行\n第二行")}+ if got, want := mc.quotedContext(), "> [Quote] 第一行\n> 第二行"; got != want {+ t.Errorf("quotedContext() = %q, want %q", got, want)+ }+ })++ t.Run("a quoted attachment shows the same placeholder a sent one does", 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 {+ t.Errorf("quotedContext() = %q, want %q", got, want)+ }+ })++ t.Run("a quoted mixed message renders its runs", func(t *testing.T) {+ t.Parallel()+ var q quotedMessage+ q.MsgType = "mixed"+ var words mixedItem+ words.MsgType = "text"+ words.Text.Content = "看这个"+ 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 {+ t.Errorf("quotedContext() = %q, want %q", got, want)+ }+ })++ t.Run("no quote renders nothing", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgType: "text"}+ mc.Text.Content = "hello"+ if got := mc.quotedContext(); got != "" {+ t.Errorf("quotedContext() = %q, want empty", got)+ }+ })++ t.Run("a quote of a kind we do not know renders nothing", func(t *testing.T) {+ t.Parallel()+ var q quotedMessage+ q.MsgType = "location"+ mc := aibotMsgCallback{MsgType: "text", Quote: q}+ if got := mc.quotedContext(); got != "" {+ t.Errorf("quotedContext() = %q, want empty", got)+ }+ })+}++// TestChannelMessageFromCallback_QuoteLeadsBodyButNotCommand is the contract+// that makes the quote safe to add: the agent sees what was pointed at, and+// the command parsers still only ever see the line the sender typed here.+func TestChannelMessageFromCallback_QuoteLeadsBodyButNotCommand(t *testing.T) {+ t.Parallel()++ t.Run("the quote leads the stored body", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m1", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = "这个怎么处理"+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "生产库连接数打满了"++ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-q1")++ want := "> [Quote] 生产库连接数打满了\n\n这个怎么处理"+ if msg.Text != want {+ t.Errorf("Text = %q, want %q", msg.Text, want)+ }+ // The sender typed three words; that is all the parsers may read.+ if msg.CommandText != "这个怎么处理" {+ t.Errorf("CommandText = %q, want the sender's own line", msg.CommandText)+ }+ })++ t.Run("quoting somebody else's /issue does not file an issue", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m2", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = "他这条是什么意思"+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "/issue 登录坏了"++ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-q2")++ if _, ok := engine.ParseIssueCommand(msg.CommandText); ok {+ t.Fatalf("CommandText %q parsed as an issue command", msg.CommandText)+ }+ if msg.SkipAgentRun {+ t.Error("SkipAgentRun set: the quoted command was read as this sender's")+ }+ })++ t.Run("a control command keeps the quote in its first turn", func(t *testing.T) {+ t.Parallel()+ mc := aibotMsgCallback{MsgID: "m3", ChatID: "TUSER", ChatType: "single", MsgType: "text"}+ mc.From.UserID = "TUSER"+ mc.Text.Content = "/new 帮我看看这个"+ mc.Quote.MsgType = "text"+ mc.Quote.Text.Content = "生产库连接数打满了"++ msg := channelMessageFromCallback("bot-1", "", mc, mc.Text.Content, "req-q3")++ want := "> [Quote] 生产库连接数打满了\n\n帮我看看这个"+ if msg.Text != want {+ t.Errorf("Text = %q, want the directive gone and the quote kept", msg.Text)+ }+ if _, ok := engine.ParseNewChatCommand(msg.CommandText); !ok {+ t.Errorf("CommandText = %q, want /new still parseable", msg.CommandText)+ }+ })+}