Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(lark): show real speaker names in Feishu group context (MUL-3084) (#3828)
Bohan Jiangf8bd1d8fc2dc
diff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.goindex b2bf5fd761..7ab5fe7e30 100644--- a/server/internal/integrations/lark/client.go+++ b/server/internal/integrations/lark/client.go@@ -95,6 +95,17 @@ type APIClient interface {// stays a single round-trip. Like GetMessage, this is a thin transport// adapter: flattening and block assembly are the enricher's job.ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error)++ // BatchGetUsers resolves a set of user open_ids to their display names+ // via GET /open-apis/contact/v3/users/batch. The enricher uses it to+ // label recent-context / quoted / forwarded speakers (and the sender+ // who @-mentioned the Bot) with real names instead of positional+ // "User 1 / User 2". Returns an open_id -> name map; ids the API does+ // not return (restricted contact scope, deactivated user, …) are+ // simply absent from the map, and the caller falls back to a+ // positional label. openIDs beyond Lark's 50-per-call cap are dropped+ // by the client.+ BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error)}// ListMessagesParams selects a bounded, recent window of messages in a@@ -317,3 +328,8 @@ func (s *stubAPIClient) ListChatMessages(ctx context.Context, creds Installations.log.Warn("lark stub client: ListChatMessages called", "chat_id", string(p.ChatID))return nil, ErrAPIClientNotConfigured}++func (s *stubAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {+ s.log.Warn("lark stub client: BatchGetUsers called", "count", len(openIDs))+ return nil, ErrAPIClientNotConfigured+}diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.goindex aad0f4edaf..7087fe5356 100644--- a/server/internal/integrations/lark/http_client.go+++ b/server/internal/integrations/lark/http_client.go@@ -649,6 +649,67 @@ func (c *httpAPIClient) ListChatMessages(ctx context.Context, creds Installationreturn out, nil}+// larkBatchGetUsersMaxIDs is Lark's hard cap on user_ids per+// contact/v3/users/batch call. We drop the overflow rather than error so+// a caller asking for more still gets the first 50 resolved.+const larkBatchGetUsersMaxIDs = 50++// BatchGetUsers resolves user open_ids to display names via+// GET /open-apis/contact/v3/users/batch?user_ids=…&user_id_type=open_id.+// It mirrors fetchBotUnionID's single-user contact lookup, batched. Only+// id->name pairs the API actually returns are included; a restricted+// contact scope or an unknown id simply yields a smaller map (code==0+// with fewer items), never an error, so the enricher degrades to+// positional speaker labels. Ids past Lark's 50-per-call cap are dropped.+func (c *httpAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {+ if len(openIDs) == 0 {+ return map[string]string{}, nil+ }+ if len(openIDs) > larkBatchGetUsersMaxIDs {+ openIDs = openIDs[:larkBatchGetUsersMaxIDs]+ }+ token, err := c.tenantAccessToken(ctx, creds)+ if err != nil {+ return nil, err+ }+ q := url.Values{}+ q.Set("user_id_type", "open_id")+ for _, id := range openIDs {+ if id != "" {+ q.Add("user_ids", id)+ }+ }+ path := "/open-apis/contact/v3/users/batch?" + q.Encode()++ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ Items []struct {+ OpenID string `json:"open_id"`+ Name string `json:"name"`+ } `json:"items"`+ } `json:"data"`+ }+ if err := c.doJSON(ctx, c.resolveBaseURL(creds), http.MethodGet, path, token, nil, &resp); err != nil {+ return nil, fmt.Errorf("lark http client: batch get users: %w", err)+ }+ if resp.Code != 0 {+ if isTokenError(resp.Code) {+ c.invalidateToken(creds.AppID)+ }+ return nil, fmt.Errorf("lark http client: batch get users: code=%d msg=%q", resp.Code, resp.Msg)+ }++ out := make(map[string]string, len(resp.Data.Items))+ for _, it := range resp.Data.Items {+ if it.OpenID != "" && it.Name != "" {+ out[it.OpenID] = it.Name+ }+ }+ return out, nil+}+// larkRESTMessageItem is the IM v1 message item shape returned by the// get / list endpoints. It differs from the WS receive event in two// ways the enricher cares about: msg_type (not message_type), and adiff --git a/server/internal/integrations/lark/http_client_batchusers_test.go b/server/internal/integrations/lark/http_client_batchusers_test.gonew file mode 100644index 0000000000..2491373b13--- /dev/null+++ b/server/internal/integrations/lark/http_client_batchusers_test.go@@ -0,0 +1,69 @@+package lark++import (+ "context"+ "net/http"+ "sort"+ "testing"+ "time"+)++// TestHTTPClient_BatchGetUsers exercises the contact name-resolution+// path: the request carries user_id_type=open_id and a user_ids list, and+// the response items[] are folded into an open_id -> name map (entries+// without a name are dropped).+func TestHTTPClient_BatchGetUsers(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok", 7200)+ fake.mux.HandleFunc("/open-apis/contact/v3/users/batch", func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ t.Errorf("want GET, got %s", r.Method)+ }+ q := r.URL.Query()+ if q.Get("user_id_type") != "open_id" {+ t.Errorf("user_id_type = %q", q.Get("user_id_type"))+ }+ ids := q["user_ids"]+ sort.Strings(ids)+ if len(ids) != 3 || ids[0] != "ou_a" || ids[1] != "ou_b" || ids[2] != "ou_c" {+ t.Errorf("user_ids = %v", q["user_ids"])+ }+ writeJSON(w, map[string]any{+ "code": 0, "msg": "ok",+ "data": map[string]any{+ "items": []any{+ map[string]any{"open_id": "ou_a", "name": "Alice"},+ map[string]any{"open_id": "ou_b", "name": "Bob"},+ map[string]any{"open_id": "ou_c"}, // no name -> dropped+ },+ },+ })+ })++ c := newTestClient(fake, time.Now)+ names, err := c.BatchGetUsers(context.Background(), testCreds(), []string{"ou_a", "ou_b", "ou_c"})+ if err != nil {+ t.Fatalf("BatchGetUsers: %v", err)+ }+ if len(names) != 2 || names["ou_a"] != "Alice" || names["ou_b"] != "Bob" {+ t.Errorf("names = %v", names)+ }+ if _, ok := names["ou_c"]; ok {+ t.Errorf("ou_c should be dropped (no name): %v", names)+ }+}++// TestHTTPClient_BatchGetUsersEmpty returns an empty map and makes no HTTP+// call when given no ids.+func TestHTTPClient_BatchGetUsersEmpty(t *testing.T) {+ fake := newLarkFake(t)+ // No token stub and no handler: any HTTP call would panic the fake.+ c := newTestClient(fake, time.Now)+ names, err := c.BatchGetUsers(context.Background(), testCreds(), nil)+ if err != nil {+ t.Fatalf("BatchGetUsers(empty): %v", err)+ }+ if len(names) != 0 {+ t.Errorf("names = %v, want empty", names)+ }+}diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.goindex 11120049ff..452d304664 100644--- a/server/internal/integrations/lark/inbound_enricher.go+++ b/server/internal/integrations/lark/inbound_enricher.go@@ -99,7 +99,7 @@ func NewInboundEnricher(client APIClient, cfg InboundEnricherConfig) Enricher {//// <quoted_message …>…</quoted_message>//-// <the user's own message, or the forwarded transcript>+// <[sender name]: the user's own message, or the forwarded transcript>//// The <recent_context> block is only produced for a group message// addressed to the Bot, and only when RecentContextSize > 0 — it answers@@ -107,6 +107,15 @@ func NewInboundEnricher(client APIClient, cfg InboundEnricherConfig) Enricher {// conversation). It is the one fetch here NOT triggered by something the// user explicitly attached.//+// In group chats, every speaker across ALL blocks (recent + quoted ++// forwarded) and the sender who @-mentioned the Bot are resolved to real+// 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).+//// Persistence note: like the quoted/forwarded blocks, the rewritten Body// is persisted into the addressed turn's chat_message.content downstream// (AppendUserMessage). Inlining nearby group messages — including ones@@ -130,24 +139,76 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, credsreturn msg}+ // Phase 1 — fetch every set of messages we may render. Each is+ // best-effort; its error is handled where the block is rendered. We+ // fetch up front (rather than fetch-and-render per block) so Phase 2+ // can resolve display names for EVERY speaker across ALL blocks in a+ // single Contact batch — otherwise a quoted/forwarded sender that+ // isn't in the recent window would fall back to "User N".+ var recentItems []LarkMessage+ var recentErr error+ if wantRecent {+ recentItems, recentErr = e.fetchRecentItems(ctx, creds, msg)+ }+ var quotedItems []LarkMessage+ var quotedErr error+ if msg.ParentID != "" {+ quotedItems, quotedErr = e.client.GetMessage(ctx, creds, msg.ParentID)+ }+ var forwardItems []LarkMessage+ var forwardErr error+ if isForward {+ forwardItems, forwardErr = e.client.GetMessage(ctx, creds, msg.MessageID)+ }++ // 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)+ }++ // Phase 3 — render broadest-to-narrowest with the complete name map.var b strings.Builderif wantRecent {- if blk := e.renderRecentContext(ctx, creds, msg); blk != "" {- b.WriteString(blk)+ if recentErr != nil {+ b.WriteString(recentContextErrorBlock())+ } else if len(recentItems) > 0 {+ b.WriteString(e.renderRecentContextBlock(recentItems, names))}}if msg.ParentID != "" {if b.Len() > 0 {b.WriteString("\n\n")}- b.WriteString(e.renderQuoted(ctx, creds, msg.ParentID))+ b.WriteString(e.renderQuotedBlock(msg.ParentID, quotedItems, quotedErr, names))}var core stringif isForward {- core = e.renderForwarded(ctx, creds, msg.MessageID)+ if forwardErr != nil {+ e.logger.Warn("lark enricher: forward fetch failed", "message_id", msg.MessageID, "err", forwardErr)+ core = forwardedErrorBlock()+ } else {+ core = e.renderForwardedItems(forwardItems, msg.MessageID, names)+ }} else {core = msg.Body+ // 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 != "" {+ core = fmt.Sprintf("[%s]: %s", name, msg.Body)+ }}if b.Len() > 0 && core != "" {b.WriteString("\n\n")@@ -158,34 +219,70 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, credsreturn msg}-// renderRecentContext fetches the most recent messages in the group and-// renders a <recent_context> block of the surrounding conversation,-// excluding the triggering message itself and the directly-quoted parent-// (which gets its own <quoted_message> block, so it isn't duplicated).-// Messages render oldest-first as "[<speaker>]: <text>" using the same-// positional speaker labels the forwarded-transcript renderer uses. Any-// fetch failure degrades to a visible placeholder; like the rest of the-// enricher it never blocks ingestion. An empty/whitespace window yields-// "" so Enrich emits no block at all.-func (e *inboundEnricher) renderRecentContext(ctx context.Context, creds InstallationCredentials, msg InboundMessage) string {+// senderOpenIDs returns the distinct non-app sender open_ids across the+// given messages, in first-appearance order — the input set for a+// Contact name lookup.+func senderOpenIDs(msgs []LarkMessage) []string {+ seen := make(map[string]bool, len(msgs))+ out := make([]string, 0, len(msgs))+ for _, m := range msgs {+ if m.SenderType == "app" || m.SenderID == "" || seen[m.SenderID] {+ continue+ }+ seen[m.SenderID] = true+ out = append(out, m.SenderID)+ }+ return out+}++// resolveNames batch-resolves open_ids to display names, best-effort: a+// failure (restricted contact scope, transport error) logs and returns+// nil so every speaker labeler degrades to positional "User N" rather+// than blocking ingestion. Duplicate / empty ids are dropped first.+func (e *inboundEnricher) resolveNames(ctx context.Context, creds InstallationCredentials, ids []string) map[string]string {+ uniq := make([]string, 0, len(ids))+ seen := make(map[string]bool, len(ids))+ for _, id := range ids {+ if id == "" || seen[id] {+ continue+ }+ seen[id] = true+ uniq = append(uniq, id)+ }+ if len(uniq) == 0 {+ return nil+ }+ names, err := e.client.BatchGetUsers(ctx, creds, uniq)+ if err != nil {+ e.logger.Warn("lark enricher: speaker name resolution failed", "ids", len(uniq), "err", err)+ return nil+ }+ 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+// oldest-first. The window is anchored to the trigger message's time so+// it captures the conversation up to the @-mention rather than whatever+// is newest by the time this fetch runs. A fetch failure is returned to+// the caller (which renders the documented placeholder); it never blocks+// ingestion.+func (e *inboundEnricher) fetchRecentItems(ctx context.Context, creds InstallationCredentials, msg InboundMessage) ([]LarkMessage, error) {items, err := e.client.ListChatMessages(ctx, creds, ListMessagesParams{ChatID: msg.ChatID,PageSize: e.recentContextSize,- // Anchor the window to the trigger message's time (Lark sends it- // as epoch millis; end_time wants seconds) so we pull the- // conversation up to the @-mention, not whatever is newest by the- // time this prefetch runs. A missing/unparseable time yields 0,- // which the client treats as "no end_time" (newest N).+ // Lark sends create_time as epoch millis; end_time wants seconds. A+ // missing/unparseable time yields 0, which the client treats as+ // "no end_time" (newest N).EndTime: parseLarkMillis(msg.CreateTime) / 1000,})if err != nil {e.logger.Warn("lark enricher: recent context fetch failed","chat_id", string(msg.ChatID), "err", err)- return recentContextErrorBlock()+ return nil, err}- // Drop the trigger and the quoted parent so neither is duplicated- // alongside the user's core message / its own <quoted_message> block.exclude := map[string]bool{msg.MessageID: true}if msg.ParentID != "" {exclude[msg.ParentID] = true@@ -197,17 +294,21 @@ func (e *inboundEnricher) renderRecentContext(ctx context.Context, creds Install}kept = append(kept, it)}- if len(kept) == 0 {- return ""- }// The list endpoint returns newest-first; render oldest-first so the// transcript reads top-to-bottom like the chat does.sort.SliceStable(kept, func(i, j int) bool {return parseLarkMillis(kept[i].CreateTime) < parseLarkMillis(kept[j].CreateTime)})+ return kept, nil+}- labeler := newSpeakerLabeler()+// renderRecentContextBlock renders the surrounding conversation as a+// <recent_context> block: one "[<speaker>]: <text>" line per message,+// oldest-first, speakers labeled with real names from `names` (falling+// back to positional "User N"). Callers pass a non-empty `kept`.+func (e *inboundEnricher) renderRecentContextBlock(kept []LarkMessage, names map[string]string) string {+ labeler := newSpeakerLabeler(names)lines := make([]string, 0, len(kept))for _, m := range kept {label := labeler.label(m)@@ -231,14 +332,14 @@ func recentContextErrorBlock() string {return "<recent_context type=\"error\">[unable to fetch recent context]</recent_context>"}-// renderQuoted fetches the directly-quoted parent and renders a-// <quoted_message> block. A parent that is itself a merge_forward nests-// a <forwarded_messages> transcript inside the quoted block (the-// GetMessage response already carries both the forward sentinel and its-// children, so no extra round-trip is needed). Any failure degrades to-// the documented error block.-func (e *inboundEnricher) renderQuoted(ctx context.Context, creds InstallationCredentials, parentID string) string {- items, err := e.client.GetMessage(ctx, creds, parentID)+// renderQuotedBlock renders a <quoted_message> block from the already-+// fetched GetMessage(parentID) result. A parent that is itself a+// merge_forward nests a <forwarded_messages> transcript inside the quoted+// block (the GetMessage response already carries both the forward+// sentinel and its children). A fetch error / empty / deleted parent+// degrades to the documented error block. Speakers are labeled from+// `names` (the shared, already-resolved map), falling back to "User N".+func (e *inboundEnricher) renderQuotedBlock(parentID string, items []LarkMessage, err error, names map[string]string) string {if err != nil || len(items) == 0 {e.logger.Warn("lark enricher: quoted parent fetch failed","parent_id", parentID, "items", len(items), "err", err)@@ -249,11 +350,11 @@ func (e *inboundEnricher) renderQuoted(ctx context.Context, creds InstallationCrreturn quotedErrorBlock(parentID)}- labeler := newSpeakerLabeler()+ labeler := newSpeakerLabeler(names)sender := labeler.label(parent)if parent.MessageType == larkMsgTypeMergeForward {- inner := e.renderForwardedItems(items, parentID)+ inner := e.renderForwardedItems(items, parentID, names)return wrapQuoted(parentID, sender, larkMsgTypeMergeForward, inner)}text := e.flattenMessage(parent)@@ -263,25 +364,12 @@ func (e *inboundEnricher) renderQuoted(ctx context.Context, creds InstallationCrreturn wrapQuoted(parentID, sender, parent.MessageType, text)}-// renderForwarded fetches a merge_forward by id and renders its bundled-// children. The GetMessage response is [sentinel, child…]; we filter the-// forward's own record out by id (robust to whether Lark returns the-// sentinel first or not) and render the rest.-func (e *inboundEnricher) renderForwarded(ctx context.Context, creds InstallationCredentials, forwardID string) string {- items, err := e.client.GetMessage(ctx, creds, forwardID)- if err != nil {- e.logger.Warn("lark enricher: forward fetch failed", "message_id", forwardID, "err", err)- return forwardedErrorBlock()- }- return e.renderForwardedItems(items, forwardID)-}-// renderForwardedItems renders the children of a forward whose own// record id is forwardID. Children are time-ordered, capped, and each// rendered as "[<speaker>]: <text>"; a child that is itself a forward is// not recursed into (it gets a manual-expand placeholder) so the HTTP// fan-out on the ACK-latency-sensitive inbound path stays bounded.-func (e *inboundEnricher) renderForwardedItems(items []LarkMessage, forwardID string) string {+func (e *inboundEnricher) renderForwardedItems(items []LarkMessage, forwardID string, names map[string]string) string {// The verified contract is that GetMessage(forward_id) returns one// level of bundling: [sentinel, direct-children…]. We therefore// treat every non-sentinel item as a direct child. We filter by id@@ -312,7 +400,7 @@ func (e *inboundEnricher) renderForwardedItems(items []LarkMessage, forwardID stchildren = children[:e.maxForwardChildren]}- labeler := newSpeakerLabeler()+ labeler := newSpeakerLabeler(names)lines := make([]string, 0, len(children))for _, c := range children {label := labeler.label(c)@@ -388,18 +476,20 @@ 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 — resolving real names needs a separate Contact API-// lookup, tracked as a follow-up), so we map each distinct user id to-// "User 1", "User 2", … in first-appearance order, and app senders to-// "Bot". This keeps the conversation's turn-taking structure legible-// without a per-sender network round-trip.+// (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".type speakerLabeler struct {- seen map[string]string- n int+ names map[string]string // resolved open_id -> display name (may be nil)+ seen map[string]string+ n int}-func newSpeakerLabeler() *speakerLabeler {- return &speakerLabeler{seen: make(map[string]string)}+func newSpeakerLabeler(names map[string]string) *speakerLabeler {+ return &speakerLabeler{names: names, seen: make(map[string]string)}}func (l *speakerLabeler) label(m LarkMessage) string {@@ -413,8 +503,13 @@ func (l *speakerLabeler) label(m LarkMessage) string {if lbl, ok := l.seen[key]; ok {return lbl}- l.n++- lbl := fmt.Sprintf("User %d", l.n)+ var lbl string+ if name := l.names[key]; name != "" {+ lbl = name+ } else {+ l.n+++ lbl = fmt.Sprintf("User %d", l.n)+ }l.seen[key] = lblreturn lbl}diff --git a/server/internal/integrations/lark/inbound_enricher_recent_test.go b/server/internal/integrations/lark/inbound_enricher_recent_test.goindex cb094dd9b8..25b9be79e3 100644--- a/server/internal/integrations/lark/inbound_enricher_recent_test.go+++ b/server/internal/integrations/lark/inbound_enricher_recent_test.go@@ -77,13 +77,109 @@ func TestEnrichRecentContextGroupMention(t *testing.T) {}}+// TestEnrichRecentContextResolvesNames covers the MUL-3084 follow-up:+// speakers in <recent_context> show real display names (not User 1/2),+// and the user's own @-message is labeled with the sender's name so the+// agent knows WHO @-mentioned it.+func TestEnrichRecentContextResolvesNames(t *testing.T) {+ t.Parallel()+ fake := newEnricherFake()+ fake.userNames = map[string]string{+ "ou_alice": "Alice",+ "ou_bob": "Bob",+ "ou_charlie": "Charlie",+ }+ fake.byChat["oc_g"] = []LarkMessage{+ textMsg("om_trigger", "ou_charlie", "总结一下", "3000"),+ textMsg("om_b", "ou_bob", "明天发布", "2000"),+ textMsg("om_a", "ou_alice", "我改完了登录页", "1000"),+ }+ in := InboundMessage{+ MessageType: "text",+ MessageID: "om_trigger",+ ChatID: "oc_g",+ ChatType: ChatTypeGroup,+ AddressedToBot: true,+ SenderOpenID: "ou_charlie",+ Body: "总结一下",+ CreateTime: "3000",+ }++ out := enrich(t, fake, in, groupCfg())++ want := `<recent_context count="2">+[Alice]: 我改完了登录页+[Bob]: 明天发布+</recent_context>++[Charlie]: 总结一下`+ if out.Body != want {+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)+ }+ if len(fake.userCalls) != 1 {+ t.Fatalf("expected one BatchGetUsers call, got %d", len(fake.userCalls))+ }+ // The batch must include the surrounding speakers AND the trigger sender.+ got := map[string]bool{}+ for _, id := range fake.userCalls[0] {+ got[id] = true+ }+ for _, want := range []string{"ou_alice", "ou_bob", "ou_charlie"} {+ if !got[want] {+ t.Errorf("BatchGetUsers missing id %q (got %v)", want, fake.userCalls[0])+ }+ }+}++// TestEnrichRecentContextNameFallback pins the mixed case: a sender whose+// name resolved shows the name; one that did not falls back to positional+// "User N"; and an unresolved trigger sender leaves the core unlabeled.+func TestEnrichRecentContextNameFallback(t *testing.T) {+ t.Parallel()+ fake := newEnricherFake()+ fake.userNames = map[string]string{"ou_alice": "Alice"} // bob + charlie unresolved+ fake.byChat["oc_g"] = []LarkMessage{+ textMsg("om_trigger", "ou_charlie", "总结一下", "3000"),+ textMsg("om_b", "ou_bob", "明天发布", "2000"),+ textMsg("om_a", "ou_alice", "我改完了登录页", "1000"),+ }+ in := InboundMessage{+ MessageType: "text",+ MessageID: "om_trigger",+ ChatID: "oc_g",+ ChatType: ChatTypeGroup,+ AddressedToBot: true,+ SenderOpenID: "ou_charlie",+ Body: "总结一下",+ CreateTime: "3000",+ }++ out := enrich(t, fake, in, groupCfg())++ want := `<recent_context count="2">+[Alice]: 我改完了登录页+[User 1]: 明天发布+</recent_context>++总结一下`+ if out.Body != want {+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)+ }+}+// TestEnrichRecentContextWithQuotedReply composes both expansions: the// recent_context block comes first (broadest), then the quoted parent,// then the user's prose. The quoted parent is excluded from the// recent_context window so it isn't duplicated.+//+// It also pins the MUL-3084 review fix: the quoted parent's sender+// (ou_alice) is NOT in the recent window, yet still resolves to a real+// name ("Alice") — i.e. quoted/forwarded senders are folded into the same+// Contact batch as the recent-window senders, not left as "User N".func TestEnrichRecentContextWithQuotedReply(t *testing.T) {t.Parallel()fake := newEnricherFake()+ fake.userNames = map[string]string{"ou_alice": "Alice", "ou_bob": "Bob"}fake.byID["om_parent"] = []LarkMessage{textMsg("om_parent", "ou_alice", "删除按钮加一下", "1000"),}@@ -105,10 +201,10 @@ func TestEnrichRecentContextWithQuotedReply(t *testing.T) {out := enrich(t, fake, in, groupCfg())want := `<recent_context count="1">-[User 1]: 顺便看下样式+[Bob]: 顺便看下样式</recent_context>-<quoted_message message_id="om_parent" sender="User 1" type="text">+<quoted_message message_id="om_parent" sender="Alice" type="text">删除按钮加一下</quoted_message>@@ -122,6 +218,57 @@ func TestEnrichRecentContextWithQuotedReply(t *testing.T) {if len(fake.calls) != 1 || fake.calls[0] != "om_parent" {t.Errorf("expected one GetMessage(om_parent), got %v", fake.calls)}+ // The single name batch must include the quoted parent's sender even+ // though it is not in the recent window.+ if len(fake.userCalls) != 1 {+ t.Fatalf("expected one BatchGetUsers call, got %d", len(fake.userCalls))+ }+ found := false+ for _, id := range fake.userCalls[0] {+ if id == "ou_alice" {+ found = true+ }+ }+ if !found {+ t.Errorf("BatchGetUsers must include quoted parent sender ou_alice, got %v", fake.userCalls[0])+ }+}++// TestEnrichForwardedResolvesNames proves the review fix also covers the+// forwarded transcript: in a group, merge_forward children are folded+// into the same Contact batch and render with real names. Recent prefetch+// is disabled here to isolate the forwarded path; name resolution still+// runs because it is a group chat.+func TestEnrichForwardedResolvesNames(t *testing.T) {+ t.Parallel()+ fake := newEnricherFake()+ fake.userNames = map[string]string{"ou_jiayuan": "Jiayuan", "ou_bohan": "Bohan"}+ fake.byID["om_forward"] = []LarkMessage{+ {MessageID: "om_forward", MessageType: "merge_forward", SenderID: "ou_bohan", SenderType: "user", Content: `{"content":"Merged and Forwarded Message"}`},+ textMsg("c1", "ou_jiayuan", "你们线上的 Multica 能用吗", "1000"),+ textMsg("c2", "ou_bohan", "我这边都能登陆", "2000"),+ }+ in := InboundMessage{+ MessageType: "merge_forward",+ MessageID: "om_forward",+ ChatID: "oc_g",+ ChatType: ChatTypeGroup,+ AddressedToBot: true,+ SenderOpenID: "ou_bohan",+ }++ out := enrich(t, fake, in, InboundEnricherConfig{})++ want := `<forwarded_messages count="2">+[Jiayuan]: 你们线上的 Multica 能用吗+[Bohan]: 我这边都能登陆+</forwarded_messages>`+ if out.Body != want {+ t.Errorf("body\n got = %q\nwant = %q", out.Body, want)+ }+ if len(fake.userCalls) != 1 {+ t.Fatalf("expected one BatchGetUsers call, got %d", len(fake.userCalls))+ }}// TestEnrichRecentContextFetchError degrades to a visible placeholder ondiff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.goindex 6c4387e179..eb9911de0f 100644--- a/server/internal/integrations/lark/inbound_enricher_test.go+++ b/server/internal/integrations/lark/inbound_enricher_test.go@@ -22,6 +22,12 @@ type enricherFakeClient struct {errByChat map[ChatID]errorlistCalls []ChatIDlistParams []ListMessagesParams++ // BatchGetUsers canned open_id -> name map + recorder. Empty by+ // default, so speakers fall back to positional "User N".+ userNames map[string]string+ usersErr error+ userCalls [][]string}func newEnricherFake() *enricherFakeClient {@@ -50,6 +56,19 @@ func (f *enricherFakeClient) ListChatMessages(ctx context.Context, creds Install}return f.byChat[p.ChatID], nil}+func (f *enricherFakeClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {+ f.userCalls = append(f.userCalls, openIDs)+ if f.usersErr != nil {+ return nil, f.usersErr+ }+ out := map[string]string{}+ for _, id := range openIDs {+ if name := f.userNames[id]; name != "" {+ out[id] = name+ }+ }+ return out, nil+}// Unused-by-enricher methods — present only to satisfy APIClient.func (f *enricherFakeClient) SendInteractiveCard(context.Context, SendCardParams) (string, error) {diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.goindex 118a4f292f..a5e195d1d2 100644--- a/server/internal/integrations/lark/outbound_test.go+++ b/server/internal/integrations/lark/outbound_test.go@@ -125,6 +125,9 @@ func (f *fakeAPIClient) GetMessage(ctx context.Context, creds InstallationCredenfunc (f *fakeAPIClient) ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {return nil, nil}+func (f *fakeAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {+ return nil, nil+}func newTestPatcher(t *testing.T) (*Patcher, *fakePatcherQueries, *fakeAPIClient) {t.Helper()diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.goindex 6a176553a6..1dd3850cd1 100644--- a/server/internal/integrations/lark/outcome_replier_test.go+++ b/server/internal/integrations/lark/outcome_replier_test.go@@ -78,6 +78,9 @@ func (s *stubAPIClientWithRecorder) GetMessage(ctx context.Context, creds Instalfunc (s *stubAPIClientWithRecorder) ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {return nil, nil}+func (s *stubAPIClientWithRecorder) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {+ return nil, nil+}// stubCredentialsResolver returns a fixed plaintext secret.type stubCredentialsResolver struct{ secret string }