Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8205 feat(lark): deliver reply images and files (#9477)
Frezc8a95f0d3b95b
diff --git a/apps/docs/content/docs/lark-bot-integration.fr.mdx b/apps/docs/content/docs/lark-bot-integration.fr.mdxindex 7f35c843d0..e1fa158f50 100644--- a/apps/docs/content/docs/lark-bot-integration.fr.mdx+++ b/apps/docs/content/docs/lark-bot-integration.fr.mdx@@ -74,6 +74,10 @@ Safari reste sur la page de connexion après une connexion réussie.La première ligne devient le titre et le reste la description. Envoyer `/issue` seul ne crée rien ; le bot répond alors en indiquant le format attendu.+## Images et fichiers produits par l’agent++Lorsque l’envoi de pièces jointes est activé, le texte et les images prises en charge d’une réponse apparaissent dans un même message Feishu. Les images mettent ce message à jour une fois importées ; les fichiers arrivent séparément dans la même conversation. Une réponse composée uniquement d’images peut utiliser un message image. La limite est de 10 Mo par image ; les formats non pris en charge, les images plus grandes ou explicitement refusées sont envoyés comme fichiers, dans la limite de 30 Mo. Le stockage objet et l’autorisation d’importer des ressources de l’application sont nécessaires. En cas d’échec ou de livraison incertaine, les pièces jointes restent disponibles dans la réponse Multica. Vérifiez la conversation avant de demander un nouvel envoi.+## Gérer les connexionsOuvrez **Paramètres → Messagerie → Lark** pour voir les bots connectés dans l'espace de travail. Les propriétaires et administrateurs de l'espace de travail peuvent les déconnecter ici ; le propriétaire d'un agent peut aussi gérer son propre bot depuis la page **Intégrations** de cet agent.diff --git a/apps/docs/content/docs/lark-bot-integration.ja.mdx b/apps/docs/content/docs/lark-bot-integration.ja.mdxindex ef1950e49b..a94d8f5f58 100644--- a/apps/docs/content/docs/lark-bot-integration.ja.mdx+++ b/apps/docs/content/docs/lark-bot-integration.ja.mdx@@ -74,6 +74,10 @@ Safari ではログインに成功してもログイン画面に残ります。1 行目がタイトルになり、残りの内容が説明になります。`/issue` だけを送信してもタスクは作成されず、Bot が使い方を返信します。+## エージェントが生成した画像とファイル++添付ファイルの送信が有効な場合、エージェントの返信本文と対応形式の画像は、同じ Feishu メッセージ内に表示されます。画像はアップロード完了後に元のメッセージへ反映され、ファイルは同じ会話へ別のメッセージで送信されます。本文のない画像のみの返信は、画像メッセージで送信できます。画像の上限は 10 MB です。非対応形式、上限超過、または Feishu が明示的に拒否した画像は、30 MB を上限にファイルとして送信されます。オブジェクトストレージとアプリのリソースアップロード権限が必要です。送信に失敗した場合や到着を確認できない場合も、添付ファイルは Multica の返信に残ります。再送を依頼する前に、会話を確認してください。+## 接続を管理する**設定 → メッセージング → Lark**を開くと、ワークスペースに接続済みの Bot を確認できます。ワークスペースの owner と admin はここから接続を解除できます。エージェントの所有者は、そのエージェントの**連携**ページから自分の Bot を管理できます。diff --git a/apps/docs/content/docs/lark-bot-integration.ko.mdx b/apps/docs/content/docs/lark-bot-integration.ko.mdxindex 8cdcca9a5f..6791612cb7 100644--- a/apps/docs/content/docs/lark-bot-integration.ko.mdx+++ b/apps/docs/content/docs/lark-bot-integration.ko.mdx@@ -74,6 +74,10 @@ Safari에서 로그인에 성공해도 로그인 페이지에 계속 머뭅니첫 줄이 제목이 되고 나머지 내용이 설명이 됩니다. `/issue`만 보내면 태스크가 만들어지지 않고, Bot이 사용법을 답장으로 보냅니다.+## 에이전트가 생성한 이미지와 파일++첨부 파일 전송이 활성화되면 에이전트 응답의 텍스트와 지원되는 이미지가 같은 Feishu 메시지에 함께 표시됩니다. 이미지 업로드가 완료되면 원래 메시지가 업데이트되고, 파일은 같은 대화에 별도 메시지로 전송됩니다. 본문 없이 이미지만 있는 응답은 이미지 메시지로 보낼 수 있습니다. 이미지 한도는 10 MB입니다. 지원되지 않는 형식, 한도를 초과하거나 Feishu가 명시적으로 거부한 이미지는 최대 30 MB의 파일로 전송됩니다. 객체 스토리지와 앱의 리소스 업로드 권한이 필요합니다. 전송에 실패하거나 전달 여부를 확인할 수 없어도 첨부 파일은 Multica 응답에 남습니다. 재전송을 요청하기 전에 대화를 확인하세요.+## 연결 관리**설정 → 메신저 → Lark**에서 워크스페이스에 연결된 Bot을 확인할 수 있습니다. 워크스페이스 owner와 admin은 여기서 연결을 해제할 수 있고, 에이전트 owner도 해당 에이전트의 **연동** 페이지에서 자신의 Bot을 관리할 수 있습니다.diff --git a/apps/docs/content/docs/lark-bot-integration.mdx b/apps/docs/content/docs/lark-bot-integration.mdxindex 975baee5f5..fa9d726647 100644--- a/apps/docs/content/docs/lark-bot-integration.mdx+++ b/apps/docs/content/docs/lark-bot-integration.mdx@@ -74,6 +74,10 @@ Safari stays on the login page after a successful sign-in.The first line becomes the title and the rest becomes the description. Sending `/issue` alone creates nothing; the Bot replies with the required format instead.+## Images and files from the agent++When file delivery is enabled, text and supported images attached to an agent’s reply appear together in one Feishu message. Images update that message as they finish uploading; files arrive separately in the same conversation. An image-only reply can use an image message. Supported images are limited to 10 MB; unsupported, larger, or explicitly rejected images are sent as files, up to 30 MB. This requires object storage and the application’s resource upload permission. If delivery fails or cannot be confirmed, the attachments remain available on the reply in Multica. Check the conversation before requesting a resend.+## Manage connectionsOpen **Settings → Messaging → Lark** to view the Bots connected in the workspace. Workspace owners and admins can disconnect them here; an agent's owner can also manage their own Bot from that agent's **Integrations** page.diff --git a/apps/docs/content/docs/lark-bot-integration.zh.mdx b/apps/docs/content/docs/lark-bot-integration.zh.mdxindex bfce8e2c4b..0748e03745 100644--- a/apps/docs/content/docs/lark-bot-integration.zh.mdx+++ b/apps/docs/content/docs/lark-bot-integration.zh.mdx@@ -74,6 +74,10 @@ Safari 登录成功后仍然停留在登录页。第一行作为标题,其余内容作为描述。只发送 `/issue` 不会创建任务;Bot 会回复用法提示。+## 接收智能体生成的图片和文件++部署启用附件回传后,智能体回复中的文字与受支持图片会在同一条飞书消息中混排,图片上传完成后更新原消息;文件另发到同一会话。没有正文的图片回复可直接发送图片消息。图片上限为 10 MB;不受支持、过大或被飞书明确拒绝的图片会按文件发送,文件上限为 30 MB。此功能需要服务端配置对象存储,并授予飞书应用资源上传权限。发送失败或无法确认送达时,附件仍保留在 Multica 的回复中;请求重发前,请先检查当前会话。+## 管理连接打开 **设置 → 消息渠道 → 飞书** 可以查看工作区内已连接的 Bot。工作区 owner 和 admin 可以在这里断开连接;智能体所有者也可以回到该智能体的 **集成** 页面管理自己的 Bot。diff --git a/docs/lark-outbound-media.md b/docs/lark-outbound-media.mdnew file mode 100644index 0000000000..1426f57f1f--- /dev/null+++ b/docs/lark-outbound-media.md@@ -0,0 +1,78 @@+# Lark outbound images and files++The Lark integration delivers attachments bound to the assistant message in a+completed chat turn. The server reads their bytes from its configured object+store and uploads them with the conversation's bot credentials. Agent runtimes+bind their output files through the existing attachment upload API.++## Delivery++Text and supported images share one schema-2.0 message card. Text is sent first;+uploaded images update the same message at their Markdown positions. Images+without a reference are appended to the card. A reply containing only images+can use image messages. Other attachments are sent separately to the same+conversation and reply target.++Image upload uses an explicit format allowlist and a 10,000,000-byte limit.+Unsupported formats, larger images and images explicitly refused by the image+endpoint fall back to file upload, with a 30,000,000-byte limit. Empty files and+larger files are rejected before upload. MP4 and Opus uploads use their matching+video and audio message types; their existing file keys are sufficient, without+requiring a generated thumbnail or duration.++The integration requires object storage, bot capability and the application's+`im:resource:upload` or `im:resource` permission. Uploads use the resource HTTP+client and its longer timeout. Multipart bodies reuse the file buffer.++## Rendering and ownership++Goldmark identifies image references and their source spans, including reference+syntax, escapes and entities. Only attachments bound to the current assistant+message can supply an uploaded image key. Other image destinations remain+ordinary links. No remote URL in model output is fetched to render an image.++Initial cards and full replacement updates use `config.update_multi=true`.+Updates retain images whose previous update was accepted or remains uncertain.+Retries target the same message and content.++The existing durable reply ledger fences the whole reply across duplicate+completion events and replicas. Admission happens before spawning a worker or+looking up attachments. Pending batches and active transfers are bounded, and+waiting for a transfer slot respects the delivery budget. Each external write+rechecks the installation, active conversation, frozen destination and lease.++Attachment sends reuse a UUID derived from the installation, assistant message+and attachment. Lost responses and the provider's 230049 pending result remain+uncertain, with bounded retries. Definite failure and uncertainty have distinct+notices, each with a separate deadline after the transfer budget expires.+Attachments remain available in Multica. Interrupted batches are not replayed+without per-file delivery receipts.++## Verification++Run the Lark package tests and static checks from `server/`:++```sh+go test -race ./internal/integrations/lark -count=1+go vet ./internal/integrations/lark+```++Set `DATABASE_URL` to an isolated, migrated test database to include the reply+ownership and attachment-to-HTTP pipeline tests. These tests skip when it is+unset. The suite covers multipart transport, token refresh, upload/message type+pairing, reply routing, idempotency, size/format fallback, pending sends,+authorization changes and same-message Markdown updates.++With an authorized test bot, verify an image-only reply, a downloadable file,+text before and after an image in one message, and an SVG or oversized image+delivered as a file. Download the image and file to compare their bytes with the+platform attachments. Capture the rendered chat as well as the message payload;+message GET requires `card_msg_content_type=user_card_content` for the card body.++See the official [upload image][image], [upload file][file], [message content][content]+and [update card][patch] contracts.++[image]: https://open.feishu.cn/document/server-docs/im-v1/image/create+[file]: https://open.feishu.cn/document/server-docs/im-v1/file/create+[content]: https://open.feishu.cn/document/server-docs/im-v1/message-content-description/create_json+[patch]: https://open.feishu.cn/document/server-docs/im-v1/message-card/patchdiff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 2a6ce4128e..1f1b70a8c9 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -618,6 +618,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// wrap *db.Queries internally, so they keep taking queries.cs := lark.NewChannelStore(queries)patcher := lark.NewPatcher(cs, installSvc, larkClient, lark.PatcherConfig{})+ if store != nil && patcher.SetAttachments(store) {+ h.DeclareChannelFileDelivery(string(channel.TypeFeishu))+ }patcher.Register(bus)// Typing indicator: shows a "processing" reaction on the user'sdiff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.goindex ece913366c..8d47307df9 100644--- a/server/internal/integrations/lark/http_client.go+++ b/server/internal/integrations/lark/http_client.go@@ -108,13 +108,13 @@ type HTTPClientConfig struct {// stripped.BaseURL string- // HTTPClient is the transport used for every outbound call. Tests+ // HTTPClient is the transport used for JSON API calls. Tests// substitute an *http.Client whose Transport routes to an// httptest.Server. Empty defaults to a fresh http.Client with// defaultRequestTimeout.HTTPClient *http.Client- // ResourceHTTPClient is used only for message resource downloads. It+ // ResourceHTTPClient is used for resource downloads and media uploads. It// deliberately does not share HTTPClient's shorter timeout: image/video// resource transfers are bounded by ResourceDownloadTimeout instead.ResourceHTTPClient *http.Client@@ -415,6 +415,31 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (return resp.Data.MessageID, nil}+func markdownCardContent(markdown, summary string) (string, error) {+ return markdownCardJSON(markdownImageLinks(markdown), summary)+}++// Only callers holding uploaded image keys may bypass URL-image degradation.+func markdownCardJSON(markdown, summary string) (string, error) {+ card := map[string]any{+ "schema": "2.0",+ "config": map[string]any{"update_multi": true},+ "body": map[string]any{+ "elements": []any{+ map[string]any{"tag": "markdown", "content": markdown},+ },+ },+ }+ if summary != "" {+ card["config"].(map[string]any)["summary"] = map[string]any{"content": summary}+ }+ cardBytes, err := json.Marshal(card)+ if err != nil {+ return "", fmt.Errorf("lark http client: encode markdown card: %w", err)+ }+ return string(cardBytes), nil+}+// SendMarkdownCard posts the agent's reply as an interactive card// using Lark's schema-2.0 envelope with a single `tag: "markdown"`// body element. Lark's client renders the markdown into formatted@@ -437,24 +462,11 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardif p.Markdown == "" {return "", errors.New("lark http client: missing markdown body")}- card := map[string]any{- "schema": "2.0",- "body": map[string]any{- "elements": []any{- map[string]any{"tag": "markdown", "content": p.Markdown},- },- },- }- if p.Summary != "" {- card["config"] = map[string]any{- "summary": map[string]any{"content": p.Summary},- }- }- cardBytes, err := json.Marshal(card)+ content, err := markdownCardContent(p.Markdown, p.Summary)if err != nil {- return "", fmt.Errorf("lark http client: encode markdown card: %w", err)+ return "", err}- path, body := outboundMessageRequest(p.ChatID, "interactive", string(cardBytes), p.ReplyTarget)+ path, body := outboundMessageRequest(p.ChatID, "interactive", content, p.ReplyTarget)var resp struct {Code int `json:"code"`Msg string `json:"msg"`@@ -497,7 +509,7 @@ func (c *httpAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParif isTokenError(resp.Code) {c.invalidateToken(p.InstallationID.AppID)}- return fmt.Errorf("lark http client: patch interactive card: code=%d msg=%q", resp.Code, resp.Msg)+ return &APIError{Op: "patch interactive card", Code: resp.Code, Msg: resp.Msg}}return nil}diff --git a/server/internal/integrations/lark/http_client_media.go b/server/internal/integrations/lark/http_client_media.gonew file mode 100644index 0000000000..b19597726b--- /dev/null+++ b/server/internal/integrations/lark/http_client_media.go@@ -0,0 +1,358 @@+package lark++// http_client_media.go — the transport half of agent-file delivery.+//+// Four methods, and they are declared on the concrete client rather than+// added to APIClient on purpose. APIClient is the seam every consumer in+// this package is wired through, including the production stub and four+// test fakes; four more methods there would mean four more no-op stubs in+// each of them for a capability exactly one call site uses. The delivery+// path asks for the narrow interface in outbound_media.go instead and+// degrades to "attachments are not deliverable here" when the client does+// not implement it — which is precisely what the stub means.++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "mime/multipart"+ "net/http"+ "path/filepath"+ "strings"+)++const (+ // larkImageUploadMaxBytes is Lark's ceiling for image_type=message.+ // Enforced here rather than left to Lark because a file that is too+ // big has to reach the user as a sentence, and by the time Lark+ // refuses the body the delivery path has already told itself the+ // file was sendable.+ larkImageUploadMaxBytes = 10_000_000++ // larkFileUploadMaxBytes is Lark's ceiling for POST /im/v1/files.+ larkFileUploadMaxBytes = 30_000_000++ // The two upload endpoints. Both take multipart/form-data and both+ // answer with the usual {code,msg,data} envelope.+ larkUploadPathImage = "/open-apis/im/v1/images"+ larkUploadPathFile = "/open-apis/im/v1/files"+)++// mediaUploadForm is one multipart POST to a Lark upload endpoint: a few+// text fields followed by a single file part. Both endpoints share that+// shape (image_type + image; file_type + file_name + file), so one+// builder serves both.+type mediaUploadForm struct {+ // textFields are written in order, ahead of the file part.+ textFields [][2]string+ fileField string+ filename string+ data []byte+}++// build renders the form into a fresh buffer.+//+// Called once per attempt, not once per upload: the token-refresh retry+// in doAuthedUpload re-sends, and a multipart body is a one-shot reader.+func (f mediaUploadForm) build() (io.Reader, int64, string, error) {+ var body bytes.Buffer+ w := multipart.NewWriter(&body)+ for _, kv := range f.textFields {+ if err := w.WriteField(kv[0], kv[1]); err != nil {+ return nil, 0, "", fmt.Errorf("write field %s: %w", kv[0], err)+ }+ }+ // CreateFormFile rather than CreatePart: it escapes the filename for+ // us, and Lark reads the declared content type as a hint only — the+ // bytes are what it validates a file against.+ _, err := w.CreateFormFile(f.fileField, filepath.Base(f.filename))+ if err != nil {+ return nil, 0, "", fmt.Errorf("create file part: %w", err)+ }+ headerSize := body.Len()+ if err := w.Close(); err != nil {+ return nil, 0, "", fmt.Errorf("close multipart writer: %w", err)+ }+ // Replayable framing without copying the file into a second full buffer.+ framing := body.Bytes()+ return io.MultiReader(bytes.NewReader(framing[:headerSize]), bytes.NewReader(f.data), bytes.NewReader(framing[headerSize:])),+ int64(len(framing) + len(f.data)), w.FormDataContentType(), nil+}++// doAuthedUpload posts one multipart form to a Lark upload endpoint,+// minting a tenant_access_token first and refreshing it once on a token+// rejection.+//+// That contract is copied from doAuthedJSON because it is needed for the+// same reason: an app_secret can be rotated under a long-lived process,+// and the cached token then fails every call until something invalidates+// it. An upload that skipped the retry would report a credential event to+// the user as "your file could not be sent".+func (c *httpAPIClient) doAuthedUpload(ctx context.Context, creds InstallationCredentials, path string, form mediaUploadForm, out any) error {+ attempt := func(token string) error {+ body, size, contentType, err := form.build()+ if err != nil {+ return err+ }+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.resolveBaseURL(creds)+path, body)+ if err != nil {+ return fmt.Errorf("new request: %w", err)+ }+ req.Header.Set("Content-Type", contentType)+ req.ContentLength = size+ req.Header.Set("Authorization", "Bearer "+token)+ uploadCtx, cancel := context.WithTimeout(ctx, c.cfg.ResourceDownloadTimeout)+ defer cancel()+ resp, err := c.cfg.ResourceHTTPClient.Do(req.WithContext(uploadCtx))+ if err != nil {+ return fmt.Errorf("http do: %w", err)+ }+ defer resp.Body.Close()+ rawBody, err := io.ReadAll(io.LimitReader(resp.Body, (64<<10)+1))+ if err != nil {+ return fmt.Errorf("read body: %w", err)+ }+ if len(rawBody) > 64<<10 {+ return errors.New("lark upload response exceeds limit")+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ // Same reasoning as doJSON: Lark reports its business code in+ // the body of a non-2xx reply, so parse it instead of+ // collapsing the response into an opaque transport error.+ code, msg := parseLarkErrorBody(rawBody)+ return &larkAPIStatusError{+ StatusCode: resp.StatusCode,+ Code: code,+ Msg: msg,+ Raw: truncate(string(rawBody), 512),+ }+ }+ code, msg := parseLarkErrorBody(rawBody)+ if code != 0 {+ return &APIError{Op: "upload resource", Code: code, Msg: msg}+ }+ if out != nil && len(rawBody) > 0 {+ if err := json.Unmarshal(rawBody, out); err != nil {+ return fmt.Errorf("decode body: %w (raw=%s)", err, truncate(string(rawBody), 256))+ }+ }+ return nil+ }++ token, err := c.tenantAccessToken(ctx, creds)+ if err != nil {+ return err+ }+ err = attempt(token)+ if !isTokenError(larkErrorCode(err)) {+ return err+ }+ c.cfg.Logger.Warn("lark http client: tenant_access_token rejected on upload; refreshing and retrying once",+ "app_id", creds.AppID, "path", path, "err", err)+ c.invalidateToken(creds.AppID)+ fresh, refreshErr := c.tenantAccessToken(ctx, creds)+ if refreshErr != nil {+ return fmt.Errorf("%w (token refresh failed: %v)", err, refreshErr)+ }+ return attempt(fresh)+}++// UploadImage puts image bytes into Lark's media store and returns the+// image_key the senders consume.+//+// The size ceiling lives here rather than in the caller because the two+// endpoints disagree about it and the caller reasons in "an image" versus+// "a file" — this is the layer that knows which endpoint is which.+func (c *httpAPIClient) UploadImage(ctx context.Context, p UploadImageParams) (string, error) {+ if len(p.Data) == 0 {+ return "", errors.New("lark http client: empty image body")+ }+ if len(p.Data) > larkImageUploadMaxBytes {+ return "", fmt.Errorf("lark http client: image %q is %d bytes, over the %d-byte limit",+ p.Filename, len(p.Data), larkImageUploadMaxBytes)+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ ImageKey string `json:"image_key"`+ } `json:"data"`+ }+ form := mediaUploadForm{+ // image_type=message is the only value that yields a key usable+ // in a chat; avatar keys are refused by the message senders.+ textFields: [][2]string{{"image_type", "message"}},+ fileField: "image",+ filename: filenameOr(p.Filename, "image"),+ data: p.Data,+ }+ if err := c.doAuthedUpload(ctx, p.InstallationID, larkUploadPathImage, form, &resp); err != nil {+ return "", fmt.Errorf("lark http client: upload image: %w", err)+ }+ if resp.Code != 0 || resp.Data.ImageKey == "" {+ return "", &APIError{Op: "upload image", Code: resp.Code, Msg: resp.Msg}+ }+ return resp.Data.ImageKey, nil+}++// UploadFile is UploadImage's non-image sibling: bytes to Lark's file+// endpoint, file_key back.+func (c *httpAPIClient) UploadFile(ctx context.Context, p UploadFileParams) (string, error) {+ if len(p.Data) == 0 {+ return "", errors.New("lark http client: empty file body")+ }+ if len(p.Data) > larkFileUploadMaxBytes {+ return "", fmt.Errorf("lark http client: file %q is %d bytes, over the %d-byte limit",+ p.Filename, len(p.Data), larkFileUploadMaxBytes)+ }+ name := filenameOr(p.Filename, "file")+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ FileKey string `json:"file_key"`+ } `json:"data"`+ }+ form := mediaUploadForm{+ textFields: [][2]string{+ {"file_type", p.FileType},+ {"file_name", name},+ },+ fileField: "file",+ filename: name,+ data: p.Data,+ }+ if err := c.doAuthedUpload(ctx, p.InstallationID, larkUploadPathFile, form, &resp); err != nil {+ return "", fmt.Errorf("lark http client: upload file: %w", err)+ }+ if resp.Code != 0 || resp.Data.FileKey == "" {+ return "", &APIError{Op: "upload file", Code: resp.Code, Msg: resp.Msg}+ }+ return resp.Data.FileKey, nil+}++// SendImageMessage posts an uploaded image as its own message.+func (c *httpAPIClient) SendImageMessage(ctx context.Context, p SendImageParams) (string, error) {+ if p.ChatID == "" {+ return "", errors.New("lark http client: missing chat_id")+ }+ if p.ImageKey == "" {+ return "", errors.New("lark http client: missing image_key")+ }+ content, err := json.Marshal(map[string]string{"image_key": p.ImageKey})+ if err != nil {+ return "", fmt.Errorf("lark http client: encode image content: %w", err)+ }+ return c.sendTypedMessage(ctx, p.InstallationID, p.ChatID, "image", string(content), p.ReplyTarget, p.UUID, "send image message")+}++// SendFileMessage posts an uploaded file as its own message. Lark has no+// way to embed a non-image in an answer, so this is necessarily a second+// message rather than part of the reply.+func (c *httpAPIClient) SendFileMessage(ctx context.Context, p SendFileParams) (string, error) {+ if p.ChatID == "" {+ return "", errors.New("lark http client: missing chat_id")+ }+ if p.FileKey == "" {+ return "", errors.New("lark http client: missing file_key")+ }+ content, err := json.Marshal(map[string]string{"file_key": p.FileKey})+ if err != nil {+ return "", fmt.Errorf("lark http client: encode file content: %w", err)+ }+ msgType := "file"+ switch p.FileType {+ case "mp4":+ msgType = "media"+ case "opus":+ msgType = "audio"+ }+ return c.sendTypedMessage(ctx, p.InstallationID, p.ChatID, msgType, string(content), p.ReplyTarget, p.UUID, "send file message")+}++// sendTypedMessage posts one already-encoded content body and returns+// Lark's message_id.+//+// The three senders above (card / text / markdown) predate it and keep+// their own copies of this envelope; this one exists so the two media+// senders do not add a fourth and fifth.+func (c *httpAPIClient) sendTypedMessage(ctx context.Context, creds InstallationCredentials, chatID ChatID, msgType, content string, target ReplyTarget, idempotencyKey, op string) (string, error) {+ path, body := outboundMessageRequest(chatID, msgType, content, target)+ if len(idempotencyKey) > 50 {+ return "", errors.New("lark message uuid exceeds limit")+ }+ if idempotencyKey != "" {+ body["uuid"] = idempotencyKey+ }+ for attempt := 0; attempt < 2; attempt++ {+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ MessageID string `json:"message_id"`+ } `json:"data"`+ }+ if err := c.doAuthedJSON(ctx, creds, http.MethodPost, path, body, &resp); err != nil {+ return "", fmt.Errorf("lark http client: %s: %w", op, err)+ }+ if isTokenError(resp.Code) && attempt == 0 {+ c.invalidateToken(creds.AppID)+ continue+ }+ if resp.Code != 0 || resp.Data.MessageID == "" {+ if isTokenError(resp.Code) {+ c.invalidateToken(creds.AppID)+ }+ return "", &APIError{Op: op, Code: resp.Code, Msg: resp.Msg}+ }+ return resp.Data.MessageID, nil+ }+ return "", errors.New("lark send authentication retry exhausted")+}++// larkFileTypeFor maps a filename onto Lark's file_type enum: opus, mp4,+// pdf, doc, xls, ppt, stream.+//+// Only extensions that name a kind exactly are mapped, and everything+// else is `stream`. That is deliberate rather than lazy: Lark validates+// the body against the declared type and REFUSES a mismatch instead of+// downgrading it, so a wrong specific type loses the file outright while+// `stream` always sends. We cannot tell from an extension alone whether+// an `.xlsx` is one Lark's `xls` slot will accept, so the honest answer+// is the general one.+func larkFileTypeFor(filename string) string {+ switch strings.ToLower(filepath.Ext(filename)) {+ case ".opus":+ return "opus"+ case ".mp4":+ return "mp4"+ case ".pdf":+ return "pdf"+ case ".doc":+ return "doc"+ case ".xls":+ return "xls"+ case ".ppt":+ return "ppt"+ }+ return "stream"+}++// filenameOr keeps every log line and multipart part named, even for an+// attachment row that arrived without a filename.+func filenameOr(name, fallback string) string {+ name = filepath.Base(strings.ReplaceAll(name, `\`, "/"))+ name = strings.Map(func(r rune) rune {+ if r < 32 || r == 127 {+ return -1+ }+ return r+ }, name)+ if strings.TrimSpace(name) == "" || name == "." || name == "/" {+ return fallback+ }+ return name+}diff --git a/server/internal/integrations/lark/http_client_media_test.go b/server/internal/integrations/lark/http_client_media_test.gonew file mode 100644index 0000000000..137245c1b0--- /dev/null+++ b/server/internal/integrations/lark/http_client_media_test.go@@ -0,0 +1,397 @@+package lark++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++func TestMediaHTTPMultipartAndDedicatedTransport(t *testing.T) {+ for _, image := range []bool{true, false} {+ t.Run(map[bool]string{true: "image", false: "file"}[image], func(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ endpoint, field, key := larkUploadPathFile, "file", "file_key"+ if image {+ endpoint, field, key = larkUploadPathImage, "image", "image_key"+ }+ data := []byte("file bytes\x00with binary")+ f.mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.ContentLength <= int64(len(data)) || r.Header.Get("Authorization") != "Bearer token" {+ t.Errorf("invalid request framing/authentication: %s size=%d", r.Method, r.ContentLength)+ }+ if err := r.ParseMultipartForm(1024); err != nil {+ t.Error(err)+ return+ }+ defer r.MultipartForm.RemoveAll()+ file, header, err := r.FormFile(field)+ if err != nil {+ t.Error(err)+ return+ }+ defer file.Close()+ got, _ := io.ReadAll(file)+ if !bytes.Equal(got, data) || header.Filename != "chart.png" {+ t.Errorf("multipart file mismatch: %q %q", got, header.Filename)+ }+ if image && r.FormValue("image_type") != "message" {+ t.Error("missing image_type")+ }+ if !image && (r.FormValue("file_type") != "stream" || r.FormValue("file_name") != "chart.png") {+ t.Error("missing file metadata")+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{key: "resource-key"}})+ })+ var ordinaryUploads atomic.Int32+ ordinary := &http.Client{Transport: mediaRoundTripper(func(r *http.Request) (*http.Response, error) {+ if r.URL.Path == endpoint {+ ordinaryUploads.Add(1)+ return nil, errors.New("upload used JSON transport")+ }+ return http.DefaultTransport.RoundTrip(r)+ })}+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), HTTPClient: ordinary, ResourceHTTPClient: f.srv.Client()}).(mediaAPIClient)+ var got string+ var err error+ if image {+ got, err = c.UploadImage(context.Background(), UploadImageParams{InstallationID: testCreds(), Filename: "chart.png", Data: data})+ } else {+ got, err = c.UploadFile(context.Background(), UploadFileParams{InstallationID: testCreds(), Filename: "chart.png", FileType: "stream", Data: data})+ }+ if err != nil || got != "resource-key" || ordinaryUploads.Load() != 0 {+ t.Fatalf("upload=%q err=%v ordinary=%d", got, err, ordinaryUploads.Load())+ }+ })+ }+}++func TestMediaHTTPAttachmentUploadAndMessageTypes(t *testing.T) {+ cases := []struct {+ filename string+ contentType string+ data []byte+ uploadType string+ messageType string+ }{+ {"clip.mp4", "video/mp4", []byte("\x00\x00\x00\x18ftypmp42 video bytes"), "mp4", "media"},+ {"voice.opus", "audio/ogg", []byte("OggS\x00OpusHead audio bytes"), "opus", "audio"},+ {"archive.zip", "application/zip", []byte("PK\x03\x04 archive bytes"), "stream", "file"},+ {"report.pdf", "application/pdf", []byte("%PDF-1.4 document bytes"), "pdf", "file"},+ }+ for _, tc := range cases {+ for _, reply := range []bool{false, true} {+ route := "send"+ if reply {+ route = "reply"+ }+ t.Run(tc.filename+"/"+route, func(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ p, q, _ := newMediaTestPatcher(t)+ client := NewHTTPAPIClient(HTTPClientConfig{+ BaseURL: f.URL(), HTTPClient: f.srv.Client(),+ ResourceHTTPClient: f.srv.Client(), Logger: newDiscardLogger(),+ })+ p.client = client+ p.media = client.(mediaAPIClient)+ if !p.SetAttachments(fakeObjectStore{objects: map[string][]byte{tc.filename: tc.data}}) {+ t.Fatal("attachment delivery unavailable")+ }+ target := ReplyTarget{}+ path := "/open-apis/im/v1/messages"+ if reply {+ target = ReplyTarget{MessageID: "om_parent", InThread: true}+ path += "/om_parent/reply"+ }+ resourceKey := "file_uploaded_" + tc.filename+ var uploadType atomic.Value+ var uploads, sends atomic.Int32+ f.mux.HandleFunc(larkUploadPathFile, func(w http.ResponseWriter, r *http.Request) {+ uploads.Add(1)+ if r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer token" {+ t.Errorf("invalid upload method or authorization: %s", r.Method)+ }+ if err := r.ParseMultipartForm(1024); err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ defer r.MultipartForm.RemoveAll()+ file, header, err := r.FormFile("file")+ if err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ defer file.Close()+ data, err := io.ReadAll(file)+ if err != nil || !bytes.Equal(data, tc.data) || header.Filename != tc.filename {+ t.Errorf("uploaded attachment changed: filename=%q data=%q err=%v", header.Filename, data, err)+ }+ gotType := r.FormValue("file_type")+ uploadType.Store(gotType)+ if gotType != tc.uploadType || r.FormValue("file_name") != tc.filename {+ t.Errorf("upload metadata: type=%q name=%q", gotType, r.FormValue("file_name"))+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"file_key": resourceKey}})+ })+ f.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {+ sends.Add(1)+ var body struct {+ ReceiveID string `json:"receive_id"`+ MessageType string `json:"msg_type"`+ Content string `json:"content"`+ ReplyInThread *bool `json:"reply_in_thread"`+ UUID string `json:"uuid"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ w.WriteHeader(http.StatusBadRequest)+ return+ }+ if r.Method != http.MethodPost || r.Header.Get("Authorization") != "Bearer token" || r.URL.Path != path {+ t.Errorf("invalid message request: %s %s", r.Method, r.URL.Path)+ }+ gotUploadType, _ := uploadType.Load().(string)+ if gotUploadType != tc.uploadType || body.MessageType != tc.messageType {+ t.Errorf("uploaded %q must be sent as %q, got upload=%q message=%q", tc.filename, tc.messageType, gotUploadType, body.MessageType)+ w.WriteHeader(http.StatusBadRequest)+ writeJSON(w, map[string]any{"code": 230055, "msg": "The type of file upload does not match the type of message being sent."})+ return+ }+ var content map[string]string+ if err := json.Unmarshal([]byte(body.Content), &content); err != nil || len(content) != 1 || content["file_key"] != resourceKey {+ t.Errorf("message did not use the uploaded file key: content=%v err=%v", content, err)+ }+ if body.UUID != "8b6fcdea-23ae-5401-9eeb-2295f8ac53a5" {+ t.Errorf("attachment UUID is not stable: %q", body.UUID)+ }+ if reply {+ if body.ReceiveID != "" || body.ReplyInThread == nil || !*body.ReplyInThread || r.URL.RawQuery != "" {+ t.Errorf("reply destination changed: receive_id=%q in_thread=%v query=%q", body.ReceiveID, body.ReplyInThread, r.URL.RawQuery)+ }+ } else if body.ReceiveID != q.binding.ChannelChatID || body.ReplyInThread != nil || r.URL.Query().Get("receive_id_type") != "chat_id" {+ t.Errorf("chat destination changed: receive_id=%q in_thread=%v query=%q", body.ReceiveID, body.ReplyInThread, r.URL.RawQuery)+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "om_attachment"}})+ })+ row := fileRow(t, "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb", tc.filename, tc.contentType)+ messageID := uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")+ if err := p.deliverOneAttachment(context.Background(), testCreds(), q.binding, &target, q.installation.WorkspaceID, messageID, row); err != nil {+ t.Fatal(err)+ }+ if uploads.Load() != 1 || sends.Load() != 1 {+ t.Fatalf("expected one upload and one message: uploads=%d sends=%d", uploads.Load(), sends.Load())+ }+ })+ }+ }+}++type mediaRoundTripper func(*http.Request) (*http.Response, error)++func (f mediaRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestMediaHTTPRefreshReplaysMultipart(t *testing.T) {+ for _, status := range []int{http.StatusBadRequest, http.StatusOK} {+ t.Run(http.StatusText(status), func(t *testing.T) {+ f := newLarkFake(t)+ f.mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {+ n := f.tokenN.Add(1)+ token := "old"+ if n > 1 {+ token = "fresh"+ }+ writeJSON(w, map[string]any{"code": 0, "tenant_access_token": token, "expire": 7200})+ })+ var calls atomic.Int32+ f.mux.HandleFunc(larkUploadPathImage, func(w http.ResponseWriter, r *http.Request) {+ if err := r.ParseMultipartForm(1024); err != nil {+ t.Error(err)+ return+ }+ defer r.MultipartForm.RemoveAll()+ file, _, err := r.FormFile("image")+ if err != nil {+ t.Error(err)+ return+ }+ defer file.Close()+ b, _ := io.ReadAll(file)+ if string(b) != "unchanged" {+ t.Errorf("replayed body=%q", b)+ }+ n := calls.Add(1)+ if n == 1 {+ w.WriteHeader(status)+ writeJSON(w, map[string]any{"code": codeTenantTokenInvalid, "msg": "expired"})+ return+ }+ if r.Header.Get("Authorization") != "Bearer fresh" {+ t.Error("token not refreshed")+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"image_key": "fresh-image"}})+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), ResourceHTTPClient: f.srv.Client()}).(mediaAPIClient)+ got, err := c.UploadImage(context.Background(), UploadImageParams{InstallationID: testCreds(), Data: []byte("unchanged")})+ if err != nil || got != "fresh-image" || calls.Load() != 2 || f.tokenN.Load() != 2 {+ t.Fatalf("got=%q err=%v calls=%d tokens=%d", got, err, calls.Load(), f.tokenN.Load())+ }+ })+ }+}++func TestMediaHTTPUploadLimits(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ var calls atomic.Int32+ f.mux.HandleFunc(larkUploadPathImage, func(w http.ResponseWriter, r *http.Request) {+ calls.Add(1)+ _, _ = io.Copy(io.Discard, r.Body)+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"image_key": "key"}})+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), ResourceHTTPClient: f.srv.Client()}).(mediaAPIClient)+ for _, size := range []int{0, larkImageUploadMaxBytes + 1} {+ if _, err := c.UploadImage(context.Background(), UploadImageParams{InstallationID: testCreds(), Data: make([]byte, size)}); err == nil {+ t.Errorf("accepted image size %d", size)+ }+ }+ if _, err := c.UploadFile(context.Background(), UploadFileParams{InstallationID: testCreds(), Data: make([]byte, larkFileUploadMaxBytes+1)}); err == nil {+ t.Error("accepted oversized file")+ }+ if calls.Load() != 0 || f.tokenN.Load() != 0 {+ t.Error("invalid bytes reached transport")+ }+ if _, err := c.UploadImage(context.Background(), UploadImageParams{InstallationID: testCreds(), Data: make([]byte, larkImageUploadMaxBytes)}); err != nil {+ t.Fatal(err)+ }+ if calls.Load() != 1 {+ t.Fatalf("boundary calls=%d", calls.Load())+ }+}++func TestMediaHTTPUploadFailuresAreBounded(t *testing.T) {+ for _, body := range []string{`{"code":0,"data":{}}`, `{"code":234001,"msg":"format rejected"}`, "not-json", strings.Repeat("x", 65<<10)} {+ t.Run(body[:min(len(body), 35)], func(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ var calls atomic.Int32+ f.mux.HandleFunc(larkUploadPathFile, func(w http.ResponseWriter, r *http.Request) { calls.Add(1); _, _ = io.WriteString(w, body) })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), ResourceHTTPClient: f.srv.Client()}).(mediaAPIClient)+ _, err := c.UploadFile(context.Background(), UploadFileParams{InstallationID: testCreds(), FileType: "stream", Data: []byte("x")})+ if err == nil || calls.Load() != 1 {+ t.Fatalf("err=%v calls=%d", err, calls.Load())+ }+ })+ }+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ f.mux.HandleFunc(larkUploadPathImage, func(w http.ResponseWriter, r *http.Request) {+ _, _ = io.Copy(io.Discard, r.Body)+ select {+ case <-r.Context().Done():+ case <-time.After(100 * time.Millisecond):+ }+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), ResourceHTTPClient: f.srv.Client(), ResourceDownloadTimeout: 20 * time.Millisecond}).(mediaAPIClient)+ _, err := c.UploadImage(context.Background(), UploadImageParams{InstallationID: testCreds(), Data: []byte("x")})+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("missing upload deadline: %v", err)+ }+}++func TestMediaHTTPMessageRoutingAndUUID(t *testing.T) {+ for _, image := range []bool{true, false} {+ for _, reply := range []bool{true, false} {+ t.Run(map[bool]string{true: "image", false: "file"}[image]+map[bool]string{true: "-reply", false: "-send"}[reply], func(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ verify := func(r *http.Request, body map[string]any) {+ kind, key := "file", "file_key"+ if image {+ kind, key = "image", "image_key"+ }+ if body["msg_type"] != kind || body["uuid"] != "stable-id" {+ t.Errorf("envelope=%v", body)+ }+ var content map[string]string+ if err := json.Unmarshal([]byte(body["content"].(string)), &content); err != nil || content[key] != "resource" {+ t.Errorf("content=%v err=%v", content, err)+ }+ if reply {+ if body["reply_in_thread"] != true {+ t.Error("thread lost")+ }+ } else if body["receive_id"] != "oc_chat" || r.URL.Query().Get("receive_id_type") != "chat_id" {+ t.Error("chat target lost")+ }+ }+ response := map[string]any{"code": 0, "data": map[string]string{"message_id": "om_result"}}+ if reply {+ f.stubReply(response, func(r *http.Request, id string, b map[string]any) {+ if id != "om_parent" {+ t.Error("wrong parent")+ }+ verify(r, b)+ })+ } else {+ f.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ var b map[string]any+ _ = json.NewDecoder(r.Body).Decode(&b)+ verify(r, b)+ writeJSON(w, response)+ })+ }+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL()}).(mediaAPIClient)+ target := ReplyTarget{}+ if reply {+ target = ReplyTarget{MessageID: "om_parent", InThread: true}+ }+ var got string+ var err error+ if image {+ got, err = c.SendImageMessage(context.Background(), SendImageParams{InstallationID: testCreds(), ChatID: "oc_chat", ImageKey: "resource", ReplyTarget: target, UUID: "stable-id"})+ } else {+ got, err = c.SendFileMessage(context.Background(), SendFileParams{InstallationID: testCreds(), ChatID: "oc_chat", FileKey: "resource", ReplyTarget: target, UUID: "stable-id"})+ }+ if err != nil || got != "om_result" {+ t.Fatalf("got=%q err=%v", got, err)+ }+ })+ }+ }+}++func TestMediaHTTPMessageRefreshesEnvelopeTokenRejection(t *testing.T) {+ f := newLarkFake(t)+ f.stubToken("token", 7200)+ var calls atomic.Int32+ f.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ var body map[string]string+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Error(err)+ return+ }+ if body["uuid"] != "same-send" {+ t.Error("authentication retry changed idempotency key")+ }+ if calls.Add(1) == 1 {+ writeJSON(w, map[string]any{"code": codeTenantTokenInvalid, "msg": "expired"})+ return+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "accepted"}})+ })+ c := NewHTTPAPIClient(HTTPClientConfig{BaseURL: f.URL(), Logger: newDiscardLogger()}).(mediaAPIClient)+ id, err := c.SendFileMessage(context.Background(), SendFileParams{InstallationID: testCreds(), ChatID: "oc_chat", FileKey: "file", UUID: "same-send"})+ if err != nil || id != "accepted" || calls.Load() != 2 || f.tokenN.Load() != 2 {+ t.Fatalf("id=%q err=%v calls=%d tokens=%d", id, err, calls.Load(), f.tokenN.Load())+ }+}diff --git a/server/internal/integrations/lark/markdown_images.go b/server/internal/integrations/lark/markdown_images.gonew file mode 100644index 0000000000..337f28be48--- /dev/null+++ b/server/internal/integrations/lark/markdown_images.go@@ -0,0 +1,37 @@+package lark++import (+ "strings"++ "github.com/yuin/goldmark"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/text"+)++// Feishu interprets Markdown image destinations as uploaded image keys, not+// URLs. Initially keep agent images as ordinary links; bound uploaded images+// can subsequently replace them in this same card. Parsing avoids rewriting code,+// escaped examples, nested labels, or reference definitions by guesswork.+func markdownImageLinks(markdown string) string {+ source := []byte(markdown)+ doc := goldmark.DefaultParser().Parse(text.NewReader(source))+ var out strings.Builder+ last := 0+ _ = ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {+ image, ok := node.(*ast.Image)+ if !ok || !entering {+ return ast.WalkContinue, nil+ }+ pos := image.Pos()+ if pos >= last && pos+1 < len(source) && source[pos] == '!' && source[pos+1] == '[' {+ out.Write(source[last:pos])+ last = pos + 1+ }+ return ast.WalkContinue, nil+ })+ if last == 0 {+ return markdown+ }+ out.Write(source[last:])+ return out.String()+}diff --git a/server/internal/integrations/lark/markdown_images_test.go b/server/internal/integrations/lark/markdown_images_test.gonew file mode 100644index 0000000000..ad582e127c--- /dev/null+++ b/server/internal/integrations/lark/markdown_images_test.go@@ -0,0 +1,51 @@+package lark++import (+ "context"+ "encoding/json"+ "net/http"+ "testing"+ "time"+)++func TestMarkdownImageLinks(t *testing.T) {+ for _, tc := range []struct{ name, input, want string }{+ {"artifact", "已交付\n", "已交付\n[图片](https://multica.example/api/attachments/id/download)"},+ {"title and parentheses", `![a [b]](<https://example/a(b).png> "title")`, `[a [b]](<https://example/a(b).png> "title")`},+ {"multiple", " ", "[一](a) [二](b)"},+ {"reference", "![a][ref]\n\n[ref]: https://example/image.png", "[a][ref]\n\n[ref]: https://example/image.png"},+ {"nested", "](a)", "[outer [inner](b)](a)"},+ {"code", "``\n\n```md\n\n```", "``\n\n```md\n\n```"},+ {"escaped", `\ [link](b)`, `\ [link](b)`},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := markdownImageLinks(tc.input); got != tc.want {+ t.Fatalf("got %q; want %q", got, tc.want)+ }+ })+ }+}++func TestHTTPClient_MarkdownArtifactImageBecomesLink(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("test-token", 7200)+ fake.stubSend(map[string]any{"code": 0, "data": map[string]string{"message_id": "om_card"}}, func(r *http.Request, body map[string]string) {+ var card struct {+ Body struct {+ Elements []struct{ Content string }+ }+ }+ if err := json.Unmarshal([]byte(body["content"]), &card); err != nil {+ t.Fatal(err)+ }+ if len(card.Body.Elements) != 1 || card.Body.Elements[0].Content != "[图片](https://multica.example/api/attachments/id/download)" {+ t.Fatalf("card contains invalid image key syntax: %+v", card)+ }+ })+ _, err := newTestClient(fake, time.Now).SendMarkdownCard(context.Background(), SendMarkdownCardParams{+ InstallationID: testCreds(), ChatID: "oc_test", Markdown: "",+ })+ if err != nil {+ t.Fatal(err)+ }+}diff --git a/server/internal/integrations/lark/mixed_media.go b/server/internal/integrations/lark/mixed_media.gonew file mode 100644index 0000000000..b0e261ed75--- /dev/null+++ b/server/internal/integrations/lark/mixed_media.go@@ -0,0 +1,161 @@+package lark++import (+ "context"+ "errors"+ "strings"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/yuin/goldmark/ast"+ "github.com/yuin/goldmark/parser"+ "github.com/yuin/goldmark/text"+ goldmarkutil "github.com/yuin/goldmark/util"+)++type mediaReplyCardContextKey struct{}+type uploadedCardImage struct{ id, url, name, key string }+type mediaReplyCard struct {+ messageID, markdown string+ images []uploadedCardImage+}++func (p *Patcher) replyNeedsMediaCard(ctx context.Context, workspaceID pgtype.UUID, payload any) bool {+ if p.objects == nil || p.media == nil {+ return false+ }+ id, err := util.ParseUUID(chatDoneMessageID(payload))+ if err != nil || !id.Valid {+ return false+ }+ select {+ case p.mediaAdmission <- struct{}{}:+ defer func() { <-p.mediaAdmission }()+ default:+ return true // Keep the reply updatable without adding another lookup.+ }+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ rows, err := p.queries.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{ChatMessageID: id, WorkspaceID: workspaceID})+ if err != nil {+ return true+ }+ for _, row := range rows {+ if isImageAttachment(row.ContentType, row.Filename) {+ return true+ }+ }+ return false+}++func (p *Patcher) patchMediaReplyCard(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, workspaceID pgtype.UUID, card *mediaReplyCard, row db.Attachment, key string) error {+ if len(key) <= len("img_") || !strings.HasPrefix(key, "img_") || strings.Trim(key, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-") != "" {+ return errors.New("invalid uploaded image key")+ }+ images := append(append([]uploadedCardImage(nil), card.images...), uploadedCardImage{uuidString(row.ID), row.Url, row.Filename, key})+ body, err := markdownCardJSON(mixedMediaMarkdown(card.markdown, images), "")+ if err != nil {+ return err+ }+ uncertain := false+ for attempt := 0; attempt < 2; attempt++ {+ current, guardErr := p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if guardErr != nil {+ err = guardErr+ break+ }+ callCtx, cancel := context.WithTimeout(ctx, defaultRequestTimeout)+ err = p.client.PatchInteractiveCard(callCtx, PatchCardParams{InstallationID: current, LarkCardMessageID: card.messageID, CardJSON: body})+ cancel()+ if err == nil {+ card.images = images+ return nil+ }+ if definiteMediaRefusal(err) {+ break+ }+ uncertain = true+ if ctx.Err() != nil {+ break+ }+ }+ if uncertain {+ // A later absolute update must not remove an image whose receipt was lost.+ card.images = images+ return &mediaSendUnconfirmed{err: err}+ }+ return err+}++// Record the source span using Goldmark's own link parser, including reference+// syntax, nested labels and titles. Never scan Markdown delimiters by regex.+type imageSpanParser struct{ parser.InlineParser }++func (p imageSpanParser) Parse(parent ast.Node, reader text.Reader, pc parser.Context) ast.Node {+ n := p.InlineParser.Parse(parent, reader, pc)+ if image, ok := n.(*ast.Image); ok {+ _, end := reader.Position()+ image.SetAttributeString("source_end", end.Start)+ }+ return n+}+func (p imageSpanParser) CloseBlock(parent ast.Node, reader text.Reader, pc parser.Context) {+ p.InlineParser.(parser.CloseBlocker).CloseBlock(parent, reader, pc)+}++func mixedMediaMarkdown(markdown string, images []uploadedCardImage) string {+ inlines := parser.DefaultInlineParsers()+ inlines[1].Value = imageSpanParser{parser.NewLinkParser()}+ p := parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...), parser.WithInlineParsers(inlines...), parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...))+ source := []byte(markdown)+ doc := p.Parse(text.NewReader(source))+ var out strings.Builder+ last := 0+ used := map[string]bool{}+ writeImage := func(label, key string) {+ label = strings.NewReplacer("\\", "\\\\", "[", "\\[", "]", "\\]", "\n", " ", "\r", " ").Replace(label)+ out.WriteString("")+ }+ _ = ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {+ image, ok := n.(*ast.Image)+ if !ok || !entering {+ return ast.WalkContinue, nil+ }+ pos := image.Pos()+ if pos < last || pos+1 >= len(source) || source[pos] != '!' || source[pos+1] != '[' {+ return ast.WalkContinue, nil+ }+ // Resolve Markdown escapes once, using the same rules as Goldmark's renderer.+ destination := string(goldmarkutil.URLEscape(image.Destination, true))+ id, _ := util.AttachmentIDFromDownloadURL(destination)+ for _, uploaded := range images {+ if destination != uploaded.url && (id == "" || id != uploaded.id) {+ continue+ }+ endValue, ok := image.AttributeString("source_end")+ end, valid := endValue.(int)+ if !ok || !valid || end <= pos || end > len(source) {+ break+ }+ out.Write(source[last:pos])+ writeImage(string(image.Text(source)), uploaded.key)+ last = end+ used[uploaded.id] = true+ return ast.WalkSkipChildren, nil+ }+ // Unknown URLs remain links, including URLs that merely look like keys.+ out.Write(source[last:pos])+ last = pos + 1+ return ast.WalkContinue, nil+ })+ out.Write(source[last:])+ for _, image := range images {+ if !used[image.id] {+ out.WriteString("\n\n")+ writeImage(image.name, image.key)+ }+ }+ return out.String()+}diff --git a/server/internal/integrations/lark/mixed_media_test.go b/server/internal/integrations/lark/mixed_media_test.gonew file mode 100644index 0000000000..8910b029b7--- /dev/null+++ b/server/internal/integrations/lark/mixed_media_test.go@@ -0,0 +1,290 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "strings"+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type controlledCardClient struct {+ *fakeMediaAPIClient+ patch func(context.Context, PatchCardParams) error+}++type metadataCallbackQueries struct {+ *fakePatcherQueries+ afterLookup func()+}++func (q metadataCallbackQueries) ListAttachmentsByChatMessage(ctx context.Context, params db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ rows, err := q.fakePatcherQueries.ListAttachmentsByChatMessage(ctx, params)+ q.afterLookup()+ return rows, err+}++func (c controlledCardClient) PatchInteractiveCard(ctx context.Context, p PatchCardParams) error {+ _ = c.fakeMediaAPIClient.PatchInteractiveCard(ctx, p)+ return c.patch(ctx, p)+}++func TestChatReplyMixedMedia(t *testing.T) {+ t.Run("authority changes during metadata lookup", func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.spawn = func(f func()) { f() }+ p.SetAttachments(fakeObjectStore{})+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ p.queries = metadataCallbackQueries{fakePatcherQueries: q, afterLookup: func() { q.installation.Status = "disabled" }}+ err := p.sendChatReply(context.Background(), testCreds(), q.binding, "", q.installation.WorkspaceID, protocol.ChatDonePayload{MessageID: "dddd4444-dddd-dddd-dddd-dddddddddddd", TaskID: "ee777777-ee77-ee77-ee77-eeeeeeeeeeee", Content: "Here is the chart."})+ if err == nil || len(api.mdCardSent) != 0 || len(api.textSent) != 0 || len(api.images) != 0 {+ t.Fatal("reply used authority revoked during metadata lookup")+ }+ })+ for _, tc := range []struct{ name, content string }{+ {"plain text", "Here is the chart."},+ {"image between paragraphs", "Before\n\n\n\nAfter"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ api.mdCardReturn = "om_answer"+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes, "notes.txt": []byte("notes")}})+ q.attachments = []db.Attachment{+ imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png"),+ fileRow(t, "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "notes.txt", "text/plain"),+ }+ payload := protocol.ChatDonePayload{MessageID: "dddd4444-dddd-dddd-dddd-dddddddddddd", TaskID: "ee777777-ee77-ee77-ee77-eeeeeeeeeeee", Content: tc.content}+ var worker func()+ p.spawn = func(f func()) { worker = f }+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ if err := p.sendChatReply(ctx, testCreds(), q.binding, "", q.installation.WorkspaceID, payload); err != nil {+ t.Fatal(err)+ }+ if len(api.mdCardSent) != 1 || len(api.images) != 0 || worker == nil {+ t.Fatalf("text card must precede background uploads: cards=%d uploads=%d worker=%v", len(api.mdCardSent), len(api.images), worker != nil)+ }+ cancel() // The event publisher may finish before background uploads.+ worker()+ if len(api.patched) != 1 || api.patched[0].LarkCardMessageID != "om_answer" || len(api.imagesOut) != 0 || len(api.filesOut) != 1 {+ t.Fatalf("image must update the answer while file is separate: patches=%+v images=%d files=%d", api.patched, len(api.imagesOut), len(api.filesOut))+ }+ var card struct {+ Config struct {+ UpdateMulti bool `json:"update_multi"`+ }+ Body struct{ Elements []struct{ Content string } }+ }+ if err := json.Unmarshal([]byte(api.patched[0].CardJSON), &card); err != nil {+ t.Fatal(err)+ }+ if !card.Config.UpdateMulti || len(card.Body.Elements) != 1 {+ t.Fatalf("invalid shared card: %+v", card)+ }+ body := card.Body.Elements[0].Content+ if !strings.Contains(body, "") && !strings.Contains(body, "") {+ t.Fatalf("missing uploaded image key: %q", body)+ }+ if tc.name == "image between paragraphs" && body != "Before\n\n\n\nAfter" {+ t.Fatalf("image moved within answer: %q", body)+ }+ if err := p.sendChatReply(context.Background(), testCreds(), q.binding, "", q.installation.WorkspaceID, payload); err != nil {+ t.Fatal(err)+ }+ if len(api.mdCardSent) != 1 || len(api.patched) != 1 || len(api.images) != 1 || len(api.filesOut) != 1 {+ t.Fatal("duplicate completion repeated mixed reply")+ }+ })+ }+}++func TestPatchMediaReplyCard(t *testing.T) {+ for _, scenario := range []string{"success", "lost response then success", "lost responses", "refused", "lost response then refused", "revoked after first attempt", "unsafe key", "empty key", "empty key suffix"} {+ t.Run(scenario, func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ calls := 0+ p.client = controlledCardClient{fakeMediaAPIClient: api, patch: func(context.Context, PatchCardParams) error {+ calls+++ switch scenario {+ case "lost response then success":+ if calls == 2 {+ return nil+ }+ case "success":+ return nil+ case "refused":+ return &APIError{Code: 230002}+ case "lost response then refused":+ if calls == 2 {+ return &APIError{Code: 230002}+ }+ case "revoked after first attempt":+ q.installation.Status = "disabled"+ }+ return errors.New("response lost")+ }}+ card := &mediaReplyCard{messageID: "om_original", markdown: "**before**\n\nAfter"}+ key := "img_fake"+ if scenario == "unsafe key" {+ key = "img_fake)\n, testCreds(), q.binding, q.installation.WorkspaceID, card, imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png"), key)+ var unknown *mediaSendUnconfirmed+ wantUnknown := strings.HasPrefix(scenario, "lost response") && scenario != "lost response then success" || scenario == "revoked after first attempt"+ if errors.As(err, &unknown) != wantUnknown {+ t.Fatalf("wrong receipt classification: %v", err)+ }+ wantCalls := 2+ if scenario == "success" || scenario == "refused" || scenario == "revoked after first attempt" {+ wantCalls = 1+ }+ if scenario == "unsafe key" || strings.HasPrefix(scenario, "empty key") {+ wantCalls = 0+ }+ if calls != wantCalls {+ t.Fatalf("patch attempts=%d; want %d", calls, wantCalls)+ }+ if (err == nil) != (scenario == "success" || scenario == "lost response then success") {+ t.Fatalf("wrong outcome: %v", err)+ }+ for _, patch := range api.patched {+ if patch.LarkCardMessageID != "om_original" || patch.CardJSON != api.patched[0].CardJSON {+ t.Fatal("retry changed target or absolute card body")+ }+ }+ if len(api.imagesOut) != 0 || len(api.sent) != 0 || len(api.mdCardSent) != 0 {+ t.Fatal("card update escaped into a separate message")+ }+ if (len(card.images) == 1) != (err == nil || wantUnknown) {+ t.Fatal("later update would lose an accepted or uncertain image")+ }+ })+ }++ t.Run("all images accumulate without moving paragraphs", func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ card := &mediaReplyCard{messageID: "om_original", markdown: "Before\n\n\n\nBetween\n\n\n\nAfter"}+ for i, name := range []string{"first.png", "second.png"} {+ row := imageRow(t, []string{"aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb"}[i], name)+ if err := p.patchMediaReplyCard(context.Background(), testCreds(), q.binding, q.installation.WorkspaceID, card, row, []string{"img_first", "img_second"}[i]); err != nil {+ t.Fatal(err)+ }+ }+ var got struct {+ Body struct{ Elements []struct{ Content string } }+ }+ if err := json.Unmarshal([]byte(api.patched[1].CardJSON), &got); err != nil {+ t.Fatal(err)+ }+ if got.Body.Elements[0].Content != "Before\n\n\n\nBetween\n\n\n\nAfter" {+ t.Fatalf("image ordering lost: %+v", got)+ }+ })+}++func TestMixedMediaMarkdown(t *testing.T) {+ image := uploadedCardImage{id: "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", url: "https://cdn.example/chart.png", name: "chart.png", key: "img_real"}+ for _, tc := range []struct{ name, input, want string }{+ {"inline title and nested label", `Before ![a [b]](<https://cdn.example/chart.png> "title") After`, `Before ![a \[b\]](img_real) After`},+ {"reference", "Before\n\n![chart][ref]\n\nAfter\n\n[ref]: https://cdn.example/chart.png", "Before\n\n\n\nAfter\n\n[ref]: https://cdn.example/chart.png"},+ {"collapsed reference", "![chart][]\n\n[chart]: https://cdn.example/chart.png", "\n\n[chart]: https://cdn.example/chart.png"},+ {"shortcut reference", "![chart]\n\n[chart]: https://cdn.example/chart.png", "\n\n[chart]: https://cdn.example/chart.png"},+ {"escaped inline attachment path", `Before  After`, `Before  After`},+ {"escaped reference attachment path", "Before ![chart][ref] After\n\n[ref]: " + `\/api\/attachments\/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa\/download`, "Before  After\n\n[ref]: " + `\/api\/attachments\/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa\/download`},+ {"escaped inline absolute url", `Before  After`, `Before  After`},+ {"escaped reference absolute url", "Before ![chart][ref] After\n\n[ref]: " + `https\:\/\/cdn\.example\/chart\.png`, "Before  After\n\n[ref]: " + `https\:\/\/cdn\.example\/chart\.png`},+ {"named entity inline absolute url", `Before  After`, `Before  After`},+ {"numeric entity reference attachment path", "Before ![chart][ref] After\n\n[ref]: /api/attachments/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa/download", "Before  After\n\n[ref]: /api/attachments/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa/download"},+ {"entity is not decoded twice", "Before  After", "Before [other](&sol;api/attachments/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa/download) After\n\n"},+ {"numeric entity is not decoded twice", "Before  After", "Before [other](&#47;api/attachments/aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa/download) After\n\n"},+ {"percent encoding is not decoded twice", "Before  After", "Before [other](%252Fapi%252Fattachments%252Faaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa%252Fdownload) After\n\n"},+ {"escaped unbound attachment", `Before  After`, "Before [other](\\/api\\/attachments\\/bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb\\/download) After\n\n"},+ {"entities cannot authorize urls or keys", " ", "[external](https://evil.example/x) [key](img_fake)\n\n"},+ {"escaped destinations in code and escaped image syntax", "``\n\n```md\n\n```\n\\", "``\n\n```md\n\n```\n\\\n\n"},+ {"unknown urls and fake keys", " ", "[external](https://evil.example/x) [key](img_fake)\n\n"},+ {"code and escapes", "``\n\n```md\n\n```\n\\", "``\n\n```md\n\n```\n\\\n\n"},+ {"unbound attachment", "", "[other](/api/attachments/bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb/download)\n\n"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := mixedMediaMarkdown(tc.input, []uploadedCardImage{image}); got != tc.want {+ t.Fatalf("got %q; want %q", got, tc.want)+ }+ })+ }+ t.Run("query entity in an exact storage url", func(t *testing.T) {+ image.url = "https://cdn.example/chart.png?width=100&height=200"+ for _, tc := range []struct{ name, input, want string }{+ {"inline", "Before  After", "Before  After"},+ {"reference", "Before ![chart][ref] After\n\n[ref]: https://cdn.example/chart.png?width=100&height=200", "Before  After\n\n[ref]: https://cdn.example/chart.png?width=100&height=200"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := mixedMediaMarkdown(tc.input, []uploadedCardImage{image}); got != tc.want {+ t.Fatalf("got %q; want %q", got, tc.want)+ }+ })+ }+ })+}++func TestReplyNeedsMediaCard(t *testing.T) {+ for _, scenario := range []string{"plain", "file", "image", "unavailable metadata", "lookup admission full", "storage absent", "invalid message"} {+ t.Run(scenario, func(t *testing.T) {+ p, q, _ := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{})+ messageID := "dddd4444-dddd-dddd-dddd-dddddddddddd"+ switch scenario {+ case "file":+ q.attachments = []db.Attachment{fileRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "report.txt", "text/plain")}+ case "image":+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ case "unavailable metadata":+ q.attachmentsErr = errors.New("database unavailable")+ case "lookup admission full":+ for i := 0; i < cap(p.mediaAdmission); i++ {+ p.mediaAdmission <- struct{}{}+ }+ case "storage absent":+ p.SetAttachments(nil)+ case "invalid message":+ messageID = "invalid"+ }+ want := scenario == "image" || scenario == "unavailable metadata" || scenario == "lookup admission full"+ if got := p.replyNeedsMediaCard(context.Background(), q.installation.WorkspaceID, protocol.ChatDonePayload{MessageID: messageID}); got != want {+ t.Fatalf("got %v; want %v", got, want)+ }+ })+ }+}++func TestChatReplyMixedMediaFailure(t *testing.T) {+ for _, uncertain := range []bool{false, true} {+ t.Run(map[bool]string{false: "card refused", true: "card response lost"}[uncertain], func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.spawn = func(f func()) { f() }+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes, "notes.txt": []byte("notes")}})+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png"), fileRow(t, "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "notes.txt", "text/plain")}+ api.patchErr = &APIError{Code: 230099, Msg: "card refused"}+ wantNotice, wantPatches := mediaSendFailedText, 1+ if uncertain {+ api.patchErr = errors.New("patch response lost")+ wantNotice, wantPatches = mediaSendUnknownText, 2+ }+ payload := protocol.ChatDonePayload{MessageID: "dddd4444-dddd-dddd-dddd-dddddddddddd", TaskID: "ee777777-ee77-ee77-ee77-eeeeeeeeeeee", Content: "**Here is the chart.**"}+ if err := p.sendChatReply(context.Background(), testCreds(), q.binding, "", q.installation.WorkspaceID, payload); err != nil {+ t.Fatal(err)+ }+ if len(api.mdCardSent) != 1 || len(api.patched) != wantPatches || len(api.imagesOut) != 0 || len(api.filesOut) != 1 || len(api.textSent) != 1 || api.textSent[0].Text != wantNotice {+ t.Fatalf("mixed failure lost text/file or escaped into another image: cards=%d patches=%d images=%d files=%d notices=%+v", len(api.mdCardSent), len(api.patched), len(api.imagesOut), len(api.filesOut), api.textSent)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.goindex 3cf15dfba1..78b4fbd368 100644--- a/server/internal/integrations/lark/outbound.go+++ b/server/internal/integrations/lark/outbound.go@@ -143,6 +143,7 @@ func (defaultRenderer) Render(in RenderInput) (CardRender, error) {// needs. Declared as an interface so the patcher is unit-testable// without a real Postgres connection.type PatcherQueries interface {+ mediaDeliveryQueriesGetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)@@ -153,6 +154,13 @@ type PatcherQueries interface {GetLarkOutboundCardByTask(ctx context.Context, taskID pgtype.UUID) (OutboundCardMessage, error)CreateLarkOutboundCardMessage(ctx context.Context, arg CreateOutboundCardMessageParams) (OutboundCardMessage, error)UpdateLarkOutboundCardStatus(ctx context.Context, arg UpdateOutboundCardStatusParams) error+ // ListAttachmentsByChatMessage reads the files an agent bound to one+ // assistant message at task completion. Taken with the generated db+ // params rather than a domain type because ChannelStore embeds+ // *db.Queries and therefore already satisfies it — this list is the+ // one seam where the narrow interface would cost a hand-written+ // adapter for no gain. See outbound_media.go for the caller.+ ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)}// CredentialsResolver decrypts an installation's app_secret for the@@ -213,19 +221,48 @@ type Patcher struct {credentials CredentialsResolverclient APIClienttypingIndicator *TypingIndicatorManager- cfg PatcherConfig+ // media is the same client as `client`, narrowed to the four+ // upload/send methods the attachment hop needs. It is nil for any+ // APIClient that does not implement them (the stub, the test+ // fakes), which is how "attachments are not deliverable in this+ // deployment" is expressed — see outbound_media.go.+ media mediaAPIClient+ // objects is the deployment's object store, or nil when this+ // deployment configured none. Set via SetAttachments. Both it and+ // media must be non-nil before a file can be delivered.+ objects mediaObjectStore+ mediaAdmission chan struct{}+ mediaPending chan struct{}+ // mediaSlots bounds concurrent transfers. Per-patcher, like the two+ // admission tiers above, so all three limits share one scope.+ mediaSlots chan struct{}+ mediaBudget time.Duration+ spawn func(func())+ cfg PatcherConfig}// NewPatcher constructs a Patcher bound to its dependencies. The// patcher does not subscribe to the bus until Register is called.func NewPatcher(queries PatcherQueries, credentials CredentialsResolver, client APIClient, cfg PatcherConfig) *Patcher {cfg = cfg.withDefaults()- return &Patcher{- queries: queries,- credentials: credentials,- client: client,- cfg: cfg,- }+ p := &Patcher{+ queries: queries,+ credentials: credentials,+ client: client,+ cfg: cfg,+ mediaAdmission: make(chan struct{}, maxAdmittedAttachmentDeliveries),+ mediaPending: make(chan struct{}, maxPendingAttachmentDeliveries),+ mediaSlots: make(chan struct{}, maxConcurrentAttachmentDeliveries),+ mediaBudget: attachmentBudget,+ spawn: func(f func()) { go f() },+ }+ // A type assertion rather than a fifth constructor argument: the+ // media methods are an optional capability of the transport, and+ // the fakes that do not have them must keep compiling.+ if m, ok := client.(mediaAPIClient); ok {+ p.media = m+ }+ return p}// SetTypingIndicatorManager wires the typing-indicator manager into the@@ -301,7 +338,8 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {return nil}binding := ChatSessionBinding{- ID: delivery.BindingID, InstallationID: delivery.InstallationID,+ ChatSessionID: chatSessionID,+ ID: delivery.BindingID, InstallationID: delivery.InstallationID,ChannelChatID: delivery.ChannelChatID, ChatType: delivery.ChatType, Config: delivery.Config,LastMessageID: delivery.ChannelMessageID, LastThreadID: delivery.ChannelThreadID,LastSenderID: delivery.ChannelSenderID,@@ -346,7 +384,7 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {switch e.Type {case protocol.EventChatDone:- return p.sendChatReply(ctx, creds, binding, mentionOpenID(binding), e.Payload)+ return p.sendChatReply(ctx, creds, binding, mentionOpenID(binding), inst.WorkspaceID, e.Payload)case protocol.EventTaskFailed:return p.fail(ctx, creds, binding, taskID, agentName, e.Payload)}@@ -436,34 +474,32 @@ func mentionOpenID(binding ChatSessionBinding) string {// The wire shape is chosen per-reply based on whether the body// contains any markdown syntax://-// - Plain prose (no markdown) → `msg_type=text`. A one-line "Hi!"+// - Plain prose without bound images → `msg_type=text`. A one-line "Hi!"// reply should feel like a normal IM message, not a notification// card with chrome around it.//-// - Anything with markdown (headings, lists, code blocks, tables,+// - Bound images or markdown (headings, lists, code blocks, tables,// bold/italic, links) → schema-2.0 interactive card with a-// `tag: "markdown"` body element so Lark's client renders the+// `tag: "markdown"` body element; uploaded images update this same+// card at their Markdown positions. Lark's client renders the// formatting instead of leaving raw `**bold**` characters in// the transcript. The card is visually subtler than the legacy// binding-prompt template — just a single markdown block, no// header / icon / CTA buttons.//-// Empty content is silently dropped: we'd rather show nothing than-// "Done." (the prior card fallback that confused Bohan in the live-// dev env). In practice an empty Content means the daemon completed-// the task without producing visible output, which only happens for-// edge cases like a chat task that just acknowledged a system event;-// not emitting a message there is the right product call.+// Empty content skips the REPLY, not the delivery. An agent that produced+// only files writes a real 'message' outcome with empty text — task.go's+// pendingAttachments branch exists precisely for that shape, "the+// attachment cards ARE the response". Returning before the attachment hop+// would make the one case where the files are the whole answer the one case+// the user hears nothing at all.//// mentionOpenID, when non-empty, prefixes the body with a native mention of// that member (see mention.go). The wire shape is chosen from the agent's own// content BEFORE the mention is attached, so a mention can never flip a plain// prose answer onto the card path.-func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, mentionOpenID string, payload any) error {+func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, mentionOpenID string, workspaceID pgtype.UUID, payload any) error {content := chatDoneContent(payload)- if content == "" {- return nil- }if topicSendWithoutTrigger(binding) {p.cfg.Logger.Warn("lark: no trigger for a topic-isolated session; skipping reply rather than posting it to the parent group","chat_session_id", uuidString(binding.ChatSessionID),@@ -471,28 +507,104 @@ func (p *Patcher) sendChatReply(ctx context.Context, creds InstallationCredentiareturn nil}target := threadReplyTarget(binding)- if containsMarkdown(content) {- markdown := prependMarkdownMention(mentionOpenID, content)- return sendWithReplyFallback(p.cfg.Logger, "send markdown card", target, func(t ReplyTarget) error {- _, err := p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{+ // Own the complete reply before any external write. The background file+ // worker inherits this lease; duplicate events cannot repeat the text while+ // waiting for the files or after the provider's UUID window has expired.+ handedOff := false+ if p.objects != nil && p.media != nil && chatDoneMessageID(payload) != "" {+ taskID, err := util.ParseUUID(chatDoneTaskID(payload))+ if err != nil || !taskID.Valid {+ return errors.New("lark reply missing task identity")+ }+ var finish func()+ var acquired bool+ ctx, finish, acquired = p.claimMediaDelivery(ctx, taskID, binding)+ if !acquired {+ return nil+ }+ defer func() {+ if !handedOff {+ finish()+ }+ }()+ ctx = context.WithValue(ctx, mediaWorkspaceContextKey{}, workspaceID)+ if !p.markMediaSending(ctx) {+ p.tellUser(ctx, creds, binding, target, mediaSendUnknownText)+ return nil+ }+ if _, err := p.currentMediaCredentials(ctx, creds, binding, workspaceID); err != nil {+ return err+ }+ }+ if content == "" {+ // Nothing to say, but there may be something to show. The+ // delivery path no-ops on its own when the reply carried no+ // files, so this costs one lookup and never a stray message.+ handedOff = p.deliverAttachmentsAsync(ctx, creds, binding, target, workspaceID, payload)+ return nil+ }+ // A plain answer with bound images also needs an updatable card. The+ // bounded metadata probe does not read bytes or wait for an upload.+ markdown := containsMarkdown(content) || p.replyNeedsMediaCard(ctx, workspaceID, payload)++ // used records the target the send actually went out on. The whole+ // point of sendWithReplyFallback is that it may retry without+ // threading, and files must land in the same conversation the answer+ // landed in — not in the topic the answer was bounced out of.+ var used ReplyTarget+ var cardID string+ send := func(t ReplyTarget) error {+ if _, owned := ctx.Value(mediaDeliveryContextKey{}).(*mediaDeliveryOwner); owned {+ // Metadata lookup and reply fallback can outlive a revocation or+ // takeover. Re-prove authority immediately before each send.+ current, err := p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if err != nil {+ return err+ }+ creds = current+ }+ used = t+ if markdown {+ var err error+ cardID, err = p.client.SendMarkdownCard(ctx, SendMarkdownCardParams{InstallationID: creds,ChatID: outboundChatID(binding),- Markdown: markdown,+ Markdown: prependMarkdownMention(mentionOpenID, content),ReplyTarget: t,})return err- })- }- text := prependTextMention(mentionOpenID, content)- return sendWithReplyFallback(p.cfg.Logger, "send text message", target, func(t ReplyTarget) error {+ }_, err := p.client.SendTextMessage(ctx, SendTextParams{InstallationID: creds,ChatID: outboundChatID(binding),- Text: text,+ Text: prependTextMention(mentionOpenID, content),ReplyTarget: t,})return err- })+ }+ op := "send text message"+ if markdown {+ op = "send markdown card"+ }+ if err := sendWithReplyFallback(p.cfg.Logger, op, target, send); err != nil {+ return err+ }+ if markdown && p.objects != nil && p.media != nil {+ if cardID == "" {+ return errors.New("lark reply card identity unconfirmed")+ }+ ctx = context.WithValue(ctx, mediaReplyCardContextKey{}, &mediaReplyCard{+ messageID: cardID, markdown: prependMarkdownMention(mentionOpenID, content),+ })+ }++ // The answer is out; the files are the second hop. Spawned rather+ // than awaited because this runs on the synchronous publish+ // goroutine — see outbound_media.go for why the answer must never+ // wait behind an upload. Best-effort by construction: the reply is+ // already delivered, so nothing here can fail the reply.+ handedOff = p.deliverAttachmentsAsync(ctx, creds, binding, used, workspaceID, payload)+ return nil}// outboundChatID recovers the real Lark chat id from the chat binding. The@@ -605,6 +717,12 @@ func sendWithReplyFallback(log *slog.Logger, op string, target ReplyTarget, sendif err == nil {return nil}+ // A later explicit refusal cannot disprove an earlier accepted send whose+ // response was lost. Never move that uncertain reply to a new destination.+ var uncertain *mediaSendUnconfirmed+ if errors.As(err, &uncertain) {+ return fmt.Errorf("%s: %w", op, err)+ }if target.IsSet() && isThreadReplyUnsupported(err) {log.Warn("lark: reply target unusable, retrying at chat level","op", op, "reply_message_id", target.MessageID, "in_thread", target.InThread, "error", err)diff --git a/server/internal/integrations/lark/outbound_media.go b/server/internal/integrations/lark/outbound_media.gonew file mode 100644index 0000000000..5ce52cd5f7--- /dev/null+++ b/server/internal/integrations/lark/outbound_media.go@@ -0,0 +1,332 @@+package lark++import (+ "context"+ "errors"+ "io"+ "path/filepath"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Based on multica-ai/multica#8332, commit 95756b4f0f98d620278619029fae863fa90bc680.+// Text is delivered first, then uploaded images update that same card; files+// are separate messages. Only server-bound attachments are read; response+// Markdown and provider URLs are never treated as authority to fetch a file.+type mediaAPIClient interface {+ UploadImage(context.Context, UploadImageParams) (string, error)+ UploadFile(context.Context, UploadFileParams) (string, error)+ SendImageMessage(context.Context, SendImageParams) (string, error)+ SendFileMessage(context.Context, SendFileParams) (string, error)+}+type mediaObjectStore interface {+ KeyFromURL(string) string+ GetReader(context.Context, string) (io.ReadCloser, error)+}++const (+ mediaSendFailedText = "部分附件未能发送到飞书,仍保留在 Multica 的这条回复中。"+ mediaSendUnknownText = "无法确认部分附件是否已送达飞书,请先检查当前会话;附件仍保留在 Multica 中。"+ mediaLookupFailedText = "暂时无法检查这条回复的附件;如有附件,请在 Multica 中查看。"+ attachmentBudget = 5 * time.Minute+ attachmentNoticeBudget = 5 * time.Second+ maxConcurrentAttachmentDeliveries = 2+ maxAdmittedAttachmentDeliveries = 64+ maxPendingAttachmentDeliveries = 32+)++// SetAttachments returns the same capability verdict announced on task claim.+func (p *Patcher) SetAttachments(objects mediaObjectStore) bool {+ p.objects = objects+ return objects != nil && p.media != nil && p.client.IsConfigured()+}++func chatDoneMessageID(payload any) string {+ switch v := payload.(type) {+ case protocol.ChatDonePayload:+ return v.MessageID+ case map[string]any:+ s, _ := v["message_id"].(string)+ return s+ }+ return ""+}+func chatDoneTaskID(payload any) string {+ switch v := payload.(type) {+ case protocol.ChatDonePayload:+ return v.TaskID+ case map[string]any:+ s, _ := v["task_id"].(string)+ return s+ }+ return ""+}++// Admission precedes both goroutine creation and the database lookup. Pending+// deliveries are bounded separately, after a lookup proves files exist.+func (p *Patcher) deliverAttachmentsAsync(parent context.Context, creds InstallationCredentials, binding ChatSessionBinding, target ReplyTarget, workspaceID pgtype.UUID, payload any) bool {+ if p.objects == nil || p.media == nil {+ return false+ }+ messageID, err := util.ParseUUID(chatDoneMessageID(payload))+ if err != nil || !messageID.Valid || !workspaceID.Valid {+ return false+ }+ taskID, err := util.ParseUUID(chatDoneTaskID(payload))+ if err != nil || !taskID.Valid {+ return false+ }+ select {+ case p.mediaAdmission <- struct{}{}:+ default:+ p.cfg.Logger.Warn("lark outbound: attachment lookup admission full", "message_id", uuidString(messageID))+ return false+ }+ p.spawn(func() {+ defer func() { <-p.mediaAdmission }()+ ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), p.mediaBudget)+ defer cancel()+ if _, ok := ctx.Value(mediaDeliveryContextKey{}).(*mediaDeliveryOwner); !ok {+ var acquired bool+ ctx, _, acquired = p.claimMediaDelivery(ctx, taskID, binding)+ if !acquired {+ return+ }+ }+ defer p.finishMediaDelivery(ctx)+ p.deliverAttachments(ctx, creds, binding, target, workspaceID, uuidString(messageID))+ })+ return true+}++func (p *Patcher) deliverAttachments(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, target ReplyTarget, workspaceID pgtype.UUID, rawMessageID string) {+ ctx = context.WithValue(ctx, mediaWorkspaceContextKey{}, workspaceID)+ messageID, err := util.ParseUUID(rawMessageID)+ if err != nil || !messageID.Valid {+ return+ }+ rows, err := p.queries.ListAttachmentsByChatMessage(ctx, db.ListAttachmentsByChatMessageParams{+ ChatMessageID: messageID, WorkspaceID: workspaceID,+ })+ if err != nil {+ p.cfg.Logger.Warn("lark outbound: attachment lookup failed", "message_id", rawMessageID, "error", err)+ p.tellUser(ctx, creds, binding, target, mediaLookupFailedText)+ return+ }+ if len(rows) == 0 {+ return+ }+ select {+ case p.mediaPending <- struct{}{}:+ defer func() { <-p.mediaPending }()+ default:+ p.tellUser(ctx, creds, binding, target, mediaSendFailedText)+ return+ }+ select {+ case p.mediaSlots <- struct{}{}:+ defer func() { <-p.mediaSlots }()+ case <-ctx.Done():+ p.tellUser(ctx, creds, binding, target, mediaSendFailedText)+ return+ }+ if !p.markMediaSending(ctx) {+ // A previous owner may have sent files. Never repeat an uncertain batch.+ p.tellUser(ctx, creds, binding, target, mediaSendUnknownText)+ return+ }+ failed, unknown := 0, 0+ for _, row := range rows {+ if err := p.deliverOneAttachment(ctx, creds, binding, &target, workspaceID, messageID, row); err != nil {+ var uncertain *mediaSendUnconfirmed+ if errors.As(err, &uncertain) {+ unknown+++ } else {+ failed+++ }+ // Object URLs and filenames can contain private data.+ p.cfg.Logger.Warn("lark outbound: attachment delivery unconfirmed",+ "attachment_id", uuidString(row.ID), "uncertain", uncertain != nil)+ }+ }+ var notices []string+ if failed > 0 {+ notices = append(notices, mediaSendFailedText)+ }+ if unknown > 0 {+ notices = append(notices, mediaSendUnknownText)+ }+ if len(notices) > 0 {+ p.tellUser(ctx, creds, binding, target, strings.Join(notices, "\n"))+ }+}++type mediaSendUnconfirmed struct{ err error }++func (e *mediaSendUnconfirmed) Error() string { return "lark media send was not confirmed" }+func (e *mediaSendUnconfirmed) Unwrap() error { return e.err }++// An explicit refusal proves the message was not accepted. A lost response,+// missing message id, or 5xx does not. Only the latter uses a bounded retry,+// with exactly the same provider idempotency key.+func definiteMediaRefusal(err error) bool {+ // A message still being sent has no confirmed outcome, even under HTTP 400.+ if larkErrorCode(err) == 230049 {+ return false+ }+ var status *larkAPIStatusError+ if errors.As(err, &status) {+ return status.StatusCode >= 400 && status.StatusCode < 500+ }+ var api *APIError+ return errors.As(err, &api) && api.Code != 0+}++func (p *Patcher) deliverOneAttachment(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, target *ReplyTarget, workspaceID, messageID pgtype.UUID, row db.Attachment) error {+ if row.SizeBytes > larkFileUploadMaxBytes {+ return errors.New("attachment exceeds file limit")+ }+ var err error+ creds, err = p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if err != nil {+ return err+ }+ key := p.objects.KeyFromURL(strings.TrimSpace(row.Url))+ if key == "" {+ return errors.New("attachment is not stored by this deployment")+ }+ rc, err := p.objects.GetReader(ctx, key)+ if err != nil {+ return errors.New("attachment object unavailable")+ }+ // A cancelled delivery must also interrupt a storage implementation whose+ // reader only unblocks when closed.+ stop := context.AfterFunc(ctx, func() { _ = rc.Close() })+ defer stop()+ data, readErr := io.ReadAll(io.LimitReader(rc, larkFileUploadMaxBytes+1))+ _ = rc.Close()+ if readErr != nil {+ return errors.New("attachment object read failed")+ }+ if len(data) == 0 || len(data) > larkFileUploadMaxBytes {+ return errors.New("attachment size invalid")+ }+ creds, err = p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if err != nil {+ return err+ }+ image := isImageAttachment(row.ContentType, row.Filename) && len(data) <= larkImageUploadMaxBytes+ fileType := larkFileTypeFor(row.Filename)+ var resourceKey string+ if image {+ resourceKey, err = p.media.UploadImage(ctx, UploadImageParams{InstallationID: creds, Filename: row.Filename, Data: data})+ if err != nil && definiteMediaRefusal(err) && !isTokenError(larkErrorCode(err)) {+ image = false+ }+ }+ if !image {+ creds, err = p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if err != nil {+ return err+ }+ resourceKey, err = p.media.UploadFile(ctx, UploadFileParams{InstallationID: creds, Filename: row.Filename, FileType: fileType, Data: data})+ }+ if err != nil {+ return errors.New("attachment upload failed")+ }+ if image {+ if card, ok := ctx.Value(mediaReplyCardContextKey{}).(*mediaReplyCard); ok {+ return p.patchMediaReplyCard(ctx, creds, binding, workspaceID, card, row, resourceKey)+ }+ }+ // Scope the key to the installation, reply and attachment, not just a file:+ // deliberate reuse of one file in a later reply must remain a new send.+ id := uuid.NewSHA1(uuid.NameSpaceOID, []byte(uuidString(binding.InstallationID)+"/"+uuidString(messageID)+"/"+uuidString(row.ID))).String()+ send := func(t ReplyTarget) error {+ uncertain := false+ for attempt := 0; attempt < 2; attempt++ {+ current, guardErr := p.currentMediaCredentials(ctx, creds, binding, workspaceID)+ if guardErr != nil {+ if uncertain {+ return &mediaSendUnconfirmed{err: guardErr}+ }+ return guardErr+ }+ callCtx, cancel := context.WithTimeout(ctx, defaultRequestTimeout)+ if image {+ _, err = p.media.SendImageMessage(callCtx, SendImageParams{InstallationID: current, ChatID: outboundChatID(binding), ImageKey: resourceKey, ReplyTarget: t, UUID: id})+ } else {+ _, err = p.media.SendFileMessage(callCtx, SendFileParams{InstallationID: current, ChatID: outboundChatID(binding), FileKey: resourceKey, FileType: fileType, ReplyTarget: t, UUID: id})+ }+ cancel()+ if err == nil {+ *target = t+ return nil+ }+ if definiteMediaRefusal(err) {+ if uncertain {+ return &mediaSendUnconfirmed{err: err}+ }+ return err+ }+ uncertain = true+ if ctx.Err() != nil {+ break+ }+ }+ return &mediaSendUnconfirmed{err: err}+ }+ return sendWithReplyFallback(p.cfg.Logger, "send attachment", *target, send)+}++// Notices outlive the failed transfer budget, but never a revoked connection.+func (p *Patcher) tellUser(ctx context.Context, creds InstallationCredentials, binding ChatSessionBinding, target ReplyTarget, body string) {+ noticeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), attachmentNoticeBudget)+ defer cancel()+ current, err := p.currentMediaCredentials(noticeCtx, creds, binding, pgtype.UUID{})+ if err != nil {+ return+ }+ if _, err := p.client.SendTextMessage(noticeCtx, SendTextParams{+ InstallationID: current, ChatID: outboundChatID(binding),+ Text: prependTextMention(mentionOpenID(binding), body), ReplyTarget: target,+ }); err != nil {+ p.cfg.Logger.Warn("lark outbound: attachment notice failed")+ }+}++func isImageAttachment(contentType, filename string) bool {+ ct := strings.ToLower(strings.TrimSpace(strings.Split(contentType, ";")[0]))+ if ct == "" || ct == "application/octet-stream" {+ switch strings.ToLower(filepath.Ext(filename)) {+ case ".jpg", ".jpeg":+ ct = "image/jpeg"+ case ".png":+ ct = "image/png"+ case ".gif":+ ct = "image/gif"+ case ".webp":+ ct = "image/webp"+ case ".bmp":+ ct = "image/bmp"+ case ".ico":+ ct = "image/x-icon"+ case ".tif", ".tiff":+ ct = "image/tiff"+ case ".heic":+ ct = "image/heic"+ }+ }+ switch ct {+ case "image/jpeg", "image/png", "image/gif", "image/webp", "image/bmp",+ "image/x-icon", "image/vnd.microsoft.icon", "image/tiff", "image/heic":+ return true+ }+ return false+}diff --git a/server/internal/integrations/lark/outbound_media_boundaries_test.go b/server/internal/integrations/lark/outbound_media_boundaries_test.gonew file mode 100644index 0000000000..63c46bb351--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_boundaries_test.go@@ -0,0 +1,365 @@+package lark++import (+ "context"+ "errors"+ "fmt"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type controlledMedia struct {+ *fakeMediaAPIClient+ uploadImage func(context.Context, UploadImageParams) (string, error)+ sendImage func(context.Context, SendImageParams) (string, error)+}++func (c *controlledMedia) UploadImage(ctx context.Context, p UploadImageParams) (string, error) {+ if c.uploadImage != nil {+ return c.uploadImage(ctx, p)+ }+ return c.fakeMediaAPIClient.UploadImage(ctx, p)+}+func (c *controlledMedia) SendImageMessage(ctx context.Context, p SendImageParams) (string, error) {+ if c.sendImage != nil {+ return c.sendImage(ctx, p)+ }+ return c.fakeMediaAPIClient.SendImageMessage(ctx, p)+}++func mediaFixture(t *testing.T) (*Patcher, *fakePatcherQueries, *fakeMediaAPIClient, string) {+ t.Helper()+ p, q, api := newMediaTestPatcher(t)+ p.spawn = func(f func()) { f() }+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ return p, q, api, "dddd4444-dddd-dddd-dddd-dddddddddddd"+}+func runMediaFixture(p *Patcher, q *fakePatcherQueries, id string) {+ p.deliverAttachments(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, id)+}++func TestOutboundImageDegradesToFile(t *testing.T) {+ for _, scenario := range []string{"svg", "oversize", "format-refused", "unknown-type"} {+ t.Run(scenario, func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ switch scenario {+ case "svg":+ q.attachments[0].ContentType = "IMAGE/SVG+XML; charset=utf-8"+ case "oversize":+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": make([]byte, larkImageUploadMaxBytes+1)}})+ case "format-refused":+ p.media = &controlledMedia{fakeMediaAPIClient: api, uploadImage: func(context.Context, UploadImageParams) (string, error) {+ return "", &APIError{Op: "upload image", Code: 234001, Msg: "format rejected"}+ }}+ case "unknown-type":+ q.attachments[0].ContentType = "image/future-format"+ }+ runMediaFixture(p, q, id)+ if len(api.files) != 1 || len(api.filesOut) != 1 || len(api.imagesOut) != 0 || len(api.textSent) != 0 {+ t.Fatalf("files=%d images=%d notices=%d", len(api.filesOut), len(api.imagesOut), len(api.textSent))+ }+ })+ }+}++func TestOutboundUncertainSendUsesSameUUID(t *testing.T) {+ for _, recovers := range []bool{true, false} {+ t.Run(map[bool]string{true: "lost-first-response", false: "both-responses-lost"}[recovers], func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ var requests []SendImageParams+ p.media = &controlledMedia{fakeMediaAPIClient: api, sendImage: func(_ context.Context, r SendImageParams) (string, error) {+ requests = append(requests, r)+ if recovers && len(requests) == 2 {+ return "accepted", nil+ }+ return "", errors.New("connection reset after write")+ }}+ runMediaFixture(p, q, id)+ if len(requests) != 2 || requests[0].UUID == "" || requests[0].UUID != requests[1].UUID {+ t.Fatalf("idempotency lost: %+v", requests)+ }+ if recovers {+ if len(api.textSent) != 0 {+ t.Fatal("successful reconciliation warned")+ }+ } else if len(api.textSent) != 1 || api.textSent[0].Text != mediaSendUnknownText {+ t.Fatalf("incorrect uncertainty notice: %+v", api.textSent)+ }+ })+ }+}++func TestOutboundDefiniteRefusalDoesNotRetry(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ calls := 0+ p.media = &controlledMedia{fakeMediaAPIClient: api, sendImage: func(context.Context, SendImageParams) (string, error) {+ calls+++ return "", &APIError{Code: 230001, Msg: "refused"}+ }}+ runMediaFixture(p, q, id)+ if calls != 1 || len(api.textSent) != 1 || api.textSent[0].Text != mediaSendFailedText {+ t.Fatalf("calls=%d notices=%+v", calls, api.textSent)+ }+}++func TestDefiniteMediaRefusal(t *testing.T) {+ beingSent := &larkAPIStatusError{StatusCode: 400, Code: 230049, Msg: "The message is being sent."}+ beingSentAPI := &APIError{Code: 230049, Msg: "The message is being sent."}+ for _, tc := range []struct {+ name string+ err error+ want bool+ }{+ {"being-sent-http400", beingSent, false},+ {"being-sent-api-error", beingSentAPI, false},+ {"wrapped-being-sent-http400", fmt.Errorf("send image message: %w", beingSent), false},+ {"wrapped-being-sent-api-error", fmt.Errorf("send image message: %w", beingSentAPI), false},+ {"explicit-http400", &larkAPIStatusError{StatusCode: 400, Code: 230055}, true},+ {"explicit-http403", &larkAPIStatusError{StatusCode: 403, Code: 230035}, true},+ {"rate-limited-http429", &larkAPIStatusError{StatusCode: 429, Code: 230020}, true},+ {"http400-without-business-code", &larkAPIStatusError{StatusCode: 400}, true},+ {"explicit-api-error", &APIError{Code: 230001}, true},+ {"wrapped-explicit-refusal", fmt.Errorf("send image message: %w", &APIError{Code: 230001}), true},+ {"http502", &larkAPIStatusError{StatusCode: 502}, false},+ {"missing-message-id", &APIError{Code: 0}, false},+ {"transport-error", errors.New("response lost"), false},+ {"no-error", nil, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := definiteMediaRefusal(tc.err); got != tc.want {+ t.Fatalf("definiteMediaRefusal(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++func TestOutboundBeingSentKeepsOriginalDelivery(t *testing.T) {+ beingSent := &larkAPIStatusError{StatusCode: 400, Code: 230049, Msg: "The message is being sent."}+ beingSentAPI := &APIError{Code: 230049, Msg: "The message is being sent."}+ for _, response := range []struct {+ name string+ err error+ }{+ {"http400", beingSent},+ {"api-error", beingSentAPI},+ {"wrapped-http400", fmt.Errorf("send image message: %w", beingSent)},+ {"wrapped-api-error", fmt.Errorf("send image message: %w", beingSentAPI)},+ } {+ t.Run(response.name, func(t *testing.T) {+ for _, outcome := range []string{"accepted-on-retry", "still-being-sent", "refused-on-retry"} {+ t.Run(outcome, func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ target := ReplyTarget{MessageID: "om_trigger", InThread: true}+ var requests []SendImageParams+ p.media = &controlledMedia{fakeMediaAPIClient: api, sendImage: func(_ context.Context, r SendImageParams) (string, error) {+ requests = append(requests, r)+ if len(requests) == 1 {+ return "", response.err+ }+ switch outcome {+ case "accepted-on-retry":+ return "om_accepted", nil+ case "refused-on-retry":+ return "", errThreadReplyClassified+ default:+ return "", response.err+ }+ }}+ p.deliverAttachments(context.Background(), testCreds(), q.binding, target, q.installation.WorkspaceID, id)+ if len(requests) != 2 {+ t.Fatalf("being-sent delivery must get one bounded retry: %+v", requests)+ }+ for _, request := range requests {+ if request.UUID == "" || request.UUID != requests[0].UUID || request.ReplyTarget != target || request.ChatID != outboundChatID(q.binding) {+ t.Fatalf("retry changed the delivery identity or destination: %+v", request)+ }+ }+ if outcome == "accepted-on-retry" {+ if len(api.textSent) != 0 {+ t.Fatalf("confirmed delivery must not warn: %+v", api.textSent)+ }+ return+ }+ if len(api.textSent) != 1 || api.textSent[0].Text != mediaSendUnknownText || api.textSent[0].ReplyTarget != target || api.textSent[0].ChatID != outboundChatID(q.binding) {+ t.Fatalf("unconfirmed delivery must remain unknown in the original topic: %+v", api.textSent)+ }+ })+ }+ })+ }+}++func TestOutboundUncertaintySurvivesClassifiedRetryRefusal(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ var requests []SendImageParams+ p.media = &controlledMedia{fakeMediaAPIClient: api, sendImage: func(_ context.Context, r SendImageParams) (string, error) {+ requests = append(requests, r)+ switch len(requests) {+ case 1:+ return "", errors.New("response lost after message submission")+ case 2:+ return "", errThreadReplyClassified+ default:+ return "unexpected-parent-message", nil+ }+ }}+ target := ReplyTarget{MessageID: "om_trigger", InThread: true}+ p.deliverAttachments(context.Background(), testCreds(), q.binding, target, q.installation.WorkspaceID, id)+ if len(requests) != 2 {+ t.Fatalf("uncertain topic reply escaped to a new destination: %d requests", len(requests))+ }+ for _, request := range requests {+ if request.ReplyTarget != target || request.UUID == "" || request.UUID != requests[0].UUID {+ t.Fatalf("retry changed the target or idempotency key: %+v", request)+ }+ }+ if len(api.textSent) != 1 || api.textSent[0].Text != mediaSendUnknownText || api.textSent[0].ReplyTarget != target {+ t.Fatalf("uncertainty must remain visible in the original topic: %+v", api.textSent)+ }+}++func TestOutboundRevocationDuringUploadStopsAllWrites(t *testing.T) {+ for _, scenario := range []string{"revoked", "app-rebound", "session-archived", "workspace-changed"} {+ t.Run(scenario, func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ p.media = &controlledMedia{fakeMediaAPIClient: api, uploadImage: func(context.Context, UploadImageParams) (string, error) {+ switch scenario {+ case "revoked":+ q.installation.Status = "revoked"+ case "app-rebound":+ q.installation.AppID = "different-app"+ case "session-archived":+ q.mediaSession = &db.ChatSession{Status: "archived", WorkspaceID: q.installation.WorkspaceID}+ case "workspace-changed":+ q.installation.WorkspaceID = pgtype.UUID{}+ }+ return "uploaded-before-revocation", nil+ }}+ runMediaFixture(p, q, id)+ if len(api.imagesOut)+len(api.filesOut)+len(api.textSent) != 0 {+ t.Fatal("a write escaped after permission was withdrawn")+ }+ })+ }+}++type noticeContextClient struct {+ *fakeMediaAPIClient+ noticeContextError error+}++func (c *noticeContextClient) SendTextMessage(ctx context.Context, p SendTextParams) (string, error) {+ c.noticeContextError = ctx.Err()+ return c.fakeMediaAPIClient.SendTextMessage(ctx, p)+}++func TestOutboundQueueDeadlineStillSendsNotice(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ client := ¬iceContextClient{fakeMediaAPIClient: api}+ p.client = client+ for i := 0; i < cap(p.mediaSlots); i++ {+ p.mediaSlots <- struct{}{}+ }+ defer func() {+ for i := 0; i < cap(p.mediaSlots); i++ {+ <-p.mediaSlots+ }+ }()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)+ defer cancel()+ p.deliverAttachments(ctx, testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, id)+ if client.noticeContextError != nil || len(api.textSent) != 1 || api.textSent[0].Text != mediaSendFailedText {+ t.Fatalf("notice context=%v messages=%+v", client.noticeContextError, api.textSent)+ }+}++func TestOutboundCapacityBoundsLookupAndWaitsForSlot(t *testing.T) {+ t.Run("admission-before-spawn", func(t *testing.T) {+ p, q, _, id := mediaFixture(t)+ for i := 0; i < cap(p.mediaAdmission); i++ {+ p.mediaAdmission <- struct{}{}+ }+ spawned := false+ p.spawn = func(func()) { spawned = true }+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, map[string]any{"message_id": id, "task_id": id})+ if spawned || len(q.attachmentLookups) != 0 {+ t.Fatal("full admission still spawned or queried")+ }+ })+ t.Run("bounded-pending", func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ for i := 0; i < cap(p.mediaPending); i++ {+ p.mediaPending <- struct{}{}+ }+ runMediaFixture(p, q, id)+ if len(api.imagesOut) != 0 || len(api.textSent) != 1 {+ t.Fatal("pending overflow not reported")+ }+ })+ t.Run("busy-upload-waits", func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ for i := 0; i < cap(p.mediaSlots); i++ {+ p.mediaSlots <- struct{}{}+ }+ var release sync.Once+ free := func() {+ release.Do(func() {+ for i := 0; i < cap(p.mediaSlots); i++ {+ <-p.mediaSlots+ }+ })+ }+ defer free()+ done := make(chan struct{})+ go func() { defer close(done); runMediaFixture(p, q, id) }()+ waitFor(t, func() bool { return len(p.mediaPending) == 1 }, "pending slot")+ api.mu.Lock()+ n := len(api.textSent)+ api.mu.Unlock()+ if n != 0 {+ t.Fatal("busy slot shed instead of waiting")+ }+ free()+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("delivery did not resume")+ }+ if len(api.imagesOut) != 1 || len(api.textSent) != 0 {+ t.Fatal("queued file was not delivered")+ }+ })+}++func TestOutboundRepeatedCompletionAndInterruptedBatch(t *testing.T) {+ t.Run("duplicate-event", func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ payload := map[string]any{"message_id": id, "task_id": id}+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, payload)+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, payload)+ if len(api.imagesOut) != 1 {+ t.Fatalf("duplicate attachment sends=%d", len(api.imagesOut))+ }+ })+ t.Run("crashed-in-flight-batch", func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ q.mediaLedger = map[string]db.ChannelReplyDelivery{id: {Phase: "terminal", SendState: "in_flight"}}+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, map[string]any{"message_id": id, "task_id": id})+ if len(api.imagesOut) != 0 || len(api.images) != 0 || len(api.textSent) != 1 || api.textSent[0].Text != mediaSendUnknownText {+ t.Fatalf("interrupted batch replayed or misreported: %+v", api.textSent)+ }+ })+ t.Run("database-unavailable", func(t *testing.T) {+ p, q, api, id := mediaFixture(t)+ q.mediaLedgerErr = errors.New("database unavailable")+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{}, q.installation.WorkspaceID, map[string]any{"message_id": id, "task_id": id})+ if len(api.imagesOut)+len(api.images) != 0 {+ t.Fatal("sent without durable ownership")+ }+ })+}diff --git a/server/internal/integrations/lark/outbound_media_delivery.go b/server/internal/integrations/lark/outbound_media_delivery.gonew file mode 100644index 0000000000..ba95108dbf--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_delivery.go@@ -0,0 +1,138 @@+package lark++import (+ "context"+ "errors"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type mediaDeliveryQueries interface {+ GetChannelReplyTurn(context.Context, pgtype.UUID) (db.GetChannelReplyTurnRow, error)+ AcquireChannelReplyDelivery(context.Context, db.AcquireChannelReplyDeliveryParams) (db.ChannelReplyDelivery, error)+ MarkChannelReplyDeliverySending(context.Context, db.MarkChannelReplyDeliverySendingParams) (int64, error)+ RenewChannelReplyDelivery(context.Context, db.RenewChannelReplyDeliveryParams) (int64, error)+ SettleChannelReplyDelivery(context.Context, db.SettleChannelReplyDeliveryParams) (int64, error)+}++type mediaDeliveryContextKey struct{}+type mediaWorkspaceContextKey struct{}+type mediaDeliveryOwner struct {+ taskID, turnID, token pgtype.UUID+ interrupted bool+ started bool+}++// The existing reply ledger fences duplicate completion events and retry+// attempts across replicas and restarts, beyond Feishu's one-hour UUID window.+// A crashed in-flight batch is never blindly replayed: per-file receipts are+// unavailable, so a successor reports the uncertainty and leaves files in Multica.+func (p *Patcher) claimMediaDelivery(ctx context.Context, taskID pgtype.UUID, binding ChatSessionBinding) (context.Context, func(), bool) {+ turn, err := p.queries.GetChannelReplyTurn(ctx, taskID)+ if errors.Is(err, pgx.ErrNoRows) {+ turn.TurnID, err = taskID, nil+ }+ if err != nil || !turn.TurnID.Valid {+ return ctx, nil, false+ }+ owner := &mediaDeliveryOwner{taskID: taskID, turnID: turn.TurnID, token: pgtype.UUID{Bytes: uuid.New(), Valid: true}}+ row, err := p.queries.AcquireChannelReplyDelivery(ctx, db.AcquireChannelReplyDeliveryParams{+ TurnID: owner.turnID, TaskID: taskID, AttemptDepth: turn.AttemptDepth,+ BindingID: binding.ID, InstallationID: binding.InstallationID,+ ChannelType: channelTypeFeishu, ChatID: binding.ChannelChatID, Phase: "terminal",+ OwnerToken: owner.token,+ // One bounded transfer plus its detached notice and settlement must+ // finish before another process can take ownership.+ LeaseSeconds: (defaultRequestTimeout + p.mediaBudget + attachmentNoticeBudget + 10*time.Second).Seconds(),+ })+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ p.cfg.Logger.Warn("lark outbound: attachment ownership unavailable")+ }+ return ctx, nil, false+ }+ owner.interrupted = row.SendState == "in_flight" || row.SendState == "unknown"+ ctx = context.WithValue(ctx, mediaDeliveryContextKey{}, owner)+ finish := func() { p.finishMediaDelivery(ctx) }+ return ctx, finish, true+}++func (p *Patcher) finishMediaDelivery(ctx context.Context) {+ owner, ok := ctx.Value(mediaDeliveryContextKey{}).(*mediaDeliveryOwner)+ if !ok {+ return+ }+ recordCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ if n, err := p.queries.SettleChannelReplyDelivery(recordCtx, db.SettleChannelReplyDeliveryParams{+ TurnID: owner.turnID, OwnerToken: owner.token, SettledReason: "attachment_attempt_ended",+ }); err != nil || n != 1 {+ p.cfg.Logger.Warn("lark outbound: attachment settlement unconfirmed")+ }+}++func (p *Patcher) markMediaSending(ctx context.Context) bool {+ owner, ok := ctx.Value(mediaDeliveryContextKey{}).(*mediaDeliveryOwner)+ if !ok {+ return true+ }+ if owner.interrupted {+ return false+ }+ if owner.started {+ return true+ }+ n, err := p.queries.MarkChannelReplyDeliverySending(ctx, db.MarkChannelReplyDeliverySendingParams{TurnID: owner.turnID, OwnerToken: owner.token})+ owner.started = err == nil && n == 1+ return owner.started+}++// The frozen task delivery remains authoritative after /new; never look up+// the session's newest binding or a different account to choose a destination.+// Recheck before uploads, sends, retries and notices so queueing does not extend+// the lifetime of a revoked installation or a deleted/archived conversation.+func (p *Patcher) currentMediaCredentials(ctx context.Context, original InstallationCredentials, binding ChatSessionBinding, workspaceID pgtype.UUID) (InstallationCredentials, error) {+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)+ defer cancel()+ if !workspaceID.Valid {+ workspaceID, _ = ctx.Value(mediaWorkspaceContextKey{}).(pgtype.UUID)+ }+ if err := ctx.Err(); err != nil {+ return InstallationCredentials{}, err+ }+ inst, err := p.queries.GetLarkInstallation(ctx, binding.InstallationID)+ if err != nil || !inst.WorkspaceID.Valid || InstallationStatus(inst.Status) != InstallationActive || inst.AppID != original.AppID ||+ inst.TenantKey.String != original.TenantKey || RegionOrDefault(inst.Region) != RegionOrDefault(string(original.Region)) ||+ (workspaceID.Valid && inst.WorkspaceID != workspaceID) {+ return InstallationCredentials{}, errors.New("attachment connection unavailable")+ }+ session, err := p.queries.GetChatSession(ctx, binding.ChatSessionID)+ if err != nil || session.Status != "active" || session.WorkspaceID != inst.WorkspaceID {+ return InstallationCredentials{}, errors.New("attachment conversation unavailable")+ }+ if owner, ok := ctx.Value(mediaDeliveryContextKey{}).(*mediaDeliveryOwner); ok {+ delivery, err := p.queries.GetChannelTaskDelivery(ctx, owner.taskID)+ if err != nil || delivery.ChannelType != channelTypeFeishu || delivery.BindingID != binding.ID ||+ delivery.InstallationID != binding.InstallationID || delivery.ChannelChatID != binding.ChannelChatID {+ return InstallationCredentials{}, errors.New("attachment destination changed")+ }+ task, err := p.queries.GetAgentTask(ctx, owner.taskID)+ if err != nil || (task.AgentID.Valid && task.AgentID != inst.AgentID) {+ return InstallationCredentials{}, errors.New("attachment agent changed")+ }+ // Re-prove the database owner before each external write, including+ // timeout notices. A previous process must stop after takeover.+ n, err := p.queries.RenewChannelReplyDelivery(ctx, db.RenewChannelReplyDeliveryParams{+ TurnID: owner.turnID, OwnerToken: owner.token,+ LeaseSeconds: (defaultRequestTimeout + p.mediaBudget + attachmentNoticeBudget + 10*time.Second).Seconds(),+ })+ if err != nil || n != 1 {+ return InstallationCredentials{}, errors.New("attachment delivery ownership lost")+ }+ }+ return p.installationCredentials(inst)+}diff --git a/server/internal/integrations/lark/outbound_media_delivery_db_test.go b/server/internal/integrations/lark/outbound_media_delivery_db_test.gonew file mode 100644index 0000000000..8734be6980--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_delivery_db_test.go@@ -0,0 +1,61 @@+package lark++import (+ "context"+ "os"+ "testing"++ "github.com/google/uuid"+ "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 TestMediaDeliveryDatabaseOwnershipAndRetryRecovery(t *testing.T) {+ if os.Getenv("DATABASE_URL") == "" {+ t.Skip("explicit disposable DATABASE_URL required")+ }+ pool := channelScopeTestDB(t)+ fx := testutil.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Media delivery test", "media-"+suffix+"@example.invalid")+ fx.WorkspaceID = fx.Workspace(t, "Media delivery test", "media-"+suffix)+ runtimeID := fx.Runtime(t, "Media delivery test")+ agentID := fx.Agent(t, "Media delivery test", runtimeID)+ root := fx.Task(t, agentID, testutil.Cols{"status": "completed", "runtime_id": runtimeID})+ retry := fx.Task(t, agentID, testutil.Cols{"status": "completed", "runtime_id": runtimeID, "retry_of_task_id": root})+ rootID := util.MustParseUUID(root)+ fx.Cleanup(t, "DELETE FROM channel_reply_delivery WHERE turn_id=$1", rootID)+ q := NewChannelStore(db.New(pool))+ api := &fakeMediaAPIClient{fakeAPIClient: &fakeAPIClient{}}+ first := NewPatcher(q, fakeCredentials{secret: "unused"}, api, PatcherConfig{Logger: newDiscardLogger()})+ second := NewPatcher(q, fakeCredentials{secret: "unused"}, api, PatcherConfig{Logger: newDiscardLogger()})+ binding := ChatSessionBinding{ID: util.MustParseUUID(uuid.NewString()), InstallationID: util.MustParseUUID(uuid.NewString()), ChannelChatID: "test-chat"}+ ctx, finish, ok := first.claimMediaDelivery(context.Background(), rootID, binding)+ if !ok || !first.markMediaSending(ctx) {+ t.Fatal("first owner did not acquire and publish send")+ }+ if _, _, ok := second.claimMediaDelivery(context.Background(), rootID, binding); ok {+ t.Fatal("two live replicas owned one delivery")+ }+ fx.Exec(t, "UPDATE channel_reply_delivery SET owner_expires_at=now()-interval '1 second' WHERE turn_id=$1", rootID)+ successor, settle, ok := second.claimMediaDelivery(context.Background(), util.MustParseUUID(retry), binding)+ if !ok {+ t.Fatal("retry could not take an expired lease")+ }+ if second.markMediaSending(successor) {+ t.Fatal("takeover silently replayed an in-flight attachment batch")+ }+ finish()+ row, err := q.GetChannelReplyDelivery(context.Background(), rootID)+ if err != nil || row.Phase == "settled" || row.AttemptDepth != 1 {+ t.Fatalf("stale owner overwrote retry: %+v err=%v", row, err)+ }+ settle()+ if _, _, ok := first.claimMediaDelivery(context.Background(), rootID, binding); ok {+ t.Fatal("settled delivery accepted a replay")+ }+ if _, _, ok := second.claimMediaDelivery(context.Background(), util.MustParseUUID(retry), binding); ok {+ t.Fatal("retry repeated a settled delivery")+ }+}diff --git a/server/internal/integrations/lark/outbound_media_delivery_test.go b/server/internal/integrations/lark/outbound_media_delivery_test.gonew file mode 100644index 0000000000..a7cbcba293--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_delivery_test.go@@ -0,0 +1,64 @@+package lark++import (+ "context"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func (f *fakePatcherQueries) GetChannelReplyTurn(_ context.Context, id pgtype.UUID) (db.GetChannelReplyTurnRow, error) {+ return db.GetChannelReplyTurnRow{TurnID: id}, nil+}+func (f *fakePatcherQueries) AcquireChannelReplyDelivery(_ context.Context, arg db.AcquireChannelReplyDeliveryParams) (db.ChannelReplyDelivery, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ if f.mediaLedgerErr != nil {+ return db.ChannelReplyDelivery{}, f.mediaLedgerErr+ }+ if f.mediaLedger == nil {+ f.mediaLedger = map[string]db.ChannelReplyDelivery{}+ }+ key := uuidString(arg.TurnID)+ row := f.mediaLedger[key]+ if row.Phase == "settled" || row.OwnerToken.Valid {+ return db.ChannelReplyDelivery{}, pgx.ErrNoRows+ }+ row.TurnID, row.TaskID, row.OwnerToken, row.Phase = arg.TurnID, arg.TaskID, arg.OwnerToken, arg.Phase+ f.mediaLedger[key] = row+ return row, nil+}+func (f *fakePatcherQueries) MarkChannelReplyDeliverySending(_ context.Context, arg db.MarkChannelReplyDeliverySendingParams) (int64, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ key := uuidString(arg.TurnID)+ row := f.mediaLedger[key]+ if row.OwnerToken != arg.OwnerToken || row.SendState == "in_flight" || row.SendState == "unknown" {+ return 0, nil+ }+ row.SendState = "in_flight"+ f.mediaLedger[key] = row+ return 1, nil+}++func (f *fakePatcherQueries) RenewChannelReplyDelivery(_ context.Context, arg db.RenewChannelReplyDeliveryParams) (int64, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ row := f.mediaLedger[uuidString(arg.TurnID)]+ if row.OwnerToken != arg.OwnerToken || row.Phase == "settled" {+ return 0, nil+ }+ return 1, f.mediaLedgerErr+}+func (f *fakePatcherQueries) SettleChannelReplyDelivery(_ context.Context, arg db.SettleChannelReplyDeliveryParams) (int64, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ key := uuidString(arg.TurnID)+ row := f.mediaLedger[key]+ if row.OwnerToken != arg.OwnerToken {+ return 0, nil+ }+ row.Phase, row.OwnerToken = "settled", pgtype.UUID{}+ f.mediaLedger[key] = row+ return 1, nil+}diff --git a/server/internal/integrations/lark/outbound_media_pipeline_db_test.go b/server/internal/integrations/lark/outbound_media_pipeline_db_test.gonew file mode 100644index 0000000000..9b0968e641--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_pipeline_db_test.go@@ -0,0 +1,177 @@+package lark++import (+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "os"+ "sync"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/events"+ "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"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestMediaPipelineDatabaseAttachmentsReachHTTPOnce(t *testing.T) {+ for _, markdown := range []bool{false, true} {+ name := "plain reply"+ if markdown {+ name = "native reply with artifact image"+ }+ t.Run(name, func(t *testing.T) { testMediaPipelineDatabaseAttachmentsReachHTTPOnce(t, markdown) })+ }+}++func testMediaPipelineDatabaseAttachmentsReachHTTPOnce(t *testing.T, markdown bool) {+ if os.Getenv("DATABASE_URL") == "" {+ t.Skip("explicit disposable DATABASE_URL required")+ }+ pool := channelScopeTestDB(t)+ fx := testutil.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Media pipeline test", "media-pipeline-"+suffix+"@example.invalid")+ fx.WorkspaceID = fx.Workspace(t, "Media pipeline test", "media-pipeline-"+suffix)+ runtimeID := fx.Runtime(t, "Media pipeline test")+ agentID := fx.Agent(t, "Media pipeline test", runtimeID)+ sessionID := fx.ChatSession(t, agentID)+ taskID := fx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "chat_session_id": sessionID})+ fx.Exec(t, "UPDATE agent_task_queue SET chat_input_task_id=id WHERE id=$1", taskID)+ fx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "task_id": taskID, "role": "user", "content": "Create a chart and report", "channel_ingested": true})+ messageID := fx.Insert(t, "chat_message", testutil.Cols{"chat_session_id": sessionID, "task_id": taskID, "role": "assistant", "content": "Here are the chart and report."})+ appID := "cli_media_" + suffix+ config, _ := json.Marshal(map[string]string{"app_id": appID, "app_secret_encrypted": ""})+ installationID := fx.Insert(t, "channel_installation", testutil.Cols{"workspace_id": fx.WorkspaceID, "agent_id": agentID, "channel_type": channelTypeFeishu,+ "installer_user_id": fx.UserID, "config": string(config)})+ bindingID := fx.Insert(t, "channel_chat_session_binding", testutil.Cols{"chat_session_id": sessionID, "installation_id": installationID, "channel_type": channelTypeFeishu, "channel_chat_id": "oc_pipeline", "chat_type": "p2p"})+ fx.InsertNoID(t, "channel_task_delivery", testutil.Cols{"task_id": taskID, "binding_id": bindingID, "installation_id": installationID, "channel_type": channelTypeFeishu, "channel_chat_id": "oc_pipeline", "chat_type": "p2p", "route_revision": 1}, "task_id=$1", taskID)+ fx.Cleanup(t, "DELETE FROM channel_reply_delivery WHERE turn_id=$1", taskID)+ data := map[string][]byte{"chart.png": pngBytes, "report.pdf": []byte("%PDF-1.4 exact report bytes")}+ var chartID string+ for name, content := range data {+ kind := "application/pdf"+ if name == "chart.png" {+ kind = "image/png"+ }+ id := fx.Insert(t, "attachment", testutil.Cols{"workspace_id": fx.WorkspaceID, "task_id": taskID, "chat_session_id": sessionID, "chat_message_id": messageID,+ "uploader_type": "agent", "uploader_id": agentID, "filename": name, "url": fakeObjectPrefix + name, "content_type": kind, "size_bytes": len(content)})+ if name == "chart.png" {+ chartID = id+ }+ }+ fake := newLarkFake(t)+ fake.stubToken("token", 7200)+ for _, image := range []bool{true, false} {+ path, field, name, key := larkUploadPathFile, "file", "report.pdf", "file_key"+ if image {+ path, field, name, key = larkUploadPathImage, "image", "chart.png", "image_key"+ }+ fake.mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {+ if err := r.ParseMultipartForm(1024); err != nil {+ t.Error(err)+ return+ }+ defer r.MultipartForm.RemoveAll()+ f, _, err := r.FormFile(field)+ if err != nil {+ t.Error(err)+ return+ }+ defer f.Close()+ got, _ := io.ReadAll(f)+ if !bytes.Equal(got, data[name]) {+ t.Error("stored attachment bytes changed")+ }+ resourceKey := name+ if image {+ resourceKey = "img_chart"+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{key: resourceKey}})+ })+ }+ kinds := map[string]int{}+ var kindsMu sync.Mutex+ patches := 0+ fake.stubPatch(map[string]any{"code": 0}, func(_ *http.Request, id string, body map[string]string) {+ kindsMu.Lock()+ defer kindsMu.Unlock()+ patches+++ if id != "om_accepted" {+ t.Errorf("updated a different answer: %q", id)+ }+ var card struct {+ Config struct {+ UpdateMulti bool `json:"update_multi"`+ }+ Body struct{ Elements []struct{ Content string } }+ }+ if err := json.Unmarshal([]byte(body["content"]), &card); err != nil {+ t.Error(err)+ return+ }+ want := "Here are the chart and report.\n\n"+ if markdown {+ want = "Here are the chart and report.\n\nAfter the chart."+ }+ if !card.Config.UpdateMulti || len(card.Body.Elements) != 1 || card.Body.Elements[0].Content != want {+ t.Errorf("mixed card lost text/image ordering: %+v", card)+ }+ })+ fake.stubSend(map[string]any{"code": 0, "data": map[string]string{"message_id": "om_accepted"}}, func(_ *http.Request, body map[string]string) {+ kindsMu.Lock()+ defer kindsMu.Unlock()+ kinds[body["msg_type"]]+++ if body["msg_type"] == "interactive" {+ var card struct {+ Body struct{ Elements []struct{ Content string } }+ }+ if err := json.Unmarshal([]byte(body["content"]), &card); err != nil {+ t.Fatal(err)+ }+ want := "Here are the chart and report."+ if markdown {+ want += "\n[chart](https://multica.example/api/attachments/" + chartID + "/download)\nAfter the chart."+ }+ if len(card.Body.Elements) != 1 || card.Body.Elements[0].Content != want {+ t.Errorf("Feishu would reject an artifact URL used as an image key: %+v", card)+ }+ }+ if (body["msg_type"] == "image" || body["msg_type"] == "file") && body["uuid"] == "" {+ t.Error("attachment send missing UUID")+ }+ })+ client := NewHTTPAPIClient(HTTPClientConfig{BaseURL: fake.URL(), ResourceHTTPClient: fake.srv.Client(), Logger: newDiscardLogger()})+ queries := db.New(pool)+ p := NewPatcher(NewChannelStore(queries), fakeCredentials{secret: "test-secret"}, client, PatcherConfig{Logger: newDiscardLogger()})+ if !p.SetAttachments(fakeObjectStore{objects: data}) {+ t.Fatal("file delivery not enabled")+ }+ p.spawn = func(f func()) { f() }+ event := events.Event{Type: protocol.EventChatDone, WorkspaceID: fx.WorkspaceID, TaskID: taskID, ChatSessionID: sessionID,+ Payload: protocol.ChatDonePayload{TaskID: taskID, ChatSessionID: sessionID, MessageID: messageID, Content: "Here are the chart and report."}}+ if markdown {+ payload := event.Payload.(protocol.ChatDonePayload)+ payload.Content += "\n\nAfter the chart."+ event.Payload = payload+ }+ if err := p.processEvent(context.Background(), event); err != nil {+ t.Fatal(err)+ }+ if err := p.processEvent(context.Background(), event); err != nil {+ t.Fatal(err)+ }+ kindsMu.Lock()+ defer kindsMu.Unlock()+ if kinds["interactive"] != 1 || kinds["text"] != 0 || kinds["image"] != 0 || kinds["file"] != 1 || patches != 1 {+ t.Fatalf("completion replay changed mixed reply: messages=%v patches=%d", kinds, patches)+ }+ row, err := queries.GetChannelReplyDelivery(context.Background(), util.MustParseUUID(taskID))+ if err != nil || row.Phase != "settled" {+ t.Fatalf("delivery not settled: %v %v", row, err)+ }+}diff --git a/server/internal/integrations/lark/outbound_media_test.go b/server/internal/integrations/lark/outbound_media_test.gonew file mode 100644index 0000000000..b4a6def954--- /dev/null+++ b/server/internal/integrations/lark/outbound_media_test.go@@ -0,0 +1,479 @@+package lark++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// fakeMediaAPIClient is the APIClient the patcher is built with, plus the+// four media methods it type-asserts for. Embedding the ordinary fake keeps+// this from drifting when APIClient grows a method.+type fakeMediaAPIClient struct {+ *fakeAPIClient++ mu sync.Mutex+ images []UploadImageParams+ files []UploadFileParams+ imagesOut []SendImageParams+ filesOut []SendFileParams++ uploadErr error+ sendErr error+ imageKey string+ fileKey string+}++func (f *fakeMediaAPIClient) UploadImage(_ context.Context, p UploadImageParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.images = append(f.images, p)+ if f.uploadErr != nil {+ return "", f.uploadErr+ }+ if f.imageKey == "" {+ return "img_fake", nil+ }+ return f.imageKey, nil+}++func (f *fakeMediaAPIClient) UploadFile(_ context.Context, p UploadFileParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.files = append(f.files, p)+ if f.uploadErr != nil {+ return "", f.uploadErr+ }+ if f.fileKey == "" {+ return "file_fake", nil+ }+ return f.fileKey, nil+}++func (f *fakeMediaAPIClient) SendImageMessage(_ context.Context, p SendImageParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.imagesOut = append(f.imagesOut, p)+ return "lark_img_msg", f.sendErr+}++func (f *fakeMediaAPIClient) SendFileMessage(_ context.Context, p SendFileParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.filesOut = append(f.filesOut, p)+ return "lark_file_msg", f.sendErr+}++// fakeObjectStore is an in-memory mediaObjectStore. URLs are the configured+// prefix plus the key, which is the shape both real implementations use.+type fakeObjectStore struct {+ objects map[string][]byte+ readErr error+}++const fakeObjectPrefix = "https://cdn.example/"++func (s fakeObjectStore) KeyFromURL(rawURL string) string {+ if !strings.HasPrefix(rawURL, fakeObjectPrefix) {+ return ""+ }+ return strings.TrimPrefix(rawURL, fakeObjectPrefix)+}++func (s fakeObjectStore) GetReader(_ context.Context, key string) (io.ReadCloser, error) {+ if s.readErr != nil {+ return nil, s.readErr+ }+ data, ok := s.objects[key]+ if !ok {+ return nil, fmt.Errorf("fake store: no object %q", key)+ }+ return io.NopCloser(bytes.NewReader(data)), nil+}++func newMediaTestPatcher(t *testing.T) (*Patcher, *fakePatcherQueries, *fakeMediaAPIClient) {+ t.Helper()+ q := &fakePatcherQueries{+ binding: ChatSessionBinding{+ ChatSessionID: uuidFromString(t, "cccccccc-cccc-cccc-cccc-cccccccccccc"),+ InstallationID: uuidFromString(t, "1111aaaa-1111-1111-1111-111111111111"),+ ChannelChatID: "oc_test_chat",+ ChatType: "p2p",+ },+ installation: Installation{+ ID: uuidFromString(t, "1111aaaa-1111-1111-1111-111111111111"),+ WorkspaceID: uuidFromString(t, "99999999-9999-9999-9999-999999999999"),+ AppID: testCreds().AppID,+ AppSecretEncrypted: []byte("ciphertext"),+ Status: string(InstallationActive),+ AgentID: uuidFromString(t, "aaaa1111-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),+ },+ agent: db.Agent{Name: "TestAgent"},+ }+ api := &fakeMediaAPIClient{+ fakeAPIClient: &fakeAPIClient{sendReturn: "lark_card_msg_1", textSendReturn: "lark_text_msg_1", mdCardReturn: "lark_card_msg_1"},+ }+ p := NewPatcher(q, fakeCredentials{secret: "shh"}, api, PatcherConfig{+ Logger: newDiscardLogger(),+ Now: time.Now,+ })+ return p, q, api+}++// pngBytes is a non-empty body with a plausible image header — enough for a+// path that only counts bytes and reads a content type off the row.+var pngBytes = append([]byte{0x89, 'P', 'N', 'G'}, bytes.Repeat([]byte{0}, 32)...)++func TestLarkFileTypeFor(t *testing.T) {+ cases := map[string]string{+ "report.pdf": "pdf",+ "clip.mp4": "mp4",+ "voice.opus": "opus",+ "legacy.doc": "doc",+ "legacy.xls": "xls",+ "legacy.ppt": "ppt",+ "REPORT.PDF": "pdf",+ // Everything else is `stream`. Deliberately not mapped by family: a+ // wrong specific type is refused by Lark, while `stream` always+ // sends.+ "sheet.xlsx": "stream",+ "deck.pptx": "stream",+ "modern.docx": "stream",+ "archive.tar.gz": "stream",+ "no-extension": "stream",+ }+ for name, want := range cases {+ if got := larkFileTypeFor(name); got != want {+ t.Errorf("larkFileTypeFor(%q) = %q, want %q", name, got, want)+ }+ }+}++func TestIsImageAttachment(t *testing.T) {+ cases := []struct {+ contentType, filename string+ want bool+ }{+ {"image/png", "a.png", true},+ {"image/jpeg; charset=binary", "a.jpg", true},+ {"application/pdf", "a.png", false},+ {"image/svg+xml", "a.png", false},+ {"image/avif", "a.png", false},+ {"image/future", "a.png", false},+ {"IMAGE/JPEG; charset=binary", "chart", true},+ {"image/tiff", "chart", true},+ {"image/heic", "chart", true},+ // Only an absent or generic content type falls back to the filename.+ {"application/octet-stream", "a.png", true},+ {"", "a.png", true},+ {"", "a.PNG", true},+ {"", "a.pdf", false},+ {"", "", false},+ }+ for _, c := range cases {+ if got := isImageAttachment(c.contentType, c.filename); got != c.want {+ t.Errorf("isImageAttachment(%q, %q) = %v, want %v", c.contentType, c.filename, got, c.want)+ }+ }+}++func TestChatDoneMessageID(t *testing.T) {+ if got := chatDoneMessageID(map[string]any{"message_id": "abc"}); got != "abc" {+ t.Errorf("map payload: got %q", got)+ }+ if got := chatDoneMessageID(map[string]any{}); got != "" {+ t.Errorf("empty map payload: got %q", got)+ }+ if got := chatDoneMessageID("not a payload"); got != "" {+ t.Errorf("unexpected payload type: got %q", got)+ }+}++func imageRow(t *testing.T, id, name string) db.Attachment {+ t.Helper()+ return db.Attachment{+ ID: uuidFromString(t, id),+ Filename: name,+ Url: fakeObjectPrefix + name,+ ContentType: "image/png",+ }+}++func fileRow(t *testing.T, id, name, contentType string) db.Attachment {+ t.Helper()+ return db.Attachment{+ ID: uuidFromString(t, id),+ Filename: name,+ Url: fakeObjectPrefix + name,+ ContentType: contentType,+ }+}++// TestDeliverAttachmentsRoutesByKind pins the one branch in this path: an+// image goes to the image endpoint as `msg_type=image`, anything else goes+// to the file endpoint as `msg_type=file`. Getting this backwards is not a+// cosmetic bug — Lark refuses a body whose bytes disagree with the declared+// kind, so a misrouted file is lost rather than degraded.+func TestDeliverAttachmentsRoutesByKind(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{+ "chart.png": pngBytes,+ "report.pdf": []byte("%PDF-1.4 fake"),+ }})+ q.attachments = []db.Attachment{+ imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png"),+ fileRow(t, "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "report.pdf", "application/pdf"),+ }++ p.deliverAttachments(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, uuidString(uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")))++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.images) != 1 || len(api.imagesOut) != 1 {+ t.Fatalf("expected one image upload + send; uploads=%d sends=%d", len(api.images), len(api.imagesOut))+ }+ if len(api.files) != 1 || len(api.filesOut) != 1 {+ t.Fatalf("expected one file upload + send; uploads=%d sends=%d", len(api.files), len(api.filesOut))+ }+ if got := api.images[0].Filename; got != "chart.png" {+ t.Errorf("image uploaded from wrong row: %q", got)+ }+ if got := api.files[0].FileType; got != "pdf" {+ t.Errorf("pdf should be declared pdf, got %q", got)+ }+ if !bytes.Equal(api.images[0].Data, pngBytes) {+ t.Error("image upload did not carry the object's bytes")+ }+ if api.imagesOut[0].ImageKey != "img_fake" || api.filesOut[0].FileKey != "file_fake" {+ t.Error("send did not use the key the upload returned")+ }+ // No notice on the happy path: a delivery is what the user sees.+ if len(api.textSent) != 0 {+ t.Errorf("happy path must not warn; got %d notices", len(api.textSent))+ }+}++// TestDeliverAttachmentsLookupFailureTellsUser: we could not read what was+// attached, so we do not know whether a file existed. Silence here is what+// leaves a user waiting for something that was never attempted.+func TestDeliverAttachmentsLookupFailureTellsUser(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{})+ q.attachmentsErr = fmt.Errorf("boom")++ p.deliverAttachments(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, uuidString(uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")))++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 || api.textSent[0].Text != mediaLookupFailedText {+ t.Fatalf("expected the lookup-failure notice; textSent=%+v", api.textSent)+ }+}++// TestDeliverAttachmentsWarnsOnceForManyFailures: files are independent, so+// one bad object must not stop the rest — but the user gets one line, not+// one per file.+func TestDeliverAttachmentsWarnsOnceForManyFailures(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ // The store has no objects, so every read fails.+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{}})+ q.attachments = []db.Attachment{+ imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "one.png"),+ imageRow(t, "bbbb3333-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "two.png"),+ }++ p.deliverAttachments(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, uuidString(uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")))++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.imagesOut) != 0 {+ t.Fatalf("nothing should have been sent; got %d", len(api.imagesOut))+ }+ if len(api.textSent) != 1 || api.textSent[0].Text != mediaSendFailedText {+ t.Fatalf("expected exactly one failure notice; textSent=%+v", api.textSent)+ }+}++// TestDeliverAttachmentsNoOpsWithoutWiring: the stub client does not+// implement the media interface and a deployment may have no storage. Both+// must be quiet no-ops, not lookups or panics.+func TestDeliverAttachmentsNoOpsWithoutWiring(t *testing.T) {+ t.Run("no object store", func(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ // SetAttachments deliberately not called.+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, map[string]any{"message_id": "dddd4444-dddd-dddd-dddd-dddddddddddd"})+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.imagesOut) != 0 || len(api.textSent) != 0 {+ t.Error("no store means no delivery and no notice")+ }+ })++ t.Run("no media client", func(t *testing.T) {+ // The ordinary fakeAPIClient does not implement mediaAPIClient,+ // which is exactly how the production stub behaves.+ p, q, api := newTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, map[string]any{"message_id": "dddd4444-dddd-dddd-dddd-dddddddddddd"})+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 0 {+ t.Error("no media client means no delivery and no notice")+ }+ })++ t.Run("no message id", func(t *testing.T) {+ p, q, _ := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}+ p.deliverAttachmentsAsync(context.Background(), testCreds(), q.binding, ReplyTarget{},+ q.installation.WorkspaceID, map[string]any{"content": "no message id here"})+ q.mu.Lock()+ defer q.mu.Unlock()+ if len(q.attachmentLookups) != 0 {+ t.Error("a payload with no message id must not trigger a lookup")+ }+ })+}++// TestChatReplySpawnsDeliveryAfterReply is the integration seam: a chat:done+// with a message id must send the answer AND then deliver the files bound to+// it, in that order.+func TestChatReplySpawnsDeliveryAfterReply(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})++ messageID := uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}++ p.handleEvent(newChatDoneEvent(t, taskID, q.binding.ChatSessionID, messageID, "Here is the chart."))++ // The spawn is asynchronous by design, so poll for its effect rather+ // than sleeping a fixed amount.+ waitFor(t, func() bool {+ api.fakeAPIClient.mu.Lock()+ defer api.fakeAPIClient.mu.Unlock()+ return len(api.patched) == 1+ }, "image update in the original reply")++ api.mu.Lock()+ defer api.mu.Unlock()+ api.fakeAPIClient.mu.Lock()+ defer api.fakeAPIClient.mu.Unlock()+ if len(api.mdCardSent) != 1 || api.mdCardSent[0].Markdown != "Here is the chart." || len(api.textSent) != 0 {+ t.Fatalf("the answer must go out exactly once as an updatable card; cards=%+v", api.mdCardSent)+ }+ if len(api.imagesOut) != 0 || !strings.Contains(api.patched[0].CardJSON, "img_fake") {+ t.Error("image must use the uploaded key inside the original message")+ }+}++// TestChatReplyDoesNotDeliverWhenReplyFails: the files are the second hop,+// so there is no first hop to follow when the answer itself did not land.+// A file arriving under no answer is worse than a missing file.+func TestChatReplyDoesNotDeliverWhenReplyFails(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})+ api.mdCardErr = fmt.Errorf("lark is down")++ messageID := uuidFromString(t, "dddd4444-dddd-dddd-dddd-dddddddddddd")+ taskID := uuidFromString(t, "ee888888-ee88-ee88-ee88-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}++ p.handleEvent(newChatDoneEvent(t, taskID, q.binding.ChatSessionID, messageID, "plain prose"))++ // Give the (supposedly absent) goroutine a chance to run, so this is+ // not passing merely because nothing was scheduled yet.+ time.Sleep(50 * time.Millisecond)+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.imagesOut) != 0 || len(api.images) != 0 {+ t.Fatalf("no delivery may follow a failed reply; uploads=%d sends=%d", len(api.images), len(api.imagesOut))+ }+}++// TestChatReplyDeliversAttachmentOnlyReply covers the shape task.go calls+// "the attachment cards ARE the response": an agent that produced a file and+// no prose writes an empty-text outcome. The reply send is skipped; the+// delivery is not. Without this the one case where the files are the whole+// answer is the one case the user hears nothing.+func TestChatReplyDeliversAttachmentOnlyReply(t *testing.T) {+ p, q, api := newMediaTestPatcher(t)+ p.SetAttachments(fakeObjectStore{objects: map[string][]byte{"chart.png": pngBytes}})++ messageID := uuidFromString(t, "dddd9999-dddd-dddd-dddd-dddddddddddd")+ taskID := uuidFromString(t, "ee999999-ee99-ee99-ee99-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true+ q.attachments = []db.Attachment{imageRow(t, "aaaa2222-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "chart.png")}++ // Empty content: the attachment is the whole reply.+ p.handleEvent(newChatDoneEvent(t, taskID, q.binding.ChatSessionID, messageID, ""))++ waitFor(t, func() bool {+ api.mu.Lock()+ defer api.mu.Unlock()+ return len(api.imagesOut) == 1+ }, "attachment-only delivery")++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 0 {+ t.Errorf("empty content must not produce a text message; textSent=%+v", api.textSent)+ }+}++// waitFor polls cond until it holds or the budget runs out. The delivery+// path is deliberately asynchronous, so a test cannot assert on it without+// waiting for the thing it is asserting on.+func waitFor(t *testing.T, cond func() bool, what string) {+ t.Helper()+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ if cond() {+ return+ }+ time.Sleep(5 * time.Millisecond)+ }+ t.Fatalf("timed out waiting for %s", what)+}++// newChatDoneEvent builds the bus event a completed chat task publishes. The+// MessageID is what the attachment hop keys off, so every test here sets one.+func newChatDoneEvent(t *testing.T, taskID, sessionID pgtype.UUID, messageID pgtype.UUID, content string) events.Event {+ t.Helper()+ return events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(sessionID),+ Payload: protocol.ChatDonePayload{+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(sessionID),+ MessageID: uuidString(messageID),+ Content: content,+ },+ }+}diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.goindex bce66a6da4..481d150fc6 100644--- a/server/internal/integrations/lark/outbound_test.go+++ b/server/internal/integrations/lark/outbound_test.go@@ -40,6 +40,27 @@ type fakePatcherQueries struct {deliveriesByTask map[string]db.ChannelTaskDelivery// tasksByID overrides `task` per task_id; empty falls back to `task`.tasksByID map[string]db.AgentTaskQueue+ // attachments is what the assistant message's files resolve to, and+ // attachmentsErr forces the lookup to fail. attachmentLookups records+ // every lookup so a test can assert what the delivery path asked for+ // (and that it did not ask at all when it had nothing to do).+ attachments []db.Attachment+ attachmentsErr error+ attachmentLookups []db.ListAttachmentsByChatMessageParams+ mediaLedger map[string]db.ChannelReplyDelivery+ mediaLedgerErr error+ mediaSession *db.ChatSession+}++// ListAttachmentsByChatMessage reads the fake's seeded rows. Unlike the+// generated query it ignores the workspace scoping — tests seed rows and+// ids together, so a workspace mismatch is not a shape any test needs to+// express.+func (f *fakePatcherQueries) ListAttachmentsByChatMessage(_ context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.attachmentLookups = append(f.attachmentLookups, arg)+ return f.attachments, f.attachmentsErr}func (f *fakePatcherQueries) GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {@@ -71,7 +92,10 @@ func (f *fakePatcherQueries) GetChannelTaskDelivery(_ context.Context, taskID pgreturn f.delivery, f.deliveryErr}func (f *fakePatcherQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {- return db.ChatSession{}, nil+ if f.mediaSession != nil {+ return *f.mediaSession, nil+ }+ return db.ChatSession{ID: id, Status: "active", WorkspaceID: f.installation.WorkspaceID}, nil}func (f *fakePatcherQueries) GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error) {return f.agent, f.agentErrdiff --git a/server/internal/integrations/lark/params.go b/server/internal/integrations/lark/params.goindex 03818bc69d..6af542de9c 100644--- a/server/internal/integrations/lark/params.go+++ b/server/internal/integrations/lark/params.go@@ -135,3 +135,57 @@ type UpdateOutboundCardStatusParams struct {ID pgtype.UUIDStatus string}++// UploadImageParams carries one image's bytes up to Lark's image endpoint+// (POST /open-apis/im/v1/images) to obtain an image_key. Lark requires+// image_type=message for anything sent into a chat; the returned key is+// what `msg_type=image` and card `img` elements both consume.+type UploadImageParams struct {+ InstallationID InstallationCredentials+ // Filename is advisory only — Lark keys the object and echoes the+ // key back; it never sees the name. Kept for log lines.+ Filename string+ // Data is the raw image bytes. Lark caps this at 10 MB and refuses+ // a zero-byte body; the caller enforces both before calling.+ Data []byte+}++// UploadFileParams carries one non-image file's bytes up to Lark's file+// endpoint (POST /open-apis/im/v1/files) to obtain a file_key.+//+// FileType is Lark's own enum — opus / mp4 / pdf / doc / xls / ppt /+// stream — and it is a claim about the bytes, not a label: Lark refuses a+// body whose type disagrees with an over-specific claim rather than+// downgrading it. See larkFileTypeFor for how the mapping is derived and+// why `stream` is the safe default.+type UploadFileParams struct {+ InstallationID InstallationCredentials+ Filename string+ // FileType must already be a value from Lark's enum; the caller+ // resolves it (larkFileTypeFor) so this stays a transport type.+ FileType string+ Data []byte+}++// SendImageParams posts an already-uploaded image (by image_key) into a+// chat as its own `msg_type=image` message.+type SendImageParams struct {+ InstallationID InstallationCredentials+ ChatID ChatID+ ImageKey string+ ReplyTarget ReplyTarget+ UUID string+}++// SendFileParams posts an already-uploaded file (by file_key) into a chat+// as its own message, with a type matching the upload.+type SendFileParams struct {+ InstallationID InstallationCredentials+ ChatID ChatID+ FileKey string+ // FileType is the type used for UploadFile. MP4 and Opus uploads require+ // media and audio messages; empty and other types use file messages.+ FileType string+ ReplyTarget ReplyTarget+ UUID string+}