Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Inbound files from Feishu and Telegram, as composer attachments (#513)

Yaowei Zhengcb21222e3e23
diff --git a/changelog/unreleased/2026-08-27-messaging-inbound-files.md b/changelog/unreleased/2026-08-27-messaging-inbound-files.md
new file mode 100644
index 00000000..5ad61b43
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-inbound-files.md
@@ -0,0 +1,37 @@
+# Files into the chat, as composer attachments
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`, `docs`
+- **PR:** [#513](https://github.com/Prism-Shadow/penguin-harness/pull/513)
+
+[中文版](2026-08-27-messaging-inbound-files.zh.md)
+
+A document sent to the bot on Feishu or Telegram now reaches the Agent instead of the "not supported" notice. It arrives as the web composer's own file attachment — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line — over the same connector seam the inbound images landed on, so a third channel implements it the same way.
+
+## Inbound files
+
+- The connector seam gained `MessagingInboundMessage.files`: lazily-fetched handles carrying the sender's file name, alongside the image handles and for the same two reasons — a redelivered message is dropped before anything is downloaded, and the cap rides into the fetch, so an oversized attachment is refused at the byte that crosses it instead of being buffered and measured afterwards. It is optional, so a channel that delivers no files never populates it.
+- A file goes down the composer's attachment path, not the conversation: `attachFilesToInput` writes it into `<agent>/scratchpad/<sessionId>/` under a name sanitized for the filesystem, and the message text gains one `[attached file: <absolute path>]` line per file, which the model opens with its ordinary file tools. Nothing scales with the file's size downstream, which is what makes the far larger ceiling reasonable.
+- The caps are the server's own attachment limits — the admin-settable per-file cap (100MB by default) and the per-message total (120MB) an authenticated composer upload answers to — read fresh per message rather than snapshotted, and narrowed further by any tighter ceiling the channel itself has. Each later file of one message is capped at what is left of the message's total, so a batch cannot add up past it.
+- There is no rolling per-binding budget like the image one: the cost that budget exists to prevent is not paid here. An inline image is written into the Trace and re-read whole on every history page and every resume; a file is bytes on disk that nothing re-reads and that are deleted with the Session.
+- A file over a cap, a batch over the per-message total, a permission the bot lacks and a transfer that failed answer with **four different** bilingual notices, each naming the file. None of them starts a Task — a model asked about a document it never received answers confidently about nothing — and none of them leaves a half-written batch behind in the scratchpad. A refusal for size is nobody's fault and stays out of the error log; a failure is recorded under `messaging_file_fetch_failed` with the channel's own reason, classified the way the inbound image download already is — a scope the app was never granted is `expected`, because the chat has already been handed the fix, and only what nobody was told about counts as a defect.
+- A size refusal names the ceiling that actually bit, which is not always the one the server asked for: `MessagingMediaTooLargeError` now carries its `maxBytes`, so a channel that narrows the transfer reports its own number rather than sending the sender to shrink a file against a limit that was never in the way.
+- A caption is the message's text, exactly as a photo's already was, so text, images and files compose one input. The caption of a message whose attachment is NOT delivered still normalizes to null.
+- A message that arrives while the Session is busy is queued as a follow-up, and withdrawing that follow-up in the Web App now hands its files back as attachment chips and deletes the scratchpad copies. The queued line counts them too. Only the writer knows where the bytes landed, so the inbound path supplies its own recall store rather than leaving one to be derived from the input — derived, the recalled text came back carrying a raw `[attached file: <path>]` line and the file stayed on disk.
+
+## Feishu
+
+- The `file` message type, downloaded through `im.v1.messageResource.get` with `type: "file"` — the same resource endpoint the images use, differing only in that query parameter, and permissioned by the same scope, so an app refused an image is refused a file by the same `99991672` denial and gets the same notice naming the scopes and the console link to grant them.
+- The event names the file, so the sender's own name reaches the model. An event carrying none gets the placeholder `file` rather than an invented extension.
+- `audio` (a voice recording) and `media` (a video) carry a `file_key` too and are deliberately left out: they are re-encoded for playback and named by nothing the sender chose, and nothing downstream decodes or transcribes them. Both keep the not-supported notice.
+
+## Telegram
+
+- The `document` field — a file the sender chose to send AS a file, and the only one of the Bot API's media fields that carries the sender's own name. A picture dragged in uncompressed is a `document` too and now arrives as an attachment, which is what the sender asked for by sending the original bytes.
+- `audio`, `video`, `voice` and `video_note` are out of scope for the same reason Feishu's are, and say so rather than faking it. A `voice` is a nameless opus blob; handing one over as an `[attached file: …]` path would offer a capability that is not there.
+- Transfers are capped at Telegram's own 20MB bot download ceiling (`TELEGRAM_MAX_DOWNLOAD_BYTES`) rather than left to the Bot API to refuse. Past it `getFile` answers a 400 whose only signal is prose Telegram is free to reword, so a size the sender can act on would have reached them as an unexplained download failure.
+
+## Notices
+
+- The not-supported notice names what is supported, so it now reads "Only text, image and file messages are supported for now." Its constant is `MESSAGING_UNSUPPORTED_NOTICE`.
diff --git a/changelog/unreleased/2026-08-27-messaging-inbound-files.zh.md b/changelog/unreleased/2026-08-27-messaging-inbound-files.zh.md
new file mode 100644
index 00000000..f98c9cd3
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-inbound-files.zh.md
@@ -0,0 +1,37 @@
+# 文件可以发进来,作为输入框附件
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`, `docs`
+- **PR:** [#513](https://github.com/Prism-Shadow/penguin-harness/pull/513)
+
+[English](2026-08-27-messaging-inbound-files.md)
+
+在飞书或 Telegram 里发给机器人的文件现在会真正送达智能体,而不再只收到「暂不支持」提示。它以网页输入框自己的文件附件形态到达——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型——走的是入站图片所用的同一条连接器接缝,第三个渠道按同样的方式实现即可。
+
+## 入站文件
+
+- 连接器接缝新增 `MessagingInboundMessage.files`:与图片句柄并列的延迟拉取句柄,携带发送者的原始文件名,理由与图片那一侧完全相同——被重复投递的消息在任何下载发生之前就被丢弃;上限随拉取一起传入,超限的附件在越界的那个字节上就被拒绝,而不是先缓冲下来再测量。该字段是可选的,不投递文件的渠道根本不必填写。
+- 文件走的是输入框的附件路径,而不是对话:`attachFilesToInput` 把它写进 `<agent>/scratchpad/<sessionId>/`,文件名经过面向文件系统的净化,消息文本则每个文件追加一行 `[attached file: <绝对路径>]`,由模型用它常规的文件工具打开。下游没有任何环节随文件大小增长,这正是那个大得多的上限得以成立的前提。
+- 上限沿用服务端自己的附件限制——管理员可设的单个文件上限(默认 100MB)与单条消息总量上限(120MB),与经过鉴权的输入框上传是同一组数值——按消息逐次读取而非启动时快照,并再取渠道自身更紧的那个上限。同一条消息中后面的文件,其上限收敛为该消息总量的剩余部分,因此一批文件也无法累加越界。
+- 这里没有图片那样的「每绑定滚动窗口预算」:该预算所要防的代价在这条路径上并不存在。内联图片会写入 Trace,并在每次翻阅历史、每次恢复 Session 时被整体读回;文件只是磁盘上的字节,没有任何环节会重读,且随 Session 一同删除。
+- 文件超过单个上限、一批文件超过单条消息总量、机器人缺少权限、传输失败,分别回复**四种不同的**双语提示,每一种都点名具体文件。四种情况都不启动 Task——让模型去回答一份它根本没收到的文档,只会得到一本正经的胡说——也都不会在 Scratchpad 里留下写了一半的批次。因大小被拒不是任何人的过错,不进错误日志;传输失败则以 `messaging_file_fetch_failed` 记录,并带上渠道自己的原因,其归类与入站图片下载一致——应用从未获授的权限记为 `expected`,因为修复方式已经交到会话里了;只有没人被告知的失败才算缺陷。
+- 因大小被拒时,提示点名的是**真正拦下它的那个上限**,未必是服务端请求的那一个:`MessagingMediaTooLargeError` 现在携带 `maxBytes`,于是收紧了传输上限的渠道报出的是自己的数值,而不是把发送者打发去对着一个根本不挡路的限制压缩文件。
+- 说明文字即该消息的文本(图片消息本来就是如此),因此文本、图片与文件可以组成同一份输入。附件**不会**被送达的那些消息,其说明文字仍然归一化为 null。
+- Session 正忙时到达的消息会作为后续任务排队,而在网页端撤回该后续任务时,其文件现在会作为附件回到输入框,Scratchpad 中的副本随之删除,排队条目上的文件计数也如实显示。字节落在哪里只有写入方知道,因此入站路径自带撤回内容,而不是交由输入去推导——推导出来的文本会把 `[attached file: <路径>]` 原样交还给输入框,文件也会滞留在磁盘上。
+
+## 飞书
+
+- 支持 `file` 消息类型,经 `im.v1.messageResource.get` 以 `type: "file"` 下载——与图片同一个资源端点,差别仅在这个查询参数,权限也是同一项:被拒绝下载图片的应用会被同一个 `99991672` 拒绝下载文件,并得到同样点名权限与授权链接的提示。
+- 事件本身携带文件名,因此发送者原始的名字直达模型。事件未携带文件名时使用占位名 `file`,而不是编造一个扩展名。
+- `audio`(语音)与 `media`(视频)同样带有 `file_key`,但有意不纳入:它们为播放而被重新编码,名字并非发送者所选,且下游没有任何环节能解码或转写。两者仍收到「暂不支持」提示。
+
+## Telegram
+
+- 支持 `document` 字段——发送者主动**以文件形式**发出的那一个,也是 Bot API 各媒体字段中唯一携带发送者原始文件名的。以「原图」拖入的图片同样是 `document`,现在会作为附件到达,而这正是发送者以原始字节发送时所要的。
+- `audio`、`video`、`voice` 与 `video_note` 出于与飞书同样的理由不在范围内,并如实说明而非假装支持。`voice` 是一段无名的 opus 数据;把它以 `[attached file: …]` 路径交出去,等于承诺一项并不存在的能力。
+- 传输上限取 Telegram 自身对机器人的 20MB 下载上限(`TELEGRAM_MAX_DOWNLOAD_BYTES`),而不是交由 Bot API 去拒绝。超过之后 `getFile` 回的是一个 400,其唯一信号是 Telegram 随时可改写的散文,于是一件发送者本可处理的「文件太大」,会以「下载莫名失败」的面目抵达他们。
+
+## 提示语
+
+- 「暂不支持」提示改为点明现在支持什么,因此改为「目前仅支持文本、图片和文件消息。」,其常量名为 `MESSAGING_UNSUPPORTED_NOTICE`。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 3fbd8e27..4bd25e08 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -337,7 +337,7 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th
| POST | /messaging/qq/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its key is forgotten now rather than at the sweep |
| POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |
-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` and `finalReplyOnly` are the two saved fields that are not credentials. With `linePerMessage` set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs. Inbound processing accepts text and images: an image becomes an ordinary `image_url` input part (a PHOTO's caption is that message's text; a caption on any other media kind is not, since its bytes are never delivered and running the model on the caption alone answers about a file it never received), capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, and none of them runs half a message; a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` and `finalReplyOnly` are the two saved fields that are not credentials. With `linePerMessage` set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs. Inbound processing accepts text, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20. `finalReplyOnly` cuts both ways here: it spends the least budget a run can spend — one reply — but the passive-reply window is only a few minutes wide, and holding the reply until the run ends spends that window on the run, so a run that outlives it delivers nothing at all where an every-message relay would have sent whatever completed inside it. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index a0d3c99d..7dd85401 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -336,7 +336,7 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr
| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 |
| POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |
-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 与 `finalReplyOnly` 是仅有的两个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本与图片:图片按普通 `image_url` 输入部分送入(**图片**消息的说明文字即该消息的文本;其他媒体类型的说明文字不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈),单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示,且都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 与 `finalReplyOnly` 是仅有的两个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 5db8dc60..0e7e2f8c 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -23,7 +23,7 @@ import path from "node:path";
import { Hono } from "hono";
import type { Context, MiddlewareHandler } from "hono";
import { bodyLimit } from "hono/body-limit";
-import { bodyLimitBytes } from "./services/attachment-limits.js";
+import { bodyLimitBytes, toAttachmentLimits } from "./services/attachment-limits.js";
import type { DatabaseSync } from "node:sqlite";
import type { ServerConfig } from "./config.js";
import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";
@@ -847,6 +847,10 @@ export function buildAppDeps(
// The same service the Files panel reads through: mirroring a file the reply mentions
// must obey exactly the containment rules browsing it does, not a second copy of them.
files: workspaceFiles,
+ root: config.root,
+ // Read through per message, not snapshotted: these are admin-settable, and every other
+ // caller resolves them per request so a change applies without a restart.
+ attachmentLimits: () => toAttachmentLimits(serverSettingsRepo.getAttachmentLimitsMb()),
channels,
runner: manager,
connectors: [
diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.ts
index 519666c4..1f0fa3e1 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -21,10 +21,15 @@
* follow-up, never 409. A message carrying images becomes that same composer input with
* the pictures attached: the caption's text (when there is one) plus one `image_url` part
* per image, as a base64 `data:` URL, which is byte for byte the shape the web composer
- * submits. Anything else (sticker, voice, video, file) gets a polite bilingual "not
- * supported" reply. Only once that work is done is the binding row's watermark advanced,
- * so a process that dies mid-message has the channel replay it rather than find it already
- * marked.
+ * submits. A message carrying FILES becomes the composer's other attachment shape: each
+ * one is written into the Session scratchpad and named on the message text as an
+ * `[attached file: <path>]` line, so the model opens it with its ordinary file tools and
+ * the bytes never enter the conversation (see services/task-attachments.ts, which owns
+ * that path and its caps for the web composer too). The three combine — text, images and
+ * files in one message compose one input — and a message with none of them (sticker,
+ * voice, video) gets a polite bilingual "not supported" reply. Only once that work is done
+ * is the binding row's watermark advanced, so a process that dies mid-message has the
+ * channel replay it rather than find it already marked.
*
* Outbound (Session → channel): the bridge subscribes to the Session's in-process channel
* and relays the main conversation's completed assistant messages — by default each of them
@@ -60,7 +65,7 @@
* is a bad place to receive a directory. What the caps drop is named in the chat rather
* than dropped quietly.
*/
-import { imageUrlMessage, userText } from "@prismshadow/penguin-core";
+import { imageUrlMessage, scratchpadDir, userText } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
import type { MessagingDeliveryError, MessagingRuntimeStatus } from "../../api/types.js";
import type {
@@ -68,11 +73,17 @@ import type {
MessagingBindingsRepo,
} from "../../db/repos/messaging-bindings.js";
import { INLINE_IMAGE_MAX_BYTES } from "../../services/attachment-limits.js";
+import type { AttachmentLimits } from "../../services/attachment-limits.js";
+import { attachFilesToInput, removeAttachments } from "../../services/task-attachments.js";
+import type { AttachedFiles, TaskAttachment } from "../../services/task-attachments.js";
import type { ChannelEvent, ChannelHub } from "../channel.js";
import type { ErrorSink } from "../error-recorder.js";
+import { recallStoreOf } from "../session-manager.js";
+import type { RecallStore } from "../session-manager.js";
import type {
MessagingChannelConnector,
MessagingClient,
+ MessagingInboundFile,
MessagingInboundImage,
MessagingInboundMessage,
MessagingSendNote,
@@ -127,8 +138,8 @@ export const MESSAGING_LINE_DELAY_MS = 1000;
// The fixed outbound notices are user-facing chat content, deliberately bilingual
// like the rest of the product's user-facing copy (the server has no locale for an
// external chat, so both languages ride each notice).
-export const MESSAGING_TEXT_ONLY_NOTICE =
- "Only text and image messages are supported for now. 目前仅支持文本和图片消息。";
+export const MESSAGING_UNSUPPORTED_NOTICE =
+ "Only text, image and file messages are supported for now. 目前仅支持文本、图片和文件消息。";
/**
* The two ways an inbound image does not arrive, deliberately worded as two notices.
*
@@ -200,6 +211,51 @@ export function messagingImageFailedNotice(reason: string): string {
export function messagingImageBudgetNotice(): string {
return "Too many images from this chat just now, so this one was not sent to the Agent. Try again in a few minutes. 该会话短时间内发来的图片过多,本张未发送给智能体,请过几分钟再试。";
}
+
+/**
+ * The four ways an inbound FILE does not arrive, deliberately worded as four notices, for
+ * the reason the image pair above states: a message that names two causes names neither.
+ * They are their own functions rather than the image ones reused because a file has a NAME
+ * — a message can carry several, and "that file" would leave the user guessing which — and
+ * because "try a smaller picture" is not advice about a spreadsheet.
+ *
+ * `maxBytes` is the ceiling that actually refused the transfer (see
+ * MessagingMediaTooLargeError.maxBytes), not the server's per-file cap: a channel with a
+ * tighter download limit of its own is the one the user has to fit under.
+ */
+export function messagingInboundFileTooLargeNotice(fileName: string, maxBytes: number): string {
+ const mb = Math.floor(maxBytes / (1024 * 1024));
+ return `"${fileName}" is larger than the ${mb}MB limit, so it was not sent to the Agent. 文件“${fileName}”超过 ${mb}MB 上限,未发送给智能体。`;
+}
+
+/**
+ * The files of one message together past the per-message total. Its own notice rather than
+ * the per-file one because no single file is at fault, so naming one would send the user to
+ * shrink a file that was never too big — what has to go is one of the others.
+ */
+export function messagingInboundFilesTooLargeNotice(totalBytes: number): string {
+ const mb = Math.floor(totalBytes / (1024 * 1024));
+ return `The files in that message add up to more than the ${mb}MB one message may carry, so none of them was sent to the Agent. 该消息中的文件总大小超过单条消息 ${mb}MB 的上限,均未发送给智能体。`;
+}
+
+/**
+ * An inbound file this bot's app is not permitted to download — the same ten-second fix the
+ * image version describes, and on Feishu the same scope: receiving a message and reading the
+ * resources in it are separate permissions.
+ */
+export function messagingInboundFilePermissionNotice(
+ fileName: string,
+ scopes: readonly string[],
+ grantUrl: string | null,
+): string {
+ return `"${fileName}" could not be downloaded: this bot's app is missing a permission. Grant it, then send the file again. 无法下载文件“${fileName}”:机器人应用缺少所需权限,开通后重新发送即可。\n${permissionDetail(scopes, grantUrl)}`;
+}
+
+/** A file the channel would not hand over, carrying the channel's OWN reason (see the image version). */
+export function messagingInboundFileFailedNotice(fileName: string, reason: string): string {
+ return `"${fileName}" could not be downloaded from the chat, so nothing was sent to the Agent. 无法从会话中下载文件“${fileName}”,未发送给智能体。(${noticeReason(reason)})`;
+}
+
export const MESSAGING_APPROVAL_NOTICE =
"A tool call is waiting for your approval in the PenguinHarness web UI. 有工具调用正在等待你在网页端审批。";
export const MESSAGING_TEST_MESSAGE =
@@ -452,13 +508,45 @@ function inboundKey(sessionId: string, channel: string): string {
return `${sessionId}:${channel}`;
}
+/**
+ * The recall store of an inbound message that wrote file attachments — what the Web App
+ * hands back to the composer when the user withdraws the follow-up it was queued as.
+ *
+ * `input` is the message BEFORE the `[attached file: …]` lines were folded into it, so the
+ * text and images come back the way they were sent; `written` is where the bytes actually
+ * landed, which is the half no derivation from the input can recover. Without it a
+ * withdrawn message loses its files silently, its text comes back carrying a raw scratchpad
+ * path, and the on-disk copies stay behind — the recall route deletes exactly the files
+ * this store names.
+ */
+function inboundRecallStore(
+ input: OmniMessage[],
+ attachments: readonly TaskAttachment[],
+ written: readonly string[],
+): RecallStore {
+ return {
+ ...recallStoreOf(input),
+ files: written.map((filePath, i) => ({
+ fileName: attachments[i]!.fileName,
+ path: filePath,
+ mime: attachments[i]!.mime,
+ })),
+ };
+}
+
/** Minimal dependency on SessionManager (eases test doubles; mirrors ScheduleTaskRunner). */
export interface MessagingTaskRunner {
statusOf(sessionId: string): string;
startTask(
sessionId: string,
input: OmniMessage[],
- opts: { queueIfBusy: boolean },
+ /**
+ * `recall` is what a queued follow-up hands back when the user withdraws it in the Web
+ * App. It is optional because the manager derives one from the input for every caller
+ * that has nothing to add; the inbound path supplies its own only when it wrote file
+ * attachments, whose on-disk paths the input does not carry (see inboundRecallStore).
+ */
+ opts: { queueIfBusy: boolean; recall?: RecallStore },
): Promise<{ sessionId: string; queued: boolean }>;
}
@@ -500,6 +588,19 @@ export interface MessagingBridgeDeps {
repo: MessagingBindingsRepo;
sessions: MessagingSessionIndex;
files: MessagingWorkspaceFiles;
+ /**
+ * The data root, so an inbound file can be written into the Session scratchpad the web
+ * composer's uploads land in (`scratchpadDir(root, projectId, agentId)/<sessionId>`,
+ * deleted with the Session). The bridge holds the root rather than a pre-resolved
+ * directory because the Project and Agent are per Session, not per binding.
+ */
+ root: string;
+ /**
+ * The attachment limits in force right now. A function, not a snapshot: the per-file and
+ * per-message ceilings are admin-settable and read fresh per request everywhere else, so
+ * a change has to reach the next inbound message without a restart.
+ */
+ attachmentLimits: () => AttachmentLimits;
channels: ChannelHub;
runner: MessagingTaskRunner;
/** One connector per channel; a stored binding whose channel has no connector is skipped with an error record. */
@@ -1009,12 +1110,13 @@ export class MessagingBridge {
// off the row.
this.deps.repo.recordChat(entry.sessionId, entry.channel, msg.chatId, isDirect);
entry.lastInboundMessageId = isDirect ? null : msg.messageId;
- // A caption is this message's text; an image with none carries no text at all.
+ // A caption is this message's text; an attachment sent with none carries no text at all.
const text = msg.text !== null && msg.text.trim() !== "" ? msg.text : null;
const images = msg.images ?? [];
- if (images.length === 0) {
+ const files = msg.files ?? [];
+ if (images.length === 0 && files.length === 0) {
if (text === null) {
- await this.replyInbound(entry, msg, MESSAGING_TEXT_ONLY_NOTICE);
+ await this.replyInbound(entry, msg, MESSAGING_UNSUPPORTED_NOTICE);
} else {
// An ordinary user input, exactly as if typed into the web composer: no marker
// block, no special sender — the model deliberately does not learn the message
@@ -1024,21 +1126,11 @@ export class MessagingBridge {
});
}
} else {
- const result = await this.inboundImageParts(entry, images);
- if ("notice" in result) {
- // The whole message stops here rather than running on the caption alone: a model
- // asked "what is wrong with this?" about a picture it never received answers
- // confidently about nothing, which is worse than a notice saying so.
- await this.replyInbound(entry, msg, result.notice);
- } else {
- // Text first, then the images — the same order and the same parts the web composer
- // submits, so a chat message with a picture is indistinguishable from a pasted one.
- await this.deps.runner.startTask(
- entry.sessionId,
- [...(text === null ? [] : [userText(text)]), ...result.parts],
- { queueIfBusy: true },
- );
- }
+ const notice = await this.startAttachedTask(entry, text, images, files);
+ // The whole message stops on a notice rather than running on the caption alone: a
+ // model asked "what is wrong with this?" about a picture it never received answers
+ // confidently about nothing, which is worse than a notice saying so.
+ if (notice !== null) await this.replyInbound(entry, msg, notice);
}
// The durable watermark goes LAST, and its own UPDATE is the price of that. What it
// marks is a message this process finished with: the follow-up a busy Session queues
@@ -1059,16 +1151,169 @@ export class MessagingBridge {
}
}
+ /**
+ * Turns a message carrying attachments into one Task, or resolves the notice to answer
+ * the chat with when it could not be made whole.
+ *
+ * All-or-nothing across BOTH kinds, and in this order: the images are downloaded first,
+ * then the files, and only then is anything written to disk. A refusal on either side
+ * stops the message — a message is one thing the user sent, and half of it reaching the
+ * Agent is not a partial success but a misleading one — and refusing before the write
+ * means a rejected message leaves nothing behind in the scratchpad to clean up.
+ */
+ private async startAttachedTask(
+ entry: BridgeEntry,
+ text: string | null,
+ images: readonly MessagingInboundImage[],
+ files: readonly MessagingInboundFile[],
+ ): Promise<string | null> {
+ const parts = await this.inboundImageParts(entry, images);
+ if ("notice" in parts) return parts.notice;
+ const attachments = await this.inboundFileAttachments(entry, files);
+ if ("notice" in attachments) return attachments.notice;
+ // Text first, then the images — the same order and the same parts the web composer
+ // submits, so a chat message with a picture is indistinguishable from a pasted one. The
+ // files' `[attached file: …]` lines are appended by core's shared placement rule, which
+ // puts them after the last user text message exactly as a composer upload's are.
+ const input = [...(text === null ? [] : [userText(text)]), ...parts.parts];
+ const { input: withFiles, written } = await this.writeInboundFiles(
+ entry,
+ input,
+ attachments.attachments,
+ );
+ try {
+ await this.deps.runner.startTask(entry.sessionId, withFiles, {
+ queueIfBusy: true,
+ // Only when files were written: for everything else the manager derives an
+ // equivalent store from the input itself, and a caller that adds nothing should not
+ // carry a second copy of that derivation.
+ ...(written.length > 0
+ ? { recall: inboundRecallStore(input, attachments.attachments, written) }
+ : {}),
+ });
+ } catch (err) {
+ // Nothing references these files and nothing will ever clean them up: the Task never
+ // started, so the message they belong to does not exist. The route path owns the same
+ // half of attachFilesToInput's all-or-nothing contract.
+ await removeAttachments(written);
+ throw err;
+ }
+ return null;
+ }
+
+ /**
+ * Lands this message's files in the Session scratchpad and folds their path lines into the
+ * input. Returns the input untouched when there are none, so a message with no files
+ * creates no directory.
+ *
+ * A failure here is NOT answered in the chat, unlike a refused download: a write that
+ * fails is a fault of this server (a full disk, a scratchpad that is not writable), the
+ * same class as a Session that cannot load, and it reaches the user through
+ * recordDeliveryFailure and the binding's status line. The chat is told about the things
+ * the person in it can act on.
+ */
+ private async writeInboundFiles(
+ entry: BridgeEntry,
+ input: OmniMessage[],
+ attachments: readonly TaskAttachment[],
+ ): Promise<AttachedFiles> {
+ if (attachments.length === 0) return { input, written: [] };
+ const row = this.deps.sessions.findById(entry.sessionId);
+ if (row === null) throw new Error(`session ${entry.sessionId} no longer exists`);
+ return attachFilesToInput(
+ input,
+ [...attachments],
+ scratchpadDir(this.deps.root, row.projectId, row.agentId),
+ entry.sessionId,
+ );
+ }
+
+ /**
+ * Downloads the message's files into composer attachments, or the notice to answer with
+ * when one of them could not be delivered.
+ *
+ * The caps are the server's attachment limits — the very numbers an authenticated
+ * composer upload answers to — because these files land in exactly the same place, the
+ * Session scratchpad, and are read back the same way, through the model's bounded file
+ * tools. Both byte budgets apply:
+ *
+ * - the per-file ceiling rides into each `fetch`, so an oversized attachment is refused at
+ * the byte that crosses it and is never resident in this process;
+ * - the per-message total is spent as the batch is collected, each later file's cap
+ * shrinking to what is left, so a message carrying several cannot add up past it either.
+ *
+ * The per-message file COUNT is deliberately not enforced: attachment-limits.ts calls it a
+ * composer-usability bound rather than a resource one, the byte budgets being what actually
+ * bound memory and disk — and a chat message carries one file today on both channels.
+ *
+ * There is no rolling per-binding budget like the image one, because the cost it exists to
+ * prevent is not paid here: an inline image is written into the Trace and re-read whole on
+ * every history page and every resume, while a file is bytes on disk that nothing re-reads
+ * and that are deleted with the Session.
+ *
+ * A refusal for size is the user's to fix and is not an error record — they sent something
+ * too big and the chat says so. A failure is somebody's fault (a scope the bot was never
+ * granted, most likely) and lands in the error log with the channel's reason, so it is
+ * diagnosable from the dashboard and not only from a chat bubble.
+ */
+ private async inboundFileAttachments(
+ entry: BridgeEntry,
+ files: readonly MessagingInboundFile[],
+ ): Promise<{ attachments: TaskAttachment[] } | { notice: string }> {
+ if (files.length === 0) return { attachments: [] };
+ const limits = this.deps.attachmentLimits();
+ const attachments: TaskAttachment[] = [];
+ let spent = 0;
+ for (const file of files) {
+ const remaining = limits.totalBytes - spent;
+ if (remaining <= 0) return { notice: messagingInboundFilesTooLargeNotice(limits.totalBytes) };
+ const cap = Math.min(limits.maxBytes, remaining);
+ try {
+ const data = await file.fetch(cap);
+ spent += data.length;
+ // `mime` is what a queued message's recall re-encodes its data URL from. A channel
+ // states a media type about a file nothing here parses, so an empty one is the honest
+ // value rather than a guess — readRecalledFiles substitutes the generic type.
+ attachments.push({ fileName: file.fileName, bytes: data, mime: "" });
+ } catch (err) {
+ const reason = err instanceof Error ? err.message : String(err);
+ this.log(`[messaging] ${entry.channel} file fetch failed: ${reason}`);
+ if (err instanceof MessagingMediaTooLargeError) {
+ // Which ceiling stopped it decides what the chat is told: one file over a per-file
+ // ceiling is that file's problem, while a batch over the message total is nobody's
+ // in particular — naming a file there would send the user to shrink one that was
+ // never too big. What decides is the ceiling the transfer REPORTS refusing at, not
+ // the one it was offered: a connector may narrow the cap further to its own
+ // platform's limit (Telegram serves a bot no file over 20MB), and that refusal is
+ // still about this one file even on a later file whose cap the message's remaining
+ // budget had already shrunk.
+ const spentTheMessage = err.maxBytes === remaining && remaining < limits.maxBytes;
+ return {
+ notice: spentTheMessage
+ ? messagingInboundFilesTooLargeNotice(limits.totalBytes)
+ : messagingInboundFileTooLargeNotice(file.fileName, err.maxBytes),
+ };
+ }
+ this.recordError(entry.sessionId, err, "messaging_file_fetch_failed");
+ return {
+ notice:
+ err instanceof MessagingPermissionError
+ ? messagingInboundFilePermissionNotice(file.fileName, err.scopes, err.grantUrl)
+ : messagingInboundFileFailedNotice(file.fileName, reason),
+ };
+ }
+ }
+ return { attachments };
+ }
+
/**
* Downloads the message's images into `image_url` input parts, or the notice to answer
* with when one of them could not be delivered.
*
- * All-or-nothing on purpose: a message is one thing the user sent, and half of it
- * reaching the Agent is not a partial success but a misleading one. The cap is the
- * server's inline-image ceiling — the same number the web composer's uploads answer to,
- * because these images land in exactly the same place (the conversation, and from there
- * the Trace, which is read back whole on every resume). It happens to match Telegram's
- * own 20MB download ceiling for bots.
+ * The cap is the server's inline-image ceiling — the same number the web composer's
+ * uploads answer to, because these images land in exactly the same place (the
+ * conversation, and from there the Trace, which is read back whole on every resume). It
+ * happens to match Telegram's own 20MB download ceiling for bots.
*
* A refusal for size is the user's to fix and is not an error record — they sent
* something too big and the chat says so. A failure is somebody's fault (a scope the bot
diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.ts
index af673939..66c9cf01 100644
--- a/packages/server/src/runtime/messaging/connector.ts
+++ b/packages/server/src/runtime/messaging/connector.ts
@@ -4,7 +4,8 @@
* and register in app assembly). A connector owns everything channel-specific — credential
* shape, wire protocol, event normalization — and hands the bridge a channel-neutral
* view: a client for outbound sends and credential checks, and a long-lived event
- * connection delivering normalized inbound messages.
+ * connection delivering normalized inbound messages (text, images and files, each as far as
+ * the channel actually carries them).
*
* Config documents are the repo's stored per-channel JSON (`MessagingBindingRow.config`);
* every connector method validates its own shape and throws a readable error on a
@@ -44,6 +45,33 @@ export interface MessagingInboundImage {
fetch(maxBytes: number): Promise<MessagingInboundImageData>;
}
+/**
+ * A non-image file attached to an inbound message: a handle, not the bytes, for exactly the
+ * reasons MessagingInboundImage is one — a redelivery is dropped before anything is
+ * transferred, and the cap rides into `fetch` so an oversized attachment is refused at the
+ * byte that crosses it rather than buffered whole and measured afterwards. A file's ceiling
+ * is the server's per-file attachment limit, which is far larger than an image's, so the
+ * difference between refusing during and after the transfer is correspondingly larger.
+ *
+ * There is no MIME type on this seam. An image needs one because its bytes become a `data:`
+ * URL inside the conversation; a file's bytes go to the Session scratchpad and reach the
+ * model as a PATH, so the name's extension is the whole of what says what it is — and a
+ * channel's declared media type is the sender's claim about a file nothing here parses.
+ */
+export interface MessagingInboundFile {
+ /**
+ * The sender's own file name, extension included — what the model sees at the end of the
+ * `[attached file: …]` path, and what a refusal notice names. Channel text, so it is
+ * neither trusted nor pre-sanitized here: the attachment writer maps it onto a name that
+ * is safe on disk (see services/task-attachments.ts). A channel with no name for a file
+ * says so with a plain fallback rather than inventing one, since a made-up extension
+ * would tell the model the file is something it is not.
+ */
+ fileName: string;
+ /** Downloads the file; the same two failure shapes MessagingInboundImage.fetch documents. */
+ fetch(maxBytes: number): Promise<Buffer>;
+}
+
/** One inbound chat message, normalized across channels. */
export interface MessagingInboundMessage {
/**
@@ -68,10 +96,12 @@ export interface MessagingInboundMessage {
*/
messageId: string;
/**
- * The message's plain text; null for anything that carries none (stickers, voice,
- * files, …) — a message with neither text nor images gets the not-supported notice.
- * An image sent with a caption puts the caption here: the caption IS that message's
- * text, so a channel needs no second field for it and the bridge no second rule.
+ * The message's plain text; null for anything that carries none (stickers, voice, …) — a
+ * message with no text, no image and no file gets the not-supported notice. An image or a
+ * file sent with a caption puts the caption here: the caption IS that message's text, so
+ * a channel needs no second field for it and the bridge no second rule. A channel that
+ * carries a caption on media it does NOT deliver must still report null, or the model
+ * answers a question about an attachment it never received.
*/
text: string | null;
/**
@@ -80,6 +110,16 @@ export interface MessagingInboundMessage {
* message lists them in the order the user sees them.
*/
images?: readonly MessagingInboundImage[];
+ /**
+ * Non-image files attached to this message, in the order the user sees them (absent or
+ * empty when there are none) — see MessagingInboundFile.
+ *
+ * Optional, like `images`, so a channel that delivers no files simply never populates it
+ * rather than carrying an empty list through its whole normalizer. A message may carry
+ * text, images and files together; the bridge composes one composer input out of whatever
+ * is there.
+ */
+ files?: readonly MessagingInboundFile[];
/** Sender display name when the channel's event carries one. */
senderName?: string;
}
diff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.ts
index bca359ec..9a17f181 100644
--- a/packages/server/src/runtime/messaging/error-kind.ts
+++ b/packages/server/src/runtime/messaging/error-kind.ts
@@ -37,14 +37,16 @@ import {
/**
* The capture points that put the refusal in front of the person in the chat.
*
- * `messaging_image_fetch_failed` answers the sender in the chat it came from (see
- * messagingImagePermissionNotice and its siblings), and `messaging_file_send_failed` names the
- * file that did not make it and why (see noteFileFailure). Every other code fails with the chat
- * hearing nothing at all — a reply that never went out, an inbound message whose Task never
- * started, a connection that will not come up — so the dashboard is where it has to be noticed.
+ * `messaging_image_fetch_failed` and `messaging_file_fetch_failed` answer the sender in the
+ * chat it came from (see messagingImagePermissionNotice and its siblings), and
+ * `messaging_file_send_failed` names the file that did not make it and why (see
+ * noteFileFailure). Every other code fails with the chat hearing nothing at all — a reply that
+ * never went out, an inbound message whose Task never started, a connection that will not come
+ * up — so the dashboard is where it has to be noticed.
*/
const CODES_EXPLAINED_IN_CHAT = new Set([
"messaging_image_fetch_failed",
+ "messaging_file_fetch_failed",
"messaging_file_send_failed",
]);
diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.ts
index b8e05d76..17cb06eb 100644
--- a/packages/server/src/runtime/messaging/feishu-connector.ts
+++ b/packages/server/src/runtime/messaging/feishu-connector.ts
@@ -5,14 +5,15 @@
* (injectable for tests — see feishu-sdk.ts), and the reduction of
* `im.message.receive_v1` events to the bridge's normalized inbound shape (text extracted
* from the content JSON and its mention placeholders resolved — see resolveFeishuMentions,
- * an `image` message's `image_key` turned into a lazy download handle; anything else
- * reads as neither text nor image).
+ * an `image` message's `image_key` and a `file` message's `file_key` each turned into a
+ * lazy download handle; anything else reads as neither text, image nor file).
*/
import type {
MessagingChannelConnector,
MessagingClient,
MessagingConnection,
MessagingConnectorHandlers,
+ MessagingInboundFile,
MessagingInboundImage,
} from "./connector.js";
import type { FeishuApiClient, FeishuCredentials, FeishuMention, FeishuSdk } from "./feishu-sdk.js";
@@ -136,6 +137,27 @@ function imageKeyOfContent(content: string): string | null {
}
}
+/**
+ * The key and display name of a `file` message's content JSON (null when unparseable or
+ * keyless — a message whose file cannot be addressed is not a file message as far as this
+ * connector is concerned).
+ *
+ * Feishu names the file in the event itself, so the sender's own name reaches the model
+ * without a second call. `file` is the fallback for an event that carries none: an
+ * invented extension would tell the model the bytes are something they are not.
+ */
+function fileOfContent(content: string): { fileKey: string; fileName: string } | null {
+ try {
+ const parsed = JSON.parse(content) as { file_key?: unknown; file_name?: unknown };
+ if (typeof parsed.file_key !== "string" || parsed.file_key === "") return null;
+ const fileName =
+ typeof parsed.file_name === "string" && parsed.file_name !== "" ? parsed.file_name : "file";
+ return { fileKey: parsed.file_key, fileName };
+ } catch {
+ return null;
+ }
+}
+
export class FeishuConnector implements MessagingChannelConnector {
readonly channel = "feishu" as const;
@@ -202,12 +224,34 @@ export class FeishuConnector implements MessagingChannelConnector {
}),
},
];
+ // `file` only, of the several types that carry a `file_key`. `audio` (a voice
+ // recording) and `media` (a video) are re-encoded for playback and named by nothing
+ // the sender chose — handing them over as `[attached file: …]` paths would offer a
+ // capability that is not there, since nothing downstream decodes or transcribes
+ // them. A recording the user genuinely wants the Agent to have arrives as a `file`
+ // the moment they send it as one, which is a menu item away.
+ const file = evt.messageType === "file" ? fileOfContent(evt.content) : null;
+ const files: MessagingInboundFile[] =
+ file === null
+ ? []
+ : [
+ {
+ fileName: file.fileName,
+ fetch: async (maxBytes) =>
+ (await api()).fetchMessageFile({
+ messageId: evt.messageId,
+ fileKey: file.fileKey,
+ maxBytes,
+ }),
+ },
+ ];
return handlers.onMessage({
chatId: evt.chatId,
chatKind: evt.chatType === "p2p" ? "direct" : "group",
messageId: evt.messageId,
text: raw === null ? null : resolveFeishuMentions(raw, evt.mentions, botOpenId),
...(images.length > 0 ? { images } : {}),
+ ...(files.length > 0 ? { files } : {}),
...(evt.senderName !== undefined ? { senderName: evt.senderName } : {}),
});
},
diff --git a/packages/server/src/runtime/messaging/feishu-sdk.ts b/packages/server/src/runtime/messaging/feishu-sdk.ts
index 6bebb99d..7f1daf39 100644
--- a/packages/server/src/runtime/messaging/feishu-sdk.ts
+++ b/packages/server/src/runtime/messaging/feishu-sdk.ts
@@ -45,7 +45,10 @@ export interface FeishuInboundEvent {
/** `p2p` for a direct chat with the bot, `group` for a group chat. */
chatType: string;
messageId: string;
- /** Feishu message type (`text`, `image`, `sticker`, …); only `text` is processed. */
+ /**
+ * Feishu message type (`text`, `image`, `file`, `sticker`, …). The connector reads the
+ * three it delivers and normalizes everything else to a message with no content.
+ */
messageType: string;
/** Raw message content JSON (for `text`: `{"text":"..."}`). */
content: string;
@@ -111,6 +114,18 @@ export interface FeishuApiClient {
fileKey: string;
maxBytes: number;
}): Promise<FeishuImageData>;
+ /**
+ * Downloads a non-image file carried by an inbound message (`file_key` is the content
+ * JSON's own). The same endpoint the image download uses, asked for a different resource
+ * `type` — which is the whole of the difference on the wire, and the reason both live
+ * behind one adapter — and permissioned by the same scope, so an app refused one is
+ * refused the other. Throws the same two shapes: `MessagingMediaTooLargeError` past
+ * `maxBytes`, a plain Error carrying the API's own reason otherwise.
+ *
+ * Bytes only, no media type: the bytes go to disk under the sender's file name, and it is
+ * the name's extension that says what they are (see MessagingInboundFile).
+ */
+ fetchMessageFile(args: { messageId: string; fileKey: string; maxBytes: number }): Promise<Buffer>;
/** Uploads a picture (`im.v1.image.create`) and sends the resulting key as an `image` message. */
sendImage(chatId: string, file: FeishuOutboundFile): Promise<void>;
/** Uploads a file (`im.v1.file.create`) and sends the resulting key as a `file` message. */
@@ -506,6 +521,33 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
/** Every call this client makes goes out under the deadline — see withDeadline. */
const deadline = <T>(call: Promise<T>, what: string): Promise<T> =>
withDeadline(call, timeoutMs, what);
+ /**
+ * One `im.v1.messageResource.get`, shared by both inbound downloads: the resource
+ * `type` differs, nothing else does. The stream is handed back UNREAD so the caller
+ * applies its own cap while the bytes arrive — reading here would put the whole file
+ * in memory before anyone could refuse it.
+ *
+ * The endpoint is scoped to the message, so a bot can only read resources from
+ * conversations it is in; there is no key-only fetch to abuse.
+ */
+ const fetchResource = async (args: {
+ messageId: string;
+ fileKey: string;
+ type: "image" | "file";
+ what: string;
+ }): Promise<LarkStreamResponse> => {
+ try {
+ return await deadline(
+ client.im.v1.messageResource.get({
+ path: { message_id: args.messageId, file_key: args.fileKey },
+ params: { type: args.type },
+ }),
+ args.what,
+ );
+ } catch (err) {
+ throw larkFailure(await larkStreamErrorEnvelope(err), err);
+ }
+ };
/** One `im.v1.message.create`, shared by every message kind: the content JSON differs, nothing else does. */
const sendContent = async (
chatId: string,
@@ -577,18 +619,12 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
}
},
async fetchMessageImage({ messageId, fileKey, maxBytes }): Promise<FeishuImageData> {
- let res: LarkStreamResponse;
- try {
- res = await deadline(
- client.im.v1.messageResource.get({
- path: { message_id: messageId, file_key: fileKey },
- params: { type: "image" },
- }),
- "Image download",
- );
- } catch (err) {
- throw larkFailure(await larkStreamErrorEnvelope(err), err);
- }
+ const res = await fetchResource({
+ messageId,
+ fileKey,
+ type: "image",
+ what: "Image download",
+ });
const data = await collectUnderCap(res.getReadableStream(), maxBytes, "The image");
// The response header states what the SENDER uploaded, which is a claim; the
// magic bytes are the file. PNG is the last resort — a data URL needs some type,
@@ -600,6 +636,15 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
: null;
return { data, mimeType: sniffImageMime(data) ?? headerType ?? "image/png" };
},
+ async fetchMessageFile({ messageId, fileKey, maxBytes }): Promise<Buffer> {
+ const res = await fetchResource({
+ messageId,
+ fileKey,
+ type: "file",
+ what: "File download",
+ });
+ return collectUnderCap(res.getReadableStream(), maxBytes, "The file");
+ },
async sendImage(chatId: string, file: FeishuOutboundFile): Promise<void> {
// Two steps, as Feishu requires: the bytes are uploaded on their own and the
// message carries only the key they were stored under.
diff --git a/packages/server/src/runtime/messaging/media.ts b/packages/server/src/runtime/messaging/media.ts
index f0aac435..abce02f2 100644
--- a/packages/server/src/runtime/messaging/media.ts
+++ b/packages/server/src/runtime/messaging/media.ts
@@ -82,9 +82,19 @@ export function sniffImageMime(bytes: Uint8Array): string | null {
* too large or the download failed".
*/
export class MessagingMediaTooLargeError extends Error {
+ /**
+ * The ceiling that actually refused this transfer, which is not necessarily the one the
+ * caller asked for: a connector may narrow it further because its own platform does (the
+ * Bot API serves a bot no file over 20MB, whatever the server would accept). The notice
+ * has to name the number that bit, or it sends the user to shrink a file against a limit
+ * that was never the one in the way.
+ */
+ readonly maxBytes: number;
+
constructor(what: string, maxBytes: number) {
super(`${what} is larger than the ${Math.floor(maxBytes / (1024 * 1024))}MB limit`);
this.name = "MessagingMediaTooLargeError";
+ this.maxBytes = maxBytes;
}
}
diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.ts
index 777fccef..8fc44702 100644
--- a/packages/server/src/runtime/messaging/telegram-api.ts
+++ b/packages/server/src/runtime/messaging/telegram-api.ts
@@ -1,7 +1,7 @@
/**
* The Telegram Bot API seam: the methods the Telegram connector uses (`getMe`,
- * `getWebhookInfo`, `sendMessage`, `getUpdates`, the file download behind an inbound photo,
- * and the `sendPhoto` / `sendDocument` uploads behind an outbound one),
+ * `getWebhookInfo`, `sendMessage`, `getUpdates`, the file download behind an inbound photo
+ * or document, and the `sendPhoto` / `sendDocument` uploads behind an outbound one),
* behind an injectable transport so unit
* tests substitute a fake and never open real network. Telegram needs no SDK — the Bot API is plain HTTPS
* POSTs against https://api.telegram.org — so the production transport is a thin fetch
@@ -16,6 +16,15 @@ import { MessagingMediaTooLargeError, collectUnderCap } from "./media.js";
/** Telegram Bot API host. Deliberately not configurable: bindings carry only the token. */
export const TELEGRAM_API_BASE = "https://api.telegram.org";
+/**
+ * The largest file the Bot API will serve a BOT through `getFile`, whatever the sender was
+ * allowed to upload. Past it the call is refused with a 400 whose only signal is prose
+ * Telegram is free to reword, so the connector caps its own transfers here instead: a size
+ * refusal the user can act on ("send something smaller") must not reach them as an
+ * unexplained download failure.
+ */
+export const TELEGRAM_MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024;
+
/** One credential set (a binding's stored token, or a test request's draft). */
export interface TelegramCredentials {
/** The whole credential: `<numeric bot id>:<secret>` as issued by @BotFather. */
@@ -69,6 +78,19 @@ export interface TelegramPhotoSize {
file_size?: number;
}
+/**
+ * An inbound `document` — a file the sender chose to send AS a file. The Bot API models it
+ * separately from `audio` / `video` / `voice` precisely because those are media it re-encodes
+ * for playback, and this is the only one of them that carries the sender's own name.
+ */
+export interface TelegramDocument {
+ file_id: string;
+ /** The sender's file name. Optional on the wire; a client that sends none leaves it absent. */
+ file_name?: string;
+ /** The Bot API marks it optional, so it can only refuse a transfer early, never authorize one. */
+ file_size?: number;
+}
+
/** The slice of a Bot API `Message` the connector consumes. */
export interface TelegramMessage {
message_id: number;
@@ -105,6 +127,8 @@ export interface TelegramMessage {
is_topic_message?: boolean;
/** Size variants of an inbound photo, smallest first; absent for every other message kind. */
photo?: TelegramPhotoSize[];
+ /** An inbound file sent as a file; absent for every other message kind. */
+ document?: TelegramDocument;
/** The text sent WITH a photo (or another media message) — a text message carries `text` instead. */
caption?: string;
/**
@@ -190,10 +214,17 @@ export interface TelegramBotClient {
* endpoint serves the bytes. That second URL is not the method endpoint — it is
* `/file/bot<token>/<file_path>` — and it embeds the bot token, so no failure here may
* ever echo it (see fetchErrorText). Throws when the transfer fails or exceeds
- * `maxBytes`; the Bot API itself refuses to serve a bot anything over 20MB this way, so
- * whichever ceiling is lower is the one that bites.
+ * `maxBytes`; the Bot API itself refuses to serve a bot anything over 20MB this way
+ * (TELEGRAM_MAX_DOWNLOAD_BYTES), so whichever ceiling is lower is the one that bites.
+ *
+ * `what` names the transfer in a size error, so the chat and the log say which kind of
+ * thing was refused. It never carries the URL, which embeds the token.
*/
- getFileBytes(args: { fileId: string; maxBytes: number }): Promise<TelegramFileBytes>;
+ getFileBytes(args: {
+ fileId: string;
+ maxBytes: number;
+ what?: string;
+ }): Promise<TelegramFileBytes>;
/**
* Sends a picture into a chat as a photo, so it renders inline. Multipart upload from
* bytes rather than by URL — the file lives in a Workspace this server can read and
@@ -421,7 +452,7 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Teleg
// The overall deadline must outlive the server-side long poll.
{ signal, timeoutMs: (timeoutSec + 15) * 1000 },
),
- async getFileBytes({ fileId, maxBytes }): Promise<TelegramFileBytes> {
+ async getFileBytes({ fileId, maxBytes, what = "The file" }): Promise<TelegramFileBytes> {
const file = await call<TelegramFile>("getFile", { file_id: fileId });
if (file.file_path === undefined || file.file_path === "") {
throw new Error("getFile failed: this file cannot be downloaded");
@@ -429,7 +460,7 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Teleg
// The declared size refuses an oversized transfer before it starts; the capped
// read below is what actually holds, since the claim can be absent or wrong.
if (file.file_size !== undefined && file.file_size > maxBytes) {
- throw new MessagingMediaTooLargeError("The image", maxBytes);
+ throw new MessagingMediaTooLargeError(what, maxBytes);
}
let res: Awaited<ReturnType<TelegramFetch>>;
try {
@@ -446,7 +477,7 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Teleg
if (!res.ok || res.body === null) {
throw new Error(`file download failed: HTTP ${res.status}`);
}
- const data = await collectUnderCap(bodyChunks(res.body), maxBytes, "The image");
+ const data = await collectUnderCap(bodyChunks(res.body), maxBytes, what);
return { data, filePath: file.file_path };
},
async sendPhoto({ chatId, fileName, data }): Promise<void> {
diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.ts
index 76f3799c..1ca0af48 100644
--- a/packages/server/src/runtime/messaging/telegram-connector.ts
+++ b/packages/server/src/runtime/messaging/telegram-connector.ts
@@ -41,6 +41,7 @@ import type {
MessagingClient,
MessagingConnection,
MessagingConnectorHandlers,
+ MessagingInboundFile,
MessagingInboundImage,
MessagingInboundMessage,
MessagingSendNote,
@@ -56,7 +57,7 @@ import type {
TelegramTransport,
TelegramUpdate,
} from "./telegram-api.js";
-import { TelegramApiError } from "./telegram-api.js";
+import { TELEGRAM_MAX_DOWNLOAD_BYTES, TelegramApiError } from "./telegram-api.js";
/** The Telegram binding's stored config document (`messaging_bindings.config_json`). */
export interface TelegramBindingConfig extends Record<string, unknown> {
@@ -287,11 +288,25 @@ function largestPhoto(sizes: readonly TelegramPhotoSize[]): TelegramPhotoSize |
return best;
}
+/**
+ * The ceiling one inbound transfer actually runs under: the caller's, or Telegram's own
+ * download limit where that is tighter.
+ *
+ * Applied here rather than left to the Bot API because of what the API does past it — a 400
+ * whose only signal is prose, which would reach the chat as an unexplained download failure
+ * when the truth is a size the sender can act on. For a photo the two numbers happen to be
+ * equal (the server's inline-image ceiling is also 20MB); for a document the server's
+ * per-file attachment cap is far larger, so this is the number that bites.
+ */
+function downloadCap(maxBytes: number): number {
+ return Math.min(maxBytes, TELEGRAM_MAX_DOWNLOAD_BYTES);
+}
+
/**
* One update reduced to the bridge's normalized shape; null for updates that are not chat
- * messages. `bot` is captured by an inbound photo's `fetch`, so the bytes are pulled only
- * if the bridge asks for them. `me` is this bot's own account (null before the first `getMe`
- * of a connection has answered), used only to recognize its own mention.
+ * messages. `bot` is captured by an inbound photo's or document's `fetch`, so the bytes are
+ * pulled only if the bridge asks for them. `me` is this bot's own account (null before the
+ * first `getMe` of a connection has answered), used only to recognize its own mention.
*/
function normalizeUpdate(
update: TelegramUpdate,
@@ -311,7 +326,8 @@ function normalizeUpdate(
fetch: async (maxBytes) => {
const { data, filePath } = await bot.getFileBytes({
fileId: photo.file_id,
- maxBytes,
+ maxBytes: downloadCap(maxBytes),
+ what: "The image",
});
// Telegram re-encodes what it serves as a photo, so the served path's
// extension is the type; JPEG is what that re-encoding almost always yields.
@@ -319,6 +335,38 @@ function normalizeUpdate(
},
},
];
+ // `document` only, of the media fields an update can carry. A document is a file the
+ // sender chose to send AS a file, and the only one of them that carries the sender's own
+ // name; `audio`, `video`, `voice` and `video_note` are streams Telegram re-encodes for
+ // playback (a `voice` is a nameless opus blob), and handing one to the Agent as an
+ // `[attached file: …]` path would offer a capability that is not there — nothing
+ // downstream decodes or transcribes it. What a sender actually wants delivered arrives
+ // here the moment they attach it as a file, which is one menu item away; anything else
+ // keeps the not-supported notice, which at least says so.
+ //
+ // A picture dragged in uncompressed is a `document` too, and lands as an attachment
+ // rather than as an inline image: the sender asked for the original bytes to arrive, and
+ // the model opens the path with `read_image` like any other file.
+ const doc = msg.document ?? null;
+ const files: MessagingInboundFile[] =
+ doc === null
+ ? []
+ : [
+ {
+ // Absent for a client that sent none. `document` is the fallback rather than a
+ // name derived from the served path, whose extension Telegram picks: a guess
+ // that reads as the sender's own name is worse than an obvious placeholder.
+ fileName: doc.file_name ?? "document",
+ fetch: async (maxBytes) => {
+ const { data } = await bot.getFileBytes({
+ fileId: doc.file_id,
+ maxBytes: downloadCap(maxBytes),
+ what: "The file",
+ });
+ return data;
+ },
+ },
+ ];
return {
// The topic rides the chat id so the binding remembers the LAST one written in, the same
// way it already remembers the last chat: a user who moves to a new topic gets the
@@ -326,19 +374,19 @@ function normalizeUpdate(
chatId: chatRefOf(msg.chat.id, topicId),
chatKind: msg.chat.type === "private" ? "direct" : "group",
messageId: replyRefOf(msg.chat.id, msg.message_id, topicId),
- // A text message carries `text`; a PHOTO carries its words in `caption` instead, which
- // is that message's text as far as the bridge is concerned. Every other media kind
- // (document, video, audio, voice, …) normalizes to null EVEN WHEN it has a caption:
- // its bytes are not delivered, so running the model on the caption alone would answer
- // confidently about a file it never received. A picture dragged in uncompressed
- // arrives as a document, which makes that the common case rather than a corner one.
+ // A text message carries `text`; a photo or a document carries its words in `caption`
+ // instead, which is that message's text as far as the bridge is concerned. A caption on
+ // any OTHER media kind (video, audio, voice, …) normalizes to null: those bytes are not
+ // delivered, so running the model on the caption alone would answer confidently about a
+ // file it never received.
text:
typeof msg.text === "string"
? stripBotMention(msg.text, msg.entities, me)
- : photo !== null && typeof msg.caption === "string"
+ : (photo !== null || doc !== null) && typeof msg.caption === "string"
? stripBotMention(msg.caption, msg.caption_entities, me)
: null,
...(images.length > 0 ? { images } : {}),
+ ...(files.length > 0 ? { files } : {}),
...(senderName !== undefined ? { senderName } : {}),
};
}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index eee0c18d..52f4729d 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -427,13 +427,17 @@ function followUpInfo(f: QueuedFollowUp): PendingFollowUpInfo {
}
/**
- * The recall store of a queued input whose caller supplied none (the messaging bridge's
- * inbound path): everything recallable is already in the input itself — the user's text and
- * the inline image URLs, the only two shapes a task input is ever built from. `files` is
- * empty because only the HTTP route writes file attachments to the Session scratchpad, and
- * only it knows the paths they landed on.
+ * The recall store of a queued input whose caller supplied none: everything recallable is
+ * already in the input itself — the user's text and the inline image URLs, the only two
+ * shapes a task input is ever built from.
+ *
+ * `files` is empty because the path a written attachment landed on is known only to
+ * whoever wrote it. A caller that wrote some therefore builds its store on top of this one
+ * instead of leaving it to be derived, and passes the input as it stood BEFORE the
+ * `[attached file: …]` lines were folded in — derived from the folded input, `text` would
+ * hand a recall back a raw scratchpad path in place of the chip it was meant to restore.
*/
-function recallStoreOf(input: OmniMessage[]): RecallStore {
+export function recallStoreOf(input: OmniMessage[]): RecallStore {
const text = input
.filter(isPlainText("user"))
.map((m) => m.payload.text)
diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.ts
index 72279b39..e3b85d1e 100644
--- a/packages/server/test/followup.test.ts
+++ b/packages/server/test/followup.test.ts
@@ -282,11 +282,12 @@ describe("follow-up queue route", () => {
await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "task 1" }] });
await waitFor(() => t.deps.manager.pendingApprovalCount(SID) === 1);
- // What the messaging bridge does with a Feishu/Telegram message on a busy Session: the
- // manager API directly, with no recall store of its own (only the HTTP route knows the
- // parts of one the input does not carry). The queued entry must still show its content
- // and still be recallable — a queued message's recallability cannot depend on which
- // door it came through.
+ // What the messaging bridge does with a text-only Feishu/Telegram message on a busy
+ // Session: the manager API directly, with no recall store of its own (a message that
+ // wrote file attachments supplies one, because their on-disk paths are the half the
+ // input does not carry). The queued entry must still show its content and still be
+ // recallable — a queued message's recallability cannot depend on which door it came
+ // through.
const queued = await t.deps.manager.startTask(SID, [userText("from the chat channel")], {
queueIfBusy: true,
});
diff --git a/packages/server/test/messaging-error-kind.test.ts b/packages/server/test/messaging-error-kind.test.ts
index fd4630d9..cd65400d 100644
--- a/packages/server/test/messaging-error-kind.test.ts
+++ b/packages/server/test/messaging-error-kind.test.ts
@@ -31,6 +31,10 @@ describe("messagingErrorKind", () => {
// and the outbound upload names the file that did not make it: both have already handed
// the fix to the only person who can apply it, so a dashboard adds nothing.
expect(messagingErrorKind(scopeDenial(), "messaging_image_fetch_failed")).toBe("expected");
+ // An inbound FILE download is the same capture point in every way that matters here: on
+ // Feishu it is the very same scope denial, answered into the chat with the same scope
+ // names and console link (see messagingInboundFilePermissionNotice).
+ expect(messagingErrorKind(scopeDenial(), "messaging_file_fetch_failed")).toBe("expected");
expect(
messagingErrorKind(
new MessagingUnsupportedError('QQ cannot receive "chart.png": requires a public URL'),
diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.ts
index 007b04b0..7e831c62 100644
--- a/packages/server/test/messaging-qq.test.ts
+++ b/packages/server/test/messaging-qq.test.ts
@@ -29,7 +29,7 @@ import type { RuntimeSession } from "../src/runtime/session-manager.js";
import {
MESSAGING_APPROVAL_NOTICE,
MESSAGING_TEST_MESSAGE,
- MESSAGING_TEXT_ONLY_NOTICE,
+ MESSAGING_UNSUPPORTED_NOTICE,
} from "../src/runtime/messaging/bridge.js";
import type { MessagingClient } from "../src/runtime/messaging/connector.js";
import { MessagingUnsupportedError } from "../src/runtime/messaging/media.js";
@@ -542,7 +542,7 @@ describe("qq binding routes and the passive reply budget", () => {
.fire({ kind: "c2c", openid: USER_OPENID, messageId: "msg_img", content: "" });
await waitFor(() => fake.allSends().length === 1);
expect(fake.allSends()[0]).toMatchObject({
- content: MESSAGING_TEXT_ONLY_NOTICE,
+ content: MESSAGING_UNSUPPORTED_NOTICE,
msgId: "msg_img",
msgSeq: 1,
});
diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.ts
index 39eb8e17..94bc1efd 100644
--- a/packages/server/test/messaging-telegram.test.ts
+++ b/packages/server/test/messaging-telegram.test.ts
@@ -7,7 +7,10 @@
* reads, and the connector's long-poll loop through a fake Bot API transport — offset
* advancement, the connect-time backlog drain, inbound routing as plain user input,
* an inbound photo (largest variant, caption as the message text, a failed download
- * degrading to a notice), per-message mirroring with one reply thread per run in groups,
+ * degrading to a notice), an inbound `document` (the one media field the file seam takes —
+ * scratchpad attachment, caption as the message text, and Telegram's own 20MB bot download
+ * ceiling reported as a size refusal rather than an unexplained failure),
+ * per-message mirroring with one reply thread per run in groups,
* mentioned files leaving as a photo or a document, 4096-safe chunking,
* non-text notices, poll-failure status flips, and the conflict path a second poller
* produces (the 409 backoff, the connect-time webhook clear, and the actionable text the
@@ -16,7 +19,14 @@
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { approvalDecision, assistantText, toolCall } from "@prismshadow/penguin-core";
+import {
+ approvalDecision,
+ assistantText,
+ matchAttachedFileLine,
+ modelVisiblePath,
+ scratchpadDir,
+ toolCall,
+} from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type {
FeishuBindingResponse,
@@ -29,11 +39,12 @@ import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { INLINE_IMAGE_MAX_BYTES } from "../src/services/attachment-limits.js";
import {
MESSAGING_APPROVAL_NOTICE,
- MESSAGING_TEXT_ONLY_NOTICE,
+ MESSAGING_UNSUPPORTED_NOTICE,
MESSAGING_TEST_MESSAGE,
messagingImageFailedNotice,
+ messagingInboundFileTooLargeNotice,
} from "../src/runtime/messaging/bridge.js";
-import { collectUnderCap } from "../src/runtime/messaging/media.js";
+import { MessagingMediaTooLargeError, collectUnderCap } from "../src/runtime/messaging/media.js";
import type {
TelegramBotClient,
TelegramBotUser,
@@ -45,6 +56,7 @@ import type {
TelegramWebhookInfo,
} from "../src/runtime/messaging/telegram-api.js";
import {
+ TELEGRAM_MAX_DOWNLOAD_BYTES,
TelegramApiError,
createTelegramTransport,
} from "../src/runtime/messaging/telegram-api.js";
@@ -94,6 +106,7 @@ type Sent = SentMessage | SentMedia;
interface FileFetch {
fileId: string;
maxBytes: number;
+ what?: string;
}
/** The bytes as a stream, so the fake reads them through the real capped reader. */
@@ -189,10 +202,20 @@ class FakeBotClient implements TelegramBotClient {
async getFileBytes(args: FileFetch): Promise<TelegramFileBytes> {
this.fileFetches.push(args);
if (this.t.failFileFetch !== null) throw new Error(this.t.failFileFetch);
+ // The declared size refuses an oversized transfer before it starts, exactly as the real
+ // transport does off `getFile`'s answer — which is what makes a document past
+ // Telegram's own download ceiling a SIZE refusal rather than an unexplained failure.
+ if (this.t.declaredFileSize !== null && this.t.declaredFileSize > args.maxBytes) {
+ throw new MessagingMediaTooLargeError(args.what ?? "The file", args.maxBytes);
+ }
// The cap is enforced through the REAL machinery the transport uses, not a hand-written
// imitation of it (see the Feishu suite's note: an imitation is free to disagree with
// production about which failure this is).
- const data = await collectUnderCap(oneChunk(this.t.fileBytes), args.maxBytes, "The image");
+ const data = await collectUnderCap(
+ oneChunk(this.t.fileBytes),
+ args.maxBytes,
+ args.what ?? "The file",
+ );
return { data, filePath: this.t.filePath };
}
@@ -265,6 +288,8 @@ class FakeTelegramTransport {
failMediaSend: string | null = null;
/** What a file download resolves to; oversize bytes exercise the cap. */
fileBytes: Buffer = PHOTO_BYTES;
+ /** `getFile`'s claimed size, refused before the transfer starts; null leaves the claim absent. */
+ declaredFileSize: number | null = null;
/** The path the Bot API served the bytes from — its extension names the type. */
filePath = "photos/file_7.jpg";
/** The webhook registered on the bot; the empty string means none, as the Bot API encodes it. */
@@ -342,6 +367,9 @@ class FakeFeishuSdk implements FeishuSdk {
async fetchMessageImage(): Promise<never> {
throw new Error("the feishu side of these tests never carries an image");
},
+ async fetchMessageFile(): Promise<never> {
+ throw new Error("the feishu side of these tests never carries a file");
+ },
async sendImage() {},
async sendFile() {},
};
@@ -380,6 +408,29 @@ function privatePhoto(caption?: string, messageId = 1): TelegramUpdate["message"
};
}
+/**
+ * A private-chat document message — a file the sender chose to send AS a file, which is the
+ * one media field the connector takes into the file seam. `caption` carries whatever the
+ * user typed with it, exactly as a photo's does.
+ */
+function privateDocument(args: {
+ messageId: number;
+ fileName?: string | null;
+ caption?: string;
+}): TelegramUpdate["message"] {
+ const fileName = args.fileName === undefined ? "report.pdf" : args.fileName;
+ return {
+ message_id: args.messageId,
+ chat: { id: 42424242, type: "private" },
+ document: { file_id: "doc-1", ...(fileName === null ? {} : { file_name: fileName }) },
+ ...(args.caption !== undefined ? { caption: args.caption } : {}),
+ from: { first_name: "Ada" },
+ };
+}
+
+/** An inbound document's contents — text, so a failed write shows up as the wrong bytes on disk. */
+const DOCUMENT_BYTES = Buffer.from("quarterly revenue: 42\n", "utf8");
+
/**
* One input part as the fake Sessions record it. Deliberately a loose shape rather than
* core's payload union: a run's input mixes composer text with `image_url` parts, and the
@@ -1138,7 +1189,7 @@ describe("telegram binding routes and connector loop", () => {
const sends = fake.allTexts();
// Bob's message got its notice where Bob wrote it — the live target is right for that.
expect(sends[0]).toMatchObject({
- text: MESSAGING_TEXT_ONLY_NOTICE,
+ text: MESSAGING_UNSUPPORTED_NOTICE,
threadId: 77,
replyTo: 202,
});
@@ -1341,7 +1392,7 @@ describe("telegram binding routes and connector loop", () => {
from: { first_name: "Ada" },
});
await waitFor(() => fake.allSends().length > 0);
- expect(fake.allTexts()[0]!.text).toBe(MESSAGING_TEXT_ONLY_NOTICE);
+ expect(fake.allTexts()[0]!.text).toBe(MESSAGING_UNSUPPORTED_NOTICE);
expect(runs).toHaveLength(0);
});
@@ -1357,33 +1408,13 @@ describe("telegram binding routes and connector loop", () => {
await waitFor(() => fake.allSends().length > 0);
expect(fake.allSends()).toContainEqual({
chatId: "42424242",
- text: MESSAGING_TEXT_ONLY_NOTICE,
+ text: MESSAGING_UNSUPPORTED_NOTICE,
});
expect(runs).toHaveLength(0);
// Even a rejected type teaches the bridge where the user is.
expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe("42424242");
});
- it("a captioned document still gets the not-supported notice and starts no task", async () => {
- await bindEnabled(SID);
- // The common shape of this: a picture dragged into Telegram uncompressed arrives as a
- // `document`, caption and all, with no `photo` array. The caption is not this message
- // on its own — the file it describes is never downloaded — so falling back to it would
- // run the model on "summarize this for me" with nothing attached.
- fake.push({
- message_id: 22,
- chat: { id: 42424242, type: "private" },
- caption: "summarize this for me",
- from: { first_name: "Ada" },
- });
- await waitFor(() => fake.allSends().length > 0);
- expect(fake.allSends()).toContainEqual({
- chatId: "42424242",
- text: MESSAGING_TEXT_ONLY_NOTICE,
- });
- expect(runs).toHaveLength(0);
- });
-
it("an inbound photo becomes an image_url part, downloaded at its largest size", async () => {
await bindEnabled(SID);
fake.push(privatePhoto(undefined, 31));
@@ -1396,7 +1427,7 @@ describe("telegram binding routes and connector loop", () => {
// The largest variant, not the thumbnails the Bot API lists first, and under the
// shared inline-image ceiling (which is also Telegram's own bot download ceiling).
expect(fake.allFileFetches()).toEqual([
- { fileId: "full-1280", maxBytes: INLINE_IMAGE_MAX_BYTES },
+ { fileId: "full-1280", maxBytes: INLINE_IMAGE_MAX_BYTES, what: "The image" },
]);
});
@@ -1443,6 +1474,104 @@ describe("telegram binding routes and connector loop", () => {
expect(runs).toHaveLength(0);
});
+ // —— Inbound documents ————————————————————————————————————————————————————
+ // `document` is the one media field a Telegram update carries that the file seam takes:
+ // a file the sender chose to send AS a file, and the only one that carries their own
+ // name. It reaches the Agent the way a composer upload does — written into the Session
+ // scratchpad, named on the message text as an `[attached file: <path>]` line.
+
+ it("an inbound document lands in the Session scratchpad and rides as a path line", async () => {
+ await bindEnabled(SID);
+ fake.fileBytes = DOCUMENT_BYTES;
+ fake.push(privateDocument({ messageId: 41 }));
+ await waitFor(() => runs.length === 1);
+ // No caption: the file is the whole message, so the path line is the whole text.
+ expect(runs[0]).toHaveLength(1);
+ expect(runs[0]![0]!.type).toBe("text");
+ const written = matchAttachedFileLine(runs[0]![0]!.text!.trim());
+ expect(written).not.toBeNull();
+ expect(path.basename(written!)).toBe("report.pdf");
+ // The line carries the MODEL-VISIBLE spelling of the path, not the native one: core runs
+ // every path it composes for the model through `modelVisiblePath`, which on Windows swaps
+ // the separators for forward slashes (they survive JSON escaping into tool arguments, Git
+ // Bash runs them, and Node's fs accepts them). The expected side therefore has to go
+ // through the same transform — a bare `path.join` matches everywhere except Windows,
+ // where the two differ by nothing but the separator.
+ expect(path.dirname(written!)).toBe(
+ modelVisiblePath(path.join(scratchpadDir(t.root, projectId, "default_agent"), SID)),
+ );
+ // And the shape itself, which is the whole point of the transform: nothing in the line a
+ // model would have to escape. Vacuous on POSIX, load-bearing on Windows.
+ expect(written).not.toContain("\\");
+ expect((await fs.readFile(written!)).equals(DOCUMENT_BYTES)).toBe(true);
+ // Downloaded under Telegram's own 20MB bot ceiling, which is tighter than the server's
+ // per-file attachment cap and therefore the number that bites.
+ expect(fake.allFileFetches()).toEqual([
+ { fileId: "doc-1", maxBytes: TELEGRAM_MAX_DOWNLOAD_BYTES, what: "The file" },
+ ]);
+ });
+
+ it("a document's caption rides along as the message's text, ahead of its path line", async () => {
+ await bindEnabled(SID);
+ fake.push(privateDocument({ messageId: 42, caption: "summarize this for me" }));
+ await waitFor(() => runs.length === 1);
+ const text = runs[0]![0]!.text!;
+ expect(text.startsWith("summarize this for me\n\n[attached file: ")).toBe(true);
+ expect(runs[0]![0]!.role).toBe("user");
+ expect("sender" in runs[0]![0]!).toBe(false);
+ });
+
+ it("refuses a document past Telegram's own download ceiling as a size problem", async () => {
+ await bindEnabled(SID);
+ // The Bot API serves a bot nothing over 20MB through `getFile`, whatever the sender was
+ // allowed to upload, and past it answers a 400 whose only signal is prose. Capping the
+ // transfer at that number instead is what makes this a refusal the sender can act on
+ // rather than an unexplained download failure.
+ fake.declaredFileSize = 45 * 1024 * 1024;
+ fake.push(privateDocument({ messageId: 44, fileName: "raw-footage.mp4" }));
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allTexts()[0]!.text).toBe(
+ messagingInboundFileTooLargeNotice("raw-footage.mp4", TELEGRAM_MAX_DOWNLOAD_BYTES),
+ );
+ expect(fake.allTexts()[0]!.text).toContain("20MB");
+ expect(runs).toHaveLength(0);
+ });
+
+ it("a document with no name of its own attaches under an obvious placeholder", async () => {
+ await bindEnabled(SID);
+ fake.push({
+ message_id: 46,
+ chat: { id: 42424242, type: "private" },
+ document: { file_id: "doc-noname" },
+ from: { first_name: "Ada" },
+ });
+ await waitFor(() => runs.length === 1);
+ // Not a name derived from the served path, whose extension Telegram picks: a guess that
+ // reads as the sender's own name is worse than a placeholder that reads as one.
+ expect(path.basename(matchAttachedFileLine(runs[0]![0]!.text!.trim())!)).toBe("document");
+ });
+
+ it("video, audio and voice keep the not-supported notice, caption and all", async () => {
+ await bindEnabled(SID);
+ // Deliberately out of the file seam: those are streams Telegram re-encodes for playback
+ // (a `voice` is a nameless opus blob), and handing one over as an `[attached file: …]`
+ // path would offer a capability that is not there. A sender who wants one delivered
+ // attaches it as a file, which arrives as a `document`.
+ fake.push({
+ message_id: 48,
+ chat: { id: 42424242, type: "private" },
+ caption: "transcribe this",
+ from: { first_name: "Ada" },
+ });
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allSends()).toContainEqual({
+ chatId: "42424242",
+ text: MESSAGING_UNSUPPORTED_NOTICE,
+ });
+ expect(runs).toHaveLength(0);
+ expect(fake.allFileFetches()).toHaveLength(0);
+ });
+
it("sends the files the reply mentions as a photo and a document, after its text", async () => {
// The Feishu suite carries the whole outbound-file rule (existence, caps, containment);
// this is the channel half of it — a picture must reach Telegram as a photo, so it
diff --git a/packages/server/test/messaging-wire.test.ts b/packages/server/test/messaging-wire.test.ts
index 8bb343a5..f2610c57 100644
--- a/packages/server/test/messaging-wire.test.ts
+++ b/packages/server/test/messaging-wire.test.ts
@@ -144,6 +144,28 @@ describe("feishu adapter against the SDK's HTTP boundary", () => {
expect(call.params).toEqual({ type: "image" });
});
+ it("downloads a message file from the same endpoint, asked for as a `file` resource", async () => {
+ // The `type` param is the whole of the difference on the wire between an inbound image
+ // and an inbound file — and it is a query parameter the SDK serializes, which is
+ // exactly the layer a fake of our own seam stubs out along with the wire.
+ const DOC = Buffer.from("quarterly revenue: 42\n", "utf8");
+ const { http, calls } = larkHttp((url) =>
+ url.includes("tenant_access_token") ? TOKEN_ANSWER : { stream: DOC },
+ );
+ const client = await createLarkSdk({ httpInstance: http }).createClient(CREDS);
+ const out = await client.fetchMessageFile({
+ messageId: "om_wire_file",
+ fileKey: "file_v3_wire",
+ maxBytes: 20 * 1024 * 1024,
+ });
+ expect(out.equals(DOC)).toBe(true);
+ const call = calls.at(-1)!;
+ expect(call.url).toBe(
+ "https://open.feishu.cn/open-apis/im/v1/messages/om_wire_file/resources/file_v3_wire",
+ );
+ expect(call.params).toEqual({ type: "file" });
+ });
+
it("reports the API's own refusal reason, which arrives as a STREAM (the shipped bug)", async () => {
// A Feishu app that receives messages happily is still refused here until the resource
// read scope is granted. Because the request asks for a stream, the ERROR body is a
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index 27fef133..3208e9ae 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -8,8 +8,12 @@
* Feishu SDK — inbound text becomes an ordinary user task
* exactly as if typed in the composer (no marker, no special sender; queueIfBusy), an
* inbound image becomes the composer's `image_url` part (and a download that fails or
- * exceeds the inline-image cap degrades to a notice instead of a half-message),
- * anything else gets the bilingual not-supported reply, each completed assistant message
+ * exceeds the inline-image cap degrades to a notice instead of a half-message), an inbound
+ * FILE becomes the composer's other attachment shape — written into the Session scratchpad
+ * and named on the message text as an `[attached file: …]` line, under the server's own
+ * attachment caps, with a size refusal, a permission refusal and a transfer failure each
+ * answered by its own notice — anything else gets the bilingual not-supported reply,
+ * each completed assistant message
* mirrors on
* its own to the last known chat as soon as it completes (the run's first one threaded onto
* the inbound message in groups), the files the reply MENTIONED follow it (existing ones
@@ -29,13 +33,16 @@ import {
approvalDecision,
compactionBegin,
compactionEnd,
+ matchAttachedFileLine,
+ modelVisiblePath,
+ scratchpadDir,
toolCall,
} from "@prismshadow/penguin-core";
import type { ApproveFn, OmniMessage } from "@prismshadow/penguin-core";
import type { FeishuBindingResponse, FeishuTestResponse } from "../src/api/types.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
-import { INLINE_IMAGE_MAX_BYTES } from "../src/services/attachment-limits.js";
+import { INLINE_IMAGE_MAX_BYTES, toAttachmentLimits } from "../src/services/attachment-limits.js";
import {
MESSAGING_APPROVAL_NOTICE,
MESSAGING_MAX_LINE_MESSAGES,
@@ -43,7 +50,7 @@ import {
MESSAGING_OUTBOUND_IMAGE_MAX_BYTES,
MESSAGING_TEST_MESSAGE,
MESSAGING_TEXT_CHUNK_CHARS,
- MESSAGING_TEXT_ONLY_NOTICE,
+ MESSAGING_UNSUPPORTED_NOTICE,
MessagingBridge,
chunkMessagingText,
messagingFileFailedNotice,
@@ -55,9 +62,19 @@ import {
messagingImageFailedNotice,
messagingImagePermissionNotice,
messagingImageTooLargeNotice,
+ messagingInboundFileFailedNotice,
+ messagingInboundFilePermissionNotice,
+ messagingInboundFileTooLargeNotice,
+ messagingInboundFilesTooLargeNotice,
splitReplyLines,
} from "../src/runtime/messaging/bridge.js";
import type { MessagingTaskRunner } from "../src/runtime/messaging/bridge.js";
+import type {
+ MessagingChannelConnector,
+ MessagingInboundFile,
+ MessagingInboundImage,
+ MessagingInboundMessage,
+} from "../src/runtime/messaging/connector.js";
import { FeishuConnector } from "../src/runtime/messaging/feishu-connector.js";
import {
MessagingPermissionError,
@@ -107,7 +124,7 @@ interface SentMedia {
/** Everything one client sent, in order — the ordering of text against media is the point. */
type Sent = SentText | SentMedia;
-/** One image download the bridge asked for, cap included (the fake stands in for the SDK adapter). */
+/** One resource download the bridge asked for, cap included (the fake stands in for the SDK adapter). */
interface ImageFetch {
messageId: string;
fileKey: string;
@@ -122,11 +139,15 @@ async function* oneChunk(bytes: Buffer): AsyncGenerator<Uint8Array> {
/** A PNG's magic bytes plus a little payload: enough for a data URL to be asserted verbatim. */
const IMAGE_BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x01, 0x02, 0x03]);
+/** An inbound file's contents — text, so a failed write shows up as the wrong bytes on disk. */
+const FILE_BYTES = Buffer.from("quarterly revenue: 42\n", "utf8");
+
class FakeClient implements FeishuApiClient {
readonly sends: Sent[] = [];
/** When each send was recorded, parallel to `sends`: what the pacing test measures. */
readonly sentAt: number[] = [];
readonly imageFetches: ImageFetch[] = [];
+ readonly fileFetches: ImageFetch[] = [];
checks = 0;
constructor(
readonly creds: FeishuCredentials,
@@ -169,6 +190,13 @@ class FakeClient implements FeishuApiClient {
const data = await collectUnderCap(oneChunk(this.sdk.imageBytes), args.maxBytes, "The image");
return { data, mimeType: "image/png" };
}
+ async fetchMessageFile(args: ImageFetch): Promise<Buffer> {
+ this.fileFetches.push(args);
+ if (this.sdk.failFileFetchWith !== null) throw this.sdk.failFileFetchWith;
+ if (this.sdk.failFileFetch !== null) throw new Error(this.sdk.failFileFetch);
+ // Through the REAL capped reader, for the reason fetchMessageImage gives.
+ return collectUnderCap(oneChunk(this.sdk.fileBytes), args.maxBytes, "The file");
+ }
async sendImage(chatId: string, file: { fileName: string; data: Buffer }): Promise<void> {
this.sdk.failMediaSendOnce();
this.sends.push({
@@ -245,6 +273,12 @@ class FakeSdk implements FeishuSdk {
failImageFetchWith: Error | null = null;
/** What an image download resolves to; oversize bytes exercise the cap. */
imageBytes: Buffer = IMAGE_BYTES;
+ /** Non-null makes fetchMessageFile throw with this message (a dead file_key, a network fault). */
+ failFileFetch: string | null = null;
+ /** Non-null makes it throw THIS — for the failure shapes that carry data, not just text. */
+ failFileFetchWith: Error | null = null;
+ /** What a file download resolves to; oversize bytes exercise the cap. */
+ fileBytes: Buffer = FILE_BYTES;
/** Fails this many upcoming outbound image/file sends (the channel refusing an upload). */
failMediaSends = 0;
/** Non-null makes EVERY media send throw this — for the failure shapes that carry data. */
@@ -288,6 +322,10 @@ class FakeSdk implements FeishuSdk {
allImageFetches(): ImageFetch[] {
return this.clients.flatMap((c) => c.imageFetches);
}
+ /** Every file download asked of any client, in order. */
+ allFileFetches(): ImageFetch[] {
+ return this.clients.flatMap((c) => c.fileFetches);
+ }
lastConnection(): FakeConnection {
const conn = this.connections.at(-1);
if (!conn) throw new Error("no fake connection was opened");
@@ -635,6 +673,8 @@ describe("messaging binding routes and bridge", () => {
repo: t.deps.messagingRepo,
sessions: t.deps.sessionsRepo,
files: t.deps.workspaceFiles,
+ root: t.root,
+ attachmentLimits: () => toAttachmentLimits(t.deps.serverSettingsRepo.getAttachmentLimitsMb()),
channels: t.deps.channels,
runner,
connectors: [new FeishuConnector(fake)],
@@ -1253,9 +1293,9 @@ describe("messaging binding routes and bridge", () => {
// One send carrying the notice whole. The notices are single-line by construction, so
// this is asserted from both ends: the text has no line break to split on, and it
// arrives as one message — a notice routed through the reply path would break the pair.
- expect(MESSAGING_TEXT_ONLY_NOTICE).not.toContain("\n");
+ expect(MESSAGING_UNSUPPORTED_NOTICE).not.toContain("\n");
expect(fake.allSends()).toEqual([
- { kind: "send", target: "oc_notice", text: MESSAGING_TEXT_ONLY_NOTICE },
+ { kind: "send", target: "oc_notice", text: MESSAGING_UNSUPPORTED_NOTICE },
]);
// And the test message, sent through its own path, is one message too.
const sent = fake.allSends().length;
@@ -1442,24 +1482,26 @@ describe("messaging binding routes and bridge", () => {
expect(fake.allTexts().map((s) => s.text)).toEqual(["the actual answer"]);
});
- it("a message that is neither text nor image gets the bilingual notice and starts no task", async () => {
+ it("a message that is neither text, image nor file gets the bilingual notice and starts no task", async () => {
await bindEnabled(SID);
- // A file: inbound documents are deliberately out of scope, so they keep answering with
- // the notice — as do stickers, voice and video.
+ // A sticker: it carries a `file_key` like a file message does, and is still not one —
+ // as are `audio` (a voice recording) and `media` (a video), which the connector
+ // deliberately leaves out of the file seam.
await fake.lastConnection().fire({
chatId: "oc_chat_1",
chatType: "p2p",
messageId: "om_2",
- messageType: "file",
- content: JSON.stringify({ file_key: "file_1", file_name: "notes.pdf" }),
+ messageType: "sticker",
+ content: JSON.stringify({ file_key: "sticker_1" }),
});
await waitFor(() => fake.allSends().length > 0);
expect(fake.allSends()).toContainEqual({
kind: "send",
target: "oc_chat_1",
- text: MESSAGING_TEXT_ONLY_NOTICE,
+ text: MESSAGING_UNSUPPORTED_NOTICE,
});
expect(runs).toHaveLength(0);
+ expect(fake.allFileFetches()).toHaveLength(0);
// Even a rejected type teaches the bridge where the user is.
expect(t.deps.messagingRepo.find(SID, "feishu")?.lastChatId).toBe("oc_chat_1");
});
@@ -1630,6 +1672,177 @@ describe("messaging binding routes and bridge", () => {
expect(runs).toHaveLength(1);
});
+ // —— Inbound files ————————————————————————————————————————————————————————
+ // A document sent to the bot has to reach the model the way the web composer's uploads
+ // do: written into the Session scratchpad and named on the message text as an
+ // `[attached file: <path>]` line, so the bytes never enter the conversation. The download
+ // is lazy for the same reason an image's is (a redelivery is dropped before it happens)
+ // and capped by the server's per-file attachment limit.
+
+ /** The absolute path an `[attached file: …]` line names, or null when the text is not one. */
+ const attachedFilePath = (part: InputPayload | undefined): string | null =>
+ matchAttachedFileLine((part?.text ?? "").trim());
+
+ it("an inbound file lands in the Session scratchpad and rides as a path line", async () => {
+ await bindEnabled(SID);
+ await fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_1",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_abc", file_name: "notes.pdf" }),
+ });
+ await waitFor(() => runs.length === 1);
+ // File only: a Feishu file message carries no caption, so the path line IS the message
+ // (core's shared placement rule turns attachments-only input into a line-only text
+ // message) — and the bytes are on disk, not in the conversation.
+ expect(runs[0]).toHaveLength(1);
+ expect(runs[0]![0]!.type).toBe("text");
+ expect(runs[0]![0]!.role).toBe("user");
+ const written = attachedFilePath(runs[0]![0]);
+ expect(written).not.toBeNull();
+ expect(path.basename(written!)).toBe("notes.pdf");
+ // Under this Session's own scratchpad, which is deleted along with the Session.
+ // The line carries the MODEL-VISIBLE spelling of the path, not the native one: core runs
+ // every path it composes for the model through `modelVisiblePath`, which on Windows swaps
+ // the separators for forward slashes (they survive JSON escaping into tool arguments, Git
+ // Bash runs them, and Node's fs accepts them). The expected side therefore has to go
+ // through the same transform — a bare `path.join` matches everywhere except Windows,
+ // where the two differ by nothing but the separator.
+ expect(path.dirname(written!)).toBe(
+ modelVisiblePath(path.join(scratchpadDir(t.root, projectId, "default_agent"), SID)),
+ );
+ // And the shape itself, which is the whole point of the transform: nothing in the line a
+ // model would have to escape. Vacuous on POSIX, load-bearing on Windows.
+ expect(written).not.toContain("\\");
+ expect((await fs.readFile(written!)).equals(FILE_BYTES)).toBe(true);
+ // Downloaded from the message that carried it, under the server's per-file attachment
+ // cap — the same number an authenticated composer upload answers to.
+ expect(fake.allFileFetches()).toEqual([
+ {
+ messageId: "om_file_1",
+ fileKey: "file_v3_abc",
+ maxBytes: toAttachmentLimits(t.deps.serverSettingsRepo.getAttachmentLimitsMb()).maxBytes,
+ },
+ ]);
+ // Nothing about the file is announced back to the chat; the reply mirrors as usual.
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allTexts().map((s) => s.text)).toEqual(["Reply text"]);
+ });
+
+ it("a file over the per-file cap says so by name, with the limit, and is not an error record", async () => {
+ await bindEnabled(SID);
+ const limits = toAttachmentLimits(t.deps.serverSettingsRepo.getAttachmentLimitsMb());
+ fake.fileBytes = Buffer.alloc(limits.maxBytes + 1, 0x41);
+ await fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_big",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_huge", file_name: "dump.bin" }),
+ });
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allTexts().at(-1)!.text).toBe(
+ messagingInboundFileTooLargeNotice("dump.bin", limits.maxBytes),
+ );
+ // The name is in the notice: a message may carry several, and "that file" leaves the
+ // sender guessing which one to shrink.
+ expect(fake.allTexts().at(-1)!.text).toContain("dump.bin");
+ // Nobody's fault: the chat notice is the whole report, and the error log stays clean.
+ expect(fileFetchErrors()).toHaveLength(0);
+ expect(runs).toHaveLength(0);
+ });
+
+ it("a file the channel will not hand over reports the channel's OWN reason", async () => {
+ await bindEnabled(SID);
+ fake.failFileFetch = "Access denied. app has no permission to access resource (code 99991672)";
+ await fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_gone",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_gone", file_name: "notes.pdf" }),
+ });
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allTexts().at(-1)!.text).toBe(
+ messagingInboundFileFailedNotice(
+ "notes.pdf",
+ "Access denied. app has no permission to access resource (code 99991672)",
+ ),
+ );
+ // A failure is somebody's fault and belongs in the error log too, with the channel's
+ // reason, so it is diagnosable from the dashboard and not only from a chat bubble.
+ const recorded = fileFetchErrors();
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0]).toContain("no permission to access resource");
+ expect(runs).toHaveLength(0);
+ });
+
+ it("a file the app has no permission to download says which scope to grant, and where", async () => {
+ await bindEnabled(SID);
+ // Feishu permissions resources per SCOPE, not per resource type, so the app refused an
+ // inbound image is refused an inbound file by the same denial — and the fix is the same
+ // console link.
+ fake.failFileFetchWith = new MessagingPermissionError(
+ ["im:resource"],
+ "https://open.feishu.cn/app/cli_x/auth?q=im:resource",
+ "Access denied (code 99991672)",
+ );
+ await fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_scope",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_denied", file_name: "report.xlsx" }),
+ });
+ await waitFor(() => fake.allSends().length > 0);
+ expect(fake.allTexts().at(-1)!.text).toBe(
+ messagingInboundFilePermissionNotice(
+ "report.xlsx",
+ ["im:resource"],
+ "https://open.feishu.cn/app/cli_x/auth?q=im:resource",
+ ),
+ );
+ expect(fileFetchErrors()).toHaveLength(1);
+ expect(runs).toHaveLength(0);
+ });
+
+ it("a redelivered file is dropped before anything is downloaded", async () => {
+ await bindEnabled(SID);
+ const file = {
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_replay",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_replay", file_name: "notes.pdf" }),
+ };
+ await fake.lastConnection().fire(file);
+ await waitFor(() => runs.length === 1);
+ await fake.lastConnection().fire(file);
+ await settle(80);
+ // The whole point of a lazy handle: the replay costs no transfer, and writes no second
+ // copy into the scratchpad.
+ expect(fake.allFileFetches()).toHaveLength(1);
+ expect(runs).toHaveLength(1);
+ const dir = path.join(scratchpadDir(t.root, projectId, "default_agent"), SID);
+ expect(await fs.readdir(dir)).toEqual(["notes.pdf"]);
+ });
+
+ it("an event whose file has no name still attaches, under an obvious placeholder", async () => {
+ await bindEnabled(SID);
+ // Feishu names the file in the event; an event that carries none gets a placeholder
+ // rather than an invented extension, which would tell the model it is something it is not.
+ await fake.lastConnection().fire({
+ chatId: "oc_chat_1",
+ chatType: "p2p",
+ messageId: "om_file_noname",
+ messageType: "file",
+ content: JSON.stringify({ file_key: "file_v3_noname" }),
+ });
+ await waitFor(() => runs.length === 1);
+ expect(path.basename(attachedFilePath(runs[0]![0])!)).toBe("file");
+ });
+
it("an approval_request sends the waiting-for-approval notice", async () => {
const row2 = sessionRowOf(SID2, projectId);
row2.approvalMode = "always-ask";
@@ -1801,7 +2014,7 @@ describe("messaging binding routes and bridge", () => {
messageType: "sticker",
content: JSON.stringify({}),
});
- await waitFor(() => fake.allTexts().some((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE));
+ await waitFor(() => fake.allTexts().some((x) => x.text === MESSAGING_UNSUPPORTED_NOTICE));
const status = await statusOf(SID);
// The question this line answers is whether the channel is delivering anything, and a
// sticker answers it. Stamping only what starts a Task would report a mute bot for a
@@ -2010,7 +2223,7 @@ describe("messaging binding routes and bridge", () => {
await waitFor(() => runs.length === 1);
expect(runs[0]![0]!.text).toBe("帮我看看 build 好了没 🚀");
// The run's own reply mirrors back; what must NOT appear is the no-words notice.
- expect(fake.allTexts().some((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toBe(false);
+ expect(fake.allTexts().some((x) => x.text === MESSAGING_UNSUPPORTED_NOTICE)).toBe(false);
});
it("a message that is nothing but a mention starts no Task", async () => {
@@ -2025,7 +2238,7 @@ describe("messaging binding routes and bridge", () => {
// Nothing but the mention: no words to run a Task on, so it takes the same branch a
// sticker does rather than spending a turn on a bare placeholder.
await waitFor(() => fake.allSends().length === 1);
- expect(fake.allTexts()[0]!.text).toBe(MESSAGING_TEXT_ONLY_NOTICE);
+ expect(fake.allTexts()[0]!.text).toBe(MESSAGING_UNSUPPORTED_NOTICE);
expect(runs).toHaveLength(0);
});
@@ -2143,6 +2356,13 @@ describe("messaging binding routes and bridge", () => {
.all()
.map((r) => r.message as string);
+ /** The same, for the file-download failures (a distinct code, so the two are separable). */
+ const fileFetchErrors = (): string[] =>
+ t.deps.db
+ .prepare("SELECT message FROM error_records WHERE code = 'messaging_file_fetch_failed'")
+ .all()
+ .map((r) => r.message as string);
+
/** How the messaging failures recorded so far were classified, newest last (see error-kind.ts). */
const messagingErrorKinds = (): Array<{ code: string; kind: string }> =>
t.deps.db
@@ -2515,7 +2735,7 @@ describe("messaging binding routes and bridge", () => {
await waitFor(() => fake.allSends().length === 1);
await fake.lastConnection().fire(sticker);
await settle(80);
- expect(fake.allTexts().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toHaveLength(1);
+ expect(fake.allTexts().filter((x) => x.text === MESSAGING_UNSUPPORTED_NOTICE)).toHaveLength(1);
});
it("bounds what it remembers: an id far enough back is forgotten rather than kept forever", async () => {
@@ -2625,11 +2845,13 @@ describe("messaging binding routes and bridge", () => {
await successor.start();
await fake.lastConnection().fire(sticker);
await settle(80);
- expect(fake.allTexts().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toHaveLength(1);
+ expect(fake.allTexts().filter((x) => x.text === MESSAGING_UNSUPPORTED_NOTICE)).toHaveLength(
+ 1,
+ );
// Control: a sticker the binding has never seen still gets its notice.
await fake.lastConnection().fire({ ...sticker, messageId: "om_sticker_after_restart" });
await waitFor(
- () => fake.allTexts().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE).length === 2,
+ () => fake.allTexts().filter((x) => x.text === MESSAGING_UNSUPPORTED_NOTICE).length === 2,
);
} finally {
successor.stop();
@@ -2841,3 +3063,234 @@ describe("a redelivered inbound message", () => {
expect(t.deps.messaging.statusOf(SID, "feishu").lastInboundAt).toBe("2026-08-26T09:01:00.000Z");
});
});
+
+/**
+ * The bridge's own loop over a message's file list, driven by a connector that hands it
+ * exactly the message a test constructs.
+ *
+ * It is a fake at the bridge's seam rather than at a wire, deliberately and narrowly:
+ * neither channel here delivers two files in ONE message — a Feishu `file` message carries
+ * one `file_key`, and a Telegram media group arrives as one update per document — while the
+ * seam carries a LIST, because the image seam does and a batching channel is the obvious
+ * next one. What no wire can produce is therefore what this drives: the order several
+ * attachments reach the Agent in, how they compose with a caption and an image, the
+ * per-message byte budget spent across them, and what a message whose files were written
+ * hands back when the follow-up it queued as is withdrawn again. Everything a real wire CAN
+ * produce is tested against the real wire, in the two channel suites.
+ */
+describe("a message carrying several files", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let bridge: MessagingBridge;
+ let runs: InputPayload[][];
+ let fired: ((msg: MessagingInboundMessage) => Promise<void>) | null;
+ /** Every cap the bridge asked a file handle to download under, in order. */
+ let caps: number[];
+ /** Every notice the scripted client was asked to send, in order. */
+ let notices: string[];
+ /** Set by a test that needs the Session BUSY: its run parks until `release` is called. */
+ let park: boolean;
+ let release: (() => void) | null;
+
+ /** Small enough to overrun with a few bytes: the real defaults are 100MB and 120MB. */
+ const LIMITS = { maxBytes: 40, totalBytes: 60, maxCount: 20 };
+
+ /** One file handle over fixed bytes, recording the cap it was offered. */
+ const fileOf = (fileName: string, bytes: Buffer): MessagingInboundFile => ({
+ fileName,
+ fetch: async (maxBytes) => {
+ caps.push(maxBytes);
+ return collectUnderCap(oneChunk(bytes), maxBytes, "The file");
+ },
+ });
+
+ const imageOf = (bytes: Buffer): MessagingInboundImage => ({
+ fetch: async (maxBytes) => ({
+ data: await collectUnderCap(oneChunk(bytes), maxBytes, "The image"),
+ mimeType: "image/png",
+ }),
+ });
+
+ /** The scripted connector: `fired` is how a test delivers one inbound message. */
+ const connector: MessagingChannelConnector = {
+ channel: "feishu",
+ createClient: () =>
+ Promise.resolve({
+ checkCredentials: () => Promise.resolve(null),
+ sendText: (_chatId: string, text: string) => {
+ notices.push(text);
+ return Promise.resolve();
+ },
+ replyText: (_messageId: string, text: string) => {
+ notices.push(text);
+ return Promise.resolve();
+ },
+ sendImage: () => Promise.resolve(),
+ sendFile: () => Promise.resolve(),
+ }),
+ connect: (_config, handlers) => {
+ fired = async (msg) => {
+ await handlers.onMessage(msg);
+ };
+ handlers.onReady?.();
+ return Promise.resolve({ close: () => {} });
+ },
+ };
+
+ /** Deliver one inbound message, with whatever mix of text, images and files it carries. */
+ const fire = (msg: Partial<MessagingInboundMessage> & { messageId: string }) =>
+ fired!({ chatId: "oc_scripted", chatKind: "direct", text: null, ...msg });
+
+ /** echoFakeSession, but parking for as long as a test holds it. */
+ const heldEchoSession = (): RuntimeSession => ({
+ sessionId: SID,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run(input: OmniMessage[]) {
+ runs.push(input.map((m) => m.payload as InputPayload));
+ if (park) await new Promise<void>((resolve) => (release = resolve));
+ yield assistantText("Reply text");
+ },
+ async *compact() {},
+ });
+
+ beforeEach(async () => {
+ caps = [];
+ notices = [];
+ fired = null;
+ park = false;
+ release = null;
+ runs = [];
+ t = await createTestApp({ feishuSdk: new FakeSdk() });
+ const { cookie } = await provisionUser(t.app, "birder");
+ api = apiClient(t.app, cookie);
+ const row = sessionRowOf(SID, "birder-default_project");
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, heldEchoSession());
+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);
+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);
+ // The app's own bridge holds the same binding through the real connector; only one of
+ // the two may own it.
+ t.deps.messaging.stop();
+ bridge = new MessagingBridge({
+ repo: t.deps.messagingRepo,
+ sessions: t.deps.sessionsRepo,
+ files: t.deps.workspaceFiles,
+ root: t.root,
+ attachmentLimits: () => LIMITS,
+ channels: t.deps.channels,
+ runner: t.deps.manager,
+ connectors: [connector],
+ errors: t.deps.errors,
+ });
+ await bridge.start();
+ });
+ afterEach(async () => {
+ release?.();
+ bridge.stop();
+ await t.cleanup();
+ });
+
+ /** The one text part of a run's input (the path lines ride it). */
+ const textOf = (run: InputPayload[]): string => run.find((p) => p.type === "text")!.text!;
+
+ it("attaches every file of one message, in the order they were sent", async () => {
+ await fire({
+ messageId: "om_many",
+ files: [
+ fileOf("first.txt", Buffer.from("a")),
+ fileOf("second.txt", Buffer.from("bb")),
+ fileOf("third.txt", Buffer.from("ccc")),
+ ],
+ });
+ await waitFor(() => runs.length === 1);
+ // One line per file, in the order the user sees them, as one trailing block on a
+ // message that had no text of its own.
+ const lines = textOf(runs[0]!).split("\n");
+ expect(lines.map((line) => path.basename(matchAttachedFileLine(line)!))).toEqual([
+ "first.txt",
+ "second.txt",
+ "third.txt",
+ ]);
+ for (const [i, bytes] of ["a", "bb", "ccc"].entries()) {
+ expect((await fs.readFile(matchAttachedFileLine(lines[i]!)!)).toString()).toBe(bytes);
+ }
+ // Each file rides in under the per-file ceiling while the message's remaining budget is
+ // still above it (60, then 59, then 57 bytes left against a 40-byte cap) — the shrink
+ // only bites once the batch approaches the total, which the overrun test drives.
+ expect(caps).toEqual([40, 40, 40]);
+ });
+
+ it("composes text, an image and a file into the one input the composer submits", async () => {
+ await fire({
+ messageId: "om_mixed",
+ text: "what is in these?",
+ images: [imageOf(IMAGE_BYTES)],
+ files: [fileOf("notes.txt", Buffer.from("n"))],
+ });
+ await waitFor(() => runs.length === 1);
+ // Text first, then the image part — and the file's line on the text, where core's
+ // shared placement rule puts a composer upload's.
+ expect(runs[0]!.map((p) => p.type)).toEqual(["text", "image_url"]);
+ expect(textOf(runs[0]!).startsWith("what is in these?\n\n[attached file: ")).toBe(true);
+ expect(runs[0]![1]!.image_url).toBe(`data:image/png;base64,${IMAGE_BYTES.toString("base64")}`);
+ });
+
+ it("hands a queued message's files back when the follow-up is withdrawn", async () => {
+ // A file that arrives while the Session is busy is written before its Task is queued, so
+ // the queued entry is the only thing that knows where the bytes landed. Withdrawing it in
+ // the Web App has to return them as chips and delete the copies; a store derived from the
+ // input instead would hand the composer a raw `[attached file: <scratchpad path>]` line
+ // back, lose the file, and strand it on disk.
+ park = true;
+ await fire({ messageId: "om_busy", text: "start something long" });
+ await waitFor(() => runs.length === 1);
+ await fire({
+ messageId: "om_queued",
+ text: "look at this",
+ files: [fileOf("notes.txt", Buffer.from("hi"))],
+ });
+ await waitFor(() => t.deps.manager.pendingFollowUpCount(SID) === 1);
+ const pending = t.deps.manager.pendingFollowUpsOf(SID);
+ expect(pending[0]).toMatchObject({ text: "look at this", images: 0, files: 1 });
+
+ const res = await api.delete(`/api/sessions/${SID}/follow-ups/${pending[0]!.id}`);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({
+ text: "look at this",
+ images: [],
+ // No media type rides an inbound file, so the recall re-encodes it as the generic one.
+ files: [{ fileName: "notes.txt", dataUrl: "data:application/octet-stream;base64,aGk=" }],
+ });
+ // Nothing references the scratchpad copy any more: leaving it would strand a second copy
+ // the moment the user resends what came back.
+ const dir = path.join(scratchpadDir(t.root, "birder-default_project", "default_agent"), SID);
+ expect(await fs.readdir(dir)).toEqual([]);
+ });
+
+ it("refuses a batch that adds up past the per-message total, naming no file", async () => {
+ await fire({
+ messageId: "om_overrun",
+ files: [
+ fileOf("big.bin", Buffer.alloc(35, 0x41)),
+ fileOf("also-big.bin", Buffer.alloc(35, 0x42)),
+ ],
+ });
+ await waitFor(() => notices.length > 0);
+ // The second file crosses what is left of the message's budget, so the batch is
+ // refused as a batch: no single file is at fault, and naming one would send the sender
+ // to shrink a file that was never too big.
+ expect(notices).toEqual([messagingInboundFilesTooLargeNotice(LIMITS.totalBytes)]);
+ expect(notices[0]).not.toContain("also-big.bin");
+ // Refused at the byte that crossed, under the remaining budget rather than the
+ // per-file cap — the transfer is never completed and measured afterwards.
+ expect(caps).toEqual([40, 25]);
+ // All-or-nothing: the file that did arrive starts no Task and leaves nothing behind.
+ expect(runs).toHaveLength(0);
+ const dir = path.join(scratchpadDir(t.root, "birder-default_project", "default_agent"), SID);
+ await expect(fs.readdir(dir)).rejects.toThrow();
+ });
+});