Skip to content

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

Go

fix(telegram): attach the file a reply quotes (#8828)

pseudoyu64b06b3de840
diff --git a/apps/docs/content/docs/telegram-bot-integration.fr.mdx b/apps/docs/content/docs/telegram-bot-integration.fr.mdx
index 67d2a4d0d9..72d73563c3 100644
--- a/apps/docs/content/docs/telegram-bot-integration.fr.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.fr.mdx
@@ -50,7 +50,7 @@ Ouvrez le bot et envoyez-lui directement du texte. Aucune @mention n'est nécess
### Groupes et sujets de forum
-Ajoutez le bot à un groupe, puis @mentionnez-le ou répondez directement à l'un de ses messages. Les messages acceptés restent dans la conversation Multica qui se poursuit. Un message de groupe qui ne s'adresse pas au bot ne démarre jamais, à lui seul, une conversation ni un tour. Il est toutefois conservé dans une petite mémoire tampon : les 10 derniers messages reçus par le bot pour chaque groupe (ou chaque sujet de forum), effacés à chaque redémarrage du serveur. Lorsqu'un membre s'adresse ensuite au bot — par une @mention ou en répondant à l'un de ses messages —, ces messages en mémoire tampon sont ajoutés en tête de ce tour comme contexte en lecture seule, et enregistrés avec le tour dans la conversation. `/new` démarre une nouvelle discussion sans ce contexte. Ce qui arrive dans la mémoire tampon dépend de ce que Telegram transmet : avec Group Privacy activé, il s'agit uniquement des commandes, des @mentions explicites et des réponses au bot ; le contexte ne contient donc que des messages qui lui étaient déjà adressés. Pour inclure les échanges ordinaires du groupe, désactivez Group Privacy dans @BotFather, puis retirez le bot du groupe et ajoutez-le de nouveau ; il reçoit dès lors tous les messages du groupe. Un bot administrateur du groupe reçoit tous les messages quel que soit le réglage de confidentialité : son contexte inclut donc les échanges ordinaires sans aucune modification dans @BotFather. Lorsque vous répondez au message d'une autre personne, @mentionnez explicitement le bot : c'est seulement dans ce cas que l'expéditeur et le texte (ou la légende) cités sont inclus avec votre instruction. Répondre au message d'une personne sans mentionner le bot ne le déclenche pas. Chaque groupe ordinaire a sa propre discussion Multica continue ; les sujets de forum sont isolés dans des discussions distinctes.
+Ajoutez le bot à un groupe, puis @mentionnez-le ou répondez directement à l'un de ses messages. Les messages acceptés restent dans la conversation Multica qui se poursuit. Un message de groupe qui ne s'adresse pas au bot ne démarre jamais, à lui seul, une conversation ni un tour. Il est toutefois conservé dans une petite mémoire tampon : les 10 derniers messages reçus par le bot pour chaque groupe (ou chaque sujet de forum), effacés à chaque redémarrage du serveur. Lorsqu'un membre s'adresse ensuite au bot — par une @mention ou en répondant à l'un de ses messages —, ces messages en mémoire tampon sont ajoutés en tête de ce tour comme contexte en lecture seule, et enregistrés avec le tour dans la conversation. Une photo ou un fichier en mémoire tampon n'y apparaît que sous forme de marqueur, tel que `[Image]`, suivi de sa légende ; le fichier lui-même n'est pas récupéré. `/new` démarre une nouvelle discussion sans ce contexte. Ce qui arrive dans la mémoire tampon dépend de ce que Telegram transmet : avec Group Privacy activé, il s'agit uniquement des commandes, des @mentions explicites et des réponses au bot ; le contexte ne contient donc que des messages qui lui étaient déjà adressés. Pour inclure les échanges ordinaires du groupe, désactivez Group Privacy dans @BotFather, puis retirez le bot du groupe et ajoutez-le de nouveau ; il reçoit dès lors tous les messages du groupe. Un bot administrateur du groupe reçoit tous les messages quel que soit le réglage de confidentialité : son contexte inclut donc les échanges ordinaires sans aucune modification dans @BotFather. Lorsque vous répondez au message d'une autre personne, @mentionnez explicitement le bot : c'est seulement dans ce cas que l'expéditeur et le texte (ou la légende) cités sont inclus avec votre instruction. Lorsqu'une réponse adressée au bot cite un message contenant une photo ou un fichier, ce fichier est joint lui aussi, quel qu'en soit l'expéditeur. Répondre au message d'une personne sans mentionner le bot ne le déclenche pas. Chaque groupe ordinaire a sa propre discussion Multica continue ; les sujets de forum sont isolés dans des discussions distinctes.
### Commandes
@@ -63,7 +63,7 @@ Ajoutez le bot à un groupe, puis @mentionnez-le ou répondez directement à l'u
Le bot diffuse le texte en continu en publiant puis en modifiant un message Telegram, cite le message déclencheur, respecte les sujets de forum et découpe les longues réponses pour rester sous la limite de taille des messages Telegram. Les réponses finales sont livrées de façon asynchrone par une file d'attente interne au processus. Normalement, le backoff d'une conversation n'occupe pas de worker ; si la pression sur le cache compacte l'état exact du backoff, d'autres conversations de la même installation du bot peuvent être retardées par précaution. La file d'attente finale a une capacité fixe : les dépassements sont rejetés et journalisés, et les réponses en file ne sont pas récupérées après un redémarrage du service.
-Les photos, fichiers, vidéos, messages vocaux et audio parviennent à l'agent sous forme de pièces jointes dans la même conversation, la légende servant de texte du message. Telegram ne permet à un bot de télécharger que des fichiers de 20 Mo au maximum ; lorsqu'un fichier ne peut pas être récupéré (trop volumineux, ou échec du téléchargement), le bot vous le signale et l'agent ne voit qu'un espace réservé. Les fichiers produits par l'agent sont renvoyés dans la conversation sous forme de messages distincts, après sa réponse : les photos jusqu'à 10 Mo s'affichent directement, tout le reste arrive sous forme de fichier, jusqu'à 50 Mo ; si la livraison d'un fichier ne peut pas être confirmée, le bot le signale et le fichier reste joint à la réponse dans Multica. Dans les deux sens, le serveur doit disposer d'un stockage des pièces jointes (voir la section Configuration en auto-hébergement ci-dessous) ; sans cela, le bot répond aux médias en indiquant qu'ils ne sont pas pris en charge, et l'agent est informé qu'il ne peut pas envoyer de fichiers. Les stickers, positions, sondages et autres messages qui ne sont pas des fichiers reçoivent la même réponse dans les conversations privées et lorsqu'ils sont adressés au bot dans un groupe ; dans un groupe, ceux qui ne lui sont pas adressés restent sans réponse.
+Les photos, fichiers, vidéos, messages vocaux et audio parviennent à l'agent sous forme de pièces jointes dans la même conversation, la légende servant de texte du message. Répondre à un message qui en contient un — dans une conversation privée ou, en s'adressant au bot, dans un groupe, quel qu'en soit l'expéditeur — cite ce message avant votre instruction et joint son fichier, ce qui permet de désigner à l'agent une photo ou une vidéo antérieure. Telegram ne permet à un bot de télécharger que des fichiers de 20 Mo au maximum ; lorsqu'un fichier ne peut pas être récupéré (trop volumineux, ou échec du téléchargement), le bot vous le signale et l'agent ne voit qu'un espace réservé. Les fichiers produits par l'agent sont renvoyés dans la conversation sous forme de messages distincts, après sa réponse : les photos jusqu'à 10 Mo s'affichent directement, tout le reste arrive sous forme de fichier, jusqu'à 50 Mo ; si la livraison d'un fichier ne peut pas être confirmée, le bot le signale et le fichier reste joint à la réponse dans Multica. Dans les deux sens, le serveur doit disposer d'un stockage des pièces jointes (voir la section Configuration en auto-hébergement ci-dessous) ; sans cela, le bot répond aux médias en indiquant qu'ils ne sont pas pris en charge, et l'agent est informé qu'il ne peut pas envoyer de fichiers. Les stickers, positions, sondages et autres messages qui ne sont pas des fichiers reçoivent la même réponse dans les conversations privées et lorsqu'ils sont adressés au bot dans un groupe ; dans un groupe, ceux qui ne lui sont pas adressés restent sans réponse.
## Gérer les connexions
diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
index c305cbc6e0..14118ae498 100644
--- a/apps/docs/content/docs/telegram-bot-integration.ja.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx
@@ -43,14 +43,14 @@ Multica は Telegram で Bot を検証し、long polling と競合する webhook
## Bot を使う
- **DM**: @mention なしでテキストを送信します。
-- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残ります。Bot 宛てでないグループメッセージは、それ自体で会話やターンを開始することはありません。ただし小さなメモリ上のバッファに保持されます。グループ(または forum topic)ごとに Bot が受信した直近 10 件で、サーバーの再起動で消えます。その後メンバーが @mention または Bot のメッセージへの返信で Bot に指示すると、バッファ内のメッセージが読み取り専用のコンテキストとしてそのターンの前に添えられ、ターンと一緒に会話として保存されます。`/new` で始めた新しい会話にはこのコンテキストは付きません。バッファに入る内容は Telegram が何を配信するかで決まります。Group Privacy が有効ならコマンド、明示的な @mention、Bot への返信だけなので、コンテキストには以前 Bot 宛てだったメッセージだけが入ります。通常の会話も含めたい場合は @BotFather で Group Privacy を無効にし、Bot をグループから外して再追加してください。以後 Bot はグループの全メッセージを受信します。グループ管理者になっている Bot はプライバシー設定に関係なく全メッセージを受信するため、@BotFather を変更しなくても通常の会話がコンテキストに含まれます。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。
+- **グループ**: Bot を追加し、@mention するか Bot のメッセージに直接返信します。受理されたメッセージは継続中の Multica 会話に残ります。Bot 宛てでないグループメッセージは、それ自体で会話やターンを開始することはありません。ただし小さなメモリ上のバッファに保持されます。グループ(または forum topic)ごとに Bot が受信した直近 10 件で、サーバーの再起動で消えます。その後メンバーが @mention または Bot のメッセージへの返信で Bot に指示すると、バッファ内のメッセージが読み取り専用のコンテキストとしてそのターンの前に添えられ、ターンと一緒に会話として保存されます。バッファ内の画像やファイルは、コンテキストでは `[Image]` のようなマーカーと caption だけで示され、ファイル自体は取得されません。`/new` で始めた新しい会話にはこのコンテキストは付きません。バッファに入る内容は Telegram が何を配信するかで決まります。Group Privacy が有効ならコマンド、明示的な @mention、Bot への返信だけなので、コンテキストには以前 Bot 宛てだったメッセージだけが入ります。通常の会話も含めたい場合は @BotFather で Group Privacy を無効にし、Bot をグループから外して再追加してください。以後 Bot はグループの全メッセージを受信します。グループ管理者になっている Bot はプライバシー設定に関係なく全メッセージを受信するため、@BotFather を変更しなくても通常の会話がコンテキストに含まれます。他のメンバーのメッセージへ返信する場合は Bot も明示的に @mention してください。その場合に限り、引用元の送信者とテキスト(または caption)が新しい指示の文脈に含まれます。Bot 宛ての返信が引用するメッセージに画像やファイルが含まれていれば、送信者が誰であれそのファイルも一緒に添付されます。@mention なしの人への返信は Bot を起動しません。forum topic は topic ごとにセッションが分離されます。
- **`/new` / `/new <message>`**: 空の新しい Multica Chat を作成し、その Telegram 会話の後続メッセージを新しい Chat にルーティングします。メッセージを付けた場合は新しい Chat の最初のターンになります。他のメンバーへの返信で Bot を明示的に @mention した場合、選択した引用内容も最初のターンに含まれます。
- **`/clear` / `/clear <message>`**: 現在の Multica Chat を維持したまま、次の空でないメッセージに新しいエージェント可視コンテキストを適用します。メッセージを付けた場合は境界後の最初のターンになり、明示的に選択した返信の引用も保持されます。
- **`/issue <title>`**: Multica issue を作成します。2 行目以降は任意の説明です。`/issue@your_bot` 形式も利用できます。
Bot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は自動分割されます。最終返信はプロセス内で非同期に配信されます。通常、あるチャットのバックオフ待機は worker を占有しません。キャッシュが上限に達してバックオフ状態が圧縮されると、同じ Bot installation の他のチャットも安全側に遅延する場合があります。終端キューの容量は固定で、上限超過は明示的に拒否されてエラーとして記録されます。キューはサービス再起動後に復元されません。
-画像、ファイル、動画、音声メッセージは、キャプションをメッセージ本文として、同じ会話の添付ファイルとしてエージェントに届きます。Telegram の Bot がダウンロードできるのは 20 MB までで、取得できなかった場合(大きすぎる、またはダウンロード失敗)は Bot がその旨を伝え、エージェントにはプレースホルダーだけが見えます。エージェントが生成したファイルは返信の後に別メッセージとして送り返されます。10 MB までの画像はインライン表示、それ以外は 50 MB までファイルとして届きます。送達を確認できなかった場合は Bot がその旨を伝え、ファイルは Multica の返信に添付されたまま残ります。どちらの方向もサーバー側にオブジェクトストレージが必要です。未設定の場合、Bot はメディアに非対応通知を返し、エージェントにはファイルを送れない旨が伝えられます。sticker、位置情報、投票などファイル以外のメッセージは、DM または Bot 宛てのグループメッセージで同じ通知を返します。
+画像、ファイル、動画、音声メッセージは、キャプションをメッセージ本文として、同じ会話の添付ファイルとしてエージェントに届きます。これらを含むメッセージに返信すると(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.mdx
index 5b24b9551e..c576ae527c 100644
--- a/apps/docs/content/docs/telegram-bot-integration.ko.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx
@@ -43,14 +43,14 @@ Multica는 Telegram에서 Bot을 검증하고 long polling과 충돌하는 webho
## Bot 사용하기
- **개인 채팅**: @mention 없이 텍스트를 보냅니다.
-- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남습니다. Bot을 지정하지 않은 그룹 메시지는 그 자체로 대화나 턴을 시작하지 않습니다. 다만 작은 메모리 버퍼에 보관됩니다. 그룹(또는 forum topic)별로 Bot이 받은 최근 10개이며, 서버가 재시작되면 지워집니다. 이후 구성원이 @mention이나 Bot 메시지에 대한 답장으로 Bot에게 지시하면, 버퍼의 메시지가 읽기 전용 컨텍스트로 그 턴 앞에 붙고 턴과 함께 대화의 일부로 저장됩니다. `/new`로 시작한 새 대화에는 이 컨텍스트가 붙지 않습니다. 버퍼에 무엇이 들어가는지는 Telegram이 무엇을 전달하느냐에 달려 있습니다. Group Privacy가 켜져 있으면 명령, 명시적 @mention, Bot에 대한 답장뿐이므로 컨텍스트에는 이전에 Bot에게 보낸 메시지만 남습니다. 일반 그룹 대화까지 포함하려면 @BotFather에서 Group Privacy를 끄고 Bot을 그룹에서 내보낸 뒤 다시 추가하세요. 그 뒤로 Bot은 그룹의 모든 메시지를 받습니다. 그룹 관리자인 Bot은 프라이버시 설정과 무관하게 모든 메시지를 받으므로, @BotFather를 바꾸지 않아도 일반 대화가 컨텍스트에 포함됩니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.
+- **그룹**: Bot을 추가한 뒤 @mention하거나 Bot 메시지에 직접 답장합니다. 수락된 메시지는 이어지는 Multica 대화에 남습니다. Bot을 지정하지 않은 그룹 메시지는 그 자체로 대화나 턴을 시작하지 않습니다. 다만 작은 메모리 버퍼에 보관됩니다. 그룹(또는 forum topic)별로 Bot이 받은 최근 10개이며, 서버가 재시작되면 지워집니다. 이후 구성원이 @mention이나 Bot 메시지에 대한 답장으로 Bot에게 지시하면, 버퍼의 메시지가 읽기 전용 컨텍스트로 그 턴 앞에 붙고 턴과 함께 대화의 일부로 저장됩니다. 버퍼에 있는 이미지나 파일은 컨텍스트에서 `[Image]` 같은 표시와 caption으로만 나타나며 파일 자체는 가져오지 않습니다. `/new`로 시작한 새 대화에는 이 컨텍스트가 붙지 않습니다. 버퍼에 무엇이 들어가는지는 Telegram이 무엇을 전달하느냐에 달려 있습니다. Group Privacy가 켜져 있으면 명령, 명시적 @mention, Bot에 대한 답장뿐이므로 컨텍스트에는 이전에 Bot에게 보낸 메시지만 남습니다. 일반 그룹 대화까지 포함하려면 @BotFather에서 Group Privacy를 끄고 Bot을 그룹에서 내보낸 뒤 다시 추가하세요. 그 뒤로 Bot은 그룹의 모든 메시지를 받습니다. 그룹 관리자인 Bot은 프라이버시 설정과 무관하게 모든 메시지를 받으므로, @BotFather를 바꾸지 않아도 일반 대화가 컨텍스트에 포함됩니다. 다른 사람의 메시지에 답장할 때는 Bot도 명시적으로 @mention해야 하며, 이 경우에만 인용한 발신자와 텍스트(또는 caption)가 새 지시의 맥락에 포함됩니다. Bot에게 보낸 답장이 인용한 메시지에 이미지나 파일이 있으면, 보낸 사람이 누구든 그 파일도 함께 첨부됩니다. Bot @mention 없이 사람에게 답장하면 Bot이 실행되지 않습니다. forum topic은 topic별로 세션이 분리됩니다.
- **`/new` / `/new <message>`**: 비어 있는 새 Multica Chat을 만들고 해당 Telegram 대화의 이후 메시지를 새 Chat으로 라우팅합니다. 메시지를 함께 보내면 새 Chat의 첫 번째 대화가 됩니다. 다른 멤버에게 답장하면서 Bot을 명시적으로 @mention하면 선택한 인용 내용도 첫 번째 대화에 포함됩니다.
- **`/clear` / `/clear <message>`**: 현재 Multica Chat을 유지하면서 다음 비어 있지 않은 메시지에 새 에이전트 컨텍스트를 적용합니다. 메시지를 함께 보내면 경계 이후의 첫 번째 대화가 되며 명시적으로 선택한 답장 인용도 유지됩니다.
- **`/issue <title>`**: Multica issue를 만듭니다. 다음 줄은 선택 설명으로 사용됩니다. `/issue@your_bot` 형식도 지원합니다.
Bot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 자동으로 나뉩니다. 최종 응답은 프로세스 내에서 비동기로 전달됩니다. 일반적으로 한 채팅의 백오프 대기는 worker를 점유하지 않습니다. 캐시가 용량 한계에 도달해 백오프 상태를 압축하면 같은 Bot installation의 다른 채팅도 안전을 위해 지연될 수 있습니다. 최종 응답 큐의 용량은 고정되어 있으며 한도를 넘은 작업은 명시적으로 거부되고 오류로 기록됩니다. 큐는 서비스 재시작 후 복구되지 않습니다.
-이미지, 파일, 영상, 음성 메시지는 caption을 메시지 본문으로 하여 같은 대화의 첨부파일로 에이전트에 전달됩니다. Telegram Bot은 20 MB까지만 내려받을 수 있으며, 파일을 가져오지 못하면(너무 크거나 다운로드 실패) Bot이 알려 주고 에이전트에게는 자리표시자만 보입니다. 에이전트가 만든 파일은 응답 뒤에 별도 메시지로 채팅에 전송됩니다. 10 MB 이하 이미지는 인라인으로, 그 외에는 50 MB까지 파일로 도착합니다. 전달을 확인하지 못하면 Bot이 알려 주며 파일은 Multica의 응답에 첨부된 채로 남습니다. 두 방향 모두 서버에 객체 스토리지가 필요합니다. 설정이 없으면 Bot은 미디어에 미지원 안내를 회신하고 에이전트는 파일을 보낼 수 없다는 안내를 받습니다. sticker, 위치, 투표 등 파일이 아닌 메시지는 개인 채팅 또는 Bot에게 보낸 그룹 메시지에서 같은 안내를 반환합니다.
+이미지, 파일, 영상, 음성 메시지는 caption을 메시지 본문으로 하여 같은 대화의 첨부파일로 에이전트에 전달됩니다. 이런 내용이 담긴 메시지에 답장하면(개인 채팅이든, 그룹에서 Bot에게 지시할 때든, 보낸 사람이 누구든) 그 메시지가 인용으로 지시 앞에 붙고 파일도 에이전트에 전달되므로 이전 이미지나 영상을 지정할 수 있습니다. 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.mdx
index edfdb2d019..7de06ec207 100644
--- a/apps/docs/content/docs/telegram-bot-integration.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.mdx
@@ -50,7 +50,7 @@ Open the Bot and send text directly. No @-mention is required.
### Groups and forum topics
-Add the Bot to a group, then either @-mention it or reply directly to one of its messages. Accepted messages remain in the continued Multica conversation. A group message that does not address the Bot never starts a conversation or a turn on its own. It is, however, held in a short in-memory buffer: the last 10 messages per group (or per forum topic) that the Bot has received, cleared whenever the server restarts. When a member then addresses the Bot — by @-mention or by replying to one of its messages — those buffered messages are prepended to that turn as read-only context, and they are saved together with the turn as part of the conversation. `/new` starts a fresh chat without that context. What reaches the buffer depends on what Telegram delivers: with Group Privacy enabled, that is only commands, explicit @-mentions, and replies to the Bot, so the context holds earlier addressed messages only. To include ordinary group chatter, turn Group Privacy off in @BotFather and then remove and re-add the Bot to the group; the Bot receives every group message from then on. A Bot that is a group admin receives every message regardless of the privacy setting, so its context includes ordinary chatter without any change in @BotFather. When replying to another person's message, explicitly @-mention the Bot: only then are that quoted sender and text (or caption) included with your instruction. Replying to a human message without mentioning the Bot does not trigger it. Each ordinary group has its own continued Multica chat; forum topics are isolated into separate chats.
+Add the Bot to a group, then either @-mention it or reply directly to one of its messages. Accepted messages remain in the continued Multica conversation. A group message that does not address the Bot never starts a conversation or a turn on its own. It is, however, held in a short in-memory buffer: the last 10 messages per group (or per forum topic) that the Bot has received, cleared whenever the server restarts. When a member then addresses the Bot — by @-mention or by replying to one of its messages — those buffered messages are prepended to that turn as read-only context, and they are saved together with the turn as part of the conversation. A buffered photo or file appears there only as a marker such as `[Image]` followed by its caption; the file itself is not fetched. `/new` starts a fresh chat without that context. What reaches the buffer depends on what Telegram delivers: with Group Privacy enabled, that is only commands, explicit @-mentions, and replies to the Bot, so the context holds earlier addressed messages only. To include ordinary group chatter, turn Group Privacy off in @BotFather and then remove and re-add the Bot to the group; the Bot receives every group message from then on. A Bot that is a group admin receives every message regardless of the privacy setting, so its context includes ordinary chatter without any change in @BotFather. When replying to another person's message, explicitly @-mention the Bot: only then are that quoted sender and text (or caption) included with your instruction. When a reply that addresses the Bot quotes a message carrying a photo or file, that file is attached as well, whoever sent it. Replying to a human message without mentioning the Bot does not trigger it. Each ordinary group has its own continued Multica chat; forum topics are isolated into separate chats.
### Commands
@@ -63,7 +63,7 @@ Add the Bot to a group, then either @-mention it or reply directly to one of its
The 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.
-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.
+Photos, files, video, voice, and audio messages reach the agent as attachments on the same conversation, with the caption as the message text. Replying to a message that carries one of these — in a private chat or, when addressing the Bot, in a group, whoever sent it — quotes that message ahead of your instruction and attaches its file, so you can point the agent at an earlier photo or video. 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 connections
diff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
index f97bd8a02e..820f0e9852 100644
--- a/apps/docs/content/docs/telegram-bot-integration.zh.mdx
+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx
@@ -50,7 +50,7 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲
### 群聊与 forum topic
-把 Bot 加入群后,@它,或直接回复它发过的消息。被接受的消息会保留在持续的 Multica 对话中。未明确发给 Bot 的群消息本身不会开启对话,也不会单独形成一轮,但会被暂存在一个很小的内存缓冲里:每个群(或每个 forum topic)保留 Bot 收到的最近 10 条,服务器重启即清空。之后当有成员通过 @ 或回复 Bot 的消息向它发出指令时,这些暂存消息会作为只读上下文附在该轮指令之前,并随这一轮一起保存进对话记录。`/new` 开启的新对话不带这段上下文。缓冲里有什么取决于 Telegram 投递了什么:Group Privacy 开启时只有命令、明确的 @ 和对 Bot 的回复,所以上下文里只有之前明确发给它的消息。想让它看到普通群聊,请在 @BotFather 里关闭 Group Privacy,再把 Bot 移出群重新加入,此后 Bot 会收到群里的每一条消息。被设为群管理员的 Bot 无论隐私设置如何都会收到全部消息,因此不改 @BotFather 也会把普通群聊纳入上下文。回复其他成员的消息时必须同时 @ Bot,只有这种情况下,被引用消息的发送者及文字(或 caption)才会随新指令进入上下文;只回复成员而不 @ Bot 不会触发。普通群聊各自延续一段 Multica 对话;forum 的每个 topic 分别隔离。
+把 Bot 加入群后,@它,或直接回复它发过的消息。被接受的消息会保留在持续的 Multica 对话中。未明确发给 Bot 的群消息本身不会开启对话,也不会单独形成一轮,但会被暂存在一个很小的内存缓冲里:每个群(或每个 forum topic)保留 Bot 收到的最近 10 条,服务器重启即清空。之后当有成员通过 @ 或回复 Bot 的消息向它发出指令时,这些暂存消息会作为只读上下文附在该轮指令之前,并随这一轮一起保存进对话记录。缓冲里的图片或文件在上下文中只显示为 `[Image]` 之类的标记和 caption,文件本身不会被获取。`/new` 开启的新对话不带这段上下文。缓冲里有什么取决于 Telegram 投递了什么:Group Privacy 开启时只有命令、明确的 @ 和对 Bot 的回复,所以上下文里只有之前明确发给它的消息。想让它看到普通群聊,请在 @BotFather 里关闭 Group Privacy,再把 Bot 移出群重新加入,此后 Bot 会收到群里的每一条消息。被设为群管理员的 Bot 无论隐私设置如何都会收到全部消息,因此不改 @BotFather 也会把普通群聊纳入上下文。回复其他成员的消息时必须同时 @ Bot,只有这种情况下,被引用消息的发送者及文字(或 caption)才会随新指令进入上下文;发给 Bot 的回复所引用的消息若带图片或文件,该文件也会一并附上,无论发送者是谁;只回复成员而不 @ Bot 不会触发。普通群聊各自延续一段 Multica 对话;forum 的每个 topic 分别隔离。
### 命令
@@ -63,7 +63,7 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲
Bot 通过发送并编辑 Telegram 消息来流式展示文字回复,引用触发消息、保留 forum topic,并按 Telegram 长度限制自动分段。最终回复在进程内异步投递。正常情况下,某个聊天的退避等待不会占用 worker;缓存达到容量上限并压缩退避状态时,同一 Bot installation 下的其他聊天可能被保守延迟。终态队列有固定容量,超限运行会被明确拒绝并记录错误;队列不会跨服务重启恢复。
-图片、文件、视频、语音和音频消息会作为同一对话的附件交给智能体,caption 作为消息正文。Telegram 只允许 Bot 下载 20 MB 以内的文件;文件无法获取时(太大或下载失败),Bot 会告诉你,智能体只会看到一个占位符。智能体生成的文件会在回复之后作为单独的消息发回聊天:10 MB 以内的图片内联显示,其余 50 MB 以内的文件以文件形式到达;无法确认送达时 Bot 会说明,文件仍保留在 Multica 的回复附件里。这两个方向都需要服务端配置对象存储(见下文自托管部分);未配置时,Bot 对媒体消息回复不支持提示,智能体也会被告知无法发送文件。贴纸、位置、投票等非文件消息在私聊中以及群里明确 @ Bot 时会收到同样的提示,群里未 @ 的此类消息保持静默。
+图片、文件、视频、语音和音频消息会作为同一对话的附件交给智能体,caption 作为消息正文。回复一条带有这类内容的消息(私聊,或在群里向 Bot 发出指令时,无论发送者是谁)会把该消息作为引用附在你的指令前,并把它的文件一并交给智能体,这样你可以指定之前的某张图片或某段视频。Telegram 只允许 Bot 下载 20 MB 以内的文件;文件无法获取时(太大或下载失败),Bot 会告诉你,智能体只会看到一个占位符。智能体生成的文件会在回复之后作为单独的消息发回聊天:10 MB 以内的图片内联显示,其余 50 MB 以内的文件以文件形式到达;无法确认送达时 Bot 会说明,文件仍保留在 Multica 的回复附件里。这两个方向都需要服务端配置对象存储(见下文自托管部分);未配置时,Bot 对媒体消息回复不支持提示,智能体也会被告知无法发送文件。贴纸、位置、投票等非文件消息在私聊中以及群里明确 @ Bot 时会收到同样的提示,群里未 @ 的此类消息保持静默。
## 管理与断开
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index f946d4928e..7e4199c9c1 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -205,7 +205,7 @@ func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {
// while every title test stays green. lark and telegram are today's only
// enriching adapters and both comply: lark maps the decoder's
// pre-enrichment CommandBody, telegram the cleaned instruction captured
- // before enrichWithQuotedHumanMessage.
+ // before enrichWithQuotedMessage.
if msg.CommandText == "" {
msg.CommandText = msg.Text
}
diff --git a/server/internal/integrations/telegram/inbound.go b/server/internal/integrations/telegram/inbound.go
index 2cc1d4be5b..20e63f7852 100644
--- a/server/internal/integrations/telegram/inbound.go
+++ b/server/internal/integrations/telegram/inbound.go
@@ -26,9 +26,11 @@ 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"`
+ // Media lists the files this message carries for the media resolver to
+ // fetch off the ACK path, in the order their placeholders appear in the
+ // body: the file of a quoted message first, then the sender's own. Empty
+ // for text-only messages.
+ Media []inboundMedia `json:"media,omitempty"`
}
// inboundMedia is what the media resolver needs to fetch a message's file:
@@ -44,8 +46,8 @@ type inboundMedia struct {
// 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
+ // PlaceholderIndex is which occurrence of Placeholder in the body is this
+ // file's: context goes in front of the sender's own marker, and a member
// who typed the same marker there must not receive the file.
PlaceholderIndex int `json:"placeholder_index,omitempty"`
}
@@ -61,6 +63,9 @@ func mediaFromMessage(m *Message) *inboundMedia {
best = p
}
}
+ if best.FileID == "" {
+ return nil
+ }
return &inboundMedia{Kind: channel.MsgTypeImage, FileID: best.FileID, FileUniqueID: best.FileUniqueID,
MimeType: "image/jpeg", FileSize: best.FileSize, Placeholder: "[Image]"}
case m.Document != nil:
@@ -87,6 +92,16 @@ func fileRefMedia(kind channel.MsgType, f *FileRef, placeholder string) *inbound
FileName: f.FileName, MimeType: f.MimeType, FileSize: f.FileSize, Placeholder: placeholder}
}
+// leadWithPlaceholder puts a file's marker above its caption, so the caption
+// reads as the caption of the file once the resolver swaps the marker for the
+// attachment link. A file without a caption is the marker alone.
+func leadWithPlaceholder(placeholder, caption string) string {
+ if strings.TrimSpace(caption) == "" {
+ return placeholder
+ }
+ return placeholder + "\n" + caption
+}
+
// inboundFromUpdate normalizes one Telegram update without any recent group
// context. See inboundFromUpdateWithContext.
func inboundFromUpdate(u Update, botID int64, botUsername string) (channel.InboundMessage, bool) {
@@ -149,28 +164,46 @@ func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, rec
// 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
- }
+ own = leadWithPlaceholder(media.Placeholder, cleaned)
agentText = own
}
+ // A quoted file is selected context in every chat and whoever sent it, as
+ // long as the reply addresses the bot at all: which of several files a
+ // reply means can only be read off the quote, and the file is one getFile
+ // away. A quoted text is selected context only for a group member who
+ // replied and mentioned the bot: in a private chat the earlier text is
+ // already part of the one continuous session, and the bot's own text is
+ // its own reply.
+ var quotedMedia *inboundMedia
+ if m.ReplyToMessage != nil && addressed {
+ quotedMedia = mediaFromMessage(m.ReplyToMessage)
+ }
quotedHuman := m.ReplyToMessage != nil && m.ReplyToMessage.From != nil && !m.ReplyToMessage.From.IsBot
- hasSelectedContext := chatType == channel.ChatTypeGroup && mentioned && quotedHuman
+ hasSelectedContext := (chatType == channel.ChatTypeGroup && mentioned && quotedHuman) || quotedMedia != nil
+ fromQuote := ""
if hasSelectedContext {
- agentText = enrichWithQuotedHumanMessage(agentText, m.Chat.ID, m.ReplyToMessage)
+ agentText = enrichWithQuotedMessage(agentText, m.Chat.ID, m.ReplyToMessage, quotedMedia)
+ fromQuote = agentText
}
if recent != nil && chatType == channel.ChatTypeGroup && addressed && !startChat {
agentText = enrichWithRecentContext(agentText, m, recent)
}
+ // The engine replaces a placeholder by occurrence, and the context
+ // enrichers only ever prepend, so each segment is a suffix of the final
+ // text: the sender's own segment last, the quoted block ahead of it. Count
+ // every occurrence before a marker — user-typed literals included — so a
+ // member who wrote "[Image]" in the window does not receive the file.
+ // Same rule as DingTalk's quoted block.
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)
}
+ if quotedMedia != nil {
+ // The quoted file's marker opens the block body, right after the
+ // one-line header.
+ start := len(agentText) - len(fromQuote)
+ body := start + strings.IndexByte(agentText[start:], '\n') + 1
+ quotedMedia.PlaceholderIndex = strings.Count(agentText[:body], quotedMedia.Placeholder)
+ }
senderID := strconv.FormatInt(m.From.ID, 10)
chatID := strconv.FormatInt(m.Chat.ID, 10)
@@ -179,11 +212,18 @@ func inboundFromUpdateWithContext(u Update, botID int64, botUsername string, rec
threadID = strconv.FormatInt(m.MessageThreadID, 10)
}
+ var files []inboundMedia
+ if quotedMedia != nil {
+ files = append(files, *quotedMedia)
+ }
+ if media != nil {
+ files = append(files, *media)
+ }
raw, _ := json.Marshal(telegramRawEvent{
BotID: strconv.FormatInt(botID, 10),
EventType: "message",
SenderName: senderDisplayName(m.From),
- Media: media,
+ Media: files,
})
var reply *channel.ReplyCtx
@@ -302,16 +342,20 @@ func normalizeText(text, botUsername string) string {
return strings.TrimSpace(cleaned)
}
-// enrichWithQuotedHumanMessage prepends only the message a group member
-// explicitly selected by replying and mentioning the bot. Ambient group
-// history never enters the agent context. CommandText remains the sender's own
-// cleaned instruction so commands inside the quoted message stay historical.
-func enrichWithQuotedHumanMessage(instruction string, chatID int64, quoted *Message) string {
+// enrichWithQuotedMessage prepends the one message the sender explicitly
+// selected by replying; ambient group history never enters the agent context
+// this way. A quoted file leads its caption as the placeholder the resolver
+// swaps for the attachment link, the same way the sender's own file leads
+// their text. CommandText remains the sender's own cleaned instruction so
+// commands inside the quoted message stay historical.
+func enrichWithQuotedMessage(instruction string, chatID int64, quoted *Message, media *inboundMedia) string {
quotedText := quoted.Text
if quotedText == "" {
quotedText = quoted.Caption
}
- if strings.TrimSpace(quotedText) == "" {
+ if media != nil {
+ quotedText = leadWithPlaceholder(media.Placeholder, quotedText)
+ } else if strings.TrimSpace(quotedText) == "" {
quotedText = "[empty or non-text message]"
}
sender := "Unknown user"
diff --git a/server/internal/integrations/telegram/media_ingest.go b/server/internal/integrations/telegram/media_ingest.go
index caf329f791..c241add4c5 100644
--- a/server/internal/integrations/telegram/media_ingest.go
+++ b/server/internal/integrations/telegram/media_ingest.go
@@ -2,10 +2,11 @@ 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.
+// the message's files — the sender's own and the one they quoted — 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"
@@ -68,12 +69,12 @@ func NewMediaResolver(decrypt Decrypter, storage objectStore, ledger engine.Medi
func (r *mediaResolver) HasMedia(msg channel.InboundMessage) bool {
raw, err := decodeTelegramRaw(msg)
- return err == nil && raw.Media != nil && raw.Media.FileID != ""
+ return err == nil && len(raw.Media) > 0
}
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 == "" {
+ if err != nil || len(raw.Media) == 0 {
return msg
}
row, ok := inst.Platform.(db.ChannelInstallation)
@@ -87,20 +88,29 @@ func (r *mediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedIn
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)
+ // Every file is attempted; one that fails keeps its placeholder in the
+ // body, and the sender hears about it once.
+ failed := false
+ for i, m := range raw.Media {
+ ref, err := r.ingest(ctx, inst, chatMessageID, i, m, api)
+ if err != nil {
+ r.logWarn(msg, err)
+ failed = true
+ continue
+ }
+ msg.MediaRefs = append(msg.MediaRefs, ref)
+ }
+ if failed {
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.
+// notifyUnavailable tells the sender a file did not make it — their own or
+// the one they quoted, 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 {
@@ -125,7 +135,7 @@ func (r *mediaResolver) notifyUnavailable(ctx context.Context, api *botAPI, msg
// 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) {
+func (r *mediaResolver) ingest(ctx context.Context, inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, index int, 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)
}
@@ -139,7 +149,7 @@ func (r *mediaResolver) ingest(ctx context.Context, inst engine.ResolvedInstalla
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)
+ key := mediaObjectKey(inst, chatMessageID, index, m)
link := r.storage.ObjectURL(key)
owned, err := r.ledger.RecordPendingMediaObject(ctx, engine.RecordPendingMediaObjectParams{
StorageKey: key,
@@ -175,12 +185,13 @@ func (r *mediaResolver) ingest(ctx context.Context, inst engine.ResolvedInstalla
}, 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)))
+// mediaObjectKey is keyed by the chat message the object binds to and the
+// file's position in it, not the platform file alone: a reclaimed dedup claim
+// can ingest one platform message twice, and a reply can quote the very file
+// it sends, so 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, index int, m inboundMedia) string {
+ sum := sha256.Sum256([]byte(util.UUIDToString(chatMessageID) + "\x00" + strconv.Itoa(index) + "\x00" + firstNonEmpty(m.FileUniqueID, m.FileID)))
return path.Join("workspaces", util.UUIDToString(inst.WorkspaceID), "telegram", util.UUIDToString(inst.ID), hex.EncodeToString(sum[:]))
}
diff --git a/server/internal/integrations/telegram/media_test.go b/server/internal/integrations/telegram/media_test.go
index d6c2806b8f..bead41a323 100644
--- a/server/internal/integrations/telegram/media_test.go
+++ b/server/internal/integrations/telegram/media_test.go
@@ -47,14 +47,15 @@ func TestInboundPhotoWithCaptionCarriesMediaAndPlaceholder(t *testing.T) {
t.Fatalf("text=%q command=%q", msg.Text, msg.CommandText)
}
raw, err := decodeTelegramRaw(msg)
- if err != nil || raw.Media == nil {
+ if err != nil || len(raw.Media) != 1 {
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)
+ media := raw.Media[0]
+ if media.FileID != "large" || media.Kind != channel.MsgTypeImage || media.Placeholder != "[Image]" || media.FileSize != 120000 {
+ t.Fatalf("media = %+v, want the largest rendition", media)
}
- if raw.Media.PlaceholderIndex != 0 {
- t.Fatalf("a p2p photo has nothing ahead of its placeholder, index = %d", raw.Media.PlaceholderIndex)
+ if media.PlaceholderIndex != 0 {
+ t.Fatalf("a p2p photo has nothing ahead of its placeholder, index = %d", media.PlaceholderIndex)
}
}
@@ -103,17 +104,18 @@ func TestInboundPlaceholderIndexSkipsLiteralsInRecentContext(t *testing.T) {
}
msg := handled[1]
raw, _ := decodeTelegramRaw(msg)
- if raw.Media == nil || raw.Media.PlaceholderIndex != 1 {
+ if len(raw.Media) != 1 || raw.Media[0].PlaceholderIndex != 1 {
t.Fatalf("media = %+v, want placeholder index 1 (Ada's literal is occurrence 0)", raw.Media)
}
+ media := raw.Media[0]
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, media.Placeholder, media.PlaceholderIndex); pos < contextEnd {
+ t.Fatalf("occurrence %d is inside the context block (at %d, block ends %d):\n%s", media.PlaceholderIndex, pos, contextEnd, msg.Text)
}
- if pos := nthOccurrence(msg.Text, raw.Media.Placeholder, 0); pos > contextEnd {
+ if pos := nthOccurrence(msg.Text, media.Placeholder, 0); pos > contextEnd {
t.Fatalf("Ada's literal should be occurrence 0, found at %d:\n%s", pos, msg.Text)
}
}
@@ -131,12 +133,13 @@ func TestInboundPlaceholderIndexSkipsLiteralsInQuotedMessage(t *testing.T) {
t.Fatalf("ok=%v selected=%v", ok, msg.HasSelectedContext)
}
raw, _ := decodeTelegramRaw(msg)
- if raw.Media == nil || raw.Media.PlaceholderIndex != 1 {
+ if len(raw.Media) != 1 || raw.Media[0].PlaceholderIndex != 1 {
t.Fatalf("media = %+v, want placeholder index 1", raw.Media)
}
+ media := raw.Media[0]
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)
+ if pos := nthOccurrence(msg.Text, media.Placeholder, media.PlaceholderIndex); quoteEnd < 0 || pos < quoteEnd {
+ t.Fatalf("occurrence %d is not on Bob's line (at %d, quote ends %d):\n%s", media.PlaceholderIndex, pos, quoteEnd, msg.Text)
}
}
@@ -175,12 +178,12 @@ func TestInboundMediaKindsAndPlaceholders(t *testing.T) {
}
raw, _ := decodeTelegramRaw(msg)
if tc.wantNoMedia {
- if raw.Media != nil {
- t.Fatalf("unexpected media %+v", *raw.Media)
+ if len(raw.Media) != 0 {
+ t.Fatalf("unexpected media %+v", raw.Media)
}
return
}
- if raw.Media == nil || raw.Media.FileName != tc.wantName || raw.Media.Placeholder != tc.wantText {
+ if len(raw.Media) != 1 || raw.Media[0].FileName != tc.wantName || raw.Media[0].Placeholder != tc.wantText {
t.Fatalf("media = %+v", raw.Media)
}
})
@@ -198,6 +201,109 @@ func TestInboundControlCommandWithPhotoKeepsMediaTurn(t *testing.T) {
}
}
+// A reply to a message that carries a file selects that file, in a private
+// chat and whoever sent it — here the bot's own photo, one of several the
+// agent sent — so the quote is rendered and the file fetched the way a group
+// member's quoted photo is. A quoted text in a private chat is already part
+// of the one continuous session and stays unrendered, as before; and a reply
+// that addresses nobody in a group is neither rendered nor fetched, since the
+// Router drops it.
+func TestInboundReplyToFileQuotesAndFetchesIt(t *testing.T) {
+ ada := &User{ID: 111, FirstName: "Ada"}
+ botPhoto := &Message{
+ MessageID: 3, From: &User{ID: 999, IsBot: true, FirstName: "Team Bot"},
+ Caption: "sprites", Photo: []PhotoSize{{FileID: "bot-photo", FileUniqueID: "u-bot"}},
+ }
+ msg, ok := inboundFromUpdate(Update{UpdateID: 1, Message: &Message{
+ MessageID: 7, From: ada, Chat: Chat{ID: 555, Type: "private"},
+ Text: "which one is this?", ReplyToMessage: botPhoto,
+ }}, 999, "my_bot")
+ if !ok || !msg.HasSelectedContext || msg.CommandText != "which one is this?" {
+ t.Fatalf("message = %+v", msg)
+ }
+ want := "<quoted_message message_id=\"555:3\" sender=\"Team Bot\" type=\"image\">\n[Image]\nsprites\n</quoted_message>\n\nwhich one is this?"
+ if msg.Text != want {
+ t.Fatalf("Text =\n%s\nwant\n%s", msg.Text, want)
+ }
+ raw, _ := decodeTelegramRaw(msg)
+ if len(raw.Media) != 1 || raw.Media[0].FileID != "bot-photo" || raw.Media[0].Placeholder != "[Image]" || raw.Media[0].PlaceholderIndex != 0 {
+ t.Fatalf("media = %+v, want the quoted photo at occurrence 0", raw.Media)
+ }
+
+ msg, ok = inboundFromUpdate(Update{UpdateID: 2, Message: &Message{
+ MessageID: 8, From: ada, Chat: Chat{ID: 555, Type: "private"},
+ Text: "expand on that", ReplyToMessage: &Message{MessageID: 4, From: &User{ID: 999, IsBot: true}, Text: "earlier answer"},
+ }}, 999, "my_bot")
+ if !ok || msg.HasSelectedContext || msg.Text != "expand on that" {
+ t.Fatalf("message = %+v", msg)
+ }
+ if raw, _ := decodeTelegramRaw(msg); len(raw.Media) != 0 {
+ t.Fatalf("media = %+v, want none", raw.Media)
+ }
+
+ msg, ok = inboundFromUpdate(groupUpdate(9, ada, "which one is this?", &Message{
+ MessageID: 5, From: &User{ID: 222, FirstName: "Carol"}, Photo: []PhotoSize{{FileID: "carol-photo"}},
+ }, 0), 999, "my_bot")
+ if !ok || msg.AddressedToBot || msg.HasSelectedContext || msg.Text != "which one is this?" {
+ t.Fatalf("message = %+v", msg)
+ }
+ if raw, _ := decodeTelegramRaw(msg); len(raw.Media) != 0 {
+ t.Fatalf("media = %+v, want none for unaddressed chatter", raw.Media)
+ }
+}
+
+// A group member replies to another member's video with a photo of their
+// own: both files are carried, the quoted one first, and each marker's
+// occurrence skips the literals ahead of it — a member who typed "[Video]"
+// in the window must not receive the quoted video. The quoted video is
+// buffered like any group message but stays out of the window, since the
+// quote already renders it.
+func TestInboundReplyWithFileToFileCarriesBoth(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),
+ }
+ ctx := context.Background()
+ if err := c.dispatch(ctx, groupUpdate(1, &User{ID: 111, FirstName: "Ada"}, "the [Video] tag broke the page", nil, 0)); err != nil {
+ t.Fatal(err)
+ }
+ video := groupUpdate(2, &User{ID: 222, FirstName: "Carol"}, "", nil, 0)
+ video.Message.Video = &FileRef{FileID: "v1", FileUniqueID: "u-v1", MimeType: "video/mp4"}
+ if err := c.dispatch(ctx, video); err != nil {
+ t.Fatal(err)
+ }
+ reply := groupUpdate(3, &User{ID: 333, FirstName: "Bob"}, "", video.Message, 0)
+ reply.Message.Caption = "@my_bot is my witch as cute as hers?"
+ reply.Message.CaptionEntities = []MessageEntity{{Type: "mention", Offset: 0, Length: 7}}
+ reply.Message.Photo = []PhotoSize{{FileID: "p1", FileUniqueID: "u-p1"}}
+ if err := c.dispatch(ctx, reply); err != nil {
+ t.Fatal(err)
+ }
+ if len(handled) != 2 || !handled[1].AddressedToBot || !handled[1].HasSelectedContext {
+ t.Fatalf("handler calls = %+v", handled)
+ }
+ msg := handled[1]
+ want := "<recent_context count=\"1\">\n[Ada]: the [Video] tag broke the page\n</recent_context>\n\n" +
+ "<quoted_message message_id=\"-100200:2\" sender=\"Carol\" type=\"video\">\n[Video]\n</quoted_message>\n\n" +
+ "[Image]\nis my witch as cute as hers?"
+ if msg.Text != want {
+ t.Fatalf("Text =\n%s\nwant\n%s", msg.Text, want)
+ }
+ raw, _ := decodeTelegramRaw(msg)
+ if len(raw.Media) != 2 {
+ t.Fatalf("media = %+v, want the quoted video then the sender's photo", raw.Media)
+ }
+ if quoted := raw.Media[0]; quoted.FileID != "v1" || quoted.Placeholder != "[Video]" || quoted.PlaceholderIndex != 1 {
+ t.Fatalf("quoted media = %+v, want v1 at occurrence 1 (Ada's literal is occurrence 0)", quoted)
+ }
+ if own := raw.Media[1]; own.FileID != "p1" || own.Placeholder != "[Image]" || own.PlaceholderIndex != 0 {
+ t.Fatalf("own media = %+v, want p1 at occurrence 0", own)
+ }
+}
+
func TestDispatchForwardsPhotoToEngine(t *testing.T) {
var handled []channel.InboundMessage
c := &telegramChannel{
@@ -326,7 +432,7 @@ func (f *fakeBotFiles) serve(w http.ResponseWriter, r *http.Request) {
}
}
-func mediaResolverFixture(t *testing.T, media *inboundMedia) (engine.ResolvedInstallation, pgtype.UUID, channel.InboundMessage) {
+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
@@ -335,16 +441,19 @@ func mediaResolverFixture(t *testing.T, media *inboundMedia) (engine.ResolvedIns
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
+ if len(media) > 0 {
+ text = ""
+ for _, m := range media {
+ text += m.Placeholder + "\n"
+ }
}
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)
+ _, _, with := mediaResolverFixture(t, inboundMedia{Kind: channel.MsgTypeImage, FileID: "p", Placeholder: "[Image]"})
+ _, _, without := mediaResolverFixture(t)
if !r.HasMedia(with) || r.HasMedia(without) {
t.Fatalf("HasMedia with=%v without=%v", r.HasMedia(with), r.HasMedia(without))
}
@@ -357,7 +466,7 @@ func TestMediaResolverIngestsPhoto(t *testing.T) {
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})
+ 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 {
@@ -391,7 +500,7 @@ func TestMediaResolverKeepsSenderFilenameWithoutDeclaredType(t *testing.T) {
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]"})
+ 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 {
@@ -422,13 +531,13 @@ func TestMediaResolverRefusesFailuresWithoutTouchingStorage(t *testing.T) {
defer srv.Close()
for _, tc := range []struct {
name string
- media *inboundMedia
+ 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},
+ {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")}
@@ -453,6 +562,56 @@ func TestMediaResolverRefusesFailuresWithoutTouchingStorage(t *testing.T) {
}
}
+// Both files a reply names are carried across, under distinct keys even when
+// the reply quotes the very file it sends (the same file_unique_id twice).
+func TestMediaResolverIngestsQuotedAndOwnFiles(t *testing.T) {
+ jpeg := []byte("\xff\xd8\xff\xe0fake-jpeg")
+ bot := &fakeBotFiles{files: map[string]fakeBotFile{
+ "quoted": {path: "photos/quoted.jpg", data: jpeg},
+ "own": {path: "photos/own.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: "quoted", FileUniqueID: "same", MimeType: "image/jpeg", Placeholder: "[Image]", PlaceholderIndex: 0},
+ inboundMedia{Kind: channel.MsgTypeImage, FileID: "own", FileUniqueID: "same", MimeType: "image/jpeg", Placeholder: "[Image]", PlaceholderIndex: 1},
+ )
+
+ got := r.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 2 || got.MediaRefs[0].InlineIndex != 0 || got.MediaRefs[1].InlineIndex != 1 {
+ t.Fatalf("media refs = %+v", got.MediaRefs)
+ }
+ if got.MediaRefs[0].StorageKey == got.MediaRefs[1].StorageKey {
+ t.Fatalf("both files share key %q", got.MediaRefs[0].StorageKey)
+ }
+ if len(store.objects) != 2 || len(ledger.records) != 2 || bot.getFileCalls != 2 || len(bot.notices) != 0 {
+ t.Fatalf("uploads=%d ledger=%d getFile=%d notices=%+v", len(store.objects), len(ledger.records), bot.getFileCalls, bot.notices)
+ }
+}
+
+// One file failing does not cost the other: the refs that fetched are kept
+// with their own occurrence indexes, and the sender is told once.
+func TestMediaResolverKeepsTheFilesThatFetchedAndNotifiesOnce(t *testing.T) {
+ bot := &fakeBotFiles{files: map[string]fakeBotFile{"own": {path: "photos/own.jpg", data: []byte("x")}}}
+ srv := httptest.NewServer(http.HandlerFunc(bot.serve))
+ defer srv.Close()
+ r := NewMediaResolver(nil, newFakeObjectStore(nil), &fakeMediaLedger{}, srv.URL, srv.Client(), testLogger())
+ inst, chatMessageID, msg := mediaResolverFixture(t,
+ inboundMedia{Kind: channel.MsgTypeVideo, FileID: "missing", Placeholder: "[Video]", PlaceholderIndex: 0},
+ inboundMedia{Kind: channel.MsgTypeImage, FileID: "own", Placeholder: "[Image]", PlaceholderIndex: 0},
+ )
+
+ got := r.ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{}, pgtype.UUID{}, chatMessageID, msg)
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].InlinePlaceholder != "[Image]" || got.MediaRefs[0].InlineIndex != 0 {
+ t.Fatalf("media refs = %+v, want only the photo", got.MediaRefs)
+ }
+ if len(bot.notices) != 1 || bot.notices[0].Text != msgMediaUnavailable {
+ t.Fatalf("notices = %+v, want exactly one", bot.notices)
+ }
+}
+
// ---- multipart client ----
type multipartRecord struct {
diff --git a/server/internal/integrations/telegram/recent_context.go b/server/internal/integrations/telegram/recent_context.go
index 598eac2b82..c8a8bea4b5 100644
--- a/server/internal/integrations/telegram/recent_context.go
+++ b/server/internal/integrations/telegram/recent_context.go
@@ -158,8 +158,9 @@ func (b *recentContextBuffer) evictOldestLocked() {
}
// recentEntryFromMessage renders one Telegram message the way a group member
-// saw it: raw text or caption (bot mentions included), or a typed placeholder
-// for media without a caption. Never called for bot senders — the polling
+// saw it: raw text or caption (bot mentions included), a file's placeholder
+// above its caption as in the sender's own turn, or a typed placeholder for
+// anything else without text. Never called for bot senders — the polling
// loop drops those before recording, and the bot's own replies never arrive
// through getUpdates anyway.
func recentEntryFromMessage(m *Message) recentEntry {
@@ -167,7 +168,9 @@ func recentEntryFromMessage(m *Message) recentEntry {
if text == "" {
text = m.Caption
}
- if strings.TrimSpace(text) == "" {
+ if media := mediaFromMessage(m); media != nil {
+ text = leadWithPlaceholder(media.Placeholder, text)
+ } else if strings.TrimSpace(text) == "" {
text = fmt.Sprintf("[%s message]", classifyMessage(m))
}
sender := "Unknown user"
diff --git a/server/internal/integrations/telegram/recent_context_test.go b/server/internal/integrations/telegram/recent_context_test.go
index 14f78b55b0..f50134f989 100644
--- a/server/internal/integrations/telegram/recent_context_test.go
+++ b/server/internal/integrations/telegram/recent_context_test.go
@@ -89,12 +89,16 @@ func TestRecentContextBufferTruncatesLongMessages(t *testing.T) {
func TestRecentEntryFromMessageRendersMediaPlaceholder(t *testing.T) {
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)
+ if e.Sender != "Ada" || e.Text != "[Image]" {
+ t.Fatalf("media without caption should render its placeholder, got %+v", e)
}
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)
+ if e.Sender != "Unknown user" || e.Text != "[Image]\nsee this" {
+ t.Fatalf("the placeholder should lead the caption and a missing sender should fall back, got %+v", e)
+ }
+ e = recentEntryFromMessage(&Message{MessageID: 6, From: &User{ID: 1, FirstName: "Ada"}, Sticker: &struct{}{}})
+ if e.Text != "[unknown message]" {
+ t.Fatalf("a kind without a file should keep the typed placeholder, got %+v", e)
}
}
@@ -223,7 +227,7 @@ func TestDispatchBuffersGroupMessagesForLaterMentions(t *testing.T) {
if len(seen) != 2 || seen[0].AddressedToBot || !seen[1].AddressedToBot {
t.Fatalf("handler calls = %+v", seen)
}
- want := "<recent_context count=\"2\">\n[Ada]: deploy is failing on staging\n[Bob]: [image message]\n</recent_context>\n\nwhat should we check first?"
+ want := "<recent_context count=\"2\">\n[Ada]: deploy is failing on staging\n[Bob]: [Image]\n</recent_context>\n\nwhat should we check first?"
if seen[1].Text != want {
t.Fatalf("mention Text =\n%s\nwant\n%s", seen[1].Text, want)
}
diff --git a/server/internal/integrations/telegram/telegram_test.go b/server/internal/integrations/telegram/telegram_test.go
index 5bcd505808..bc1b72c708 100644
--- a/server/internal/integrations/telegram/telegram_test.go
+++ b/server/internal/integrations/telegram/telegram_test.go
@@ -202,19 +202,27 @@ func TestInboundGroupHumanReplyUsesCaptionAndHandlesNonText(t *testing.T) {
name string
reply *Message
wanted string
+ file string // the quoted file carried for the resolver, if any
}{
{
name: "caption",
reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},
Caption: "diagram caption", Photo: []PhotoSize{{FileID: "p1"}},
},
- wanted: "diagram caption",
+ wanted: "[Image]\ndiagram caption",
+ file: "p1",
},
{
- name: "empty non-text",
+ name: "file without caption",
reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"},
Document: &FileRef{FileID: "d1", FileName: "notes.txt"},
},
+ wanted: "[File: notes.txt]",
+ file: "d1",
+ },
+ {
+ name: "empty non-text",
+ reply: &Message{MessageID: 9, From: &User{ID: 222, Username: "ada"}, Sticker: &struct{}{}},
wanted: "[empty or non-text message]",
},
} {
@@ -228,6 +236,14 @@ func TestInboundGroupHumanReplyUsesCaptionAndHandlesNonText(t *testing.T) {
!strings.Contains(msg.Text, "sender=\"ada\"") || !strings.Contains(msg.Text, tc.wanted) {
t.Fatalf("message = %+v", msg)
}
+ raw, _ := decodeTelegramRaw(msg)
+ file := ""
+ if len(raw.Media) == 1 {
+ file = raw.Media[0].FileID
+ }
+ if file != tc.file || len(raw.Media) > 1 {
+ t.Fatalf("media = %+v, want quoted file %q", raw.Media, tc.file)
+ }
})
}
}