Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7620 feat(telegram): send and receive photos, videos and files (#8727)
pseudoyu62efe26aa09f
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdxindex 74215b6eb6..081ce7426b 100644--- a/apps/docs/content/docs/channels.ja.mdx+++ b/apps/docs/content/docs/channels.ja.mdx@@ -29,7 +29,7 @@ DingTalk、WeCom、Telegram は[コミュニティメンテナンス](/communityWeCom が現在扱えるのはテキストメッセージのみです。音声、画像、ファイルのメッセージにはその旨の短い返信が返り、エージェントには渡されません。-Telegram が現在扱えるのはテキストメッセージのみです。未対応のメディアにはその旨の短い返信が返り、エージェントには渡されません。+Telegram は画像、ファイル、動画、音声を添付ファイルとしてエージェントに渡し、エージェントが生成したファイルをチャットに送り返します。どちらもサーバー側にオブジェクトストレージの設定が必要で、未設定の場合メディアには従来どおり非対応の短い返信が返ります。sticker などファイル以外のメッセージにも同じ返信が返り、エージェントには渡されません。詳しい手順:diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdxindex b2a3cce00e..b83f71954d 100644--- a/apps/docs/content/docs/channels.ko.mdx+++ b/apps/docs/content/docs/channels.ko.mdx@@ -29,7 +29,7 @@ DingTalk, WeCom, Telegram은 [커뮤니티에서 유지 관리](/community-maintWeCom은 현재 텍스트 메시지만 처리합니다. 음성, 이미지, 파일 메시지에는 안내 문구만 회신하며 에이전트로 전달하지 않습니다.-Telegram은 현재 텍스트 메시지만 처리합니다. 미지원 미디어에는 안내 문구만 회신하며 에이전트로 전달하지 않습니다.+Telegram은 이미지, 파일, 영상, 음성을 첨부파일로 에이전트에 전달하고, 에이전트가 만든 파일을 채팅으로 다시 보냅니다. 두 방향 모두 서버에 객체 스토리지가 설정되어 있어야 하며, 없으면 미디어에는 이전처럼 미지원 안내만 회신합니다. sticker 등 파일이 아닌 메시지에도 같은 안내를 회신하며 에이전트로 전달하지 않습니다.자세한 단계는 다음 문서를 참고하세요.diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdxindex 6bb7bf302c..a7bcda5b60 100644--- a/apps/docs/content/docs/channels.mdx+++ b/apps/docs/content/docs/channels.mdx@@ -29,7 +29,7 @@ DingTalk, WeCom, and Telegram are [community-maintained](/community-maintained):WeCom handles text messages today. Voice, image, and file messages get a short reply explaining that, and are not passed to the agent.-Telegram handles text messages today. Unsupported media gets a short reply explaining that, and is not passed to the agent.+Telegram passes photos, files, video, and audio to the agent as attachments, and sends files the agent produces back into the chat, when the server has object storage configured; without it, media gets the same short unsupported reply as before. Stickers and other non-file messages get that reply and are not passed to the agent.Step-by-step guides:diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdxindex 8106bc2dd9..e903cfa9cd 100644--- a/apps/docs/content/docs/channels.zh.mdx+++ b/apps/docs/content/docs/channels.zh.mdx@@ -29,7 +29,7 @@ import { Callout } from "fumadocs-ui/components/callout";企业微信目前只处理文字消息。语音、图片和文件消息会收到一句说明,不会转交给智能体。-Telegram 目前只处理文字消息。不支持的媒体消息会收到一句说明,不会转交给智能体。+Telegram 会把图片、文件、视频和音频作为附件转交给智能体,并把智能体生成的文件发回聊天;这两个方向都需要服务端配置对象存储,未配置时媒体消息仍像以前一样收到不支持提示。贴纸等非文件消息会收到同样的提示,不会转交给智能体。详细步骤:diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdxindex d181f75692..c305cbc6e0 100644--- a/apps/docs/content/docs/telegram-bot-integration.ja.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx@@ -50,7 +50,7 @@ Multica は Telegram で Bot を検証し、long polling と競合する webhookBot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は自動分割されます。最終返信はプロセス内で非同期に配信されます。通常、あるチャットのバックオフ待機は worker を占有しません。キャッシュが上限に達してバックオフ状態が圧縮されると、同じ Bot installation の他のチャットも安全側に遅延する場合があります。終端キューの容量は固定で、上限超過は明示的に拒否されてエラーとして記録されます。キューはサービス再起動後に復元されません。-現在はテキストのみ対応しています。画像、ファイル、動画、音声、sticker などは、DM または Bot 宛てのグループメッセージで明確な非対応通知を返します。+画像、ファイル、動画、音声メッセージは、キャプションをメッセージ本文として、同じ会話の添付ファイルとしてエージェントに届きます。Telegram の Bot がダウンロードできるのは 20 MB までで、取得できなかった場合(大きすぎる、またはダウンロード失敗)は Bot がその旨を伝え、エージェントにはプレースホルダーだけが見えます。エージェントが生成したファイルは返信の後に別メッセージとして送り返されます。10 MB までの画像はインライン表示、それ以外は 50 MB までファイルとして届きます。送達を確認できなかった場合は Bot がその旨を伝え、ファイルは Multica の返信に添付されたまま残ります。どちらの方向もサーバー側にオブジェクトストレージが必要です。未設定の場合、Bot はメディアに非対応通知を返し、エージェントにはファイルを送れない旨が伝えられます。sticker、位置情報、投票などファイル以外のメッセージは、DM または Bot 宛てのグループメッセージで同じ通知を返します。## 管理とセルフホスティングdiff --git a/apps/docs/content/docs/telegram-bot-integration.ko.mdx b/apps/docs/content/docs/telegram-bot-integration.ko.mdxindex 08f5fe8c59..5b24b9551e 100644--- a/apps/docs/content/docs/telegram-bot-integration.ko.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx@@ -50,7 +50,7 @@ Multica는 Telegram에서 Bot을 검증하고 long polling과 충돌하는 webhoBot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 자동으로 나뉩니다. 최종 응답은 프로세스 내에서 비동기로 전달됩니다. 일반적으로 한 채팅의 백오프 대기는 worker를 점유하지 않습니다. 캐시가 용량 한계에 도달해 백오프 상태를 압축하면 같은 Bot installation의 다른 채팅도 안전을 위해 지연될 수 있습니다. 최종 응답 큐의 용량은 고정되어 있으며 한도를 넘은 작업은 명시적으로 거부되고 오류로 기록됩니다. 큐는 서비스 재시작 후 복구되지 않습니다.-현재 버전은 텍스트만 받습니다. 이미지, 파일, 영상, 음성, sticker 등은 개인 채팅 또는 Bot에게 보낸 그룹 메시지에서 명확한 미지원 안내를 반환합니다.+이미지, 파일, 영상, 음성 메시지는 caption을 메시지 본문으로 하여 같은 대화의 첨부파일로 에이전트에 전달됩니다. Telegram Bot은 20 MB까지만 내려받을 수 있으며, 파일을 가져오지 못하면(너무 크거나 다운로드 실패) Bot이 알려 주고 에이전트에게는 자리표시자만 보입니다. 에이전트가 만든 파일은 응답 뒤에 별도 메시지로 채팅에 전송됩니다. 10 MB 이하 이미지는 인라인으로, 그 외에는 50 MB까지 파일로 도착합니다. 전달을 확인하지 못하면 Bot이 알려 주며 파일은 Multica의 응답에 첨부된 채로 남습니다. 두 방향 모두 서버에 객체 스토리지가 필요합니다. 설정이 없으면 Bot은 미디어에 미지원 안내를 회신하고 에이전트는 파일을 보낼 수 없다는 안내를 받습니다. sticker, 위치, 투표 등 파일이 아닌 메시지는 개인 채팅 또는 Bot에게 보낸 그룹 메시지에서 같은 안내를 반환합니다.## 관리 및 자체 호스팅diff --git a/apps/docs/content/docs/telegram-bot-integration.mdx b/apps/docs/content/docs/telegram-bot-integration.mdxindex b8639d0826..edfdb2d019 100644--- a/apps/docs/content/docs/telegram-bot-integration.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.mdx@@ -63,7 +63,7 @@ Add the Bot to a group, then either @-mention it or reply directly to one of itsThe Bot streams text by posting and editing a Telegram message, quotes the triggering message, preserves forum topics, and splits long replies under Telegram's message limit. Final replies are delivered asynchronously by an in-process queue. Normally, one chat's backoff does not occupy a worker; if cache pressure compacts exact backoff state, other chats under the same Bot installation may be conservatively delayed. The terminal queue has fixed capacity: overflow is rejected and logged, and queued replies are not recovered after a service restart.-This version accepts text only. Photos, files, video, voice, stickers, and other non-text messages receive a clear unsupported-message response in private chats; addressed group media receives the same response, while unaddressed group media remains silent.+Photos, files, video, voice, and audio messages reach the agent as attachments on the same conversation, with the caption as the message text. Telegram lets a Bot download files up to 20 MB; when a file can't be fetched (too large, or the download fails) the Bot tells you so, and the agent sees only a placeholder. Files the agent produces are sent back into the chat as separate messages after its reply: photos up to 10 MB render inline, everything else up to 50 MB arrives as a file; if a file can't be confirmed delivered, the Bot says so and the file stays attached to the reply in Multica. Both directions need object storage on the server (see the self-hosting section below); without it the Bot answers media with the unsupported-message notice, and the agent is told it cannot send files. Stickers, locations, polls, and other non-file messages receive the same notice in private chats and when addressed in groups; unaddressed group messages of those kinds remain silent.## Manage connectionsdiff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdxindex b8f5420729..f97bd8a02e 100644--- a/apps/docs/content/docs/telegram-bot-integration.zh.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx@@ -63,7 +63,7 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲Bot 通过发送并编辑 Telegram 消息来流式展示文字回复,引用触发消息、保留 forum topic,并按 Telegram 长度限制自动分段。最终回复在进程内异步投递。正常情况下,某个聊天的退避等待不会占用 worker;缓存达到容量上限并压缩退避状态时,同一 Bot installation 下的其他聊天可能被保守延迟。终态队列有固定容量,超限运行会被明确拒绝并记录错误;队列不会跨服务重启恢复。-当前版本只接收文字。图片、文件、视频、语音、贴纸等非文字消息在私聊中会收到明确的不支持提示;群里明确 @ Bot 的媒体消息也会收到提示,未 @ 的媒体消息保持静默。+图片、文件、视频、语音和音频消息会作为同一对话的附件交给智能体,caption 作为消息正文。Telegram 只允许 Bot 下载 20 MB 以内的文件;文件无法获取时(太大或下载失败),Bot 会告诉你,智能体只会看到一个占位符。智能体生成的文件会在回复之后作为单独的消息发回聊天:10 MB 以内的图片内联显示,其余 50 MB 以内的文件以文件形式到达;无法确认送达时 Bot 会说明,文件仍保留在 Multica 的回复附件里。这两个方向都需要服务端配置对象存储(见下文自托管部分);未配置时,Bot 对媒体消息回复不支持提示,智能体也会被告知无法发送文件。贴纸、位置、投票等非文件消息在私聊中以及群里明确 @ Bot 时会收到同样的提示,群里未 @ 的此类消息保持静默。## 管理与断开diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 7ad585fc9d..1cb7b321d1 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1183,8 +1183,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusLogger: slog.Default(),})telegramTyping := telegram.NewTypingNotifier(box.Open, "", nil, slog.Default())- channelRouter.Register(telegram.TypeTelegram, telegram.NewTelegramResolverSet(queries, pool, telegramReplier, telegramTyping))+ // Media both ways needs object storage: inbound photos/files become+ // chat attachments only when there is somewhere to put the bytes,+ // and the agent is promised outbound file delivery only where the+ // same storage exists to read them back from. One `if` decides both+ // halves so the capability and the promise cannot drift (same rule+ // as WeCom above).+ var telegramMedia engine.MediaResolvertelegramOutbound := telegram.NewOutbound(queries, box.Open, "", nil, slog.Default())+ if store != nil {+ telegramMedia = telegram.NewMediaResolver(box.Open, store, engine.NewDBMediaIntentLedger(queries), "", nil, slog.Default())+ telegramOutbound.EnableFileDelivery(store)+ h.DeclareChannelFileDelivery(string(telegram.TypeTelegram))+ }+ channelRouter.Register(telegram.TypeTelegram, telegram.NewTelegramResolverSet(queries, pool, telegramReplier, telegramTyping, telegramMedia))telegramOutbound.Register(bus)h.TelegramOutbound = telegramOutbound@@ -1194,6 +1206,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusDecrypt: box.Open,Logger: slog.Default(),RecentContextSize: telegram.DefaultRecentContextSize,+ AcceptsMedia: store != nil,})installSvc, ierr := telegram.NewInstallService(queries, pool, box, slog.Default())diff --git a/server/internal/daemon/execenv/channel_type.go b/server/internal/daemon/execenv/channel_type.goindex 2a33f8636d..fb2753e463 100644--- a/server/internal/daemon/execenv/channel_type.go+++ b/server/internal/daemon/execenv/channel_type.go@@ -17,6 +17,7 @@ const (ChannelTypeFeishu = "feishu"ChannelTypeWecom = "wecom"ChannelTypeDingtalk = "dingtalk"+ ChannelTypeTelegram = "telegram")// SurfacePersistsTranscript reports whether a chat surface stores its@@ -128,6 +129,8 @@ func ChannelDisplayName(channelType string) string {return "WeCom"case ChannelTypeDingtalk:return "DingTalk"+ case ChannelTypeTelegram:+ return "Telegram"default:return channelType}diff --git a/server/internal/integrations/channel/engine/channel_title_adapters_db_test.go b/server/internal/integrations/channel/engine/channel_title_adapters_db_test.goindex 6f173c9699..47c4ead813 100644--- a/server/internal/integrations/channel/engine/channel_title_adapters_db_test.go+++ b/server/internal/integrations/channel/engine/channel_title_adapters_db_test.go@@ -67,7 +67,7 @@ func TestChannelStartTitleCommandMappingDB(t *testing.T) {case "feishu":binder = lark.NewFeishuResolverSet(nil, session, nil, nil, nil, nil).Sessioncase "telegram":- binder = telegram.NewTelegramResolverSet(q, pool, nil, nil).Session+ binder = telegram.NewTelegramResolverSet(q, pool, nil, nil, nil).Sessioncase "dingtalk":binder = dingtalk.NewDingTalkResolverSet(q, pool, nil, nil, nil, nil).Sessioncase "slack":diff --git a/server/internal/integrations/telegram/api.go b/server/internal/integrations/telegram/api.goindex a5dfc768ca..8c4bd31ad2 100644--- a/server/internal/integrations/telegram/api.go+++ b/server/internal/integrations/telegram/api.go@@ -7,7 +7,11 @@ import ("errors""fmt""io"+ "mime/multipart""net/http"+ "net/textproto"+ "strconv"+ "strings""time")@@ -117,6 +121,11 @@ func (a *botAPI) call(ctx context.Context, method string, params any, out any) eif params != nil {req.Header.Set("Content-Type", "application/json")}+ return a.do(req, method, out)+}++// do performs one prepared Bot API request and decodes the envelope.+func (a *botAPI) do(req *http.Request, method string, out any) error {resp, err := a.client.Do(req)if err != nil {return &requestError{method: method, cause: err}@@ -169,13 +178,132 @@ type Message struct {ReplyToMessage *Message `json:"reply_to_message,omitempty"`MessageThreadID int64 `json:"message_thread_id,omitempty"`IsTopicMessage bool `json:"is_topic_message,omitempty"`- Photo []any `json:"photo,omitempty"`- Document *struct {- FileName string `json:"file_name"`- } `json:"document,omitempty"`- Voice *struct{} `json:"voice,omitempty"`- Video *struct{} `json:"video,omitempty"`- Sticker *struct{} `json:"sticker,omitempty"`+ // A message carries at most one of the media below (an album arrives as+ // one message per item). Photo lists the available sizes, smallest first.+ Photo []PhotoSize `json:"photo,omitempty"`+ Document *FileRef `json:"document,omitempty"`+ Video *FileRef `json:"video,omitempty"`+ VideoNote *FileRef `json:"video_note,omitempty"`+ Animation *FileRef `json:"animation,omitempty"`+ Audio *FileRef `json:"audio,omitempty"`+ Voice *FileRef `json:"voice,omitempty"`+ Sticker *struct{} `json:"sticker,omitempty"`+}++// PhotoSize is one rendition of a photo message.+type PhotoSize struct {+ FileID string `json:"file_id"`+ FileUniqueID string `json:"file_unique_id"`+ Width int `json:"width"`+ Height int `json:"height"`+ FileSize int64 `json:"file_size,omitempty"`+}++// FileRef is the common shape of Document / Video / Animation / Audio / Voice:+// the fields getFile needs plus the display metadata the attachment row keeps.+// Kinds without a file_name simply leave it empty.+type FileRef struct {+ FileID string `json:"file_id"`+ FileUniqueID string `json:"file_unique_id"`+ FileName string `json:"file_name,omitempty"`+ MimeType string `json:"mime_type,omitempty"`+ FileSize int64 `json:"file_size,omitempty"`+}++// File is the getFile result. FilePath is relative to the file download host.+type File struct {+ FileID string `json:"file_id"`+ FileSize int64 `json:"file_size,omitempty"`+ FilePath string `json:"file_path,omitempty"`+}++// maxBotDownloadBytes is Telegram's cap on what a bot may download via getFile+// (20 MB). Larger media is refused by Telegram itself, so the resolver refuses+// it up front without spending an intent row on it.+const maxBotDownloadBytes = 20 << 20++// GetFile resolves a file_id to a download path.+func (a *botAPI) GetFile(ctx context.Context, fileID string) (File, error) {+ var f File+ err := a.call(ctx, "getFile", struct {+ FileID string `json:"file_id"`+ }{FileID: fileID}, &f)+ return f, err+}++// DownloadFile fetches a file the getFile call located. The download host+// puts the bot token in the URL, so failures are reported without it.+func (a *botAPI) DownloadFile(ctx context.Context, filePath string, maxBytes int64) ([]byte, string, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/file/bot"+a.token+"/"+strings.TrimPrefix(filePath, "/"), nil)+ if err != nil {+ return nil, "", errors.New("telegram: build file download request failed")+ }+ resp, err := a.client.Do(req)+ if err != nil {+ return nil, "", &requestError{method: "downloadFile", cause: err}+ }+ defer resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return nil, "", fmt.Errorf("telegram: file download: http %d", resp.StatusCode)+ }+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes+1))+ if err != nil {+ return nil, "", fmt.Errorf("telegram: read file download: %w", err)+ }+ if int64(len(data)) > maxBytes {+ return nil, "", fmt.Errorf("telegram: file exceeds the %d byte download limit", maxBytes)+ }+ contentType := resp.Header.Get("Content-Type")+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {+ contentType = strings.TrimSpace(contentType[:semi])+ }+ return data, contentType, nil+}++// sendMediaParams addresses one outbound file. Field is the multipart part the+// Bot API method expects ("photo" for sendPhoto, "document" for sendDocument,+// …); the method name is derived from it.+type sendMediaParams struct {+ ChatID int64+ MessageThreadID int64+ Field string+ Filename string+ ContentType string+ Data []byte+}++// SendMedia uploads one file as its own message via sendPhoto / sendDocument /+// sendVideo / sendAudio — the multipart counterpart of SendMessage.+func (a *botAPI) SendMedia(ctx context.Context, p sendMediaParams) (Message, error) {+ var body bytes.Buffer+ mw := multipart.NewWriter(&body)+ _ = mw.WriteField("chat_id", strconv.FormatInt(p.ChatID, 10))+ if p.MessageThreadID != 0 {+ _ = mw.WriteField("message_thread_id", strconv.FormatInt(p.MessageThreadID, 10))+ }+ header := textproto.MIMEHeader{}+ header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename=%q`, p.Field, p.Filename))+ if p.ContentType != "" {+ header.Set("Content-Type", p.ContentType)+ }+ part, err := mw.CreatePart(header)+ if err != nil {+ return Message{}, fmt.Errorf("telegram: encode media upload: %w", err)+ }+ if _, err := part.Write(p.Data); err != nil {+ return Message{}, fmt.Errorf("telegram: encode media upload: %w", err)+ }+ if err := mw.Close(); err != nil {+ return Message{}, fmt.Errorf("telegram: encode media upload: %w", err)+ }+ method := "send" + strings.ToUpper(p.Field[:1]) + p.Field[1:]+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.base+"/bot"+a.token+"/"+method, &body)+ if err != nil {+ return Message{}, fmt.Errorf("telegram: build %s request: %w", method, err)+ }+ req.Header.Set("Content-Type", mw.FormDataContentType())+ var m Message+ return m, a.do(req, method, &m)}// MessageEntity is the Bot API's structured annotation for mentions,diff --git a/server/internal/integrations/telegram/delivery.go b/server/internal/integrations/telegram/delivery.goindex 1355d6ce54..f59e94ab49 100644--- a/server/internal/integrations/telegram/delivery.go+++ b/server/internal/integrations/telegram/delivery.go@@ -340,11 +340,27 @@ func (o *Outbound) settleDelivery(ctx context.Context, lease *deliveryLease, rea}}+// closeOutcome is what closeTurn learned about the turn. The two closed+// outcomes are kept apart because a file-only reply delivers its files from+// the close: only the call that actually ended the turn may do that, or a+// duplicate chat:done would send them again.+type closeOutcome int++const (+ // closeHeld: a live owner still holds the turn; worth waiting for.+ closeHeld closeOutcome = iota+ // closedNow: this call ended the turn.+ closedNow+ // closedAlready: settled earlier, or superseded by a later attempt —+ // closed as far as this attempt is concerned, but not by it.+ closedAlready+)+// closeTurn ends a turn with no answer to deliver — cancelled, or completed// empty. It creates the row when the turn never reached Telegram at all:// without that, a first text frame arriving after the cancellation would find// nothing, open a placeholder, and leave it there with nothing to finish it.-func (o *Outbound) closeTurn(ctx context.Context, target *replyTarget, turn replyTurn, reason string) (bool, error) {+func (o *Outbound) closeTurn(ctx context.Context, target *replyTarget, turn replyTurn, reason string) (closeOutcome, error) {turnID := turn.id_, err := o.q.CloseChannelReplyDeliveryTurn(ctx, db.CloseChannelReplyDeliveryTurnParams{TurnID: turnID,@@ -357,24 +373,27 @@ func (o *Outbound) closeTurn(ctx context.Context, target *replyTarget, turn replSettledReason: reason,})if err == nil {- return true, nil+ return closedNow, nil}if !errors.Is(err, pgx.ErrNoRows) {- return false, err+ return closeHeld, err}// Settled, superseded, or held by a live owner — only the last is worth// waiting for.current, readErr := o.q.GetChannelReplyDelivery(ctx, turnID)if readErr != nil {- return false, readErr+ return closeHeld, readErr}if turn.depth < current.AttemptDepth {// A later attempt owns this turn. Closing it is not this attempt's to// do, and waiting for the chance would hold the session's queue for a// reply that is already someone else's.- return true, nil+ return closedAlready, nil+ }+ if current.Phase == deliveryPhaseSettled {+ return closedAlready, nil}- return current.Phase == deliveryPhaseSettled, nil+ return closeHeld, nil}// recordContext detaches a write that records what Telegram did from thediff --git a/server/internal/integrations/telegram/inbound.go b/server/internal/integrations/telegram/inbound.goindex 6aaaa8eff4..2cc1d4be5b 100644--- a/server/internal/integrations/telegram/inbound.go+++ b/server/internal/integrations/telegram/inbound.go@@ -26,6 +26,65 @@ type telegramRawEvent struct {// SenderName is the sender's Telegram display name, carried for// group-context attribution.SenderName string `json:"sender_name,omitempty"`+ // Media is the one file this message carries, for the media resolver to+ // fetch off the ACK path. Nil for text-only messages.+ Media *inboundMedia `json:"media,omitempty"`+}++// inboundMedia is what the media resolver needs to fetch a message's file:+// the getFile handle plus the display metadata Telegram already told us.+type inboundMedia struct {+ Kind channel.MsgType `json:"kind"`+ FileID string `json:"file_id"`+ FileUniqueID string `json:"file_unique_id,omitempty"`+ FileName string `json:"file_name,omitempty"`+ MimeType string `json:"mime_type,omitempty"`+ FileSize int64 `json:"file_size,omitempty"`+ // Placeholder is the exact marker in the message body the bound+ // attachment replaces with its Markdown link. It stays as plain text when+ // the fetch fails, so the agent still knows a file was there.+ Placeholder string `json:"placeholder"`+ // PlaceholderIndex is which occurrence of Placeholder in the body is the+ // sender's: quoted and recent context go in front of it, and a member+ // who typed the same marker there must not receive the file.+ PlaceholderIndex int `json:"placeholder_index,omitempty"`+}++// mediaFromMessage picks the message's downloadable file, or nil. Photos come+// in several renditions; the largest is the one worth keeping.+func mediaFromMessage(m *Message) *inboundMedia {+ switch {+ case len(m.Photo) > 0:+ best := m.Photo[0]+ for _, p := range m.Photo[1:] {+ if p.Width*p.Height >= best.Width*best.Height {+ best = p+ }+ }+ return &inboundMedia{Kind: channel.MsgTypeImage, FileID: best.FileID, FileUniqueID: best.FileUniqueID,+ MimeType: "image/jpeg", FileSize: best.FileSize, Placeholder: "[Image]"}+ case m.Document != nil:+ return fileRefMedia(channel.MsgTypeFile, m.Document, "[File: "+firstNonEmpty(m.Document.FileName, "attachment")+"]")+ case m.Video != nil:+ return fileRefMedia(channel.MsgTypeVideo, m.Video, "[Video]")+ case m.VideoNote != nil:+ return fileRefMedia(channel.MsgTypeVideo, m.VideoNote, "[Video note]")+ case m.Animation != nil:+ return fileRefMedia(channel.MsgTypeVideo, m.Animation, "[Animation]")+ case m.Audio != nil:+ return fileRefMedia(channel.MsgTypeAudio, m.Audio, "[Audio]")+ case m.Voice != nil:+ return fileRefMedia(channel.MsgTypeAudio, m.Voice, "[Voice message]")+ }+ return nil+}++func fileRefMedia(kind channel.MsgType, f *FileRef, placeholder string) *inboundMedia {+ if f.FileID == "" {+ return nil+ }+ return &inboundMedia{Kind: kind, FileID: f.FileID, FileUniqueID: f.FileUniqueID,+ FileName: f.FileName, MimeType: f.MimeType, FileSize: f.FileSize, Placeholder: placeholder}}// inboundFromUpdate normalizes one Telegram update without any recent group@@ -69,6 +128,7 @@ func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, rectext = m.Caption}msgType := classifyMessage(m)+ media := mediaFromMessage(m)mentioned := mentionsBot(m, botUsername)repliedToBot := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && m.ReplyToMessage.From.ID == botID@@ -84,14 +144,33 @@ func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, recstartChat = control.Kind == engine.ControlCommandNewChat}agentText := cleaned+ own := ""+ if media != nil {+ // The placeholder leads the sender's own text, so a caption reads as+ // the caption of the file above it once the resolver swaps the marker+ // for the attachment link. Quoted and recent context still go in front.+ own = media.Placeholder+ if cleaned != "" {+ own += "\n" + cleaned+ }+ agentText = own+ }quotedHuman := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && !m.ReplyToMessage.From.IsBothasSelectedContext := chatType == channel.ChatTypeGroup && mentioned && quotedHumanif hasSelectedContext {- agentText = enrichWithQuotedHumanMessage(cleaned, m.Chat.ID, m.ReplyToMessage)+ agentText = enrichWithQuotedHumanMessage(agentText, m.Chat.ID, m.ReplyToMessage)}if recent != nil && chatType == channel.ChatTypeGroup && addressed && !startChat {agentText = enrichWithRecentContext(agentText, m, recent)}+ if media != nil {+ // The engine replaces the placeholder by occurrence, and the context+ // enrichers only ever prepend, so the sender's own segment is the+ // suffix. Count every occurrence ahead of it — user-typed literals+ // included — so a member who wrote "[Image]" in the window does not+ // receive the sender's file. Same rule as DingTalk's quoted block.+ media.PlaceholderIndex = strings.Count(agentText[:len(agentText)-len(own)], media.Placeholder)+ }senderID := strconv.FormatInt(m.From.ID, 10)chatID := strconv.FormatInt(m.Chat.ID, 10)@@ -104,6 +183,7 @@ func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, recBotID: strconv.FormatInt(botID, 10),EventType: "message",SenderName: senderDisplayName(m.From),+ Media: media,})var reply *channel.ReplyCtx@@ -158,18 +238,18 @@ func telegramChatType(t string) (channel.ChatType, bool) {}}-// classifyMessage maps the message payload to the normalized MsgType. Only-// text is actionable in v1 (aligned with Feishu/Slack); media kinds are-// reported so the caller can reply "unsupported" rather than stay silent.+// classifyMessage maps the message payload to the normalized MsgType. Text and+// the downloadable media kinds are ingested; MsgTypeUnknown (stickers,+// locations, polls, …) is what the caller answers with the unsupported notice.func classifyMessage(m *Message) channel.MsgType {switch {case m.Text != "":return channel.MsgTypeTextcase len(m.Photo) > 0:return channel.MsgTypeImage- case m.Voice != nil:+ case m.Voice != nil, m.Audio != nil:return channel.MsgTypeAudio- case m.Video != nil:+ case m.Video != nil, m.VideoNote != nil, m.Animation != nil:return channel.MsgTypeVideocase m.Document != nil:return channel.MsgTypeFilediff --git a/server/internal/integrations/telegram/media_ingest.go b/server/internal/integrations/telegram/media_ingest.gonew file mode 100644index 0000000000..caf329f791--- /dev/null+++ b/server/internal/integrations/telegram/media_ingest.go@@ -0,0 +1,263 @@+package telegram++// Inbound media: the engine.MediaResolver for Telegram. HasMedia is a pure+// decode of the raw envelope; ResolveMedia runs off the ACK path and carries+// one file from Telegram into object storage — getFile for the download path,+// the file host for the bytes, an intent-ledger row before the PUT so a crash+// anywhere leaves something the reconciler settles. Mirrors slack/media_ingest.go+// minus the redirect handling: Telegram's download host is fixed.++import (+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "mime"+ "net/http"+ "path"+ "strconv"+ "strings"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// objectStore is the slice of storage.Storage both media directions need:+// Upload + ObjectURL to ingest (ObjectURL is pure, so the intent row can carry+// the final URL before the PUT), KeyFromURL + GetReader to read an agent's+// attachment back out for delivery.+type objectStore interface {+ Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)+ ObjectURL(key string) string+ KeyFromURL(rawURL string) string+ GetReader(ctx context.Context, key string) (io.ReadCloser, error)+}++type mediaResolver struct {+ decrypt Decrypter+ storage objectStore+ ledger engine.MediaIntentLedger+ apiBase string+ client *http.Client+ logger *slog.Logger+}++var _ engine.MediaResolver = (*mediaResolver)(nil)++// NewMediaResolver builds the Telegram media resolver. apiBase and client+// override the Bot API host and HTTP client (tests); empty / nil use+// production. The Router's media deadline bounds each resolution; the client+// timeout only guards a single stalled transfer.+func NewMediaResolver(decrypt Decrypter, storage objectStore, ledger engine.MediaIntentLedger, apiBase string, client *http.Client, logger *slog.Logger) engine.MediaResolver {+ if logger == nil {+ logger = slog.Default()+ }+ if client == nil {+ client = &http.Client{Timeout: 30 * time.Second}+ }+ return &mediaResolver{decrypt: decrypt, storage: storage, ledger: ledger, apiBase: apiBase, client: client, logger: logger}+}++func (r *mediaResolver) HasMedia(msg channel.InboundMessage) bool {+ raw, err := decodeTelegramRaw(msg)+ return err == nil && raw.Media != nil && raw.Media.FileID != ""+}++func (r *mediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {+ raw, err := decodeTelegramRaw(msg)+ if err != nil || raw.Media == nil || raw.Media.FileID == "" {+ return msg+ }+ row, ok := inst.Platform.(db.ChannelInstallation)+ if !ok {+ r.logWarn(msg, errors.New("installation platform row unavailable"))+ return msg+ }+ creds, err := decodeCredentials(row.Config, r.decrypt)+ if err != nil {+ r.logWarn(msg, fmt.Errorf("decode credentials: %w", err))+ return msg+ }+ api := newBotAPI(r.apiBase, creds.BotToken, r.client)+ ref, err := r.ingest(ctx, inst, chatMessageID, *raw.Media, api)+ if err != nil {+ r.logWarn(msg, err)+ r.notifyUnavailable(ctx, api, msg)+ return msg+ }+ msg.MediaRefs = append(msg.MediaRefs, ref)+ return msg+}++// notifyUnavailable tells the sender their file did not make it — over+// Telegram's 20 MB bot download limit, or a failed fetch — so the placeholder+// the agent is left with is not mistaken for a file it saw. Best effort, on+// its own short budget: the failure may be the fetch context running out.+func (r *mediaResolver) notifyUnavailable(ctx context.Context, api *botAPI, msg channel.InboundMessage) {+ chatID, err := strconv.ParseInt(msg.Source.ChatID, 10, 64)+ if err != nil {+ return+ }+ var threadID int64+ if msg.Source.ThreadID != "" {+ threadID, _ = strconv.ParseInt(msg.Source.ThreadID, 10, 64)+ }+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)+ defer cancel()+ if _, err := api.SendMessage(ctx, sendMessageParams{+ ChatID: chatID,+ Text: msgMediaUnavailable,+ MessageThreadID: threadID,+ ReplyParameters: optionalReplyParameters(parseMessageRef(msg.MessageID)),+ }); err != nil {+ r.logger.Warn("telegram media: unavailable notice failed", "message_id", msg.MessageID, "error", err)+ }+}++// ingest carries one file from Telegram to object storage. The intent row goes+// first: from that point on every failure leaves a row the reconciler settles,+// and nothing here deletes anything.+func (r *mediaResolver) ingest(ctx context.Context, inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, m inboundMedia, api *botAPI) (channel.MediaRef, error) {+ if m.FileSize > maxBotDownloadBytes {+ return channel.MediaRef{}, fmt.Errorf("file size %d exceeds the %d MiB bot download limit", m.FileSize, maxBotDownloadBytes>>20)+ }+ file, err := api.GetFile(ctx, m.FileID)+ if err != nil {+ return channel.MediaRef{}, fmt.Errorf("getFile: %w", err)+ }+ if file.FilePath == "" {+ return channel.MediaRef{}, errors.New("getFile returned no file_path")+ }+ if file.FileSize > maxBotDownloadBytes {+ return channel.MediaRef{}, fmt.Errorf("file size %d exceeds the %d MiB bot download limit", file.FileSize, maxBotDownloadBytes>>20)+ }+ key := mediaObjectKey(inst, chatMessageID, m)+ link := r.storage.ObjectURL(key)+ owned, err := r.ledger.RecordPendingMediaObject(ctx, engine.RecordPendingMediaObjectParams{+ StorageKey: key,+ WorkspaceID: inst.WorkspaceID,+ ChatMessageID: chatMessageID,+ StorageURL: link,+ InstallationID: inst.ID,+ })+ if err != nil {+ return channel.MediaRef{}, fmt.Errorf("record media intent: %w", err)+ }+ if !owned {+ return channel.MediaRef{}, errors.New("media key owned by reconciler")+ }+ data, responseType, err := api.DownloadFile(ctx, file.FilePath, maxBotDownloadBytes)+ if err != nil {+ return channel.MediaRef{}, err+ }+ contentType := mediaContentType(m.MimeType, responseType, data)+ filename := mediaFilename(m, file.FilePath, contentType)+ if _, err := r.storage.Upload(ctx, key, data, contentType, filename); err != nil {+ return channel.MediaRef{}, fmt.Errorf("upload file: %w", err)+ }+ return channel.MediaRef{+ Type: m.Kind,+ StorageKey: key,+ StorageURL: link,+ Filename: filename,+ MimeType: contentType,+ SizeBytes: int64(len(data)),+ InlinePlaceholder: m.Placeholder,+ InlineIndex: m.PlaceholderIndex,+ }, nil+}++// mediaObjectKey is keyed by the chat message the object binds to, not the+// platform message alone: a reclaimed dedup claim can ingest one platform+// message twice, and a shared key would run the second ingest into the first+// one's (possibly tombstoned) ledger row.+func mediaObjectKey(inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, m inboundMedia) string {+ sum := sha256.Sum256([]byte(util.UUIDToString(chatMessageID) + "\x00" + firstNonEmpty(m.FileUniqueID, m.FileID)))+ return path.Join("workspaces", util.UUIDToString(inst.WorkspaceID), "telegram", util.UUIDToString(inst.ID), hex.EncodeToString(sum[:]))+}++// mediaContentType prefers what Telegram declared, then the download's own+// header, then a sniff of the bytes.+func mediaContentType(declared, responseType string, data []byte) string {+ if ct := strings.ToLower(strings.TrimSpace(declared)); ct != "" {+ return ct+ }+ if ct := strings.ToLower(strings.TrimSpace(responseType)); ct != "" && ct != "application/octet-stream" {+ return ct+ }+ sniff := data+ if len(sniff) > 512 {+ sniff = sniff[:512]+ }+ ct := http.DetectContentType(sniff)+ if semi := strings.IndexByte(ct, ';'); semi >= 0 {+ ct = strings.TrimSpace(ct[:semi])+ }+ return ct+}++// mediaFilename is the stored display name: the sender's own file name when+// there is one, else Telegram's path segment (photos and voice notes have no+// name of their own), with an extension matching the content type.+func mediaFilename(m inboundMedia, filePath, contentType string) string {+ name := cleanFilename(m.FileName)+ if name == "" {+ name = cleanFilename(filePath)+ }+ if name == "" {+ name = "telegram-" + string(m.Kind)+ }+ if path.Ext(name) == "" {+ name += mediaExtension(contentType)+ }+ return name+}++func cleanFilename(name string) string {+ name = path.Base(strings.ReplaceAll(strings.TrimSpace(name), "\\", "/"))+ if strings.Trim(name, ".") == "" || name == "/" {+ return ""+ }+ return name+}++// mediaExtension pins the familiar spellings (image/jpeg is ".jfif" first on+// some mime databases) and falls back to the system table.+func mediaExtension(contentType string) string {+ switch contentType {+ case "image/jpeg":+ return ".jpg"+ case "image/png":+ return ".png"+ case "image/gif":+ return ".gif"+ case "image/webp":+ return ".webp"+ case "video/mp4":+ return ".mp4"+ case "audio/ogg":+ return ".ogg"+ case "audio/mpeg":+ return ".mp3"+ case "application/pdf":+ return ".pdf"+ case "text/plain":+ return ".txt"+ }+ if exts, err := mime.ExtensionsByType(contentType); err == nil && len(exts) > 0 {+ return exts[0]+ }+ return ""+}++func (r *mediaResolver) logWarn(msg channel.InboundMessage, err error) {+ r.logger.Warn("telegram media resolve skipped", "message_id", msg.MessageID, "error", err)+}diff --git a/server/internal/integrations/telegram/media_test.go b/server/internal/integrations/telegram/media_test.gonew file mode 100644index 0000000000..d6c2806b8f--- /dev/null+++ b/server/internal/integrations/telegram/media_test.go@@ -0,0 +1,917 @@+package telegram++import (+ "bytes"+ "context"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// ---- inbound translation ----++func TestInboundPhotoWithCaptionCarriesMediaAndPlaceholder(t *testing.T) {+ u := Update{UpdateID: 1, Message: &Message{+ MessageID: 7, From: &User{ID: 111, FirstName: "Ada"}, Chat: Chat{ID: 555, Type: "private"},+ Caption: "what is this",+ Photo: []PhotoSize{+ {FileID: "small", FileUniqueID: "u-small", Width: 90, Height: 60},+ {FileID: "large", FileUniqueID: "u-large", Width: 1280, Height: 853, FileSize: 120000},+ },+ }}+ msg, ok := inboundFromUpdate(u, 999, "my_bot")+ if !ok {+ t.Fatal("photo must be ingested")+ }+ if msg.Type != channel.MsgTypeImage {+ t.Fatalf("type = %q", msg.Type)+ }+ if msg.Text != "[Image]\nwhat is this" || msg.CommandText != "what is this" {+ t.Fatalf("text=%q command=%q", msg.Text, msg.CommandText)+ }+ raw, err := decodeTelegramRaw(msg)+ if err != nil || raw.Media == nil {+ t.Fatalf("raw media missing: %+v err=%v", raw, err)+ }+ if raw.Media.FileID != "large" || raw.Media.Kind != channel.MsgTypeImage || raw.Media.Placeholder != "[Image]" || raw.Media.FileSize != 120000 {+ t.Fatalf("media = %+v, want the largest rendition", *raw.Media)+ }+ if raw.Media.PlaceholderIndex != 0 {+ t.Fatalf("a p2p photo has nothing ahead of its placeholder, index = %d", raw.Media.PlaceholderIndex)+ }+}++// nthOccurrence scans the way the engine does (channel/engine/session.go+// nthSubstringIndex): non-overlapping, left to right, zero-based.+func nthOccurrence(s, marker string, n int) int {+ offset := 0+ for i := 0; ; i++ {+ found := strings.Index(s[offset:], marker)+ if found < 0 {+ return -1+ }+ found += offset+ if i == n {+ return found+ }+ offset = found + len(marker)+ }+}++// A member who typed the marker in the recent window must not receive the+// sender's file: the index the resolver carries skips their literal.+func TestInboundPlaceholderIndexSkipsLiteralsInRecentContext(t *testing.T) {+ var handled []channel.InboundMessage+ c := &telegramChannel{+ botID: 999, botUsername: "my_bot", acceptsMedia: true,+ handler: func(_ context.Context, msg channel.InboundMessage) error { handled = append(handled, msg); return nil },+ logger: testLogger(),+ recent: newRecentContextBuffer(DefaultRecentContextSize),+ }+ ada := &User{ID: 111, FirstName: "Ada"}+ bob := &User{ID: 222, FirstName: "Bob"}+ ctx := context.Background()+ if err := c.dispatch(ctx, groupUpdate(1, ada, "I pasted [Image] in the doc, not here", nil, 0)); err != nil {+ t.Fatal(err)+ }+ photo := groupUpdate(2, bob, "", nil, 0)+ photo.Message.Caption = "@my_bot what is wrong here?"+ photo.Message.CaptionEntities = []MessageEntity{{Type: "mention", Offset: 0, Length: 7}}+ photo.Message.Photo = []PhotoSize{{FileID: "p1"}}+ if err := c.dispatch(ctx, photo); err != nil {+ t.Fatal(err)+ }+ if len(handled) != 2 || !handled[1].AddressedToBot {+ t.Fatalf("handler calls = %+v", handled)+ }+ msg := handled[1]+ raw, _ := decodeTelegramRaw(msg)+ if raw.Media == nil || raw.Media.PlaceholderIndex != 1 {+ t.Fatalf("media = %+v, want placeholder index 1 (Ada's literal is occurrence 0)", raw.Media)+ }+ contextEnd := strings.Index(msg.Text, "</recent_context>")+ if contextEnd < 0 {+ t.Fatalf("no recent context in\n%s", msg.Text)+ }+ if pos := nthOccurrence(msg.Text, raw.Media.Placeholder, raw.Media.PlaceholderIndex); pos < contextEnd {+ t.Fatalf("occurrence %d is inside the context block (at %d, block ends %d):\n%s", raw.Media.PlaceholderIndex, pos, contextEnd, msg.Text)+ }+ if pos := nthOccurrence(msg.Text, raw.Media.Placeholder, 0); pos > contextEnd {+ t.Fatalf("Ada's literal should be occurrence 0, found at %d:\n%s", pos, msg.Text)+ }+}++// Same for an explicitly quoted human message that contains the marker.+func TestInboundPlaceholderIndexSkipsLiteralsInQuotedMessage(t *testing.T) {+ quoted := &Message{MessageID: 9, From: &User{ID: 111, FirstName: "Ada"}, Text: "the doc says [Image] where the diagram goes"}+ u := groupUpdate(10, &User{ID: 222, FirstName: "Bob"}, "", quoted, 0)+ u.Message.Caption = "@my_bot like this?"+ u.Message.CaptionEntities = []MessageEntity{{Type: "mention", Offset: 0, Length: 7}}+ u.Message.Photo = []PhotoSize{{FileID: "p1"}}++ msg, ok := inboundFromUpdate(u, 999, "my_bot")+ if !ok || !msg.HasSelectedContext {+ t.Fatalf("ok=%v selected=%v", ok, msg.HasSelectedContext)+ }+ raw, _ := decodeTelegramRaw(msg)+ if raw.Media == nil || raw.Media.PlaceholderIndex != 1 {+ t.Fatalf("media = %+v, want placeholder index 1", raw.Media)+ }+ quoteEnd := strings.Index(msg.Text, "</quoted_message>")+ if pos := nthOccurrence(msg.Text, raw.Media.Placeholder, raw.Media.PlaceholderIndex); quoteEnd < 0 || pos < quoteEnd {+ t.Fatalf("occurrence %d is not on Bob's line (at %d, quote ends %d):\n%s", raw.Media.PlaceholderIndex, pos, quoteEnd, msg.Text)+ }+}++func TestInboundMediaKindsAndPlaceholders(t *testing.T) {+ for _, tc := range []struct {+ name string+ m Message+ wantType channel.MsgType+ wantText string+ wantName string+ wantNoMedia bool+ }{+ {name: "document", m: Message{Document: &FileRef{FileID: "d", FileName: "report.pdf", MimeType: "application/pdf"}},+ wantType: channel.MsgTypeFile, wantText: "[File: report.pdf]", wantName: "report.pdf"},+ {name: "video", m: Message{Video: &FileRef{FileID: "v", MimeType: "video/mp4"}},+ wantType: channel.MsgTypeVideo, wantText: "[Video]"},+ {name: "animation", m: Message{Animation: &FileRef{FileID: "a", MimeType: "video/mp4"}},+ wantType: channel.MsgTypeVideo, wantText: "[Animation]"},+ {name: "video note", m: Message{VideoNote: &FileRef{FileID: "vn"}},+ wantType: channel.MsgTypeVideo, wantText: "[Video note]"},+ {name: "voice", m: Message{Voice: &FileRef{FileID: "vo", MimeType: "audio/ogg"}},+ wantType: channel.MsgTypeAudio, wantText: "[Voice message]"},+ {name: "audio", m: Message{Audio: &FileRef{FileID: "au", FileName: "song.mp3", MimeType: "audio/mpeg"}},+ wantType: channel.MsgTypeAudio, wantText: "[Audio]", wantName: "song.mp3"},+ {name: "sticker", m: Message{Sticker: &struct{}{}}, wantType: channel.MsgTypeUnknown, wantText: "", wantNoMedia: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ m := tc.m+ m.MessageID, m.From, m.Chat = 7, &User{ID: 111}, Chat{ID: 555, Type: "private"}+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &m}, 999, "my_bot")+ if !ok {+ t.Fatal("expected ok")+ }+ if msg.Type != tc.wantType || msg.Text != tc.wantText {+ t.Fatalf("type=%q text=%q", msg.Type, msg.Text)+ }+ raw, _ := decodeTelegramRaw(msg)+ if tc.wantNoMedia {+ if raw.Media != nil {+ t.Fatalf("unexpected media %+v", *raw.Media)+ }+ return+ }+ if raw.Media == nil || raw.Media.FileName != tc.wantName || raw.Media.Placeholder != tc.wantText {+ t.Fatalf("media = %+v", raw.Media)+ }+ })+ }+}++func TestInboundControlCommandWithPhotoKeepsMediaTurn(t *testing.T) {+ u := Update{UpdateID: 1, Message: &Message{+ MessageID: 7, From: &User{ID: 111}, Chat: Chat{ID: 555, Type: "private"},+ Caption: "/new", Photo: []PhotoSize{{FileID: "p"}},+ }}+ msg, ok := inboundFromUpdate(u, 999, "my_bot")+ if !ok || msg.CommandText != "/new" || msg.Text != "[Image]" {+ t.Fatalf("ok=%v command=%q text=%q", ok, msg.CommandText, msg.Text)+ }+}++func TestDispatchForwardsPhotoToEngine(t *testing.T) {+ var handled []channel.InboundMessage+ c := &telegramChannel{+ botID: 999, botUsername: "my_bot",+ acceptsMedia: true,+ api: newBotAPI("http://127.0.0.1:1", "123:secret", nil),+ handler: func(_ context.Context, m channel.InboundMessage) error { handled = append(handled, m); return nil },+ logger: testLogger(),+ }+ u := Update{UpdateID: 1, Message: &Message{+ MessageID: 21, From: &User{ID: 3}, Chat: Chat{ID: 42, Type: "private"},+ Photo: []PhotoSize{{FileID: "p1"}},+ }}+ if err := c.dispatch(context.Background(), u); err != nil {+ t.Fatal(err)+ }+ if len(handled) != 1 || handled[0].Text != "[Image]" {+ t.Fatalf("handled = %+v", handled)+ }+}++// ---- media resolver ----++// fakeObjectStore is the one object store fake both directions share: what+// Upload wrote is what GetReader hands back, keyed under https://cdn.example/.+type fakeObjectStore struct {+ mu sync.Mutex+ objects map[string][]byte+ names map[string]string+ types map[string]string+}++func newFakeObjectStore(objects map[string][]byte) *fakeObjectStore {+ if objects == nil {+ objects = map[string][]byte{}+ }+ return &fakeObjectStore{objects: objects, names: map[string]string{}, types: map[string]string{}}+}++func (f *fakeObjectStore) Upload(_ context.Context, key string, data []byte, contentType, filename string) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.objects[key] = append([]byte(nil), data...)+ f.names[key] = filename+ f.types[key] = contentType+ return f.ObjectURL(key), nil+}++func (f *fakeObjectStore) ObjectURL(key string) string { return "https://cdn.example/" + key }++func (f *fakeObjectStore) KeyFromURL(rawURL string) string {+ return strings.TrimPrefix(rawURL, "https://cdn.example/")+}++func (f *fakeObjectStore) GetReader(_ context.Context, key string) (io.ReadCloser, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ data, ok := f.objects[key]+ if !ok {+ return nil, fmt.Errorf("no object %q", key)+ }+ return io.NopCloser(bytes.NewReader(data)), nil+}++type fakeMediaLedger struct {+ records []engine.RecordPendingMediaObjectParams+ refuse bool+}++func (f *fakeMediaLedger) RecordPendingMediaObject(_ context.Context, p engine.RecordPendingMediaObjectParams) (bool, error) {+ f.records = append(f.records, p)+ return !f.refuse, nil+}++// fakeBotFiles serves getFile and the file download host for one token.+type fakeBotFiles struct {+ files map[string]fakeBotFile // file_id -> file+ getFileCalls int+ downloads []string+ // notices records the sendMessage calls: the fetch-failure notice.+ notices []sendMessageParams+}++type fakeBotFile struct {+ path string+ contentType string+ data []byte+}++func (f *fakeBotFiles) serve(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/getFile"):+ f.getFileCalls+++ var body struct {+ FileID string `json:"file_id"`+ }+ _ = json.NewDecoder(r.Body).Decode(&body)+ file, ok := f.files[body.FileID]+ w.Header().Set("Content-Type", "application/json")+ if !ok {+ _, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: file not found"}`))+ return+ }+ _, _ = fmt.Fprintf(w, `{"ok":true,"result":{"file_id":%q,"file_size":%d,"file_path":%q}}`, body.FileID, len(file.data), file.path)+ case strings.HasPrefix(r.URL.Path, "/file/bot123:secret/"):+ rel := strings.TrimPrefix(r.URL.Path, "/file/bot123:secret/")+ f.downloads = append(f.downloads, rel)+ for _, file := range f.files {+ if file.path == rel {+ if file.contentType != "" {+ w.Header().Set("Content-Type", file.contentType)+ }+ _, _ = w.Write(file.data)+ return+ }+ }+ http.NotFound(w, r)+ case strings.HasSuffix(r.URL.Path, "/sendMessage"):+ var p sendMessageParams+ _ = json.NewDecoder(r.Body).Decode(&p)+ f.notices = append(f.notices, p)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":9,"chat":{"id":42,"type":"private"}}}`))+ default:+ http.Error(w, "unexpected "+r.URL.Path, http.StatusTeapot)+ }+}++func mediaResolverFixture(t *testing.T, media *inboundMedia) (engine.ResolvedInstallation, pgtype.UUID, channel.InboundMessage) {+ t.Helper()+ cfg, _ := json.Marshal(installConfig{AppID: "999", BotTokenEncrypted: base64.StdEncoding.EncodeToString([]byte("123:secret"))})+ var ws, instID, chatMessageID pgtype.UUID+ ws.Bytes[0], instID.Bytes[0], chatMessageID.Bytes[0] = 0xAB, 0xCD, 0xEF+ ws.Valid, instID.Valid, chatMessageID.Valid = true, true, true+ raw, _ := json.Marshal(telegramRawEvent{BotID: "999", EventType: "message", Media: media})+ inst := engine.ResolvedInstallation{ID: instID, WorkspaceID: ws, Platform: db.ChannelInstallation{Config: cfg}}+ text := "hello"+ if media != nil {+ text = media.Placeholder+ }+ return inst, chatMessageID, channel.InboundMessage{MessageID: "42:7", Source: channel.Source{ChatID: "42"}, Type: channel.MsgTypeText, Text: text, Raw: raw}+}++func TestMediaResolverHasMedia(t *testing.T) {+ r := NewMediaResolver(nil, newFakeObjectStore(nil), &fakeMediaLedger{}, "", nil, testLogger())+ _, _, with := mediaResolverFixture(t, &inboundMedia{Kind: channel.MsgTypeImage, FileID: "p", Placeholder: "[Image]"})+ _, _, without := mediaResolverFixture(t, nil)+ if !r.HasMedia(with) || r.HasMedia(without) {+ t.Fatalf("HasMedia with=%v without=%v", r.HasMedia(with), r.HasMedia(without))+ }+}++func TestMediaResolverIngestsPhoto(t *testing.T) {+ jpeg := []byte("\xff\xd8\xff\xe0fake-jpeg")+ bot := &fakeBotFiles{files: map[string]fakeBotFile{"p1": {path: "photos/file_9.jpg", data: jpeg}}}+ srv := httptest.NewServer(http.HandlerFunc(bot.serve))+ defer srv.Close()+ store, ledger := newFakeObjectStore(nil), &fakeMediaLedger{}+ r := NewMediaResolver(nil, store, ledger, srv.URL, srv.Client(), testLogger())+ inst, chatMessageID, msg := mediaResolverFixture(t, &inboundMedia{Kind: channel.MsgTypeImage, FileID: "p1", FileUniqueID: "u1", MimeType: "image/jpeg", Placeholder: "[Image]", PlaceholderIndex: 1})++ got := r.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)+ if len(got.MediaRefs) != 1 {+ t.Fatalf("media refs = %+v", got.MediaRefs)+ }+ ref := got.MediaRefs[0]+ if ref.Type != channel.MsgTypeImage || ref.MimeType != "image/jpeg" || ref.Filename != "file_9.jpg" || ref.SizeBytes != int64(len(jpeg)) || ref.InlinePlaceholder != "[Image]" || ref.InlineIndex != 1 {+ t.Fatalf("ref = %+v", ref)+ }+ if !strings.HasPrefix(ref.StorageKey, "workspaces/") || !strings.Contains(ref.StorageKey, "/telegram/") || ref.StorageURL != store.ObjectURL(ref.StorageKey) {+ t.Fatalf("key/url = %q %q", ref.StorageKey, ref.StorageURL)+ }+ if !bytes.Equal(store.objects[ref.StorageKey], jpeg) {+ t.Fatal("uploaded bytes differ from the download")+ }+ if len(ledger.records) != 1 || ledger.records[0].StorageKey != ref.StorageKey || ledger.records[0].ChatMessageID != chatMessageID {+ t.Fatalf("ledger = %+v", ledger.records)+ }+ if bot.getFileCalls != 1 || len(bot.downloads) != 1 || bot.downloads[0] != "photos/file_9.jpg" {+ t.Fatalf("bot calls: getFile=%d downloads=%v", bot.getFileCalls, bot.downloads)+ }+}++// The fake file host sets no Content-Type, so net/http sniffs one for the+// response; this covers the "declared mime type absent" path end to end.+// mediaContentType's own byte sniff is covered directly below.+func TestMediaResolverKeepsSenderFilenameWithoutDeclaredType(t *testing.T) {+ pdf := []byte("%PDF-1.4 body")+ bot := &fakeBotFiles{files: map[string]fakeBotFile{"d1": {path: "documents/file_3", data: pdf}}}+ srv := httptest.NewServer(http.HandlerFunc(bot.serve))+ defer srv.Close()+ store := newFakeObjectStore(nil)+ r := NewMediaResolver(nil, store, &fakeMediaLedger{}, srv.URL, srv.Client(), testLogger())+ inst, chatMessageID, msg := mediaResolverFixture(t, &inboundMedia{Kind: channel.MsgTypeFile, FileID: "d1", FileName: "../report", Placeholder: "[File: report]"})++ got := r.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)+ if len(got.MediaRefs) != 1 {+ t.Fatalf("media refs = %+v", got.MediaRefs)+ }+ if ref := got.MediaRefs[0]; ref.Filename != "report.pdf" || ref.MimeType != "application/pdf" {+ t.Fatalf("ref = %+v", ref)+ }+}++func TestMediaContentTypePrecedence(t *testing.T) {+ png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("\x00", 16))+ for _, tc := range []struct{ declared, response, want string }{+ {"image/webp", "image/png", "image/webp"},+ {"", "image/png", "image/png"},+ {"", "application/octet-stream", "image/png"},+ {"", "", "image/png"},+ } {+ if got := mediaContentType(tc.declared, tc.response, png); got != tc.want {+ t.Errorf("mediaContentType(%q, %q) = %q, want %q", tc.declared, tc.response, got, tc.want)+ }+ }+}++func TestMediaResolverRefusesFailuresWithoutTouchingStorage(t *testing.T) {+ bot := &fakeBotFiles{files: map[string]fakeBotFile{}}+ srv := httptest.NewServer(http.HandlerFunc(bot.serve))+ defer srv.Close()+ for _, tc := range []struct {+ name string+ media *inboundMedia+ refuseLedger bool+ wantLedger int+ }{+ {name: "oversize declared up front", media: &inboundMedia{Kind: channel.MsgTypeFile, FileID: "big", FileSize: maxBotDownloadBytes + 1, Placeholder: "[File: big]"}},+ {name: "getFile fails", media: &inboundMedia{Kind: channel.MsgTypeImage, FileID: "missing", Placeholder: "[Image]"}},+ {name: "reconciler owns the key", media: &inboundMedia{Kind: channel.MsgTypeImage, FileID: "p1", Placeholder: "[Image]"}, refuseLedger: true, wantLedger: 1},+ } {+ t.Run(tc.name, func(t *testing.T) {+ bot.files["p1"] = fakeBotFile{path: "photos/p1.jpg", data: []byte("x")}+ before := len(bot.notices)+ store, ledger := newFakeObjectStore(nil), &fakeMediaLedger{refuse: tc.refuseLedger}+ r := NewMediaResolver(nil, store, ledger, srv.URL, srv.Client(), testLogger())+ inst, chatMessageID, msg := mediaResolverFixture(t, tc.media)+ got := r.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)+ if len(got.MediaRefs) != 0 || got.Text != msg.Text {+ t.Fatalf("message must come back unchanged: %+v", got)+ }+ if len(store.objects) != 0 || len(ledger.records) != tc.wantLedger {+ t.Fatalf("uploads=%d ledger=%d", len(store.objects), len(ledger.records))+ }+ if len(bot.notices) != before+1 {+ t.Fatalf("notices = %+v, want one more than %d", bot.notices, before)+ }+ if got := bot.notices[before]; got.Text != msgMediaUnavailable || got.ChatID != 42 || got.ReplyParameters == nil || got.ReplyParameters.MessageID != 7 {+ t.Fatalf("notice = %+v", got)+ }+ })+ }+}++// ---- multipart client ----++type multipartRecord struct {+ method string+ fields map[string]string+ part string+ filename string+ partType string+ data []byte+}++func recordMultipart(t *testing.T, r *http.Request) multipartRecord {+ t.Helper()+ if err := r.ParseMultipartForm(64 << 20); err != nil {+ t.Fatalf("parse multipart: %v", err)+ }+ rec := multipartRecord{method: r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:], fields: map[string]string{}}+ for k, v := range r.MultipartForm.Value {+ rec.fields[k] = v[0]+ }+ for name, headers := range r.MultipartForm.File {+ f, err := headers[0].Open()+ if err != nil {+ t.Fatal(err)+ }+ rec.data, _ = io.ReadAll(f)+ _ = f.Close()+ rec.part, rec.filename, rec.partType = name, headers[0].Filename, headers[0].Header.Get("Content-Type")+ }+ return rec+}++func TestSendMediaPostsMultipart(t *testing.T) {+ var got multipartRecord+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ got = recordMultipart(t, r)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":8,"chat":{"id":-42,"type":"supergroup"}}}`))+ }))+ defer srv.Close()+ m, err := newBotAPI(srv.URL, "123:secret", srv.Client()).SendMedia(context.Background(), sendMediaParams{+ ChatID: -42, MessageThreadID: 8, Field: "photo", Filename: "shot.png", ContentType: "image/png", Data: []byte("png-bytes"),+ })+ if err != nil || m.MessageID != 8 {+ t.Fatalf("message=%+v err=%v", m, err)+ }+ if got.method != "sendPhoto" || got.fields["chat_id"] != "-42" || got.fields["message_thread_id"] != "8" {+ t.Fatalf("request = %+v", got)+ }+ if got.part != "photo" || got.filename != "shot.png" || got.partType != "image/png" || string(got.data) != "png-bytes" {+ t.Fatalf("part = %+v", got)+ }+}++// ---- attachment hop ----++// attachmentOnlyQueries answers the one query the hop runs; everything else on+// outboundQueries is unreachable from sendAttachments and stays nil.+type attachmentOnlyQueries struct {+ outboundQueries+ rows []db.Attachment+ err error+ // failFirst makes that many lookups return err before rows are served;+ // zero with a non-nil err fails every lookup. calls counts them all.+ failFirst int+ calls int+}++func (q *attachmentOnlyQueries) ListAttachmentsByChatMessage(context.Context, db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ q.calls+++ if q.err != nil && (q.failFirst == 0 || q.calls <= q.failFirst) {+ return nil, q.err+ }+ return q.rows, nil+}++func attachmentRow(id byte, url, name, contentType string, size int64) db.Attachment {+ return db.Attachment{ID: telegramTestUUID(id), Url: url, Filename: name, ContentType: contentType, SizeBytes: size}+}++// fakeBotUploads records every send and answers each method per the table.+type fakeBotUploads struct {+ mu sync.Mutex+ sends []multipartRecord+ messages []string+ reject map[string]string // method -> error description (400)+}++func (f *fakeBotUploads) serve(t *testing.T) http.HandlerFunc {+ return func(w http.ResponseWriter, r *http.Request) {+ method := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]+ w.Header().Set("Content-Type", "application/json")+ f.mu.Lock()+ defer f.mu.Unlock()+ if method == "sendMessage" || method == "editMessageText" {+ var body sendMessageParams+ _ = json.NewDecoder(r.Body).Decode(&body)+ f.messages = append(f.messages, body.Text)+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":3,"chat":{"id":42,"type":"private"}}}`))+ return+ }+ rec := recordMultipart(t, r)+ f.sends = append(f.sends, rec)+ if desc, refused := f.reject[method]; refused {+ _, _ = fmt.Fprintf(w, `{"ok":false,"error_code":400,"description":%q}`, desc)+ return+ }+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":4,"chat":{"id":42,"type":"private"}}}`))+ }+}++func newAttachmentOutbound(t *testing.T, bot *fakeBotUploads, q outboundQueries, objects map[string][]byte) (*Outbound, replyTarget) {+ t.Helper()+ srv := httptest.NewServer(bot.serve(t))+ t.Cleanup(srv.Close)+ o := NewOutbound(q, nil, srv.URL, srv.Client(), testLogger())+ o.EnableFileDelivery(newFakeObjectStore(objects))+ o.spawn = func(f func()) { f() }+ o.wait = func(context.Context, time.Duration) error { return nil }+ return o, replyTarget{chatID: 42, threadID: 8, botToken: "123:secret"}+}++// The lookup is a side-effect-free read: a failure is retried, and only one+// that keeps failing is reported — in words that do not presume a file existed.+func TestDeliverAttachmentsTellsUserWhenTheLookupKeepsFailing(t *testing.T) {+ bot := &fakeBotUploads{}+ q := &attachmentOnlyQueries{err: errors.New("database unavailable")}+ o, target := newAttachmentOutbound(t, bot, q, nil)+ o.spawn = func(func()) { t.Fatal("nothing is known to deliver") }++ o.deliverAttachments(context.Background(), attachmentReply(target))++ if q.calls != attachmentLookupAttempts {+ t.Fatalf("lookup attempts = %d, want %d", q.calls, attachmentLookupAttempts)+ }+ if len(bot.sends) != 0 || len(bot.messages) != 1 || bot.messages[0] != attachmentLookupFailedText {+ t.Fatalf("sends=%+v messages=%q", bot.sends, bot.messages)+ }+}++func TestDeliverAttachmentsRetriesATransientLookupFailure(t *testing.T) {+ bot := &fakeBotUploads{}+ q := &attachmentOnlyQueries{err: errors.New("database unavailable"), failFirst: attachmentLookupAttempts - 1,+ rows: []db.Attachment{attachmentRow(1, "https://cdn.example/k/shot.png", "shot.png", "image/png", 3)}}+ o, target := newAttachmentOutbound(t, bot, q, map[string][]byte{"k/shot.png": []byte("png")})++ o.deliverAttachments(context.Background(), attachmentReply(target))++ if q.calls != attachmentLookupAttempts {+ t.Fatalf("lookup attempts = %d, want %d", q.calls, attachmentLookupAttempts)+ }+ if len(bot.sends) != 1 || bot.sends[0].method != "sendPhoto" || len(bot.messages) != 0 {+ t.Fatalf("sends=%+v messages=%q", bot.sends, bot.messages)+ }+}++func TestSendAttachmentsPicksMethodByContentType(t *testing.T) {+ bot := &fakeBotUploads{}+ o, target := newAttachmentOutbound(t, bot, &attachmentOnlyQueries{rows: []db.Attachment{+ attachmentRow(1, "https://cdn.example/k/shot", "shot.png", "image/png", 3),+ attachmentRow(2, "https://cdn.example/k/report.pdf", "report.pdf", "application/pdf", 3),+ attachmentRow(3, "https://cdn.example/k/clip.mp4", "clip.mp4", "video/mp4", 3),+ attachmentRow(4, "https://cdn.example/k/notes", "notes", "text/plain", 3),+ }}, map[string][]byte{+ "k/shot": []byte("png"), "k/report.pdf": []byte("pdf"), "k/clip.mp4": []byte("mp4"), "k/notes": []byte("txt"),+ })++ o.deliverAttachments(context.Background(), attachmentReply(target))++ want := []struct{ method, part, filename string }{+ {"sendPhoto", "photo", "shot.png"},+ {"sendDocument", "document", "report.pdf"},+ {"sendVideo", "video", "clip.mp4"},+ {"sendDocument", "document", "notes.txt"},+ }+ if len(bot.sends) != len(want) {+ t.Fatalf("sends = %+v", bot.sends)+ }+ for i, w := range want {+ got := bot.sends[i]+ if got.method != w.method || got.part != w.part || got.filename != w.filename || got.fields["chat_id"] != "42" || got.fields["message_thread_id"] != "8" {+ t.Errorf("send %d = %+v, want %+v", i, got, w)+ }+ }+ if len(bot.messages) != 0 {+ t.Fatalf("no failure notice expected, got %q", bot.messages)+ }+}++func TestSendAttachmentsFallsBackToDocumentOnPhotoRejection(t *testing.T) {+ bot := &fakeBotUploads{reject: map[string]string{"sendPhoto": "Bad Request: IMAGE_PROCESS_FAILED"}}+ o, target := newAttachmentOutbound(t, bot, &attachmentOnlyQueries{rows: []db.Attachment{+ attachmentRow(1, "https://cdn.example/k/odd.png", "odd.png", "image/png", 3),+ }}, map[string][]byte{"k/odd.png": []byte("png")})++ o.deliverAttachments(context.Background(), attachmentReply(target))++ if len(bot.sends) != 2 || bot.sends[0].method != "sendPhoto" || bot.sends[1].method != "sendDocument" || bot.sends[1].filename != "odd.png" {+ t.Fatalf("sends = %+v", bot.sends)+ }+ if len(bot.messages) != 0 {+ t.Fatalf("a delivered fallback needs no notice, got %q", bot.messages)+ }+}++func TestSendAttachmentsTellsUserAboutFilesThatDidNotArrive(t *testing.T) {+ bot := &fakeBotUploads{reject: map[string]string{"sendDocument": "Bad Request: file is too big"}}+ o, target := newAttachmentOutbound(t, bot, &attachmentOnlyQueries{rows: []db.Attachment{+ attachmentRow(1, "https://cdn.example/k/ok.png", "ok.png", "image/png", 3),+ attachmentRow(2, "https://cdn.example/k/missing.pdf", "missing.pdf", "application/pdf", 3),+ attachmentRow(3, "https://cdn.example/k/refused.pdf", "refused.pdf", "application/pdf", 3),+ }}, map[string][]byte{"k/ok.png": []byte("png"), "k/refused.pdf": []byte("pdf")})++ o.deliverAttachments(context.Background(), attachmentReply(target))++ if len(bot.sends) != 2 || bot.sends[0].method != "sendPhoto" || bot.sends[1].method != "sendDocument" {+ t.Fatalf("sends = %+v", bot.sends)+ }+ if len(bot.messages) != 1 || bot.messages[0] != attachmentNoticeText {+ t.Fatalf("notice = %q", bot.messages)+ }+}++// attachmentReply is a settled reply whose assistant message the fake queries+// answer for.+func attachmentReply(target replyTarget) *terminalReply {+ return &terminalReply{event: events.Event{WorkspaceID: "00000000-0000-0000-0000-000000000008",+ Payload: protocol.ChatDonePayload{MessageID: "00000000-0000-0000-0000-000000000009"}}, target: &target}+}++func TestDeliverAttachmentsSpawnsNothingWithoutStorageOrRows(t *testing.T) {+ bot := &fakeBotUploads{}+ o, target := newAttachmentOutbound(t, bot, &attachmentOnlyQueries{}, nil)+ o.spawn = func(func()) { t.Fatal("spawned a delivery with nothing to deliver") }+ o.deliverAttachments(context.Background(), attachmentReply(target))++ o.objects = nil+ o.deliverAttachments(context.Background(), attachmentReply(target))+ if len(bot.sends) != 0 || len(bot.messages) != 0 {+ t.Fatalf("unexpected traffic: sends=%+v messages=%q", bot.sends, bot.messages)+ }+}++// Admission is decided before the spawn: with every slot busy, a reply that+// has files is shed with the notice rather than parked behind a goroutine.+func TestDeliverAttachmentsShedsWhenEverySlotIsBusy(t *testing.T) {+ for range maxConcurrentAttachmentDeliveries {+ attachmentSlots <- struct{}{}+ }+ defer func() {+ for range maxConcurrentAttachmentDeliveries {+ <-attachmentSlots+ }+ }()+ bot := &fakeBotUploads{}+ o, target := newAttachmentOutbound(t, bot, &attachmentOnlyQueries{rows: []db.Attachment{+ attachmentRow(1, "https://cdn.example/k/shot.png", "shot.png", "image/png", 3),+ }}, map[string][]byte{"k/shot.png": []byte("png")})+ o.spawn = func(func()) { t.Fatal("a shed delivery must not be spawned") }++ o.deliverAttachments(context.Background(), attachmentReply(target))++ if len(bot.sends) != 0 || len(bot.messages) != 1 || bot.messages[0] != attachmentNoticeText {+ t.Fatalf("sends=%+v messages=%q", bot.sends, bot.messages)+ }+}++func TestOutboundMediaHelpers(t *testing.T) {+ for _, tc := range []struct {+ contentType string+ size int+ want string+ }{+ {"image/jpeg", 10, "photo"},+ {"image/png; charset=binary", 10, "photo"},+ {"image/svg+xml", 10, "document"},+ {"image/png", maxOutboundPhotoBytes + 1, "document"},+ {"video/mp4", 10, "video"},+ {"video/quicktime", 10, "document"},+ {"audio/mpeg", 10, "audio"},+ {"application/pdf", 10, "document"},+ {"", 10, "document"},+ } {+ if got := outboundMediaField(tc.contentType, tc.size); got != tc.want {+ t.Errorf("outboundMediaField(%q, %d) = %q, want %q", tc.contentType, tc.size, got, tc.want)+ }+ }+ for _, tc := range []struct{ name, contentType, want string }{+ {"shot.png", "image/png", "shot.png"},+ {"", "image/jpeg", "attachment.jpg"},+ {"../etc/passwd", "text/plain", "passwd.txt"},+ {"notes", "text/plain", "notes.txt"},+ } {+ if got := outboundMediaName(tc.name, tc.contentType); got != tc.want {+ t.Errorf("outboundMediaName(%q, %q) = %q, want %q", tc.name, tc.contentType, got, tc.want)+ }+ }+}++// TestFinalReplyDeliversBoundAttachmentsAfterText runs the real delivery state+// machine: the answer lands first, then the files the agent bound to it.+func TestFinalReplyDeliversBoundAttachmentsAfterText(t *testing.T) {+ q := newTelegramOutboundQueries(t)+ q.channelOrigin = true+ q.attachments = []db.Attachment{attachmentRow(1, "https://cdn.example/k/shot.png", "shot.png", "image/png", 3)}+ bot := &fakeBotUploads{}+ o, _ := newAttachmentOutbound(t, bot, q, map[string][]byte{"k/shot.png": []byte("png")})++ done := telegramTestEvent()+ done.WorkspaceID = "00000000-0000-0000-0000-000000000008"+ done.Payload = protocol.ChatDonePayload{+ TaskID: done.TaskID, ChatSessionID: done.ChatSessionID,+ MessageID: "00000000-0000-0000-0000-000000000009", Content: "here is the screenshot",+ }+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), o, done); err != nil {+ t.Fatalf("finish chat: %v", err)+ }+ if len(bot.messages) != 1 || !strings.Contains(bot.messages[0], "here is the screenshot") {+ t.Fatalf("text messages = %q", bot.messages)+ }+ if len(bot.sends) != 1 || bot.sends[0].method != "sendPhoto" || bot.sends[0].filename != "shot.png" {+ t.Fatalf("sends = %+v", bot.sends)+ }+}++// TestEmptyReplyStillDeliversBoundAttachments covers an agent that said nothing+// and bound a file instead: the file is the whole reply.+func TestEmptyReplyStillDeliversBoundAttachments(t *testing.T) {+ q := newTelegramOutboundQueries(t)+ q.channelOrigin = true+ q.attachments = []db.Attachment{attachmentRow(1, "https://cdn.example/k/report.pdf", "report.pdf", "application/pdf", 3)}+ bot := &fakeBotUploads{}+ o, _ := newAttachmentOutbound(t, bot, q, map[string][]byte{"k/report.pdf": []byte("pdf")})++ done := telegramTestEvent()+ done.WorkspaceID = "00000000-0000-0000-0000-000000000008"+ done.Payload = protocol.ChatDonePayload{+ TaskID: done.TaskID, ChatSessionID: done.ChatSessionID,+ MessageID: "00000000-0000-0000-0000-000000000009", Content: "",+ }+ // enqueueTerminalReply files an empty completion as a close, not an answer.+ reply := &terminalReply{event: done, kind: terminalKindClose, settleReason: "empty_reply"}+ for {+ result := o.sendNextTerminalRequest(context.Background(), reply)+ if result.err != nil {+ t.Fatalf("close turn: %v", result.err)+ }+ if result.done {+ o.cleanupTerminalReply(reply)+ break+ }+ }+ if len(bot.messages) != 0 {+ t.Fatalf("no text expected, got %q", bot.messages)+ }+ if len(bot.sends) != 1 || bot.sends[0].method != "sendDocument" {+ t.Fatalf("sends = %+v", bot.sends)+ }+}++// Without object storage the loop keeps the old contract: media gets the+// unsupported notice, and never a placeholder the agent cannot see behind.+func TestDispatchKeepsUnsupportedNoticeWithoutStorage(t *testing.T) {+ var notices []sendMessageParams+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body sendMessageParams+ _ = json.NewDecoder(r.Body).Decode(&body)+ notices = append(notices, body)+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":7,"chat":{"id":42,"type":"private"}}}`))+ }))+ defer srv.Close()+ c := &telegramChannel{+ botID: 999, botUsername: "my_bot", api: newBotAPI(srv.URL, "123:secret", srv.Client()),+ handler: func(context.Context, channel.InboundMessage) error {+ t.Fatal("media reached the handler without storage")+ return nil+ },+ logger: testLogger(),+ }+ u := Update{UpdateID: 1, Message: &Message{+ MessageID: 21, From: &User{ID: 3}, Chat: Chat{ID: 42, Type: "private"},+ Caption: "look", Photo: []PhotoSize{{FileID: "p1"}},+ }}+ if err := c.dispatch(context.Background(), u); err != nil {+ t.Fatal(err)+ }+ if len(notices) != 1 || notices[0].Text != msgUnsupportedType || notices[0].ReplyParameters == nil || notices[0].ReplyParameters.MessageID != 21 {+ t.Fatalf("notices = %+v", notices)+ }+}++// fileOnlyCompletion is a chat:done with no text and a bound file.+func fileOnlyCompletion(e events.Event, taskID string) events.Event {+ done := e+ done.TaskID = taskID+ done.WorkspaceID = "00000000-0000-0000-0000-000000000008"+ done.Payload = protocol.ChatDonePayload{TaskID: taskID, ChatSessionID: e.ChatSessionID, MessageID: "00000000-0000-0000-0000-000000000009"}+ return done+}++func enableTestFileDelivery(o *Outbound, q *review8545Queries) {+ q.routing.attachments = []db.Attachment{attachmentRow(1, "https://cdn.example/k/report.pdf", "report.pdf", "application/pdf", 3)}+ o.EnableFileDelivery(newFakeObjectStore(map[string][]byte{"k/report.pdf": []byte("pdf")}))+ o.spawn = func(f func()) { f() }+}++// A file-only reply whose chat:done arrives twice — a replay, here on another+// replica — sends its files once: the second close finds the turn ended.+func TestReview8545PostgresDuplicateEmptyCompletionSendsFilesOnce(t *testing.T) {+ bot := &auditBot{}+ a, q, c, e := review8545Setup(t, bot)+ enableTestFileDelivery(a, q)+ done := fileOnlyCompletion(e, e.TaskID)+ a.enqueueTerminalReply(done)+ auditDrain(t, a, c, done.ChatSessionID)++ b := review8545Second(a)+ enableTestFileDelivery(b, q)+ b.enqueueTerminalReply(done)+ auditDrain(t, b, c, done.ChatSessionID)++ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.uploads != 1 || len(bot.messages) != 0 {+ t.Fatalf("uploads=%d messages=%v methods=%v", bot.uploads, bot.messages, bot.methods)+ }+}++// A file-only completion belonging to an attempt the retry chain has moved+// past must not send its files: the retry owns the turn and answers it.+func TestReview8545PostgresSupersededAttemptDoesNotSendFiles(t *testing.T) {+ bot := &auditBot{}+ o, q, c, e := review8545Setup(t, bot)+ enableTestFileDelivery(o, q)+ oldTask := e.TaskID+ retryTask := util.UUIDToString(review8545ID())+ seedRetryChain(t, oldTask, retryTask)++ // The retry takes the turn and starts streaming.+ o.handleTaskMessage(telegramPartialEvent(retryTask, "retry streaming"))++ // The attempt it superseded completes late, with a file bound.+ o.enqueueTerminalReply(fileOnlyCompletion(e, oldTask))+ auditDrain(t, o, c, e.ChatSessionID)++ retry := e+ retry.TaskID = retryTask+ retry.Payload = protocol.ChatDonePayload{TaskID: retryTask, ChatSessionID: e.ChatSessionID, Content: "retry complete answer"}+ o.enqueueTerminalReply(retry)+ auditDrain(t, o, c, retry.ChatSessionID)++ review8545MessageCount(t, bot, 1)+ bot.mu.Lock()+ defer bot.mu.Unlock()+ if bot.uploads != 0 {+ t.Fatalf("superseded attempt sent its files: uploads=%d methods=%v", bot.uploads, bot.methods)+ }+ if bot.messages[1] != "retry complete answer" {+ t.Fatalf("retry's answer not delivered: %q methods=%v", bot.messages[1], bot.methods)+ }+}diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.goindex da44a44238..00ec25c992 100644--- a/server/internal/integrations/telegram/outbound.go+++ b/server/internal/integrations/telegram/outbound.go@@ -66,6 +66,12 @@ type Outbound struct {workerOnce sync.OnceworkerWG sync.WaitGroupterminalWorkerWG sync.WaitGroup++ // objects is the deployment's object storage, or nil when there is none.+ // Non-nil is what turns file delivery on (outbound_media.go).+ objects objectStore+ // spawn runs an attachment delivery. A field so a test can run it inline.+ spawn func(func())}// outboundQueries is the slice of generated queries the subscriber needs.@@ -73,6 +79,9 @@ type Outbound struct {type outboundQueries interface {GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)+ // ListAttachmentsByChatMessage is the files the agent bound to its reply,+ // read by the attachment hop (outbound_media.go).+ ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)// Reply-delivery ownership. The streamed placeholder, the final answer and// the failure notice agree on who owns a reply through these and nothing@@ -284,6 +293,7 @@ func NewOutbound(q outboundQueries, decrypt Decrypter, apiBase string, client *hterminalWake: make(chan struct{}, 1),terminalWork: make(chan terminalWork, terminalWorkerCount),terminalResults: make(chan terminalResult, terminalWorkerCount),+ spawn: func(f func()) { go f() },}return o}@@ -817,8 +827,8 @@ func (o *Outbound) initializeTerminalReply(ctx context.Context, reply *terminalR// Nothing to deliver — a cancelled run, or a completion with no answer.// The close still has to land: it is what stops a text frame arriving// afterwards from opening a placeholder nothing will ever finish.- closed, err := o.closeTurn(ctx, target, reply.turn, reply.settleReason)- if err != nil || !closed {+ outcome, err := o.closeTurn(ctx, target, reply.turn, reply.settleReason)+ if err != nil || outcome == closeHeld {budget := maxDeliveryAcquireAttemptsif err != nil {budget = maxDeliveryClaimErrorAttempts@@ -831,6 +841,13 @@ func (o *Outbound) initializeTerminalReply(ctx context.Context, reply *terminalRreturn terminalRequestResult{done: true}}o.clearStream(reply.event)+ if outcome == closedNow && reply.settleReason == "empty_reply" {+ // The agent may have said nothing and bound a file instead; the+ // files are then the whole reply. Only the call that ended the+ // turn sends them: a duplicate chat:done, or a completion an+ // automatic retry has superseded, finds the turn closed already.+ o.deliverAttachments(ctx, reply)+ }return terminalRequestResult{done: true}}@@ -981,6 +998,7 @@ func (o *Outbound) editStreamedReply(ctx context.Context, api *botAPI, reply *teo.recordSend(ctx, reply.lease, false, reply.streamedMessageID, reply.chunkIndex, nil)if reply.chunkIndex == len(reply.chunks) {o.settleDelivery(ctx, reply.lease, "delivered")+ o.deliverAttachments(ctx, reply)return terminalRequestResult{done: true}}return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}@@ -1035,6 +1053,9 @@ func (o *Outbound) sendReplyChunk(ctx context.Context, api *botAPI, reply *termischedule.setBackoffTill(time.Time{})if reply.chunkIndex == len(reply.chunks) {o.settleDelivery(ctx, reply.lease, "delivered")+ // The text is in the chat; the files the agent bound to it follow as+ // their own messages, off this worker.+ o.deliverAttachments(ctx, reply)return terminalRequestResult{done: true}}return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}diff --git a/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.goindex 0fd0fc912c..bbc0cc3ce6 100644--- a/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go+++ b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go@@ -41,6 +41,10 @@ func (q *review8545Queries) GetChannelInstallation(ctx context.Context, p db.Getreturn q.routing.GetChannelInstallation(ctx, p)}+func (q *review8545Queries) ListAttachmentsByChatMessage(ctx context.Context, p db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ return q.routing.ListAttachmentsByChatMessage(ctx, p)+}+func review8545ID() pgtype.UUID {id := pgtype.UUID{Valid: true}_, _ = rand.Read(id.Bytes[:])diff --git a/server/internal/integrations/telegram/outbound_delivery_contract_test.go b/server/internal/integrations/telegram/outbound_delivery_contract_test.goindex bafa5d9df0..9e44aee26c 100644--- a/server/internal/integrations/telegram/outbound_delivery_contract_test.go+++ b/server/internal/integrations/telegram/outbound_delivery_contract_test.go@@ -37,6 +37,9 @@ type auditBot struct {forbidEdits boolsends int64edits int+ // uploads counts sendPhoto / sendDocument / … calls: the attachment hop+ // behind a reply, which must never run twice for one turn.+ uploads int}func (a *auditBot) serve(w http.ResponseWriter, r *http.Request) {@@ -79,6 +82,9 @@ func (a *auditBot) serve(w http.ResponseWriter, r *http.Request) {return}_, _ = w.Write([]byte(`{"ok":true,"result":true}`))+ case "sendPhoto", "sendDocument", "sendVideo", "sendAudio":+ a.uploads+++ _, _ = fmt.Fprintf(w, `{"ok":true,"result":{"message_id":%d}}`, 1000+a.uploads)}}diff --git a/server/internal/integrations/telegram/outbound_media.go b/server/internal/integrations/telegram/outbound_media.gonew file mode 100644index 0000000000..e98c65e8c3--- /dev/null+++ b/server/internal/integrations/telegram/outbound_media.go@@ -0,0 +1,277 @@+package telegram++// Outbound media: the last hop for files an agent produced. The agent side is+// platform-agnostic — `multica attachment upload <path>` puts the file in+// object storage and CompleteTask binds it to the assistant message. This file+// sends those attachments into the Telegram chat once the reply text has+// settled, each as its own sendPhoto / sendDocument / … message (Telegram has+// no way to embed a file in a text message). Mirrors wecom/outbound_media.go.+//+// Duplicates: delivery starts only from the call that ended the turn — settled+// it as delivered, or closed it as an empty completion — and the delivery row+// lets exactly one call do that across replicas, replays and retries; a+// duplicate chat:done finds the turn already ended and sends nothing. A crash+// mid-way loses the remaining files; nothing resends, because Telegram offers+// no idempotency key and a duplicate cannot be taken back.++import (+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "path"+ "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/multica-ai/multica/server/pkg/protocol"+)++// Bot API upload ceilings: 10 MB for a photo, 50 MB for anything else. A photo+// past its ceiling still travels, as a document.+const (+ maxOutboundPhotoBytes = 10 << 20+ maxOutboundFileBytes = 50 << 20+ // attachmentBudget bounds one reply's whole delivery — every object read+ // and every upload. Nothing waits on it.+ attachmentBudget = 5 * time.Minute+ // maxConcurrentAttachmentDeliveries bounds the deliveries in flight, and+ // with them the goroutines and the resident bytes (one object at a time+ // each). Admission is decided before anything is spawned: a reply that+ // finds every slot busy is shed with the notice, never queued.+ maxConcurrentAttachmentDeliveries = 4+ // The attachment lookup is a side-effect-free read, so a failure is+ // retried a few times before the member is told; the whole retry stays+ // well under a second of the worker's time.+ attachmentLookupAttempts = 3+ attachmentLookupRetryDelay = 250 * time.Millisecond+)++// The two notices say only what is known at the point they are sent.+const (+ // attachmentNoticeText: a file is known to exist and may not have+ // arrived. It has to hold in every ending that leads here — a refused+ // upload, a shed delivery, and a send whose response was lost after+ // Telegram accepted it — so it claims nothing about what did or did not+ // land.+ attachmentNoticeText = "⚠️ I couldn't confirm that every file from this reply reached Telegram. Anything missing is still attached to the reply in Multica."+ // attachmentLookupFailedText: the lookup itself failed, so whether the+ // reply had files at all is unknown. Saying nothing would leave a member+ // waiting for a file the text refers to; claiming a file existed would+ // be a guess.+ attachmentLookupFailedText = "⚠️ I couldn't check whether this reply had files attached, so if it did, they were not sent. They stay attached to the reply in Multica."+)++// EnableFileDelivery turns on the attachment hop. Call at boot, before+// Register. Without it — no object storage — replies are text only, and the+// agent is told as much per turn.+func (o *Outbound) EnableFileDelivery(objects objectStore) {+ o.objects = objects+}++var attachmentSlots = make(chan struct{}, maxConcurrentAttachmentDeliveries)++// deliverAttachments sends the files bound to a reply once its text is in the+// chat. The lookup runs here, on the terminal worker: a reply with nothing+// bound — the common case — costs one indexed read and no goroutine, and a+// delivery is spawned only for files known to exist, under a slot claimed+// first. Called after the turn is ended, so the lease is no longer held.+func (o *Outbound) deliverAttachments(ctx context.Context, reply *terminalReply) {+ if o.objects == nil || reply.target == nil {+ return+ }+ messageID, err := util.ParseUUID(chatDoneMessageID(reply.event.Payload))+ if err != nil || !messageID.Valid {+ return // a turn with no assistant message has nothing bound to it+ }+ workspaceID, err := util.ParseUUID(reply.event.WorkspaceID)+ if err != nil || !workspaceID.Valid {+ return+ }+ target := *reply.target+ api := newBotAPI(o.apiBase, target.botToken, o.client)+ rows, err := o.lookupAttachments(ctx, messageID, workspaceID)+ if err != nil {+ // Whether the reply had files is now unknown. The text is already on+ // the member's screen and may refer to one, so this is said, in words+ // that do not presume a file existed.+ o.logger.WarnContext(ctx, "telegram outbound: attachment lookup failed", "error", err, "chat_message_id", uuidText(messageID))+ o.tellUser(ctx, api, target, attachmentLookupFailedText)+ return+ }+ if len(rows) == 0 {+ return+ }+ select {+ case attachmentSlots <- struct{}{}:+ default:+ // Every slot is uploading. The files are known to exist, so this is+ // said, not just logged; they stay in Multica.+ o.logger.WarnContext(ctx, "telegram outbound: attachment delivery shed, every slot busy",+ "attachments", len(rows), "chat_message_id", uuidText(messageID))+ o.tellUser(ctx, api, target, attachmentNoticeText)+ return+ }+ o.spawn(func() {+ defer func() { <-attachmentSlots }()+ ctx, cancel := context.WithTimeout(context.Background(), attachmentBudget)+ defer cancel()+ o.sendAttachments(ctx, rows, target)+ })+}++// lookupAttachments reads the files bound to the reply, retrying a failed+// read a few times. Each attempt is detached from the call budget the text+// delivery ran under, which may have just about run out, and bounded on its+// own; the spacing goes through o.wait so a test does not sleep.+func (o *Outbound) lookupAttachments(ctx context.Context, messageID, workspaceID pgtype.UUID) ([]db.Attachment, error) {+ var err error+ for attempt := 0; attempt < attachmentLookupAttempts; attempt++ {+ if attempt > 0 && o.wait(ctx, attachmentLookupRetryDelay) != nil {+ break+ }+ readCtx, cancel := o.recordContext(ctx)+ var rows []db.Attachment+ rows, err = o.q.ListAttachmentsByChatMessage(readCtx, db.ListAttachmentsByChatMessageParams{+ ChatMessageID: messageID, WorkspaceID: workspaceID,+ })+ cancel()+ if err == nil {+ return rows, nil+ }+ }+ return nil, err+}++// sendAttachments delivers every file bound to one reply. Files are+// independent: one that fails does not stop the rest.+func (o *Outbound) sendAttachments(ctx context.Context, rows []db.Attachment, target replyTarget) {+ api := newBotAPI(o.apiBase, target.botToken, o.client)+ failed := 0+ for _, row := range rows {+ if err := o.sendAttachment(ctx, api, row, target); err != nil {+ failed+++ o.logger.WarnContext(ctx, "telegram outbound: attachment not confirmed delivered",+ "error", err, "attachment_id", uuidText(row.ID), "content_type", row.ContentType, "size_bytes", row.SizeBytes)+ }+ }+ if failed > 0 {+ o.tellUser(ctx, api, target, attachmentNoticeText)+ }+}++// tellUser puts a notice into the conversation, best effort and on its own+// short budget: every caller is already on a path where something went wrong.+func (o *Outbound) tellUser(ctx context.Context, api *botAPI, target replyTarget, text string) {+ ctx, cancel := o.recordContext(ctx)+ defer cancel()+ if _, err := api.SendMessage(ctx, sendMessageParams{+ ChatID: target.chatID, Text: text, MessageThreadID: target.threadID,+ }); err != nil {+ o.logger.WarnContext(ctx, "telegram outbound: could not tell the user about the file", "error", err)+ }+}++// sendAttachment carries one file from object storage into the chat. A photo+// Telegram refuses to process (a 400 — bad dimensions, an SVG, a PNG it will+// not convert) is sent again as a document: a 400 means nothing was posted,+// and a file card beats a dropped image. Any other error is final, and not a+// verdict: a lost response may mean the message already landed, which is why+// nothing here retries and why the notice is worded the way it is.+func (o *Outbound) sendAttachment(ctx context.Context, api *botAPI, row db.Attachment, target replyTarget) error {+ if row.SizeBytes > maxOutboundFileBytes {+ return fmt.Errorf("attachment is %d bytes, over the %d MiB upload limit", row.SizeBytes, maxOutboundFileBytes>>20)+ }+ data, err := o.readObject(ctx, row.Url)+ if err != nil {+ return err+ }+ params := sendMediaParams{+ ChatID: target.chatID, MessageThreadID: target.threadID,+ Field: outboundMediaField(row.ContentType, len(data)), Filename: outboundMediaName(row.Filename, row.ContentType),+ ContentType: row.ContentType, Data: data,+ }+ _, err = api.SendMedia(ctx, params)+ if err != nil && params.Field != "document" && isBadRequest(err) {+ params.Field = "document"+ _, err = api.SendMedia(ctx, params)+ }+ return err+}++func (o *Outbound) readObject(ctx context.Context, rawURL string) ([]byte, error) {+ key := o.objects.KeyFromURL(rawURL)+ if key == "" {+ return nil, errors.New("attachment is not an object this deployment stores")+ }+ rc, err := o.objects.GetReader(ctx, key)+ if err != nil {+ return nil, fmt.Errorf("read attachment: %w", err)+ }+ defer rc.Close()+ data, err := io.ReadAll(io.LimitReader(rc, maxOutboundFileBytes+1))+ if err != nil {+ return nil, fmt.Errorf("read attachment: %w", err)+ }+ if len(data) > maxOutboundFileBytes {+ return nil, fmt.Errorf("attachment is over the %d MiB upload limit", maxOutboundFileBytes>>20)+ }+ return data, nil+}++// outboundMediaField picks the Bot API method by content type: photos render+// inline, mp4 video and common audio get native players, everything else is a+// file card. Telegram's converters only handle the common formats, so the+// fallback in sendAttachment covers the rest.+func outboundMediaField(contentType string, size int) string {+ ct := strings.ToLower(strings.TrimSpace(contentType))+ if semi := strings.IndexByte(ct, ';'); semi >= 0 {+ ct = strings.TrimSpace(ct[:semi])+ }+ switch {+ case (ct == "image/jpeg" || ct == "image/png" || ct == "image/gif" || ct == "image/webp") && size <= maxOutboundPhotoBytes:+ return "photo"+ case ct == "video/mp4":+ return "video"+ case ct == "audio/mpeg" || ct == "audio/mp4" || ct == "audio/ogg":+ return "audio"+ default:+ return "document"+ }+}++// outboundMediaName is what the recipient sees on the file card: one path+// segment, with an extension when the stored name has none.+func outboundMediaName(filename, contentType string) string {+ name := cleanFilename(filename)+ if name == "" {+ name = "attachment"+ }+ if path.Ext(name) == "" {+ name += mediaExtension(strings.ToLower(strings.TrimSpace(contentType)))+ }+ return name+}++func isBadRequest(err error) bool {+ var ae *apiError+ return errors.As(err, &ae) && ae.Code == http.StatusBadRequest+}++// chatDoneMessageID pulls the assistant message id out of a chat:done payload+// (typed, or its map form after a serialization round trip).+func chatDoneMessageID(payload any) string {+ switch p := payload.(type) {+ case protocol.ChatDonePayload:+ return p.MessageID+ case map[string]any:+ if s, ok := p["message_id"].(string); ok {+ return s+ }+ }+ return ""+}diff --git a/server/internal/integrations/telegram/outbound_test.go b/server/internal/integrations/telegram/outbound_test.goindex 2e70054d05..7a37be012c 100644--- a/server/internal/integrations/telegram/outbound_test.go+++ b/server/internal/integrations/telegram/outbound_test.go@@ -38,6 +38,13 @@ type fakeTelegramOutboundQueries struct {binding db.ChannelChatSessionBindingbindings map[[16]byte]db.ChannelChatSessionBindinginstallation db.ChannelInstallation+ // attachments is what the reply's assistant message has bound to it; the+ // attachment hop reads it instead of the real attachment table.+ attachments []db.Attachment+}++func (f *fakeTelegramOutboundQueries) ListAttachmentsByChatMessage(context.Context, db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error) {+ return f.attachments, nil}func (f *fakeTelegramOutboundQueries) GetChannelTaskDelivery(_ context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error) {diff --git a/server/internal/integrations/telegram/recent_context_test.go b/server/internal/integrations/telegram/recent_context_test.goindex 52cd7f93ff..14f78b55b0 100644--- a/server/internal/integrations/telegram/recent_context_test.go+++ b/server/internal/integrations/telegram/recent_context_test.go@@ -88,11 +88,11 @@ func TestRecentContextBufferTruncatesLongMessages(t *testing.T) {}func TestRecentEntryFromMessageRendersMediaPlaceholder(t *testing.T) {- e := recentEntryFromMessage(&Message{MessageID: 4, From: &User{ID: 1, FirstName: "Ada"}, Photo: []any{1}})+ e := recentEntryFromMessage(&Message{MessageID: 4, From: &User{ID: 1, FirstName: "Ada"}, Photo: []PhotoSize{{FileID: "p"}}})if e.Sender != "Ada" || e.Text != "[image message]" {t.Fatalf("media without caption should render a typed placeholder, got %+v", e)}- e = recentEntryFromMessage(&Message{MessageID: 5, Photo: []any{1}, Caption: "see this"})+ e = recentEntryFromMessage(&Message{MessageID: 5, Photo: []PhotoSize{{FileID: "p"}}, Caption: "see this"})if e.Sender != "Unknown user" || e.Text != "see this" {t.Fatalf("caption should win and a missing sender should fall back, got %+v", e)}@@ -210,7 +210,7 @@ func TestDispatchBuffersGroupMessagesForLaterMentions(t *testing.T) {if err := c.dispatch(ctx, groupUpdate(1, ada, "deploy is failing on staging", nil, 0)); err != nil {t.Fatal(err)}- if err := c.dispatch(ctx, Update{UpdateID: 2, Message: &Message{MessageID: 2, From: bob, Chat: Chat{ID: -100200, Type: "supergroup"}, Photo: []any{1}}}); err != nil {+ if err := c.dispatch(ctx, Update{UpdateID: 2, Message: &Message{MessageID: 2, From: bob, Chat: Chat{ID: -100200, Type: "supergroup"}, Photo: []PhotoSize{{FileID: "p"}}}}); err != nil {t.Fatal(err)}// Another bot's message is never buffered.diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.goindex e1cad0dc38..9a05d100d4 100644--- a/server/internal/integrations/telegram/resolvers.go+++ b/server/internal/integrations/telegram/resolvers.go@@ -29,8 +29,9 @@ const originTelegramChat = "telegram_chat"// NewTelegramResolverSet assembles the Telegram ResolverSet. Pass a nil// replier to disable outbound verdict notices; typing (sendChatAction) is-// enabled when deps carry a decrypter.-func NewTelegramResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing engine.TypingNotifier) engine.ResolverSet {+// enabled when deps carry a decrypter. A nil media resolver (no object+// storage) ingests photos and files as their placeholder text only.+func NewTelegramResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.OutboundReplier, typing engine.TypingNotifier, media engine.MediaResolver) engine.ResolverSet {return engine.ResolverSet{Installation: &installationResolver{q: q},Identity: &identityResolver{q: q},@@ -40,6 +41,7 @@ func NewTelegramResolverSet(q *db.Queries, tx engine.TxStarter, replier engine.ODirect: "Telegram direct message",Fallback: "Telegram chat",})},+ Media: media,Audit: &auditor{q: q},Replier: replier,Typing: typing,diff --git a/server/internal/integrations/telegram/sender.go b/server/internal/integrations/telegram/sender.goindex eba9028bc0..dace2dec7f 100644--- a/server/internal/integrations/telegram/sender.go+++ b/server/internal/integrations/telegram/sender.go@@ -34,6 +34,7 @@ const (msgAgentOffline = "⚠️ The agent is offline right now. Your message was received and will be handled once it's back online."msgAgentArchived = "⚠️ This agent has been archived and can't respond. Please contact your workspace admin."msgUnsupportedType = "Sorry, I can't handle this kind of message yet. Please send text."+ msgMediaUnavailable = "⚠️ I couldn't fetch that file from Telegram, so the agent won't see it. Bots can only download files up to 20 MB."msgBindingGroupHint = "Please message me in a direct chat first, then link your Multica account.")diff --git a/server/internal/integrations/telegram/telegram_channel.go b/server/internal/integrations/telegram/telegram_channel.goindex e795bb2f43..74688dfd22 100644--- a/server/internal/integrations/telegram/telegram_channel.go+++ b/server/internal/integrations/telegram/telegram_channel.go@@ -29,6 +29,10 @@ type telegramChannel struct {// recent buffers the group messages this loop has seen so an @-mention can// carry the surrounding conversation (see recent_context.go). Nil disables.recent *recentContextBuffer+ // acceptsMedia says a photo or file a member sends can actually be+ // stored (see ChannelDeps.AcceptsMedia). Without it media keeps getting+ // the unsupported notice instead of a placeholder nothing stands behind.+ acceptsMedia bool}// pollRetryDelay spaces retries after a transient getUpdates failure inside@@ -39,7 +43,7 @@ func (c *telegramChannel) Type() channel.Type { return TypeTelegram }func (c *telegramChannel) Capabilities() channel.Capability {return channel.CapText | channel.CapThreadReply | channel.CapQuoteReply |- channel.CapTypingIndicator | channel.CapMessageEdit+ channel.CapTypingIndicator | channel.CapMessageEdit | channel.CapAttachment}// Disconnect is a no-op: the polling loop's whole lifetime is scoped to@@ -112,8 +116,11 @@ func (c *telegramChannel) Connect(ctx context.Context) error {// dispatch translates one update and hands it to the engine. A non-nil// handler error is an infrastructure failure and propagates (Supervisor// reconnects; the un-advanced updates re-deliver and dedup absorbs-// duplicates). Product drops return nil. Unsupported media in a private chat,-// or explicitly addressed to the bot in a group, gets a courteous notice.+// duplicates). Product drops return nil. Photos, files, video and audio go+// through with a placeholder body the media resolver fills in — where there+// is storage to fill it from; otherwise, like an unsupported kind (sticker,+// location, …), they get a courteous notice in a private chat or when+// explicitly addressed to the bot in a group.func (c *telegramChannel) dispatch(ctx context.Context, u Update) error {msg, ok := inboundFromUpdateWithContext(u, c.botID, c.botUsername, c.recent)if !ok {@@ -121,10 +128,16 @@ func (c *telegramChannel) dispatch(ctx context.Context, u Update) error {}c.recordRecent(u.Message, msg)if msg.Type != channel.MsgTypeText {- if msg.Source.ChatType == channel.ChatTypeP2P || msg.AddressedToBot {+ if msg.Source.ChatType == channel.ChatTypeGroup && !msg.AddressedToBot {+ // Unaddressed group media is buffered above and never a turn — the+ // same silence unaddressed text gets from the Router, decided here+ // so a photo nobody asked about costs no pipeline run.+ return nil+ }+ if msg.Type == channel.MsgTypeUnknown || !c.acceptsMedia {c.notifyUnsupported(ctx, u)+ return nil}- return nil}if msg.Text == "" {return nil@@ -237,6 +250,11 @@ type ChannelDeps struct {// wiring sets DefaultRecentContextSize. Mirrors// lark.InboundEnricherConfig.RecentContextSize.RecentContextSize int+ // AcceptsMedia says the deployment stores what members send: object+ // storage is configured and a media resolver is registered. The wiring+ // sets it from the same condition, so the loop never accepts a photo the+ // pipeline cannot keep.+ AcceptsMedia bool}// RegisterTelegram registers the per-installation Telegram Factory so the@@ -269,12 +287,13 @@ func newTelegramFactory(deps ChannelDeps) channel.Factory {return nil, fmt.Errorf("telegram: installation app_id is not a bot id: %w", err)}return &telegramChannel{- botID: botID,- botUsername: ic.BotUsername,- api: newBotAPI(deps.APIBase, token, deps.HTTPClient),- handler: cfg.Handler,- logger: logger,- recent: newRecentContextBuffer(deps.RecentContextSize),+ botID: botID,+ botUsername: ic.BotUsername,+ api: newBotAPI(deps.APIBase, token, deps.HTTPClient),+ handler: cfg.Handler,+ logger: logger,+ recent: newRecentContextBuffer(deps.RecentContextSize),+ acceptsMedia: deps.AcceptsMedia,}, nil}}diff --git a/server/internal/integrations/telegram/telegram_test.go b/server/internal/integrations/telegram/telegram_test.goindex 44bdff5912..5bcd505808 100644--- a/server/internal/integrations/telegram/telegram_test.go+++ b/server/internal/integrations/telegram/telegram_test.go@@ -206,16 +206,14 @@ func TestInboundGroupHumanReplyUsesCaptionAndHandlesNonText(t *testing.T) {{name: "caption",reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},- Caption: "diagram caption", Photo: []any{struct{}{}},+ Caption: "diagram caption", Photo: []PhotoSize{{FileID: "p1"}},},wanted: "diagram caption",},{name: "empty non-text",reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},- Document: &struct {- FileName string `json:"file_name"`- }{FileName: "notes.txt"},+ Document: &FileRef{FileID: "d1", FileName: "notes.txt"},},wanted: "[empty or non-text message]",},@@ -611,7 +609,7 @@ func TestDispatchUnsupportedMediaInAddressedGroupPreservesTopicAndReply(t *testi}base := Message{MessageID: 21, From: &User{ID: 3, FirstName: "U"}, Chat: Chat{ID: -42, Type: "supergroup"},- Photo: []any{struct{}{}}, IsTopicMessage: true, MessageThreadID: 8,+ Sticker: &struct{}{}, IsTopicMessage: true, MessageThreadID: 8,}if err := c.dispatch(context.Background(), Update{UpdateID: 1, Message: &base}); err != nil {t.Fatal(err)@@ -619,8 +617,9 @@ func TestDispatchUnsupportedMediaInAddressedGroupPreservesTopicAndReply(t *testiif len(got) != 0 {t.Fatalf("unaddressed group media produced notice: %+v", got)}- base.Caption = "@my_bot look"- base.CaptionEntities = []MessageEntity{{Type: "mention", Offset: 0, Length: 7}}+ // A sticker cannot carry a caption, so replying to the bot is how it is+ // addressed in a group.+ base.ReplyToMessage = &Message{MessageID: 5, From: &User{ID: 999, IsBot: true}}if err := c.dispatch(context.Background(), Update{UpdateID: 2, Message: &base}); err != nil {t.Fatal(err)}