Skip to content

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

Go

feat(channel): materialize inline media references (MUL-5835) (#6529)

YYClaw7a809ddf80ec
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index 9dca04e8e3..f8c6b00caf 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -133,6 +133,7 @@ type BindMediaParams struct {
WorkspaceID pgtype.UUID
Sender pgtype.UUID
IssueID pgtype.UUID
+ Body string
MediaRefs []channel.MediaRef
}
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index 0e2f1fdbc9..34cb268e4b 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -572,6 +572,7 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,
WorkspaceID: inst.WorkspaceID,
Sender: identity.UserID,
IssueID: issue.ID,
+ Body: resolved.Text,
MediaRefs: resolved.MediaRefs,
})
if bindErr != nil {
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index ec6e87ee56..2d7aaebf9b 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -573,8 +573,8 @@ func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {
if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {
t.Fatalf("resolved media not bound after append: %+v", h.binder.boundMedia().MediaRefs)
}
- if h.binder.boundMedia().IssueID.Valid {
- t.Fatalf("plain chat media unexpectedly targeted issue %v", h.binder.boundMedia().IssueID)
+ if got := h.binder.boundMedia(); got.IssueID.Valid || got.Body != "hello" {
+ t.Fatalf("plain chat media target/body = issue:%v body:%q", got.IssueID, got.Body)
}
}
@@ -843,8 +843,8 @@ func TestRouter_IssueCommandWithMediaBindsWithoutChatRun(t *testing.T) {
if h.tasks.calls() != 0 {
t.Fatalf("media completion must not enqueue a chat task, calls=%d", h.tasks.calls())
}
- if got := h.binder.boundMedia(); len(got.MediaRefs) != 1 {
- t.Fatalf("bound media refs = %+v", got.MediaRefs)
+ if got := h.binder.boundMedia(); len(got.MediaRefs) != 1 || got.IssueID != h.issues.result.Issue.ID || got.Body != "hello" {
+ t.Fatalf("bound issue media = %+v", got)
}
}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 1fa40832a4..3e858964b6 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -5,6 +5,8 @@ import (
"errors"
"fmt"
"log/slog"
+ "sort"
+ "strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
@@ -46,6 +48,7 @@ type SessionQueries interface {
CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)
ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error
LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)
+ UpdateChatMessageContentForChannelMedia(ctx context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error)
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error)
ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error)
@@ -84,6 +87,9 @@ func (a dbSessionQueries) ClearChatMessageChannelMediaPending(ctx context.Contex
func (a dbSessionQueries) LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error) {
return a.q.LockIssueForChannelMediaBind(ctx, arg)
}
+func (a dbSessionQueries) UpdateChatMessageContentForChannelMedia(ctx context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error) {
+ return a.q.UpdateChatMessageContentForChannelMedia(ctx, arg)
+}
func (a dbSessionQueries) CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
return a.q.CreateAttachment(ctx, arg)
}
@@ -283,6 +289,7 @@ type BindMediaInput struct {
WorkspaceID pgtype.UUID
Sender pgtype.UUID
IssueID pgtype.UUID
+ Body string
MediaRefs []channel.MediaRef
}
@@ -459,6 +466,11 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
for _, k := range claimedKeys {
claimed[k] = true
}
+ type createdMedia struct {
+ id pgtype.UUID
+ ref channel.MediaRef
+ }
+ created := make([]createdMedia, 0, len(in.MediaRefs))
ids := make([]pgtype.UUID, 0, len(in.MediaRefs))
for _, ref := range in.MediaRefs {
if !claimed[ref.StorageKey] {
@@ -498,26 +510,127 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
return fmt.Errorf("create channel attachment: %w", err)
}
ids = append(ids, att.ID)
+ created = append(created, createdMedia{id: att.ID, ref: ref})
}
- if len(ids) == 0 {
- return nil
- }
- if in.IssueID.Valid {
+ if len(ids) == 0 || in.IssueID.Valid {
return nil
}
- if _, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{
+ linkedIDs, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{
ChatMessageID: in.MessageID,
ChatSessionID: in.SessionID,
WorkspaceID: in.WorkspaceID,
UploaderType: "member",
UploaderID: in.Sender,
AttachmentIds: ids,
- }); err != nil {
+ })
+ if err != nil {
return fmt.Errorf("link chat attachments: %w", err)
}
+
+ linked := make(map[pgtype.UUID]bool, len(linkedIDs))
+ for _, id := range linkedIDs {
+ linked[id] = true
+ }
+ replacements := make([]inlineMediaReplacement, 0, len(created))
+ for _, media := range created {
+ if !linked[media.id] || media.ref.InlinePlaceholder == "" {
+ continue
+ }
+ replacements = append(replacements, inlineMediaReplacement{
+ placeholder: media.ref.InlinePlaceholder,
+ index: media.ref.InlineIndex,
+ markdown: inlineAttachmentMarkdown(media.ref, media.id),
+ })
+ }
+ if body, changed := composeInlineMediaBody(in.Body, replacements); changed {
+ rows, err := qtx.UpdateChatMessageContentForChannelMedia(ctx, db.UpdateChatMessageContentForChannelMediaParams{
+ ID: in.MessageID,
+ ChatSessionID: in.SessionID,
+ Content: body,
+ })
+ if err != nil {
+ return fmt.Errorf("update chat message inline media: %w", err)
+ }
+ if rows != 1 {
+ return fmt.Errorf("update chat message inline media: updated %d rows", rows)
+ }
+ }
return nil
}
+type inlineMediaReplacement struct {
+ placeholder string
+ index int
+ markdown string
+}
+
+type inlineMediaEdit struct {
+ start int
+ end int
+ text string
+}
+
+func composeInlineMediaBody(body string, replacements []inlineMediaReplacement) (string, bool) {
+ edits := make([]inlineMediaEdit, 0, len(replacements))
+ for _, replacement := range replacements {
+ if replacement.placeholder == "" || replacement.index < 0 || replacement.markdown == "" {
+ continue
+ }
+ start := nthSubstringIndex(body, replacement.placeholder, replacement.index)
+ if start < 0 {
+ continue
+ }
+ edits = append(edits, inlineMediaEdit{
+ start: start,
+ end: start + len(replacement.placeholder),
+ text: replacement.markdown,
+ })
+ }
+ if len(edits) == 0 {
+ return body, false
+ }
+ sort.Slice(edits, func(i, j int) bool { return edits[i].start < edits[j].start })
+ var out strings.Builder
+ last := 0
+ for _, edit := range edits {
+ if edit.start < last {
+ continue
+ }
+ out.WriteString(body[last:edit.start])
+ out.WriteString(edit.text)
+ last = edit.end
+ }
+ out.WriteString(body[last:])
+ return out.String(), true
+}
+
+func nthSubstringIndex(body, marker string, target int) int {
+ offset := 0
+ for index := 0; ; index++ {
+ found := strings.Index(body[offset:], marker)
+ if found < 0 {
+ return -1
+ }
+ found += offset
+ if index == target {
+ return found
+ }
+ offset = found + len(marker)
+ }
+}
+
+func inlineAttachmentMarkdown(ref channel.MediaRef, id pgtype.UUID) string {
+ downloadPath := "/api/attachments/" + uuid.UUID(id.Bytes).String() + "/download"
+ if ref.Type == channel.MsgTypeImage {
+ return "![](" + downloadPath + ")"
+ }
+ label := strings.NewReplacer("\\", "\\\\", "[", "\\[", "]", "\\]").Replace(ref.Filename)
+ if label == "" {
+ label = "attachment"
+ }
+ return "[" + label + "](" + downloadPath + ")"
+}
+
func defaultMediaFilename(kind channel.MsgType, id, contentType string) string {
prefix := "attachment"
switch kind {
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index 1b6d8e21d1..a4d696d946 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -389,6 +389,76 @@ func TestIssueDeleteLockPreventsLateMediaBindFromOrphaningObject(t *testing.T) {
}
}
+func TestBindMediaRefs_MaterializesInlineImagesInOriginalOrder(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})
+ body := "[Image]\n这是啥?\n[Image]\n这又是啥?"
+ appendRes, err := session.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: body,
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, "workspaces/ws/dingtalk/first", "https://cdn.example.test/first", "pending")
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, "workspaces/ws/dingtalk/second", "https://cdn.example.test/second", "pending")
+ err = session.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ Body: body,
+ MediaRefs: []channel.MediaRef{
+ {
+ Type: channel.MsgTypeImage, StorageKey: "workspaces/ws/dingtalk/first",
+ StorageURL: "https://cdn.example.test/first", Filename: "first.png", MimeType: "image/png",
+ InlinePlaceholder: "[Image]", InlineIndex: 0,
+ },
+ {
+ Type: channel.MsgTypeImage, StorageKey: "workspaces/ws/dingtalk/second",
+ StorageURL: "https://cdn.example.test/second", Filename: "second.png", MimeType: "image/png",
+ InlinePlaceholder: "[Image]", InlineIndex: 1,
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+
+ var stored string
+ if err := pool.QueryRow(context.Background(), `SELECT content FROM chat_message WHERE id = $1`, appendRes.MessageID).Scan(&stored); err != nil {
+ t.Fatalf("load message content: %v", err)
+ }
+ rows, err := pool.Query(context.Background(), `
+ SELECT filename, id::text
+ FROM attachment
+ WHERE chat_message_id = $1
+ ORDER BY filename`, appendRes.MessageID)
+ if err != nil {
+ t.Fatalf("load attachment ids: %v", err)
+ }
+ defer rows.Close()
+ ids := map[string]string{}
+ for rows.Next() {
+ var filename, id string
+ if err := rows.Scan(&filename, &id); err != nil {
+ t.Fatalf("scan attachment: %v", err)
+ }
+ ids[filename] = id
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate attachments: %v", err)
+ }
+ want := "![](/api/attachments/" + ids["first.png"] + "/download)\n这是啥?\n" +
+ "![](/api/attachments/" + ids["second.png"] + "/download)\n这又是啥?"
+ if stored != want {
+ t.Fatalf("stored inline body = %q, want %q", stored, want)
+ }
+}
+
type failingLinkSessionQueries struct {
SessionQueries
}
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 6594a45ea2..4000c59cac 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -49,6 +49,8 @@ type fakeSessionQueries struct {
attachments []db.CreateAttachmentParams
linked db.LinkAttachmentsToChatMessageParams
mediaCleared int
+ updatedMediaContent string
+ updateMediaRows int64
reconcilerOwnedKeys map[string]bool
issueLookupErr error
@@ -59,7 +61,7 @@ type fakeSessionQueries struct {
}
func newFake() *fakeSessionQueries {
- return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1, messageID: uid(42)}
+ return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1, messageID: uid(42), updateMediaRows: 1}
}
func bindKey(inst pgtype.UUID, chat string) string { return fmt.Sprintf("%x|%s", inst.Bytes, chat) }
@@ -113,6 +115,11 @@ func (f *fakeSessionQueries) LockIssueForChannelMediaBind(_ context.Context, arg
return arg.ID, nil
}
+func (f *fakeSessionQueries) UpdateChatMessageContentForChannelMedia(_ context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error) {
+ f.updatedMediaContent = arg.Content
+ return f.updateMediaRows, nil
+}
+
func (f *fakeSessionQueries) CreateAttachment(_ context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
f.attachments = append(f.attachments, arg)
return db.Attachment{ID: arg.ID}, nil
@@ -349,10 +356,11 @@ func TestAppendUserMessage_OrdinaryTurnKeepsDefaultMessageKind(t *testing.T) {
func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
f := newFake()
s := newTestSession(f)
+ body := "Use [Image] literally\n[Image]"
res, err := s.AppendUserMessage(context.Background(), AppendInput{
SessionID: uid(1),
Sender: uid(7),
- Body: "[Image]",
+ Body: body,
MessageID: "om_image",
})
if err != nil {
@@ -367,21 +375,23 @@ func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
if !f.lastCreate.ChannelIngested.Valid || !f.lastCreate.ChannelIngested.Bool {
t.Fatalf("channel append must stamp channel_ingested, got %+v", f.lastCreate.ChannelIngested)
}
+ ref := channel.MediaRef{
+ Type: channel.MsgTypeImage,
+ StorageKey: "lark/cli/img.png",
+ StorageURL: "https://cdn.example.test/lark/cli/img.png",
+ Filename: "screenshot.png",
+ MimeType: "image/png",
+ SizeBytes: 3,
+ InlinePlaceholder: "[Image]",
+ InlineIndex: 1,
+ }
err = s.BindMediaRefs(context.Background(), BindMediaInput{
MessageID: res.MessageID,
SessionID: uid(1),
WorkspaceID: uid(9),
Sender: uid(7),
- MediaRefs: []channel.MediaRef{
- {
- Type: channel.MsgTypeImage,
- StorageKey: "lark/cli/img.png",
- StorageURL: "https://cdn.example.test/lark/cli/img.png",
- Filename: "screenshot.png",
- MimeType: "image/png",
- SizeBytes: 3,
- },
- },
+ Body: body,
+ MediaRefs: []channel.MediaRef{ref},
})
if err != nil {
t.Fatalf("BindMediaRefs: %v", err)
@@ -406,6 +416,40 @@ func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
if len(f.linked.AttachmentIds) != 1 || f.linked.AttachmentIds[0] != att.ID {
t.Fatalf("linked ids = %+v, want attachment id %v", f.linked.AttachmentIds, att.ID)
}
+ if want := "Use [Image] literally\n" + inlineAttachmentMarkdown(ref, att.ID); f.updatedMediaContent != want {
+ t.Fatalf("updated content = %q, want %q", f.updatedMediaContent, want)
+ }
+}
+
+func TestComposeInlineMediaBody_PartialResolutionKeepsFailedPlaceholderInPlace(t *testing.T) {
+ body := "[Image]\n这是啥?\n[Image]\n这又是啥?"
+ got, changed := composeInlineMediaBody(body, []inlineMediaReplacement{{
+ placeholder: "[Image]",
+ index: 1,
+ markdown: "![](/api/attachments/second/download)",
+ }})
+ if !changed {
+ t.Fatal("expected the successful second image to update the body")
+ }
+ want := "[Image]\n这是啥?\n![](/api/attachments/second/download)\n这又是啥?"
+ if got != want {
+ t.Fatalf("composed body = %q, want %q", got, want)
+ }
+}
+
+func TestComposeInlineMediaBody_ReplacesMarkersWithoutAddingWhitespace(t *testing.T) {
+ body := "前[Image]中\n[Image]后"
+ got, changed := composeInlineMediaBody(body, []inlineMediaReplacement{
+ {placeholder: "[Image]", index: 0, markdown: "![](/api/attachments/first/download)"},
+ {placeholder: "[Image]", index: 1, markdown: "![](/api/attachments/second/download)"},
+ })
+ if !changed {
+ t.Fatal("expected both inline image markers to be replaced")
+ }
+ want := "前![](/api/attachments/first/download)中\n![](/api/attachments/second/download)后"
+ if got != want {
+ t.Fatalf("replacement changed surrounding whitespace: got %q, want %q", got, want)
+ }
}
func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {
@@ -417,13 +461,15 @@ func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {
WorkspaceID: uid(9),
Sender: uid(7),
IssueID: uid(8),
+ Body: "[Image]",
MediaRefs: []channel.MediaRef{{
- Type: channel.MsgTypeImage,
- StorageKey: "lark/cli/issue.png",
- StorageURL: "https://cdn.example.test/lark/cli/issue.png",
- Filename: "issue.png",
- MimeType: "image/png",
- SizeBytes: 3,
+ Type: channel.MsgTypeImage,
+ StorageKey: "lark/cli/issue.png",
+ StorageURL: "https://cdn.example.test/lark/cli/issue.png",
+ Filename: "issue.png",
+ MimeType: "image/png",
+ SizeBytes: 3,
+ InlinePlaceholder: "[Image]",
}},
})
if err != nil {
@@ -442,6 +488,9 @@ func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {
if f.linked.ChatMessageID.Valid || len(f.linked.AttachmentIds) != 0 {
t.Fatalf("issue attachment must not also bind to chat message: %+v", f.linked)
}
+ if f.updatedMediaContent != "" {
+ t.Fatalf("issue-owned media must not rewrite the chat command body: %q", f.updatedMediaContent)
+ }
if f.mediaCleared != 1 {
t.Fatalf("media pending marker clears = %d, want 1", f.mediaCleared)
}
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 98cddfd16b..830ccc886c 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -97,6 +97,13 @@ type MediaRef struct {
MimeType string
// SizeBytes is the object size in bytes, or 0 when unknown.
SizeBytes int64
+ // InlinePlaceholder is an optional exact marker in the durable message
+ // body that this attachment should replace with a stable Markdown link.
+ // Empty keeps the attachment standalone and preserves existing platform
+ // behavior. InlineIndex is the zero-based occurrence of that marker, so a
+ // partial media failure cannot shift later attachments into the wrong place.
+ InlinePlaceholder string
+ InlineIndex int
}
// ReplyCtx describes the message an inbound message quotes / replies to.
diff --git a/server/internal/integrations/dingtalk/inbound.go b/server/internal/integrations/dingtalk/inbound.go
index f25be8b0be..fd66dc2973 100644
--- a/server/internal/integrations/dingtalk/inbound.go
+++ b/server/internal/integrations/dingtalk/inbound.go
@@ -79,12 +79,20 @@ type dingtalkRawEvent struct {
type dingtalkMediaResource struct {
Ref string `json:"ref"`
Alt string `json:"alt,omitempty"`
+ // InlineIndex is the occurrence of the adapter-generated marker in the
+ // visible body, including identical user-authored text.
+ InlineIndex int `json:"inline_index,omitempty"`
+}
+
+func dingtalkMediaResourceAt(ref, alt string, inlineIndex int) dingtalkMediaResource {
+ return dingtalkMediaResource{Ref: ref, Alt: alt, InlineIndex: inlineIndex}
}
// conversation type discriminators DingTalk sends in conversationType.
const (
- convTypeP2P = "1"
- convTypeGroup = "2"
+ convTypeP2P = "1"
+ convTypeGroup = "2"
+ dingtalkImagePlaceholder = "[Image]"
)
// inboundFromCallback normalizes a DingTalk bot callback. It returns ok=false
@@ -139,9 +147,9 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
return mediaUnreadableMsg(msg, rawEvent), true
}
msg.Type = channel.MsgTypeImage
- msg.Text = "[Image]"
+ msg.Text = dingtalkImagePlaceholder
msg.CommandText = msg.Text
- rawEvent.Media = []dingtalkMediaResource{{Ref: ref, Alt: alt}}
+ rawEvent.Media = []dingtalkMediaResource{dingtalkMediaResourceAt(ref, alt, 0)}
return withDingTalkRaw(msg, rawEvent), true
case "richText":
@@ -152,8 +160,9 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
return mediaUnreadableMsg(msg, rawEvent), true
}
var (
- text strings.Builder
- commandText strings.Builder
+ text strings.Builder
+ commandText strings.Builder
+ inlinePlaceholderCount int
)
for _, item := range rc.RichText {
// A single item may in principle carry BOTH a text run and a picture
@@ -163,6 +172,7 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
if item.Text != "" {
text.WriteString(item.Text)
commandText.WriteString(item.Text)
+ inlinePlaceholderCount += strings.Count(item.Text, dingtalkImagePlaceholder)
}
if item.Type == "picture" || item.DownloadCode != "" || item.PictureDownloadCode != "" {
ref, alt := refAlt(item.DownloadCode, item.PictureDownloadCode)
@@ -170,7 +180,8 @@ func inboundFromCallback(data *botCallbackData, appID string) (channel.InboundMe
continue // a picture item with no usable code
}
appendImagePlaceholder(&text)
- rawEvent.Media = append(rawEvent.Media, dingtalkMediaResource{Ref: ref, Alt: alt})
+ rawEvent.Media = append(rawEvent.Media, dingtalkMediaResourceAt(ref, alt, inlinePlaceholderCount))
+ inlinePlaceholderCount++
}
}
if len(rawEvent.Media) == 0 {
@@ -266,7 +277,7 @@ func appendImagePlaceholder(b *strings.Builder) {
if b.Len() > 0 {
b.WriteByte('\n')
}
- b.WriteString("[Image]\n")
+ b.WriteString(dingtalkImagePlaceholder + "\n")
}
// dingtalkChatType maps DingTalk's conversationType to the normalized ChatType.
diff --git a/server/internal/integrations/dingtalk/inbound_test.go b/server/internal/integrations/dingtalk/inbound_test.go
index 2078839e0e..4824cf084f 100644
--- a/server/internal/integrations/dingtalk/inbound_test.go
+++ b/server/internal/integrations/dingtalk/inbound_test.go
@@ -116,6 +116,28 @@ func TestInboundFromCallback_RichTextKeepsCommandSourceAndImagePositions(t *test
}
}
+func TestInboundFromCallback_RichTextTracksGeneratedMarkersPastUserPlaceholders(t *testing.T) {
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"text":"/new Use [Image] literally"},
+ {"type":"picture","downloadCode":"dl-1"},
+ {"text":" and another [Image] literally"},
+ {"type":"picture","downloadCode":"dl-2"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "appkey-A")
+ if !ok || !msg.ForceFresh || strings.Contains(msg.Text, "/new") {
+ t.Fatalf("expected normalized richText /new message: ok=%v msg=%+v", ok, msg)
+ }
+ raw, err := decodeDingTalkRaw(msg)
+ if err != nil || len(raw.Media) != 2 {
+ t.Fatalf("raw media = %+v, err=%v", raw.Media, err)
+ }
+ if raw.Media[0].InlineIndex != 1 || raw.Media[1].InlineIndex != 3 {
+ t.Fatalf("generated marker positions = %+v, want occurrences 1 and 3", raw.Media)
+ }
+}
+
func TestInboundFromCallback_RichTextDoesNotPrivatelyComposeFreshAndIssue(t *testing.T) {
cb := textCallback(convTypeP2P, false)
cb.Msgtype = "richText"
diff --git a/server/internal/integrations/dingtalk/media.go b/server/internal/integrations/dingtalk/media.go
index 962959a0b9..4d20c4c321 100644
--- a/server/internal/integrations/dingtalk/media.go
+++ b/server/internal/integrations/dingtalk/media.go
@@ -270,12 +270,14 @@ func (m *mediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedIn
return nil
}
refs[i] = channel.MediaRef{
- Type: channel.MsgTypeImage,
- StorageKey: key,
- StorageURL: link,
- Filename: filename,
- MimeType: contentType,
- SizeBytes: int64(len(data)),
+ Type: channel.MsgTypeImage,
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: int64(len(data)),
+ InlinePlaceholder: dingtalkImagePlaceholder,
+ InlineIndex: resource.InlineIndex,
}
valid[i] = true
return nil
diff --git a/server/internal/integrations/dingtalk/media_test.go b/server/internal/integrations/dingtalk/media_test.go
index 58ac907fb7..276ba0df6a 100644
--- a/server/internal/integrations/dingtalk/media_test.go
+++ b/server/internal/integrations/dingtalk/media_test.go
@@ -124,12 +124,16 @@ func mediaFixture(resources ...dingtalkMediaResource) (engine.ResolvedInstallati
ID: instID, WorkspaceID: ws,
Platform: db.ChannelInstallation{Config: cfg},
}
- return inst, messageID, channel.InboundMessage{MessageID: "dt-msg", Type: channel.MsgTypeImage, Text: "[Image]", Raw: raw}
+ body := strings.TrimSpace(strings.Repeat("[Image]\n", len(resources)))
+ return inst, messageID, channel.InboundMessage{MessageID: "dt-msg", Type: channel.MsgTypeImage, Text: body, Raw: raw}
}
func TestMediaResolver_HappyPathAndIntentLedger(t *testing.T) {
env := newMediaTestEnv(t, map[string][]byte{"c1": pngBytes, "c2": jpegBytes})
- inst, messageID, msg := mediaFixture(dingtalkMediaResource{Ref: "c1"}, dingtalkMediaResource{Ref: "c2"})
+ inst, messageID, msg := mediaFixture(
+ dingtalkMediaResourceAt("c1", "", 0),
+ dingtalkMediaResourceAt("c2", "", 1),
+ )
if !env.resolver.HasMedia(msg) {
t.Fatal("HasMedia=false")
}
@@ -140,6 +144,10 @@ func TestMediaResolver_HappyPathAndIntentLedger(t *testing.T) {
if got.MediaRefs[0].MimeType != "image/png" || got.MediaRefs[1].MimeType != "image/jpeg" {
t.Fatalf("mime types = %q/%q", got.MediaRefs[0].MimeType, got.MediaRefs[1].MimeType)
}
+ if got.MediaRefs[0].InlinePlaceholder != "[Image]" || got.MediaRefs[0].InlineIndex != 0 ||
+ got.MediaRefs[1].InlinePlaceholder != "[Image]" || got.MediaRefs[1].InlineIndex != 1 {
+ t.Fatalf("inline positions = %+v", got.MediaRefs)
+ }
if len(env.ledger.records) != 2 || len(env.store.uploads) != 2 {
t.Fatalf("intents/uploads = %d/%d", len(env.ledger.records), len(env.store.uploads))
}
@@ -150,6 +158,28 @@ func TestMediaResolver_HappyPathAndIntentLedger(t *testing.T) {
}
}
+func TestMediaResolver_PreservesInboundPositionPastUserPlaceholder(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"c1": pngBytes})
+ cb := textCallback(convTypeP2P, false)
+ cb.Msgtype = "richText"
+ cb.Content = json.RawMessage(`{"richText":[
+ {"text":"Use [Image] literally"},
+ {"type":"picture","downloadCode":"c1"}
+ ]}`)
+ msg, ok := inboundFromCallback(cb, "app-key")
+ if !ok {
+ t.Fatal("expected richText message")
+ }
+ inst, messageID, _ := mediaFixture()
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("media refs = %+v", got.MediaRefs)
+ }
+ if ref := got.MediaRefs[0]; ref.InlinePlaceholder != dingtalkImagePlaceholder || ref.InlineIndex != 1 {
+ t.Fatalf("inline position = %+v, want generated marker occurrence 1", ref)
+ }
+}
+
func TestMediaResolver_AltFallback(t *testing.T) {
env := newMediaTestEnv(t, map[string][]byte{"alt": pngBytes})
inst, messageID, msg := mediaFixture(dingtalkMediaResource{Ref: "expired", Alt: "alt"})
@@ -159,6 +189,23 @@ func TestMediaResolver_AltFallback(t *testing.T) {
}
}
+func TestMediaResolver_PartialFailurePreservesOriginalInlineIndex(t *testing.T) {
+ env := newMediaTestEnv(t, map[string][]byte{"second": pngBytes})
+ inst, messageID, msg := mediaFixture(
+ dingtalkMediaResourceAt("missing", "", 1),
+ dingtalkMediaResourceAt("second", "", 3),
+ )
+ msg.Text = "literal [Image]\n[Image]\nanother literal [Image]\n[Image]"
+ got := env.resolver.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, messageID, msg)
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("media refs = %+v, want only the successful image", got.MediaRefs)
+ }
+ ref := got.MediaRefs[0]
+ if ref.InlinePlaceholder != "[Image]" || ref.InlineIndex != 3 {
+ t.Fatalf("successful second image position = %+v, want occurrence 3", ref)
+ }
+}
+
func TestMediaResolver_AltFailurePreservesPrimaryError(t *testing.T) {
env := newMediaTestEnv(t, nil)
_, _, err := env.resolver.fetchResource(context.Background(), credentials{
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index ed67eb43db..ff1f3c957b 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -275,6 +275,7 @@ func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams)
WorkspaceID: p.WorkspaceID,
Sender: p.Sender,
IssueID: p.IssueID,
+ Body: p.Body,
MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index f00f6ea7f1..f1d42e77fa 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -12,7 +12,10 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-type captureChatSession struct{ append engine.AppendInput }
+type captureChatSession struct {
+ append engine.AppendInput
+ media engine.BindMediaInput
+}
func (c *captureChatSession) EnsureSession(context.Context, engine.EnsureSessionInput) (pgtype.UUID, error) {
return pgtype.UUID{}, nil
@@ -21,7 +24,10 @@ func (c *captureChatSession) AppendUserMessage(_ context.Context, in engine.Appe
c.append = in
return engine.AppendResult{}, nil
}
-func (c *captureChatSession) BindMediaRefs(context.Context, engine.BindMediaInput) error { return nil }
+func (c *captureChatSession) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {
+ c.media = in
+ return nil
+}
func TestNewDingTalkResolverSetUsesDatabaseBackedIssueOrigin(t *testing.T) {
set := NewDingTalkResolverSet(nil, nil, nil, nil, nil)
@@ -55,6 +61,25 @@ func TestSessionBinder_MapsCommandTextAndMediaDeadline(t *testing.T) {
}
}
+func TestSessionBinder_MapsMediaBodyAndIssueTarget(t *testing.T) {
+ var message, session, workspace, sender, issue pgtype.UUID
+ message.Bytes[0], session.Bytes[0], workspace.Bytes[0], sender.Bytes[0], issue.Bytes[0] = 1, 2, 3, 4, 5
+ message.Valid, session.Valid, workspace.Valid, sender.Valid, issue.Valid = true, true, true, true, true
+ ref := channel.MediaRef{Type: channel.MsgTypeImage, InlinePlaceholder: "[Image]", InlineIndex: 0}
+ capture := &captureChatSession{}
+ binder := &sessionBinder{session: capture}
+ if err := binder.BindMedia(context.Background(), engine.BindMediaParams{
+ MessageID: message, SessionID: session, WorkspaceID: workspace, Sender: sender,
+ IssueID: issue, Body: "[Image]\nfix login", MediaRefs: []channel.MediaRef{ref},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ got := capture.media
+ if got.MessageID != message || got.SessionID != session || got.WorkspaceID != workspace || got.Sender != sender || got.IssueID != issue || got.Body != "[Image]\nfix login" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
+ t.Fatalf("mapped media input = %+v", got)
+ }
+}
+
func TestDingTalkSessionRouting_P2PCarriesStaffID(t *testing.T) {
msg := channel.InboundMessage{Source: channel.Source{
ChatID: "cid-1",
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index b5cae30651..5ec14e6afe 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -227,6 +227,7 @@ func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaP
WorkspaceID: p.WorkspaceID,
Sender: p.Sender,
IssueID: p.IssueID,
+ Body: p.Body,
MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index 82d0b5b611..99abae9028 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -166,12 +166,13 @@ func TestFeishuSessionBinder_BindMediaMapping(t *testing.T) {
WorkspaceID: binderUUID(2),
Sender: binderUUID(7),
IssueID: binderUUID(8),
+ Body: "[Image]",
MediaRefs: []channel.MediaRef{ref},
}); err != nil {
t.Fatalf("BindMedia: %v", err)
}
got := f.mediaIn
- if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || got.IssueID != binderUUID(8) || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
+ if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || got.IssueID != binderUUID(8) || got.Body != "[Image]" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
t.Fatalf("media mapping wrong: %+v", got)
}
}
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index 8d183cff39..bb4e5a26db 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -358,6 +358,7 @@ func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams)
WorkspaceID: p.WorkspaceID,
Sender: p.Sender,
IssueID: p.IssueID,
+ Body: p.Body,
MediaRefs: p.MediaRefs,
})
}
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 79e67acb71..ee0018d1a7 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -2643,6 +2643,33 @@ func (q *Queries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
return err
}
+const updateChatMessageContentForChannelMedia = `-- name: UpdateChatMessageContentForChannelMedia :execrows
+UPDATE chat_message
+SET content = $1
+WHERE id = $2
+ AND chat_session_id = $3
+ AND role = 'user'
+ AND channel_ingested
+`
+
+type UpdateChatMessageContentForChannelMediaParams struct {
+ Content string `json:"content"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+// Channel messages are immutable user turns. Media resolution may finish after
+// the initial append, so materialize stable inline attachment references in the
+// same transaction that binds those attachments. The provenance and role guards
+// prevent this narrow post-append path from rewriting ordinary web/agent rows.
+func (q *Queries) UpdateChatMessageContentForChannelMedia(ctx context.Context, arg UpdateChatMessageContentForChannelMediaParams) (int64, error) {
+ result, err := q.db.Exec(ctx, updateChatMessageContentForChannelMedia, arg.Content, arg.ID, arg.ChatSessionID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const updateChatSessionProject = `-- name: UpdateChatSessionProject :one
UPDATE chat_session
SET project_id = $1
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 69720f06fe..dc8bd8436b 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -397,6 +397,18 @@ UPDATE chat_message
SET channel_media_pending_until = NULL
WHERE id = $1 AND chat_session_id = $2;
+-- name: UpdateChatMessageContentForChannelMedia :execrows
+-- Channel messages are immutable user turns. Media resolution may finish after
+-- the initial append, so materialize stable inline attachment references in the
+-- same transaction that binds those attachments. The provenance and role guards
+-- prevent this narrow post-append path from rewriting ordinary web/agent rows.
+UPDATE chat_message
+SET content = sqlc.arg(content)
+WHERE id = sqlc.arg(id)
+ AND chat_session_id = sqlc.arg(chat_session_id)
+ AND role = 'user'
+ AND channel_ingested;
+
-- name: LinkChatMessageToTask :exec
UPDATE chat_message
SET task_id = $2