Skip to content

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

Go

MUL-9242 fix(lark): name forwarded and quoted speakers from @-mentions and in p2p chats (#10584)

rawlencefd23ae812621
diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.go
index 9e008d318f..bc4ce66b2d 100644
--- a/server/internal/integrations/lark/inbound_enricher.go
+++ b/server/internal/integrations/lark/inbound_enricher.go
@@ -134,9 +134,11 @@ func NewInboundEnricher(client APIClient, cfg InboundEnricherConfig) Enricher {
// display names via ONE Contact batch call, so the agent reads
// "[Alice]: …" rather than "[User 1]: …" and knows who addressed it. This
// is why the quote/forward items are fetched up front (Phase 1) before
-// names are resolved (Phase 2). Unresolved senders fall back to positional
-// "User N"; resolution is best-effort and never blocks. p2p chats keep
-// positional labels (identity is unambiguous in a 1:1).
+// names are resolved (Phase 2). A sender the Contact lookup misses is still
+// named when an @-mention in the fetched messages carries its id; the rest
+// fall back to positional "User N". Resolution is best-effort and never
+// blocks. In p2p chats only quoted and forwarded speakers are resolved; the
+// trigger sender stays unlabeled (identity is unambiguous in a 1:1).
//
// Persistence note: like the quoted/forwarded blocks, the rewritten Body
// is persisted into the addressed turn's chat_message.content downstream
@@ -228,20 +230,24 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds
fetches.Wait()
// Phase 2 — resolve display names for every speaker we're about to
- // render (recent + quoted + forwarded) plus the sender who @-mentioned
- // the Bot, in one batch. Group chats only; p2p keeps positional labels
- // (identity is unambiguous in a 1:1). Unresolved ids fall back to
- // "User N" per speakerLabeler.
- var names map[string]string
- if msg.ChatType == ChatTypeGroup {
- ids := senderOpenIDs(recentItems)
- ids = append(ids, senderOpenIDs(quotedItems)...)
- ids = append(ids, senderOpenIDs(forwardItems)...)
- if msg.SenderOpenID != "" {
- ids = append(ids, string(msg.SenderOpenID))
- }
- names = e.resolveNames(ctx, creds, ids)
- }
+ // render (recent + quoted + forwarded), plus in groups the sender who
+ // @-mentioned the Bot, in one batch. A p2p trigger sender needs no label
+ // (identity is unambiguous in a 1:1), but a quoted or forwarded message
+ // there can come from anyone. Unresolved ids fall back to "User N" per
+ // speakerLabeler.
+ isGroup := msg.ChatType == ChatTypeGroup
+ ids := senderOpenIDs(recentItems)
+ ids = append(ids, senderOpenIDs(quotedItems)...)
+ ids = append(ids, senderOpenIDs(forwardItems)...)
+ if isGroup && msg.SenderOpenID != "" {
+ ids = append(ids, string(msg.SenderOpenID))
+ }
+ names := e.resolveNames(ctx, creds, ids)
+ // The Contact lookup only covers users inside the app's contact scope,
+ // which is often just a few people. Mentions in the fetched messages
+ // carry open_ids and display names, so user speakers can still be
+ // matched exactly when someone @-mentioned them.
+ names = addMentionNames(names, recentItems, quotedItems, forwardItems)
// Phase 3 — render broadest-to-narrowest with the complete name map.
if msg.ParentID != "" || isForward {
@@ -276,7 +282,7 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds
// Label the user's own message with their real name so the agent
// knows WHO @-mentioned it — not just what they said. Only when the
// name resolved (group path); otherwise the body passes through.
- if name := names[string(msg.SenderOpenID)]; name != "" {
+ if name := names[string(msg.SenderOpenID)]; isGroup && name != "" {
core = fmt.Sprintf("[%s]: %s", name, msg.Body)
}
}
@@ -342,6 +348,27 @@ func (e *inboundEnricher) resolveNames(ctx context.Context, creds InstallationCr
return names
}
+// addMentionNames fills missing open_ids with display names carried by
+// @-mentions in msgs, and returns the (possibly new) map. Mention open_ids
+// match user sender ids; app senders use app_ids and remain "Bot".
+// Contact-resolved names are never overwritten.
+func addMentionNames(names map[string]string, batches ...[]LarkMessage) map[string]string {
+ for _, msgs := range batches {
+ for _, m := range msgs {
+ for _, mn := range m.Mentions {
+ if mn.ID == "" || mn.Name == "" || names[mn.ID] != "" {
+ continue
+ }
+ if names == nil {
+ names = make(map[string]string)
+ }
+ names[mn.ID] = mn.Name
+ }
+ }
+ }
+ return names
+}
+
// fetchRecentItems pulls the recent group window and returns the
// messages to render — the trigger message itself and the directly-quoted
// parent (which gets its own <quoted_message> block) filtered out, sorted
@@ -739,11 +766,11 @@ func parseLarkMillis(s string) int64 {
// speakerLabeler assigns stable, human-readable labels to the senders
// within one rendered block. Lark message items carry only a sender id
// (no display name in the payload), so the enricher resolves real names
-// out of band via the Contact API and passes them in as a sender-id ->
-// name map. A sender present in that map is labeled with their real
-// name; one that is not (restricted contact scope, deactivated user,
-// name lookup failed) falls back to "User 1", "User 2", … in
-// first-appearance order. App senders are always "Bot".
+// out of band via the Contact API or fetched @-mentions and passes them
+// in as an open_id -> name map. A user present in that map is labeled
+// with their real name; one that is not (restricted contact scope,
+// deactivated user, name lookup failed) falls back to "User 1", "User 2",
+// … in first-appearance order. App senders are always "Bot".
type speakerLabeler struct {
names map[string]string // resolved open_id -> display name (may be nil)
seen map[string]string
diff --git a/server/internal/integrations/lark/inbound_enricher_recent_test.go b/server/internal/integrations/lark/inbound_enricher_recent_test.go
index 68b3649120..8627187cd3 100644
--- a/server/internal/integrations/lark/inbound_enricher_recent_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_recent_test.go
@@ -537,6 +537,119 @@ func TestEnrichForwardedResolvesNames(t *testing.T) {
}
}
+// TestEnrichForwardedNamesFromMentions covers an app whose contact scope
+// hides the forwarded speakers: Contact resolves nobody, yet a speaker
+// someone @-mentioned is named from that mention's open_id. A speaker
+// nobody mentioned keeps the positional label.
+func TestEnrichForwardedNamesFromMentions(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ mention := func(m LarkMessage, key, id, name string) LarkMessage {
+ m.Mentions = append(m.Mentions, LarkMessageMention{Key: key, ID: id, Name: name})
+ return m
+ }
+ fake.byID["om_forward"] = []LarkMessage{
+ {MessageID: "om_forward", MessageType: "merge_forward", SenderID: "ou_fwd", SenderType: "user", Content: `{"content":"Merged and Forwarded Message"}`},
+ mention(textMsg("c1", "ou_alice", "@_user_1 can you check?", "1000"), "@_user_1", "ou_bob", "Bob"),
+ textMsg("c2", "ou_bob", "on it", "2000"),
+ mention(textMsg("c3", "ou_carol", "@_user_1 thanks", "3000"), "@_user_1", "ou_alice", "Alice"),
+ }
+ in := InboundMessage{
+ MessageType: "merge_forward",
+ MessageID: "om_forward",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ SenderOpenID: "ou_fwd",
+ }
+
+ out := enrich(t, fake, in, InboundEnricherConfig{})
+
+ want := `<forwarded_messages count="3">
+[Alice]: @Bob can you check?
+[Bob]: on it
+[User 1]: @Alice thanks
+</forwarded_messages>`
+ if out.Body != want {
+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)
+ }
+}
+
+func TestSpeakerLabelerAppIgnoresNameMap(t *testing.T) {
+ t.Parallel()
+ labeler := newSpeakerLabeler(map[string]string{"cli_bot": "Helper"})
+ if got := labeler.label(appMsg("om_bot", "tracing", "1000")); got != "Bot" {
+ t.Errorf("app speaker label = %q, want Bot", got)
+ }
+}
+
+// TestEnrichP2PResolvesQuotedAndForwardedNames covers forwarding into a
+// 1:1 chat, the usual way a user hands the Bot a conversation: the
+// forwarded and quoted speakers get real names, while the trigger sender
+// stays unlabeled as before.
+func TestEnrichP2PResolvesQuotedAndForwardedNames(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.userNames = map[string]string{"ou_alice": "Alice", "ou_bob": "Bob", "ou_me": "Me"}
+ fake.byID["om_forward"] = []LarkMessage{
+ {MessageID: "om_forward", MessageType: "merge_forward", SenderID: "ou_me", SenderType: "user", Content: `{"content":"Merged and Forwarded Message"}`},
+ textMsg("c1", "ou_alice", "login is broken", "1000"),
+ textMsg("c2", "ou_me", "looking", "2000"),
+ }
+ fake.byID["om_parent"] = []LarkMessage{textMsg("om_parent", "ou_bob", "see logs", "1000")}
+
+ forward := enrich(t, fake, InboundMessage{MessageType: "merge_forward", MessageID: "om_forward", ChatID: "oc_p", ChatType: ChatTypeP2P, SenderOpenID: "ou_me"}, groupCfg())
+ quote := enrich(t, fake, InboundMessage{MessageType: "text", MessageID: "om_q", ChatID: "oc_p", ChatType: ChatTypeP2P, SenderOpenID: "ou_me", Body: "why?", ParentID: "om_parent"}, groupCfg())
+
+ wantForward := `<forwarded_messages count="2">
+[Alice]: login is broken
+[Me]: looking
+</forwarded_messages>`
+ wantQuote := `<quoted_message message_id="om_parent" sender="Bob" type="text">
+see logs
+</quoted_message>
+
+why?`
+ if forward.Body != wantForward {
+ t.Errorf("forward body\n got = %q\nwant = %q", forward.Body, wantForward)
+ }
+ if quote.Body != wantQuote {
+ t.Errorf("quote body\n got = %q\nwant = %q", quote.Body, wantQuote)
+ }
+ if len(fake.listCalls) != 0 {
+ t.Errorf("p2p must not prefetch recent context, got %v", fake.listCalls)
+ }
+}
+
+// TestEnrichContactNameWinsOverMentionName pins precedence: a mention's
+// name only fills an id the Contact lookup did not resolve.
+func TestEnrichContactNameWinsOverMentionName(t *testing.T) {
+ t.Parallel()
+ fake := newEnricherFake()
+ fake.userNames = map[string]string{"ou_alice": "Alice Chen"}
+ quoted := textMsg("om_parent", "ou_alice", "ship it", "1000")
+ fake.byID["om_parent"] = []LarkMessage{quoted}
+ recent := textMsg("om_r", "ou_bob", "@_user_1 ok", "2000")
+ recent.Mentions = []LarkMessageMention{{Key: "@_user_1", ID: "ou_alice", Name: "Ally"}}
+ fake.byChat["oc_g"] = []LarkMessage{textMsg("om_trigger", "ou_bob", "go", "3000"), recent}
+ in := InboundMessage{
+ MessageType: "text",
+ MessageID: "om_trigger",
+ ChatID: "oc_g",
+ ChatType: ChatTypeGroup,
+ AddressedToBot: true,
+ Body: "go",
+ ParentID: "om_parent",
+ CreateTime: "3000",
+ }
+
+ out := enrich(t, fake, in, groupCfg())
+
+ if !strings.Contains(out.Body, `sender="Alice Chen"`) || !strings.Contains(out.Body, "[User 1]: @Ally ok") {
+ t.Errorf("Contact name must win for the sender label; got\n%s", out.Body)
+ }
+}
+
// TestEnrichRecentContextFetchError degrades to a plain, user-readable
// note on a list failure without leaking the old internal XML placeholder
// or dropping the user's body.