Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8495 fix(lark): retain explicitly selected context media (#9813)
Frezcbe8818cbbd06
diff --git a/docs/lark-inbound-media.md b/docs/lark-inbound-media.mdnew file mode 100644index 0000000000..a74cc8d1af--- /dev/null+++ b/docs/lark-inbound-media.md@@ -0,0 +1,61 @@+# Lark inbound context media++Lark/Feishu chat turns retain attachments from the trigger message, explicit+quotes, and direct children of merged forwards. Images, files, audio and video+reuse direct-message resource downloads, upload intents, attachment binding and+authorization. This does not add parsing, transcription or video frame extraction.++## Selection and attribution++- Automatic recent group context keeps its existing text and media placeholders.+ It never collects, downloads, stores or binds historical media. Repeated group+ mentions do not reupload that history.+- Existing topic boundaries, recent-window limits, deleted-message handling and+ forward-child limits still apply. Nested forwards are not expanded.+- Resources are collected only while explicitly selected messages are rendered.+ Forward children use the containing forward's message ID for resource reads.+- Repeated appearances of one resource and source message share one attachment;+ each selected position receives the attachment ID. Different owners stay distinct.+- Markers avoid collisions with the full rendered original text, including+ rich-text spans, sender names, filenames and source wrappers.+- Failed reads keep unavailable markers at their original positions.+- `/issue` follows the existing WeCom behavior: selected media becomes issue+ attachments and its ordinary attachment blocks are appended to the description.+ Quoted/forwarded text stays out of the description, just as for text-only quotes.+ Existing marked-block merging preserves late attachments through stale or batch+ saves and respects explicit deletion after an editor adopts them.++## Deadlines and recovery++Context metadata enrichment stays inline under the existing connector+`EnrichTimeout` (two seconds by default). Independent recent, quoted and forwarded+reads start together, share that deadline, and are joined before rendering.+Cancellation reaches every read; name lookup does not start after expiration.+Timeouts retain explicit unavailable context. This PR does not extend that budget+or introduce asynchronous metadata preparation.++Only actual downloadable resources enter the existing durable media-pending+workflow. Downloads, uploads, cancellation, upload-intent cleanup and task recovery+retain their existing limits and lifecycle; text-only context does not acquire a+media fence. Attachment bytes and ordinary CLI output limits are unchanged.++A bare `/clear` records fresh-session intent without automatic context creating a+model turn. Explicit quotes, current media or a prompt still follow the ordinary+path. `/new` skips automatic recent context while allowing explicit selections.++## Verification++With an explicit disposable, migrated `DATABASE_URL`:++```sh+cd server+go test -race -p 2 -parallel 2 \+ ./internal/integrations/lark ./internal/integrations/channel/engine+```++Regression coverage includes explicit quotes/forwards and all four media kinds;+automatic recent exclusion across repeated turns; resource ownership/deduplication;+failed/omitted resources; literal marker collisions; appended issue attachments+without quoted transcripts; preserved reporter edits; existing inline issue media+and stale/batch-save handling; concurrent reads and cancellation. Redis-backed+tests additionally require `REDIS_TEST_URL`.diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex d914c511f3..5acc5f57e9 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -1127,11 +1127,13 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, inif !linked[media.id] || media.ref.InlinePlaceholder == "" {continue}- replacements = append(replacements, inlineMediaReplacement{- placeholder: media.ref.InlinePlaceholder,- index: media.ref.InlineIndex,- markdown: inlineMediaMarkdown(media.ref, media.id),- })+ for index := media.ref.InlineIndex; index < media.ref.InlineIndex+max(1, media.ref.InlineCount); index++ {+ replacements = append(replacements, inlineMediaReplacement{+ placeholder: media.ref.InlinePlaceholder,+ index: index,+ markdown: inlineMediaMarkdown(media.ref, media.id),+ })+ }}if body, changed := composeInlineMediaBody(in.Body, replacements); changed {rows, err := qtx.UpdateChatMessageContentForChannelMedia(ctx, db.UpdateChatMessageContentForChannelMediaParams{diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.goindex c8ae3a5f29..6895f328f4 100644--- a/server/internal/integrations/channel/engine/session_db_test.go+++ b/server/internal/integrations/channel/engine/session_db_test.go@@ -812,6 +812,53 @@ func (failingLinkSessionQueries) LinkAttachmentsToChatMessage(context.Context, dreturn nil, errors.New("injected attachment link failure")}+func TestBindMediaRefs_RepeatedContextMediaGetsOneReadableAttachment(t *testing.T) {+ for _, tc := range []struct {+ kind channel.MsgType+ label, ext, mime string+ }{+ {channel.MsgTypeImage, "Image", "png", "image/png"},+ {channel.MsgTypeFile, "File", "txt", "text/plain"},+ {channel.MsgTypeAudio, "Audio", "wav", "audio/wav"},+ {channel.MsgTypeVideo, "Video", "mp4", "video/mp4"},+ } {+ t.Run(tc.label, func(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})+ body := "<quoted_message>before [" + tc.label + " 1: unavailable] after [" + tc.label + " 1: unavailable]</quoted_message>\ninspect"+ appended, err := session.AppendUserMessage(t.Context(), AppendInput{SessionID: fixture.sessionID, Sender: fixture.userID, Body: body, MediaPendingSeconds: 60})+ if err != nil {+ t.Fatal(err)+ }+ key, link := "workspaces/ws/lark/context", "https://cdn.example.test/context"+ seedPendingMediaObject(t, pool, fixture, appended.MessageID, key, link, "pending")+ if err := session.BindMediaRefs(t.Context(), BindMediaInput{MessageID: appended.MessageID, SessionID: fixture.sessionID, WorkspaceID: fixture.workspaceID,+ Sender: fixture.userID, Body: body, MediaRefs: []channel.MediaRef{{Type: tc.kind, StorageKey: key, StorageURL: link,+ Filename: "context." + tc.ext, MimeType: tc.mime, InlinePlaceholder: "[" + tc.label + " 1: unavailable]", InlineCount: 2, InlineIDOnly: true}}}); err != nil {+ t.Fatal(err)+ }+ var stored, id string+ if err := pool.QueryRow(t.Context(), "SELECT content FROM chat_message WHERE id=$1", appended.MessageID).Scan(&stored); err != nil {+ t.Fatal(err)+ }+ if err := pool.QueryRow(t.Context(), "SELECT id::text FROM attachment WHERE chat_message_id=$1 AND chat_session_id=$2", appended.MessageID, fixture.sessionID).Scan(&id); err != nil {+ t.Fatal(err)+ }+ var count int+ if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM attachment WHERE chat_message_id=$1", appended.MessageID).Scan(&count); err != nil {+ t.Fatal(err)+ }+ if count != 1 {+ t.Fatalf("context resource created %d attachments, want one", count)+ }+ if strings.Count(stored, "["+tc.label+" 1: "+id+"]") != 2 || strings.Contains(stored, "unavailable") || strings.Contains(stored, "/download") {+ t.Fatalf("media positions or attribution lost: %s", stored)+ }+ })+ }+}+func TestBindMediaRefs_LinkFailureKeepsMessageAndRollsBackAttachment(t *testing.T) {pool := sessionPersistenceTestDB(t)fixture := seedSessionPersistenceFixture(t, pool)@@ -1524,3 +1571,80 @@ func newDeliveryTaskID(t *testing.T, pool *pgxpool.Pool) pgtype.UUID {})return taskID}++func TestBindMediaRefs_IssueAppendsSelectedMediaWithoutTranscript(t *testing.T) {+ for _, tc := range []struct{ edited, named bool }{{false, false}, {false, true}, {true, true}} {+ t.Run(fmt.Sprintf("edited-%v/named-%v", tc.edited, tc.named), func(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})+ prefix := "<quoted_message message_id=\"forward-owner\" sender=\"Bob\" type=\"merge_forward\">\n<forwarded_messages count=\"1\">\n[Alice]: before [Image 1: unavailable] after [Image 1: unavailable]\n[Bob]: before [File 2: unavailable] after [Audio 3: unavailable]\n</forwarded_messages>\n</quoted_message>"+ command := "/issue Investigate\nReporter details"+ body := "<recent_context>unselected history</recent_context>\n\n" + prefix + "\n\n" + command+ base := issueDescriptionFromCommandBody(body, command, "")+ if tc.named {+ body = prefix + "\n\n[Reporter]: " + command+ }+ appended, err := session.AppendUserMessage(t.Context(), AppendInput{SessionID: fixture.sessionID, Sender: fixture.userID, Body: body, CommandText: command, MediaPendingSeconds: 60})+ if err != nil {+ t.Fatal(err)+ }+ initial := base+ if tc.edited {+ initial = "Human edit retained"+ }+ var issueID pgtype.UUID+ if err := pool.QueryRow(t.Context(), `INSERT INTO issue (workspace_id,title,description,status,priority,creator_type,creator_id,number)+ VALUES ($1,'Investigate',$2,'todo','none','member',$3,1) RETURNING id`, fixture.workspaceID, initial, fixture.userID).Scan(&issueID); err != nil {+ t.Fatal(err)+ }+ refs := []channel.MediaRef{+ {Type: channel.MsgTypeImage, Filename: "historical.png", MimeType: "image/png", InlinePlaceholder: "[Image 1: unavailable]", InlineCount: 2, InlineIDOnly: true},+ {Type: channel.MsgTypeFile, Filename: "historical.txt", MimeType: "text/plain", InlinePlaceholder: "[File 2: unavailable]", InlineCount: 1, InlineIDOnly: true},+ }+ for n := range refs {+ refs[n].StorageKey = fmt.Sprintf("workspaces/ws/lark/attribution-%d", n)+ refs[n].StorageURL = fmt.Sprintf("https://cdn.example.test/attribution-%d", n)+ seedPendingMediaObject(t, pool, fixture, appended.MessageID, refs[n].StorageKey, refs[n].StorageURL, "pending")+ }+ if err := session.BindMediaRefs(t.Context(), BindMediaInput{MessageID: appended.MessageID, SessionID: fixture.sessionID, WorkspaceID: fixture.workspaceID,+ Sender: fixture.userID, IssueID: issueID, IssueDescriptionBase: pgtype.Text{String: base, Valid: true}, IssueCommandText: command, Body: body, MediaRefs: refs}); err != nil {+ t.Fatal(err)+ }+ ids := map[string]string{}+ rows, err := pool.Query(t.Context(), "SELECT filename,id::text FROM attachment WHERE issue_id=$1", issueID)+ if err != nil {+ t.Fatal(err)+ }+ for rows.Next() {+ var name, id string+ if err := rows.Scan(&name, &id); err != nil {+ t.Fatal(err)+ }+ ids[name] = id+ }+ rows.Close()+ if err := rows.Err(); err != nil {+ t.Fatal(err)+ }+ var description string+ if err := pool.QueryRow(t.Context(), "SELECT description FROM issue WHERE id=$1", issueID).Scan(&description); err != nil {+ t.Fatal(err)+ }+ if len(ids) != 2 || !strings.Contains(description, strings.Split(initial, "\n")[0]) {+ t.Fatalf("issue lost an attachment or reporter edit: ids=%v description=%q", ids, description)+ }+ for _, name := range []string{"historical.png", "historical.txt"} {+ block := channelmedia.Block(ids[name], name, name != "historical.txt")+ if strings.Count(description, block) != 1 {+ t.Fatalf("attachment %q must appear once as an issue block: %s", name, description)+ }+ }+ for _, excluded := range []string{"unselected history", "[Alice]: before", "[Bob]: before", "<quoted_message", "<forwarded_messages", "unavailable]", "channel-media-source:", "Referenced channel context:"} {+ if strings.Contains(description, excluded) {+ t.Fatalf("quoted transcript or source protocol %q entered issue description: %s", excluded, description)+ }+ }+ })+ }+}diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.goindex f4b9e1d052..a0060270bd 100644--- a/server/internal/integrations/channel/message.go+++ b/server/internal/integrations/channel/message.go@@ -104,6 +104,9 @@ type MediaRef struct {// partial media failure cannot shift later attachments into the wrong place.InlinePlaceholder stringInlineIndex int+ // InlineCount optionally replaces consecutive occurrences with one attachment,+ // for example an image repeated within explicitly quoted context.+ InlineCount 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.diff --git a/server/internal/integrations/lark/content_flatten.go b/server/internal/integrations/lark/content_flatten.goindex 37cc1fdd4f..f5abbd5c65 100644--- a/server/internal/integrations/lark/content_flatten.go+++ b/server/internal/integrations/lark/content_flatten.go@@ -152,6 +152,10 @@ type larkPostSpan struct {// Media spans degrade to the same bracketed placeholders flattenContent// uses.func flattenPostContent(raw string) string {+ return flattenPostContentWithMedia(raw, nil)+}++func flattenPostContentWithMedia(raw string, mediaMarker func(larkMediaResource) string) string {if raw == "" {return ""}@@ -171,14 +175,20 @@ func flattenPostContent(raw string) string {write(doc.Title)}for _, para := range doc.Content {- write(flattenPostParagraph(para))+ write(flattenPostParagraphWithMedia(para, mediaMarker))}return strings.TrimRight(b.String(), "\n")}-func flattenPostParagraph(spans []larkPostSpan) string {+func flattenPostParagraphWithMedia(spans []larkPostSpan, mediaMarker func(larkMediaResource) string) string {parts := make([]string, 0, len(spans))for _, s := range spans {+ if mediaMarker != nil {+ if res, ok := postSpanMediaResource(s, ""); ok {+ parts = append(parts, mediaMarker(res))+ continue+ }+ }switch s.Tag {case "text", "code_block":if s.Text != "" {@@ -205,7 +215,11 @@ func flattenPostParagraph(spans []larkPostSpan) string {parts = append(parts, "@"+s.UserName)}case "img":- parts = append(parts, "[Image]")+ if mediaMarker != nil {+ parts = append(parts, "[Image: unavailable]")+ } else {+ parts = append(parts, "[Image]")+ }case "file":if s.IsFolder || s.FileKey == "" {continue@@ -216,7 +230,11 @@ func flattenPostParagraph(spans []larkPostSpan) string {parts = append(parts, "[File]")}case "media":- parts = append(parts, "[Video]")+ if mediaMarker != nil {+ parts = append(parts, "[Video: unavailable]")+ } else {+ parts = append(parts, "[Video]")+ }case "emotion":// emoji_type is an enum key (e.g. "SMILE"), not display// text — skip it rather than leak the key.diff --git a/server/internal/integrations/lark/context_media.go b/server/internal/integrations/lark/context_media.gonew file mode 100644index 0000000000..8777e74ee2--- /dev/null+++ b/server/internal/integrations/lark/context_media.go@@ -0,0 +1,105 @@+package lark++import (+ "fmt"+ "strings"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+)++type contextMedia struct {+ items []ContextMedia+ occupied string+ next int+}++func (c *contextMedia) marker(res larkMediaResource) string {+ label := contextMediaLabel(res.kind)+ if res.messageID == "" || res.key == "" {+ return fmt.Sprintf("[%s: unavailable]", label)+ }+ for i := range c.items {+ item := &c.items[i]+ if item.MessageID == res.messageID && item.FetchType == res.fetchType && item.ResourceKey == res.key {+ item.Occurrences+++ return item.Placeholder+ }+ }+ var marker string+ for {+ c.next+++ marker = fmt.Sprintf("[%s %d: unavailable]", label, c.next)+ if !strings.Contains(c.occupied, marker) {+ break+ }+ }+ c.items = append(c.items, ContextMedia{MessageID: res.messageID, ResourceKey: res.key,+ Type: res.kind, FetchType: res.fetchType, Filename: res.filename, MimeType: res.mimeType,+ Placeholder: marker, Occurrences: 1})+ return marker+}++func (c *contextMedia) collides(body string) bool {+ for _, item := range c.items {+ if strings.Count(body, item.Placeholder) != item.Occurrences {+ return true+ }+ }+ return false+}++func contextMediaLabel(kind channel.MsgType) string {+ switch kind {+ case channel.MsgTypeImage:+ return "Image"+ case channel.MsgTypeAudio:+ return "Audio"+ case channel.MsgTypeVideo:+ return "Video"+ default:+ return "File"+ }+}++// Collect at rendering time, after topic filtering, deletion checks and forward+// truncation, so only context actually selected for this turn is downloaded.+func (e *inboundEnricher) flattenContextMessage(m LarkMessage, media *contextMedia, resourceMessageID string) string {+ if m.Deleted {+ return "[deleted message]"+ }+ messageID := m.MessageID+ // Forwarded child IDs are not valid resource download owners. Feishu+ // addresses their resource keys through the top-level forward container.+ if resourceMessageID != "" {+ messageID = resourceMessageID+ }+ marker := func(res larkMediaResource) string {+ res.messageID = messageID+ text := media.marker(res)+ // Retain names in the source transcript even when a download fails.+ if res.filename != "" {+ text += " (" + res.filename + ")"+ }+ return text+ }+ var body string+ if m.MessageType == "post" {+ body = flattenPostContentWithMedia(m.Content, marker)+ } else if resources := currentMediaResources(InboundMessage{MessageID: messageID, MessageType: m.MessageType, Content: m.Content}); len(resources) > 0 {+ body = marker(resources[0])+ } else {+ switch m.MessageType {+ case "image":+ body = "[Image: unavailable]"+ case "file":+ body = "[File: unavailable]"+ case "audio":+ body = "[Audio: unavailable]"+ case "media", "video":+ body = "[Video: unavailable]"+ default:+ return e.flattenMessage(m)+ }+ }+ return resolveMentions(body, restMentionsToEvent(m.Mentions), "", "")+}diff --git a/server/internal/integrations/lark/context_media_db_test.go b/server/internal/integrations/lark/context_media_db_test.gonew file mode 100644index 0000000000..ffbeeb6b04--- /dev/null+++ b/server/internal/integrations/lark/context_media_db_test.go@@ -0,0 +1,141 @@+package lark++import (+ "errors"+ "os"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/channelmedia"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestContextMediaCollisionPreservesBindingDB(t *testing.T) {+ if os.Getenv("DATABASE_URL") == "" {+ t.Skip("explicit disposable DATABASE_URL required")+ }+ pool := channelScopeTestDB(t)+ for _, source := range []string{"quoted-post", "quoted-forward", "partial-failure"} {+ for _, issue := range []bool{false, true} {+ name := source + "/chat"+ if issue {+ name = source + "/issue"+ }+ t.Run(name, func(t *testing.T) {+ fx := testutil.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Reporter", "marker-"+suffix+"@example.invalid")+ fx.WorkspaceID = fx.Workspace(t, "Marker collision", "marker-"+suffix)+ fx.Member(t, fx.WorkspaceID, fx.UserID, "owner")+ agentID := fx.Agent(t, "Marker agent", "")+ var issueID pgtype.UUID+ if issue {+ issueID = util.MustParseUUID(fx.Issue(t, "Compare", testutil.Cols{"description": "Reporter details"}))+ }+ sessionID := util.MustParseUUID(fx.ChatSession(t, agentID))+ installationID := util.MustParseUUID(fx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": fx.WorkspaceID, "agent_id": agentID, "channel_type": "lark", "config": "{}", "installer_user_id": fx.UserID,+ }))+ q := db.New(pool)+ if _, err := q.CreateChannelChatSessionBinding(t.Context(), db.CreateChannelChatSessionBindingParams{+ ChatSessionID: sessionID, InstallationID: installationID, ChannelType: "lark", ChannelChatID: suffix, ChatType: "group", Config: []byte("{}"),+ }); err != nil {+ t.Fatal(err)+ }+ fx.Cleanup(t, "DELETE FROM channel_chat_session_binding WHERE chat_session_id=$1", sessionID)+ fx.Cleanup(t, "DELETE FROM channel_chat_context_generation WHERE chat_session_id=$1", sessionID)+ fx.Cleanup(t, "DELETE FROM chat_message WHERE chat_session_id=$1", sessionID)+ fx.Cleanup(t, "DELETE FROM attachment WHERE workspace_id=$1", fx.WorkspaceID)+ fx.Cleanup(t, "DELETE FROM channel_media_pending_object WHERE workspace_id=$1", fx.WorkspaceID)++ literal := "Literal [Image 1: unavailable] and [Image 2: unavailable]"+ fake := newEnricherFake()+ fake.userNames = map[string]string{"alice": "Alice", "bob": "Bob", "reporter": "Reporter"}+ fake.byChat[ChatID(suffix)] = []LarkMessage{textMsg("literal", "alice", literal, "1000")}+ command := "Inspect"+ if issue {+ command = "/issue Compare\nReporter details"+ }+ in := InboundMessage{MessageID: "trigger", MessageType: "text", Body: command, CommandBody: command,+ SenderOpenID: "reporter", ChatID: ChatID(suffix), ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ media := LarkMessage{MessageID: "media", SenderID: "bob", SenderType: "user", CreateTime: "1500", MessageType: "post",+ Content: `{"content":[[{"tag":"text","text":"[Image 1: unavailable]"},{"tag":"img","image_key":"good"},{"tag":"text","text":"[Image 1: unavailable]"},{"tag":"img","image_key":"good"}]]}`}+ in.ParentID = media.MessageID+ if source == "partial-failure" {+ media.Content = strings.Replace(media.Content, `"image_key":"good"`, `"image_key":"bad"`, 1)+ }+ fake.byID[in.ParentID] = []LarkMessage{media}+ if source == "quoted-forward" {+ in.ParentID = "forward-owner"+ fake.byID[in.ParentID] = []LarkMessage{{MessageID: in.ParentID, MessageType: "merge_forward", SenderID: "bob", SenderType: "user"}, media}+ }+ enricher := NewInboundEnricher(fake, InboundEnricherConfig{RecentContextSize: 5})+ out := enricher.Enrich(t.Context(), in, InstallationCredentials{})+ session := engine.NewChatSession(q, pool, channel.TypeFeishu, engine.SessionTitles{})+ sender, workspaceID := util.MustParseUUID(fx.UserID), util.MustParseUUID(fx.WorkspaceID)+ appended, err := session.AppendUserMessage(t.Context(), engine.AppendInput{+ SessionID: sessionID, Sender: sender, Body: out.Body, CommandText: command, MediaPendingSeconds: 60,+ })+ if err != nil {+ t.Fatal(err)+ }+ api := &fakeSender{downloaded: DownloadedResource{Data: []byte("source image"), Filename: "source.png", ContentType: "image/png"},+ downloadErrByKey: map[string]error{"bad": errors.New("denied")}}+ inst := engine.ResolvedInstallation{ID: installationID, WorkspaceID: workspaceID,+ Platform: Installation{AppID: "cli_test", Region: "feishu"}}+ resolver := NewFeishuMediaResolver(api, fakeCreds{secret: "plain"}, &fakeMediaStorage{}, engine.NewDBMediaIntentLedger(q), newDiscardLogger())+ resolved := resolver.ResolveMedia(t.Context(), inst, engine.ResolvedIdentity{}, sessionID, appended.MessageID, channelMessageFromLark(out))+ if len(resolved.MediaRefs) != 1 {+ t.Fatalf("expected one deduplicated successful attachment: %+v", resolved.MediaRefs)+ }+ if err := session.BindMediaRefs(t.Context(), engine.BindMediaInput{+ MessageID: appended.MessageID, SessionID: sessionID, WorkspaceID: workspaceID, Sender: sender,+ Body: resolved.Text, MediaRefs: resolved.MediaRefs, IssueID: issueID,+ IssueDescriptionBase: pgtype.Text{String: "Reporter details", Valid: issue}, IssueCommandText: command,+ }); err != nil {+ t.Fatal(err)+ }+ var id, content string+ if err := pool.QueryRow(t.Context(), "SELECT id::text FROM attachment WHERE workspace_id=$1", workspaceID).Scan(&id); err != nil {+ t.Fatal(err)+ }+ if issue {+ err = pool.QueryRow(t.Context(), "SELECT description FROM issue WHERE id=$1", issueID).Scan(&content)+ } else {+ err = pool.QueryRow(t.Context(), "SELECT content FROM chat_message WHERE id=$1", appended.MessageID).Scan(&content)+ }+ if err != nil {+ t.Fatal(err)+ }+ ref := resolved.MediaRefs[0]+ if issue {+ want := channelmedia.Append("Reporter details", channelmedia.Block(id, ref.Filename, true))+ if content != want {+ t.Fatalf("issue must append one attachment block without quoted text: got %q, want %q", content, want)+ }+ return+ }+ bound := strings.TrimSuffix(ref.InlinePlaceholder, "unavailable]") + id + "]"+ if !strings.Contains(content, "[Alice]: "+literal) || strings.Count(content, bound) != ref.InlineCount || strings.Contains(content, ref.InlinePlaceholder) {+ t.Fatalf("attachment replaced original text or lost its source position: %s", content)+ }+ if !strings.Contains(content, `sender="Bob"`) || !strings.Contains(content, "[Image 1: unavailable] "+bound) {+ t.Fatalf("rich-text literal or source attribution changed: %s", content)+ }+ resolvedNative, err := larkMsgFromRaw(resolved)+ if err != nil {+ t.Fatal(err)+ }+ if source == "partial-failure" && !strings.Contains(content, resolvedNative.ContextMedia[0].Placeholder) {+ t.Fatalf("failed media lost its explicit unavailable position: %s", content)+ }+ })+ }+ }+}diff --git a/server/internal/integrations/lark/context_media_scope_test.go b/server/internal/integrations/lark/context_media_scope_test.gonew file mode 100644index 0000000000..fa6cfb4ed7--- /dev/null+++ b/server/internal/integrations/lark/context_media_scope_test.go@@ -0,0 +1,81 @@+package lark++import (+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++func TestRecentMediaStaysPlaceholderAcrossRepeatedTurns(t *testing.T) {+ for _, quote := range []bool{false, true} {+ t.Run(map[bool]string{false: "text-only", true: "explicit-quote"}[quote], func(t *testing.T) {+ fake := newEnricherFake()+ fake.byChat["group"] = []LarkMessage{budgetImage("recent"), textMsg("text", "source", "recent text", "1100")}+ fake.byID["parent"] = []LarkMessage{budgetImage("parent")}+ api, storage, ledger := &fakeSender{}, &fakeMediaStorage{}, &fakeMediaLedger{}+ resolver := NewFeishuMediaResolver(api, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())+ for _, id := range []string{"turn-one", "turn-two"} {+ in := InboundMessage{MessageID: id, MessageType: "text", Body: "inspect", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ if quote {+ in.ParentID = "parent"+ }+ out := enrich(t, fake, in, InboundEnricherConfig{RecentContextSize: 10})+ want := 0+ if quote {+ want = 1+ }+ if len(out.ContextMedia) != want || resolver.HasMedia(channelMessageFromLark(out)) != quote {+ t.Fatalf("automatic history acquired downloadable media or pending fence: %+v", out)+ }+ if !strings.Contains(out.Body, "recent text") || !strings.Contains(out.Body, "[Image]") {+ t.Fatalf("recent text/placeholders lost: %s", out.Body)+ }++ if quote && out.ContextMedia[0].MessageID != "parent" {+ t.Fatal("wrong explicit resource")+ }+ if !quote {+ resolved := resolver.ResolveMedia(t.Context(), testMediaInstallation(t), engine.ResolvedIdentity{}, uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(out))+ if len(resolved.MediaRefs) != 0 {+ t.Fatal("recent media was ingested")+ }+ }+ }+ if len(api.downloadCalls)+len(storage.uploads)+len(ledger.records) != 0 {+ t.Fatal("automatic recent media caused storage work")+ }+ })+ }+}++func TestInlineClearKeepsBareResetSeparateFromExplicitMedia(t *testing.T) {+ for _, tc := range []struct {+ name, command, parent, content string+ wantMedia bool+ }{+ {name: "bare", command: "/clear"},+ {name: "whitespace", command: "/clear\n \t"},+ {name: "prompt", command: "/clear inspect"},+ {name: "quote", command: "/clear", parent: "parent", wantMedia: true},+ {name: "own-media", command: "/clear", content: `{"image_key":"own"}`, wantMedia: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ fake := newEnricherFake()+ fake.byChat["group"] = []LarkMessage{budgetImage("recent")}+ fake.byID["parent"] = []LarkMessage{budgetImage("parent")}+ in := InboundMessage{MessageID: "trigger", Body: tc.command, CommandBody: tc.command, ParentID: tc.parent, MessageType: "text", Content: tc.content, ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true}+ if tc.content != "" {+ in.MessageType = "image"+ }+ out := enrich(t, fake, in, InboundEnricherConfig{RecentContextSize: 10})+ resolver := NewFeishuMediaResolver(nil, nil, nil, nil, newDiscardLogger())+ if !out.ForceFreshSession || resolver.HasMedia(channelMessageFromLark(out)) != tc.wantMedia {+ t.Fatalf("reset intent/media changed: %+v", out)+ }+ if (tc.name == "bare" || tc.name == "whitespace") && (out.Body != "" || len(fake.listCalls) != 0) {+ t.Fatalf("bare reset acquired history: %+v", out)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/context_media_test.go b/server/internal/integrations/lark/context_media_test.gonew file mode 100644index 0000000000..d7f9a5dd96--- /dev/null+++ b/server/internal/integrations/lark/context_media_test.go@@ -0,0 +1,366 @@+package lark++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+)++func TestContextMediaCollectQuotedAndForwardedImages(t *testing.T) {+ for _, kind := range []string{"quote", "forward", "quoted-forward"} {+ t.Run(kind, func(t *testing.T) {+ fake := newEnricherFake()+ image := LarkMessage{MessageID: "om_picture", MessageType: "post", SenderID: "ou_other", SenderType: "user", CreateTime: "1000",+ Content: `{"content":[[{"tag":"text","text":"before"},{"tag":"img","image_key":"img_context"},{"tag":"text","text":"after"},{"tag":"img","image_key":"img_context"}]]}`}+ in := InboundMessage{MessageID: "om_trigger", MessageType: "text", Body: "inspect", CommandBody: "inspect", ChatID: "oc_group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ cfg := InboundEnricherConfig{}+ owner := image.MessageID+ switch kind {+ case "quote":+ in.ParentID = image.MessageID+ fake.byID[in.ParentID] = []LarkMessage{image}+ case "forward", "quoted-forward":+ owner = "om_forward"+ fake.byID[owner] = []LarkMessage{{MessageID: owner, MessageType: "merge_forward"}, image}+ if kind == "forward" {+ in.MessageID = owner+ in.MessageType = "merge_forward"+ } else {+ in.ParentID = owner+ }+ }+ out := enrich(t, fake, in, cfg)+ if len(out.ContextMedia) != 1 || out.ContextMedia[0].Occurrences != 2 || out.ContextMedia[0].MessageID != owner {+ t.Fatalf("context media = %+v, want one repeated image owned by %s", out.ContextMedia, owner)+ }+ marker := out.ContextMedia[0].Placeholder+ if !strings.Contains(out.Body, "before "+marker+" after "+marker) || out.CommandBody != "inspect" {+ t.Fatalf("image positions or command changed: %+v", out)+ }+ api := &fakeSender{downloaded: DownloadedResource{Data: []byte("image bytes"), ContentType: "image/png", Filename: "context.png"}}+ storage := &fakeMediaStorage{}+ resolver := NewFeishuMediaResolver(api, fakeCreds{secret: "plain"}, storage, &fakeMediaLedger{}, newDiscardLogger())+ msg := channelMessageFromLark(out)+ if !resolver.HasMedia(msg) {+ t.Fatal("context-only image did not suspend dispatch for ingestion")+ }+ resolved := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), msg)+ if len(api.downloadCalls) != 1 || api.downloadCalls[0].MessageID != owner || api.downloadCalls[0].FileKey != "img_context" ||+ len(storage.uploads) != 1 || len(resolved.MediaRefs) != 1 {+ t.Fatalf("context image not downloaded exactly once: calls=%+v refs=%+v", api.downloadCalls, resolved.MediaRefs)+ }+ ref := resolved.MediaRefs[0]+ if ref.InlinePlaceholder != marker || ref.InlineCount != 2 || !ref.InlineIDOnly {+ t.Fatalf("missing source markers: %+v", ref)+ }+ })+ }+}++func TestContextMediaSkipsTruncatedForwardChildren(t *testing.T) {+ fake := newEnricherFake()+ image := func(id, at string) LarkMessage {+ return LarkMessage{MessageID: id, MessageType: "image", Content: `{"image_key":"img_` + id + `"}`, CreateTime: at}+ }+ fake.byID["om_forward"] = []LarkMessage{{MessageID: "om_forward", MessageType: "merge_forward"}, image("child", "100"), image("truncated", "200")}+ in := InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", ParentID: "om_forward"}+ out := enrich(t, fake, in, InboundEnricherConfig{MaxForwardChildren: 1})+ if len(out.ContextMedia) != 1 || out.ContextMedia[0].MessageID != "om_forward" || out.ContextMedia[0].ResourceKey != "img_child" {+ t.Fatalf("unexpected images downloaded beyond selected context: %+v", out.ContextMedia)+ }+ if !strings.Contains(out.Body, "1 more truncated") {+ t.Fatalf("forward cap changed: %s", out.Body)+ }+}++func TestContextMediaFailedQuoteFetchDoesNotCollectResources(t *testing.T) {+ fake := newEnricherFake()+ fake.errByID["parent"] = errors.New("denied")+ out := enrich(t, fake, InboundMessage{MessageType: "text", Body: "inspect", ParentID: "parent"}, InboundEnricherConfig{})+ if len(out.ContextMedia) != 0 || !strings.Contains(out.Body, "unable to fetch") {+ t.Fatalf("failed fetch: %+v", out)+ }+}++func TestContextMediaOneFailedDownloadKeepsOtherImageAndSourcePositions(t *testing.T) {+ fake := newEnricherFake()+ fake.byID["parent"] = []LarkMessage{{MessageID: "parent", MessageType: "post", Content: `{"content":[[{"tag":"img","image_key":"bad"},{"tag":"text","text":"between"},{"tag":"img","image_key":"good"}]]}`}}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", ParentID: "parent"}, InboundEnricherConfig{})+ api := &fakeSender{downloadErrByKey: map[string]error{"bad": errors.New("denied")}, downloaded: DownloadedResource{Data: []byte("good image"), ContentType: "image/png"}}+ resolver := NewFeishuMediaResolver(api, fakeCreds{secret: "plain"}, &fakeMediaStorage{}, &fakeMediaLedger{}, newDiscardLogger())+ got := resolver.ResolveMedia(t.Context(), testMediaInstallation(t), engine.ResolvedIdentity{}, uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(out))+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].InlinePlaceholder != out.ContextMedia[1].Placeholder || got.Text != out.Body || !strings.Contains(got.Text, "unavailable") {+ t.Fatalf("failed image shifted the successful picture: %+v", got)+ }+}++func TestContextMediaCollectFilesAudioAndVideo(t *testing.T) {+ for _, source := range []string{"quote", "forward", "quoted-forward"} {+ for _, messageType := range []string{"file", "audio", "media", "video"} {+ t.Run(source+"/"+messageType, func(t *testing.T) {+ fake := newEnricherFake()+ content := `{"file_key":"file_context","file_name":"source.bin","mime_type":"application/octet-stream","size_bytes":7}`+ parent := LarkMessage{MessageID: "om_resource", MessageType: messageType, Content: content, CreateTime: "1000"}+ in := InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", CommandBody: "inspect", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ cfg := InboundEnricherConfig{}+ owner := parent.MessageID+ switch source {+ case "quote":+ in.ParentID = owner+ fake.byID[owner] = []LarkMessage{parent}+ default:+ owner = "outer_forward"+ fake.byID[owner] = []LarkMessage{{MessageID: owner, MessageType: "merge_forward"}, parent}+ if source == "forward" {+ in.MessageID, in.MessageType = owner, "merge_forward"+ } else {+ in.ParentID = owner+ }+ }+ out := enrich(t, fake, in, cfg)+ if len(out.ContextMedia) != 1 {+ t.Fatalf("selected context media = %+v", out.ContextMedia)+ }+ item := out.ContextMedia[0]+ kind := channel.MsgTypeFile+ if messageType == "audio" {+ kind = channel.MsgTypeAudio+ } else if messageType != "file" {+ kind = channel.MsgTypeVideo+ }+ if item.MessageID != owner || item.Type != kind || item.FetchType != "file" || item.Filename != "source.bin" || item.MimeType != "application/octet-stream" || out.CommandBody != "inspect" {+ t.Fatalf("media metadata or command lost: %+v", out)+ }+ if !strings.Contains(out.Body, item.Placeholder+" (source.bin)") {+ t.Fatalf("source position/name lost: %s", out.Body)+ }+ data := []byte{0, 1, 2, 3, 4, 5, 255}+ api := &fakeSender{downloaded: DownloadedResource{Data: data}}+ storage := &fakeMediaStorage{}+ ledger := &fakeMediaLedger{}+ got := resolveContextMedia(t, out, api, storage, ledger)+ if len(api.downloadCalls) != 1 || api.downloadCalls[0] != (DownloadResourceParams{MessageID: owner, FileKey: "file_context", Type: "file"}) || len(storage.uploads) != 1 || len(ledger.records) != 1 || len(got.MediaRefs) != 1 {+ t.Fatalf("resource not ingested once: calls=%+v uploads=%+v refs=%+v", api.downloadCalls, storage.uploads, got.MediaRefs)+ }+ ref := got.MediaRefs[0]+ wantMIME := "application/octet-stream"+ if messageType == "audio" {+ wantMIME = "audio/opus" // Existing Feishu audio fallback for a generic response.+ }+ if !bytes.Equal(storage.uploads[0].data, data) || ref.Type != kind || ref.Filename != "source.bin" || ref.MimeType != wantMIME || ref.SizeBytes != 7 || ref.InlinePlaceholder != item.Placeholder || !ref.InlineIDOnly || ref.InlineCount != 1 {+ t.Fatalf("attachment bytes, metadata or source marker changed: %+v", ref)+ }+ })+ }+ }+}++func resolveContextMedia(t *testing.T, out InboundMessage, api *fakeSender, storage *fakeMediaStorage, ledger *fakeMediaLedger) channel.InboundMessage {+ t.Helper()+ resolver := NewFeishuMediaResolver(api, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())+ msg := channelMessageFromLark(out)+ if !resolver.HasMedia(msg) {+ t.Fatal("context-only media did not suspend dispatch")+ }+ return resolver.ResolveMedia(t.Context(), testMediaInstallation(t), engine.ResolvedIdentity{}, uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), msg)+}++func TestContextMediaMixedPostDeduplicatesRepeatedSpans(t *testing.T) {+ for _, paragraphs := range []string{"content", "content_v2"} {+ t.Run(paragraphs, func(t *testing.T) {+ fake := newEnricherFake()+ parent := LarkMessage{MessageID: "parent", MessageType: "post", CreateTime: "1000", Content: `{"` + paragraphs + `":[[{"tag":"text","text":"before"},{"tag":"file","file_key":"document","file_name":"notes.txt","mime_type":"text/plain"},{"tag":"text","text":"between"},{"tag":"media","file_key":"video","file_name":"clip.mp4"},{"tag":"img","image_key":"image"},{"tag":"file","file_key":"document"},{"tag":"file","file_key":"folder","is_folder":true}]],"files":[{"file_key":"document","file_name":"notes.txt"},{"file_key":"extra","file_name":"extra.pdf"},{"file_key":"ignored_folder","is_folder":true}]}`}+ fake.byChat["group"] = []LarkMessage{parent}+ fake.byID["parent"] = []LarkMessage{parent}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", ParentID: "parent", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}, InboundEnricherConfig{RecentContextSize: 5})+ if len(out.ContextMedia) != 4 {+ t.Fatalf("mixed post resources: %+v", out.ContextMedia)+ }+ if out.ContextMedia[0].Occurrences != 2 || out.ContextMedia[1].Occurrences != 1 || out.ContextMedia[2].Occurrences != 1 || out.ContextMedia[3].Occurrences != 1 {+ t.Fatalf("repeated source occurrences lost: %+v", out.ContextMedia)+ }+ if strings.Count(out.Body, "before "+out.ContextMedia[0].Placeholder+" (notes.txt) between "+out.ContextMedia[1].Placeholder+" (clip.mp4) "+out.ContextMedia[2].Placeholder) != 1 || strings.Contains(out.Body, "ignored_folder") {+ t.Fatalf("mixed post positions lost: %s", out.Body)+ }+ api := &fakeSender{downloadedByKey: map[string]DownloadedResource{+ "document": {Data: []byte("实际文本内容\n"), ContentType: "text/plain"},+ "video": {Data: []byte{0, 1, 255}, ContentType: "video/mp4"},+ "image": {Data: []byte{1, 2}, ContentType: "image/png"},+ "extra": {Data: []byte("%PDF-opaque"), ContentType: "application/pdf"},+ }}+ storage := &fakeMediaStorage{}+ got := resolveContextMedia(t, out, api, storage, &fakeMediaLedger{})+ if len(got.MediaRefs) != 4 || len(api.downloadCalls) != 4 || len(storage.uploads) != 4 {+ t.Fatalf("repeated resources downloaded more than once: %+v", api.downloadCalls)+ }+ for i, call := range api.downloadCalls {+ if call.MessageID != "parent" || !bytes.Equal(storage.uploads[i].data, api.downloadedByKey[call.FileKey].Data) || got.MediaRefs[i].InlineCount != out.ContextMedia[i].Occurrences {+ t.Fatalf("resource bytes, ownership or source count changed: %+v", call)+ }+ }+ })+ }+}++func TestContextMediaForwardPartialDownloadFailure(t *testing.T) {+ fake := newEnricherFake()+ makeFile := func(id, kind, at string) LarkMessage {+ return LarkMessage{MessageID: id, MessageType: kind, CreateTime: at, Content: `{"file_key":"` + id + `","file_name":"` + id + `.bin"}`}+ }+ fake.byID["forward"] = []LarkMessage{{MessageID: "forward", MessageType: "merge_forward"}, makeFile("bad", "file", "50"), makeFile("included", "video", "100"), makeFile("truncated", "file", "200")}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", ParentID: "forward"}, InboundEnricherConfig{MaxForwardChildren: 2})+ if len(out.ContextMedia) != 2 || out.ContextMedia[0].ResourceKey != "bad" || out.ContextMedia[1].ResourceKey != "included" || out.ContextMedia[1].MessageID != "forward" {+ t.Fatalf("media collected outside existing selection: %+v", out.ContextMedia)+ }+ api := &fakeSender{downloadErrByKey: map[string]error{"bad": errors.New("denied")}, downloaded: DownloadedResource{Data: []byte{0, 255}}}+ storage := &fakeMediaStorage{}+ got := resolveContextMedia(t, out, api, storage, &fakeMediaLedger{})+ if len(api.downloadCalls) != 2 || len(got.MediaRefs) != 1 || got.MediaRefs[0].InlinePlaceholder != out.ContextMedia[1].Placeholder || got.Text != out.Body || !strings.Contains(got.Text, out.ContextMedia[0].Placeholder+" (bad.bin)") {+ t.Fatalf("partial failure shifted successful media: %+v", got)+ }+}++func TestContextMediaResourceOwnership(t *testing.T) {+ fake := newEnricherFake()+ file := func(id string) LarkMessage {+ return LarkMessage{MessageID: id, MessageType: "file", CreateTime: "1000", Content: `{"file_key":"same_key"}`}+ }+ fake.byID["first"] = []LarkMessage{file("first")}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", ParentID: "first", MessageType: "file", Content: `{"file_key":"same_key"}`, Body: "inspect", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}, InboundEnricherConfig{RecentContextSize: 5})+ if len(out.ContextMedia) != 1 {+ t.Fatalf("same key from different owners collapsed: %+v", out.ContextMedia)+ }+ storage := &fakeMediaStorage{}+ got := resolveContextMedia(t, out, &fakeSender{downloaded: DownloadedResource{Data: []byte("x")}}, storage, &fakeMediaLedger{})+ if len(got.MediaRefs) != 2 || storage.uploads[0].key == storage.uploads[1].key {+ t.Fatal("different message owners shared an object")+ }+}++func TestContextMediaMissingKeysDoNotQueueDownloads(t *testing.T) {+ for _, kind := range []string{"image", "file", "audio", "media", "video", "post"} {+ t.Run(kind, func(t *testing.T) {+ fake := newEnricherFake()+ fake.byID["parent"] = []LarkMessage{{MessageID: "parent", MessageType: kind, Content: `{"content":[[{"tag":"img"},{"tag":"file"}]]}`}}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", MessageType: "text", ParentID: "parent", Body: "inspect"}, InboundEnricherConfig{})+ resolver := NewFeishuMediaResolver(nil, nil, nil, nil, newDiscardLogger())+ if len(out.ContextMedia) != 0 || resolver.HasMedia(channelMessageFromLark(out)) || !strings.Contains(out.Body, "unavailable]") {+ t.Fatalf("missing resource key was collected or hidden: %+v", out)+ }+ })+ }+}++func TestContextMediaOriginalTextCollision(t *testing.T) {+ for _, kind := range []string{"image", "file", "audio", "video"} {+ for _, source := range []string{"forward", "recent-and-quote"} {+ t.Run(kind+"/"+source, func(t *testing.T) {+ label := map[string]string{"image": "Image", "file": "File", "audio": "Audio", "video": "Video"}[kind]+ literal := fmt.Sprintf("Literal [%s 1: unavailable] and [%s 2: unavailable]", label, label)+ fake := newEnricherFake()+ text := textMsg("literal", "alice", literal, "1000")+ media := LarkMessage{MessageID: "picture", SenderID: "bob", SenderType: "user", MessageType: kind,+ Content: `{"image_key":"image","file_key":"file","file_name":"source.bin"}`, CreateTime: "1500"}+ in := InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect " + literal, CommandBody: "inspect " + literal,+ ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ cfg := InboundEnricherConfig{RecentContextSize: 5}+ if source == "forward" {+ cfg.RecentContextSize = 0+ in.MessageID, in.MessageType = "forward", "merge_forward"+ fake.byID["forward"] = []LarkMessage{{MessageID: "forward", MessageType: "merge_forward"}, text, media}+ } else {+ fake.byChat[in.ChatID] = []LarkMessage{text, media}+ in.ParentID = media.MessageID+ fake.byID[in.ParentID] = []LarkMessage{media}+ }+ out := enrich(t, fake, in, cfg)+ if len(out.ContextMedia) != 1 {+ t.Fatalf("selected media changed: %+v", out.ContextMedia)+ }+ item := out.ContextMedia[0]+ wantCount := 1+ if strings.Contains(literal, item.Placeholder) || strings.Count(out.Body, item.Placeholder) != wantCount || item.Occurrences != wantCount {+ t.Fatalf("literal text acquired a media marker: marker=%q occurrences=%d body=%s", item.Placeholder, item.Occurrences, out.Body)+ }+ if !strings.Contains(out.Body, "[User 1]: "+literal) || out.CommandBody != in.CommandBody {+ t.Fatalf("original sender/text or command changed: %s", out.Body)+ }+ wantFetches := 1+ if source == "recent-and-quote" {+ wantFetches+++ }+ if len(fake.calls)+len(fake.listCalls) != wantFetches {+ t.Fatalf("collision fetched extra context: get=%v list=%v", fake.calls, fake.listCalls)+ }+ })+ }+ }+}++func TestContextMediaRichTextCollision(t *testing.T) {+ fake := newEnricherFake()+ literal := "[Image 1: unavailable]"+ content, err := json.Marshal(map[string]any{"title": "literal " + literal, "content": [][]map[string]string{{+ {"tag": "text", "text": "[Image 1:"}, {"tag": "text", "text": "unavailable]"},+ {"tag": "img", "image_key": "repeated"}, {"tag": "text", "text": literal},+ {"tag": "img", "image_key": "repeated"}, {"tag": "text", "text": literal},+ }}})+ if err != nil {+ t.Fatal(err)+ }+ fake.userNames = map[string]string{"alice": "Alice " + literal}+ fake.byID["parent"] = []LarkMessage{{MessageID: "parent", MessageType: "post", Content: string(content), SenderID: "alice", SenderType: "user"}}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", MessageType: "text", Body: "/issue Investigate", CommandBody: "/issue Investigate",+ ParentID: "parent", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true}, InboundEnricherConfig{})+ if len(out.ContextMedia) != 1 {+ t.Fatalf("repeated rich-text image lost: %+v", out.ContextMedia)+ }+ marker := out.ContextMedia[0].Placeholder+ if marker == literal || strings.Count(out.Body, marker) != 2 ||+ !strings.Contains(out.Body, literal+" "+marker+" "+literal+" "+marker+" "+literal) {+ t.Fatalf("rich-text source positions collided: %s", out.Body)+ }+ if !strings.Contains(out.Body, `sender="Alice `+literal+`"`) || len(fake.calls) != 1 || len(fake.userCalls) != 1 {+ t.Fatalf("source attribution or fetch scope changed: %+v", out)+ }+}++func TestContextMediaMetadataCollision(t *testing.T) {+ for _, source := range []string{"sender", "filename"} {+ t.Run(source, func(t *testing.T) {+ fake := newEnricherFake()+ kind, name, filename := "image", "Alice [Image 1: unavailable]", "source.bin"+ body := "Inspect"+ if source == "filename" {+ kind, name, filename = "file", "Alice", "notes [File 1: unavailable].txt"+ body = "Inspect [File 2: unavailable]"+ }+ content, err := json.Marshal(map[string]string{"image_key": "image", "file_key": "file", "file_name": filename})+ if err != nil {+ t.Fatal(err)+ }+ fake.userNames = map[string]string{"alice": name}+ fake.byID["parent"] = []LarkMessage{{MessageID: "parent", MessageType: kind, SenderID: "alice", SenderType: "user", Content: string(content)}}+ out := enrich(t, fake, InboundMessage{MessageID: "trigger", Body: body, CommandBody: body, ParentID: "parent",+ ChatID: "group", ChatType: ChatTypeGroup}, InboundEnricherConfig{})+ if len(out.ContextMedia) != 1 {+ t.Fatalf("media lost: %+v", out)+ }+ marker := out.ContextMedia[0].Placeholder+ if strings.Contains(name+filename+body, marker) || strings.Count(out.Body, marker) != 1 || !strings.Contains(out.Body, name) {+ t.Fatalf("metadata acquired an attachment marker: %s", out.Body)+ }+ if source == "filename" && !strings.Contains(out.Body, filename) {+ t.Fatalf("filename changed: %s", out.Body)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.goindex 9f9a06c64c..aad0cca715 100644--- a/server/internal/integrations/lark/feishu_types.go+++ b/server/internal/integrations/lark/feishu_types.go@@ -1,6 +1,10 @@package lark-import "github.com/jackc/pgx/v5/pgtype"+import (+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+)// This file holds the Feishu adapter's native-ish inbound/outbound value// types. The WS connector decodes a raw Lark event into an InboundMessage;@@ -9,6 +13,19 @@ import "github.com/jackc/pgx/v5/pgtype"// translate back at the adapter boundary. (Formerly defined on dispatcher.go,// which the MUL-3620 Router cutover removed.)+// ContextMedia is collected only from a message rendered into this turn.+// Occurrences lets repeated explicit source positions share one attachment.+type ContextMedia struct {+ MessageID string+ ResourceKey string+ Type channel.MsgType+ FetchType string+ Filename string+ MimeType string+ Placeholder string+ Occurrences int+}+// InboundMessage is the Feishu connector's decoded, enriched event. It is the// adapter's internal shape: feishuChannel maps it to a channel.InboundMessage// (stashing this struct in Raw) so the resolvers can read the platform-@@ -26,7 +43,8 @@ type InboundMessage struct {// event.message.content. Text/post decoding consumes it immediately; media// ingestion keeps it so the adapter can extract image_key/file_key before// translating to channel.InboundMessage.- Content string+ Content string+ ContextMedia []ContextMedia// ForceFreshSession marks this dispatch as a one-off fresh start: the// daemon should skip prior session resume when it claims the resulting// chat task.diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.goindex 4ca743b3c1..9e008d318f 100644--- a/server/internal/integrations/lark/inbound_enricher.go+++ b/server/internal/integrations/lark/inbound_enricher.go@@ -9,6 +9,7 @@ import ("sort""strconv""strings"+ "sync""github.com/multica-ai/multica/server/internal/integrations/channel/engine")@@ -32,8 +33,8 @@ const defaultMaxForwardChildren = 100// guaranteed rendered count — the trigger message itself and any quoted// parent are filtered out of the result, so the <recent_context> block// usually renders one or two fewer lines. 10 keeps the agent's prompt-// meaningfully contextual without bloating it or straining the inbound-// ACK budget (one list call, page_size 10).+// meaningfully contextual without bloating it or straining the bounded+// context-read budget (one list call, page_size 10).const DefaultRecentContextSize = 10const (@@ -54,8 +55,7 @@ var errRecentContextChannelUnbound = errors.New("lark enricher: missing chat_id// Enricher expands an inbound message's body with context the user// EXPLICITLY attached — a quoted reply or a merged-and-forwarded bundle-// — by calling back into Lark's IM API. It runs after the (fast,-// HTTP-free) decoder and before the dispatcher, turning a bare+// — by calling back into Lark's IM API. It runs inline under the connector's enrichment deadline, turning a bare// "@bot 总结一下" into a body that already carries the referenced// conversation inline.//@@ -147,17 +147,21 @@ func NewInboundEnricher(client APIClient, cfg InboundEnricherConfig) Enricher {// never creates its own session row, and is only ever surfaced as read-// context attached to a turn a workspace member explicitly directed at// the Bot.-func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds InstallationCredentials) InboundMessage {+func (e *inboundEnricher) selectContext(msg InboundMessage) (InboundMessage, bool) {freshSource := msg.CommandBodyif freshSource == "" {freshSource = msg.Body}startChat := false+ bareFresh := falseif control, ok := engine.ParseControlCommand(freshSource); ok {msg.Body = control.Bodyswitch control.Kind {case engine.ControlCommandFreshSession:msg.ForceFreshSession = true+ // A bare reset records intent for the next turn. Automatic history+ // must not turn it into model input; explicit context/media still can.+ bareFresh = control.Body == "" && msg.ParentID == "" && msg.MessageType != larkMsgTypeMergeForward && len(currentMediaResources(msg)) == 0case engine.ControlCommandNewChat:// A new Chat must not inherit adapter-generated recent context from// the route's previous Chat. Explicit quote/forward context is still@@ -166,8 +170,13 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds}}+ wantRecent := !startChat && !bareFresh && e.recentContextSize > 0 && msg.ChatType == ChatTypeGroup && msg.AddressedToBot+ return msg, wantRecent+}++func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds InstallationCredentials) InboundMessage {+ msg, wantRecent := e.selectContext(msg)isForward := msg.MessageType == larkMsgTypeMergeForward- wantRecent := !startChat && e.recentContextSize > 0 && msg.ChatType == ChatTypeGroup && msg.AddressedToBotif msg.ParentID == "" && !isForward && !wantRecent {// Nothing to expand and no group prefetch wanted — no network call.return msg@@ -184,22 +193,39 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds// 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".+ // isn't in the recent window would fall back to "User N". Start the+ // independent reads together: a slow history call must not consume+ // the metadata budget before an explicit quote/forward even starts. Keep+ // the same shared deadline and join every read before rendering.var recentItems []LarkMessagevar recentErr error+ var fetches sync.WaitGroupif wantRecent {- recentItems, recentErr = e.fetchRecentItems(ctx, creds, msg)+ fetches.Add(1)+ go func() {+ defer fetches.Done()+ recentItems, recentErr = e.fetchRecentItems(ctx, creds, msg)+ }()}var quotedItems []LarkMessagevar quotedErr errorif msg.ParentID != "" {- quotedItems, quotedErr = e.client.GetMessage(ctx, creds, msg.ParentID)+ fetches.Add(1)+ go func() {+ defer fetches.Done()+ quotedItems, quotedErr = e.client.GetMessage(ctx, creds, msg.ParentID)+ }()}var forwardItems []LarkMessagevar forwardErr errorif isForward {- forwardItems, forwardErr = e.client.GetMessage(ctx, creds, msg.MessageID)+ fetches.Add(1)+ go func() {+ defer fetches.Done()+ forwardItems, forwardErr = e.client.GetMessage(ctx, creds, msg.MessageID)+ }()}+ fetches.Wait()// Phase 2 — resolve display names for every speaker we're about to// render (recent + quoted + forwarded) plus the sender who @-mentioned@@ -218,46 +244,60 @@ func (e *inboundEnricher) Enrich(ctx context.Context, msg InboundMessage, creds}// Phase 3 — render broadest-to-narrowest with the complete name map.- var b strings.Builder- if wantRecent {- if recentErr != nil {- b.WriteString(recentContextUnavailableLine(classifyRecentContextFetchError(recentErr).category))- } 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.renderQuotedBlock(msg.ParentID, quotedItems, quotedErr, names))+ if msg.ParentID != "" || isForward {msg.HasSelectedContext = true}+ render := func(media *contextMedia) string {+ var b strings.Builder+ if wantRecent {+ if recentErr != nil {+ b.WriteString(recentContextUnavailableLine(classifyRecentContextFetchError(recentErr).category))+ } 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.renderQuotedBlock(msg.ParentID, quotedItems, quotedErr, names, media))+ }- var core string- if isForward {- msg.HasSelectedContext = true- if forwardErr != nil {- e.logger.Warn("lark enricher: forward fetch failed", "message_id", msg.MessageID, "err", forwardErr)- core = forwardedErrorBlock()+ var core string+ if isForward {+ 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, media)+ }} else {- core = e.renderForwardedItems(forwardItems, msg.MessageID, names)+ 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)+ }}- } 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")}+ b.WriteString(core)+ return b.String()}- if b.Len() > 0 && core != "" {- b.WriteString("\n\n")+ media := &contextMedia{}+ body := render(media)+ if media.collides(body) {+ // Include the complete rendered text: original bodies, rich-text spans,+ // names, filenames and wrappers. Choose markers absent from that text,+ // then render the same selected messages without another API fetch.+ media = &contextMedia{occupied: body}+ body = render(media)}- b.WriteString(core)- msg.Body = b.String()+ msg.Body = body+ msg.ContextMedia = media.itemsreturn msg}@@ -291,7 +331,7 @@ func (e *inboundEnricher) resolveNames(ctx context.Context, creds InstallationCrseen[id] = trueuniq = append(uniq, id)}- if len(uniq) == 0 {+ if len(uniq) == 0 || ctx.Err() != nil {return nil}names, err := e.client.BatchGetUsers(ctx, creds, uniq)@@ -359,8 +399,8 @@ func (e *inboundEnricher) fetchRecentItems(ctx context.Context, creds Installati}classified := classifyRecentContextFetchError(err)// A retry only helps while the shared enrichment budget still has- // time left. Both attempts reuse one ctx (ws_connector caps the- // whole Enrich at EnrichTimeout, ~2s), so once ctx is done a second+ // time left. Both attempts reuse the same bounded metadata-read+ // context, so once it is done a second// call fails immediately — degrade now instead of burning a doomed// request. This is why a first-attempt deadline never "recovers".if !classified.retryable || attempt == recentContextMaxFetchAttempts || ctx.Err() != nil {@@ -561,7 +601,7 @@ func recentContextUnavailableLine(category string) string {// 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 {+func (e *inboundEnricher) renderQuotedBlock(parentID string, items []LarkMessage, err error, names map[string]string, media *contextMedia) string {if err != nil || len(items) == 0 {e.logger.Warn("lark enricher: quoted parent fetch failed","parent_id", parentID, "items", len(items), "err", err)@@ -576,10 +616,10 @@ func (e *inboundEnricher) renderQuotedBlock(parentID string, items []LarkMessagesender := labeler.label(parent)if parent.MessageType == larkMsgTypeMergeForward {- inner := e.renderForwardedItems(items, parentID, names)+ inner := e.renderForwardedItems(items, parentID, names, media)return wrapQuoted(parentID, sender, larkMsgTypeMergeForward, inner)}- text := e.flattenMessage(parent)+ text := e.flattenContextMessage(parent, media, "")if text == "" {text = "[empty message]"}@@ -590,8 +630,8 @@ func (e *inboundEnricher) renderQuotedBlock(parentID string, items []LarkMessage// 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, names map[string]string) string {+// fan-out within the inbound enrichment budget stays bounded.+func (e *inboundEnricher) renderForwardedItems(items []LarkMessage, forwardID string, names map[string]string, media *contextMedia) 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@@ -631,7 +671,7 @@ func (e *inboundEnricher) renderForwardedItems(items []LarkMessage, forwardID stcase c.MessageType == larkMsgTypeMergeForward:text = "[nested merge_forward, expand manually]"default:- text = e.flattenMessage(c)+ text = e.flattenContextMessage(c, media, forwardID)if text == "" {text = "[empty message]"}diff --git a/server/internal/integrations/lark/inbound_enricher_budget_test.go b/server/internal/integrations/lark/inbound_enricher_budget_test.gonew file mode 100644index 0000000000..bfab510152--- /dev/null+++ b/server/internal/integrations/lark/inbound_enricher_budget_test.go@@ -0,0 +1,152 @@+package lark++import (+ "context"+ "io"+ "log/slog"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++type budgetEnricherClient struct {+ *enricherFakeClient+ get func(context.Context, string) ([]LarkMessage, error)+ list func(context.Context, ListMessagesParams) ([]LarkMessage, error)+}++func (f *budgetEnricherClient) GetMessage(ctx context.Context, _ InstallationCredentials, id string) ([]LarkMessage, error) {+ return f.get(ctx, id)+}++func (f *budgetEnricherClient) ListChatMessages(ctx context.Context, _ InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {+ return f.list(ctx, p)+}++func budgetImage(id string) LarkMessage {+ return LarkMessage{MessageID: id, MessageType: "image", Content: `{"image_key":"img_budget"}`, SenderID: "source", SenderType: "user", CreateTime: "1000"}+}++func TestEnrichSlowRecentDoesNotStarveAttachedContext(t *testing.T) {+ for _, kind := range []string{"quote", "forward", "quote_and_forward"} {+ t.Run(kind, func(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)+ defer cancel()+ listStarted := make(chan struct{})+ var getCalls, listCalls atomic.Int32+ client := &budgetEnricherClient{enricherFakeClient: newEnricherFake()}+ client.list = func(ctx context.Context, _ ListMessagesParams) ([]LarkMessage, error) {+ listCalls.Add(1)+ close(listStarted)+ <-ctx.Done()+ return nil, ctx.Err()+ }+ client.get = func(ctx context.Context, id string) ([]LarkMessage, error) {+ getCalls.Add(1)+ select {+ case <-listStarted:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ if id == "parent" {+ return []LarkMessage{budgetImage(id)}, nil+ }+ return []LarkMessage{{MessageID: id, MessageType: larkMsgTypeMergeForward}, budgetImage("child")}, nil+ }+ msg := InboundMessage{MessageID: "trigger", MessageType: "text", Body: "inspect", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true, CreateTime: "2000"}+ want := 1+ if kind != "forward" {+ msg.ParentID = "parent"+ }+ if kind != "quote" {+ msg.MessageType = larkMsgTypeMergeForward+ }+ if kind == "quote_and_forward" {+ want = 2+ }+ e := NewInboundEnricher(client, InboundEnricherConfig{RecentContextSize: 10, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})+ out := e.Enrich(ctx, msg, InstallationCredentials{})+ if len(out.ContextMedia) != want || int(getCalls.Load()) != want || listCalls.Load() != 1 {+ t.Fatalf("media=%+v gets=%d lists=%d; want %d attached images and no recent retry", out.ContextMedia, getCalls.Load(), listCalls.Load(), want)+ }+ if !strings.Contains(out.Body, recentContextUnavailableLine(recentContextFailureTimeout)) || !out.HasSelectedContext {+ t.Fatalf("recent failure or selected context missing: %s", out.Body)+ }+ if len(client.userCalls) != 0 {+ t.Fatal("name lookup must not start with an exhausted budget")+ }+ for _, media := range out.ContextMedia {+ if media.MessageID != "parent" && media.MessageID != "trigger" {+ t.Fatalf("wrong resource owner: %+v", media)+ }+ }+ })+ }+}++func TestEnrichSlowQuoteRetainsRecentPlaceholder(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)+ defer cancel()+ quoteStarted := make(chan struct{})+ client := &budgetEnricherClient{enricherFakeClient: newEnricherFake()}+ client.get = func(ctx context.Context, _ string) ([]LarkMessage, error) {+ close(quoteStarted)+ <-ctx.Done()+ return nil, ctx.Err()+ }+ client.list = func(ctx context.Context, _ ListMessagesParams) ([]LarkMessage, error) {+ select {+ case <-quoteStarted:+ case <-ctx.Done():+ return nil, ctx.Err()+ }+ return []LarkMessage{budgetImage("recent")}, ctx.Err()+ }+ out := NewInboundEnricher(client, InboundEnricherConfig{RecentContextSize: 10}).Enrich(ctx, InboundMessage{MessageID: "trigger", ParentID: "parent", Body: "inspect", ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true}, InstallationCredentials{})+ if len(out.ContextMedia) != 0 || !strings.Contains(out.Body, "[Image]") || !strings.Contains(out.Body, "quoted_message") || !strings.Contains(out.Body, "unable to fetch") {+ t.Fatalf("recent placeholder lost, downloaded, or quote failure hidden: %+v", out)+ }+}++func TestEnrichCancellationJoinsAllFetches(t *testing.T) {+ t.Parallel()+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ started := make(chan struct{}, 3)+ var finished atomic.Int32+ block := func(ctx context.Context) ([]LarkMessage, error) {+ started <- struct{}{}+ <-ctx.Done()+ finished.Add(1)+ return nil, ctx.Err()+ }+ client := &budgetEnricherClient{enricherFakeClient: newEnricherFake()}+ client.get = func(ctx context.Context, _ string) ([]LarkMessage, error) { return block(ctx) }+ client.list = func(ctx context.Context, _ ListMessagesParams) ([]LarkMessage, error) { return block(ctx) }+ done := make(chan InboundMessage, 1)+ go func() {+ done <- NewInboundEnricher(client, InboundEnricherConfig{RecentContextSize: 10}).Enrich(ctx, InboundMessage{MessageID: "trigger", ParentID: "parent", MessageType: larkMsgTypeMergeForward, ChatID: "group", ChatType: ChatTypeGroup, AddressedToBot: true}, InstallationCredentials{})+ }()+ for i := 0; i < 3; i++ {+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("context reads did not start independently")+ }+ }+ cancel()+ select {+ case out := <-done:+ if finished.Load() != 3 || len(out.ContextMedia) != 0 || !out.HasSelectedContext {+ t.Fatalf("unjoined reads or invented media: finished=%d out=%+v", finished.Load(), out)+ }+ case <-time.After(time.Second):+ t.Fatal("enrichment did not stop on cancellation")+ }+}diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.goindex 9f2e546096..86030bcf29 100644--- a/server/internal/integrations/lark/inbound_enricher_test.go+++ b/server/internal/integrations/lark/inbound_enricher_test.go@@ -4,6 +4,7 @@ import ("context""errors""strings"+ "sync""testing""github.com/multica-ai/multica/server/internal/integrations/channel/engine"@@ -14,6 +15,7 @@ import (// ids it was asked for, so tests can assert both the rendered body and// the network fan-out (e.g. "no call when nothing to enrich").type enricherFakeClient struct {+ mu sync.Mutexconfigured boolbyID map[string][]LarkMessageerrByID map[string]error@@ -46,6 +48,8 @@ func newEnricherFake() *enricherFakeClient {func (f *enricherFakeClient) IsConfigured() bool { return f.configured }func (f *enricherFakeClient) GetMessage(ctx context.Context, creds InstallationCredentials, id string) ([]LarkMessage, error) {+ f.mu.Lock()+ defer f.mu.Unlock()f.calls = append(f.calls, id)if e, ok := f.errByID[id]; ok {return nil, e@@ -173,7 +177,7 @@ func TestEnrichMergeForward(t *testing.T) {[User 1]: 你们线上的 Multica 能用吗[User 1]: 我这边无法登录[User 2]: 我这边 web 和 desktop 都能登陆-[User 1]: [Image]+[User 1]: [Image 1: unavailable]</forwarded_messages>`if out.Body != want {t.Errorf("body\n got = %q\nwant = %q", out.Body, want)diff --git a/server/internal/integrations/lark/media_ingest.go b/server/internal/integrations/lark/media_ingest.goindex d489f63829..237f2832ad 100644--- a/server/internal/integrations/lark/media_ingest.go+++ b/server/internal/integrations/lark/media_ingest.go@@ -51,7 +51,7 @@ func NewFeishuMediaResolver(api APIClient, creds CredentialsResolver, storage me}// HasMedia reports whether the message carries downloadable Feishu resources-// (standalone image/video/file/audio or post-embedded img/media spans). Pure+// (standalone image/video/file/audio or post-embedded img/media/file spans). Pure// in-memory decode of the already-received payload — it runs on the connector// ACK path.func (r *feishuMediaResolver) HasMedia(msg channel.InboundMessage) bool {@@ -120,7 +120,9 @@ func (r *feishuMediaResolver) ResolveMedia(ctx context.Context, inst engine.Resocontinue}contentType := mediaContentType(res, got)- filename := mediaFilename(lm, res, got, contentType, resIndex)+ source := lm+ source.MessageID = res.messageID+ filename := mediaFilename(source, res, got, contentType, resIndex)uploadedBytes, err := r.uploadResource(ctx, key, got.Body, got.SizeBytes, contentType, filename)if err != nil {// The store may still be processing the PUT — deleting here@@ -134,12 +136,15 @@ func (r *feishuMediaResolver) ResolveMedia(ctx context.Context, inst engine.ResosizeBytes = uploadedBytes}msg.MediaRefs = append(msg.MediaRefs, channel.MediaRef{- Type: res.kind,- StorageKey: key,- StorageURL: link,- Filename: filename,- MimeType: contentType,- SizeBytes: sizeBytes,+ Type: res.kind,+ StorageKey: key,+ StorageURL: link,+ Filename: filename,+ MimeType: contentType,+ SizeBytes: sizeBytes,+ InlinePlaceholder: res.placeholder,+ InlineCount: res.occurrences,+ InlineIDOnly: res.placeholder != "",})}return msg@@ -222,16 +227,38 @@ func (r *feishuMediaResolver) logMediaWarn(msg string, lm InboundMessage, err er}type larkMediaResource struct {- key string- kind channel.MsgType- fetchType string- filename string- mimeType string- sizeBytes int64- messageID string+ key string+ kind channel.MsgType+ fetchType string+ filename string+ mimeType string+ sizeBytes int64+ messageID string+ placeholder string+ occurrences int}func mediaResourcesFromMessage(lm InboundMessage) []larkMediaResource {+ out := currentMediaResources(lm)+ for _, media := range lm.ContextMedia {+ if media.MessageID == "" || media.ResourceKey == "" || media.Placeholder == "" || media.Occurrences < 1 {+ continue+ }+ if (media.Type == channel.MsgTypeImage && media.FetchType != "image") ||+ ((media.Type == channel.MsgTypeFile || media.Type == channel.MsgTypeAudio || media.Type == channel.MsgTypeVideo) && media.FetchType != "file") {+ continue+ }+ switch media.Type {+ case channel.MsgTypeImage, channel.MsgTypeFile, channel.MsgTypeAudio, channel.MsgTypeVideo:+ out = append(out, larkMediaResource{key: media.ResourceKey, kind: media.Type,+ fetchType: media.FetchType, messageID: media.MessageID, filename: media.Filename,+ mimeType: media.MimeType, placeholder: media.Placeholder, occurrences: media.Occurrences})+ }+ }+ return out+}++func currentMediaResources(lm InboundMessage) []larkMediaResource {var payload struct {ImageKey string `json:"image_key"`FileKey string `json:"file_key"`@@ -320,43 +347,38 @@ func mediaResourcesFromPost(lm InboundMessage) []larkMediaResource {seen := make(map[string]bool)for _, para := range doc.Content {for _, span := range para {- switch span.Tag {- case "img":- if span.ImageKey == "" || seen["image\x00"+span.ImageKey] {- continue- }- seen["image\x00"+span.ImageKey] = true- out = append(out, larkMediaResource{- key: span.ImageKey,- kind: channel.MsgTypeImage,- fetchType: "image",- filename: firstNonEmpty(span.FileName, span.Name),- mimeType: span.MimeType,- messageID: lm.MessageID,- })- case "media", "file":- if span.IsFolder || span.FileKey == "" || seen["file\x00"+span.FileKey] {- continue- }- seen["file\x00"+span.FileKey] = true- kind := channel.MsgTypeVideo- if span.Tag == "file" {- kind = channel.MsgTypeFile- }- out = append(out, larkMediaResource{- key: span.FileKey,- kind: kind,- fetchType: "file",- filename: firstNonEmpty(span.FileName, span.Name),- mimeType: span.MimeType,- messageID: lm.MessageID,- })+ res, ok := postSpanMediaResource(span, lm.MessageID)+ if !ok || seen[res.fetchType+"\x00"+res.key] {+ continue}+ seen[res.fetchType+"\x00"+res.key] = true+ out = append(out, res)}}return out}+// Share the post resource contract between current-message ingestion and+// context rendering so a rendered marker always refers to the same resource.+func postSpanMediaResource(span larkPostSpan, messageID string) (larkMediaResource, bool) {+ res := larkMediaResource{filename: firstNonEmpty(span.FileName, span.Name), mimeType: span.MimeType, messageID: messageID}+ switch span.Tag {+ case "img":+ res.key, res.kind, res.fetchType = span.ImageKey, channel.MsgTypeImage, "image"+ case "media", "file":+ if span.IsFolder {+ return larkMediaResource{}, false+ }+ res.key, res.kind, res.fetchType = span.FileKey, channel.MsgTypeVideo, "file"+ if span.Tag == "file" {+ res.kind = channel.MsgTypeFile+ }+ default:+ return larkMediaResource{}, false+ }+ return res, res.key != ""+}+// mediaFilename picks a name for the stored object. index disambiguates the// generated form: every resource on one message shares a MessageID, so three// photos in one send used to produce three objects all named