A local-first multi-agent app development platform, built on PenguinHarness
fix(server): outbound files a channel cannot take are recorded in the cost center, not posted into the chat (#776)
Yaowei Zheng0bf1ed1bed48
diff --git a/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.md b/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.mdnew file mode 100644index 00000000..0af565f5--- /dev/null+++ b/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.md@@ -0,0 +1,39 @@+# Outbound files a channel cannot take are recorded in the Cost Center, not posted into the chat++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `server`, `docs`+- **PR:** [#776](https://github.com/Prism-Shadow/penguin-harness/pull/776)++[中文版](2026-09-17-messaging-outbound-file-errors.zh.md)++A reply's file that did not reach a messaging chat — on Feishu, Telegram, QQ or WeChat — no longer+brings a bilingual notice into the chat after the reply, such as the `"xx.md" could not be sent to+the chat` QQ answered with for every file it cannot take. These failures are filed as error records+under the Session's Project instead, one per reply for each cause, and show in the Cost Center's+errors table. The notices for inbound images and files that could not be downloaded, and the+approval reminder, still go to the chat.++## Details++- Four outbound notices were removed: a failed upload, an upload the bot's app lacks a permission+ for, a file over the 10MB-per-picture or 30MB-per-file ceiling, and the files past the 5 that ride+ along with one reply.+- A reply files one record per cause, naming every file it covers, the channel and the reason — one+ line per file when their reasons differ: `messaging_file_send_failed` for refused uploads, in+ separate records for uploads the channel can never carry, a missing permission (the scopes and the+ console link listed once, in place of the channel's reason for each file) and any other refusal;+ the new `messaging_file_too_large` for the files over a ceiling, each with its limit; and the new+ `messaging_files_skipped` for the files past the count. A lone file reads+ `"<file>" was not sent to the <channel> chat: <reason>`. Every message, the skipped files' record+ included, is kept under the recorder's 500-character cap by shortening its file list first, down+ to `…`.+- QQ's refusal of an outbound file no longer names the file, so a reply's refused files share one+ reason line: `QQ cannot receive files: sending a file to QQ requires a publicly reachable URL for+ it, which this server has no way to provide`.+- Kinds: the files over a ceiling, the skipped files and the uploads a channel can never carry (any+ file on QQ) are `expected`; a missing permission on an upload and every other refused upload are+ `unexpected`, since nobody in the chat is handed the fix any more. Records already written keep+ their kind.+- On QQ, a refused file no longer spends a passive-reply slot on a notice.+- The Server API reference states where these cases are recorded, in both languages.diff --git a/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.zh.md b/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.zh.mdnew file mode 100644index 00000000..2295e391--- /dev/null+++ b/changelog/unreleased/2026-09-17-messaging-outbound-file-errors.zh.md@@ -0,0 +1,30 @@+# 渠道收不下的出站文件改记入成本中心,不再发进聊天++- **Date:** 2026-09-17+- **Type:** fix+- **Scope:** `server`, `docs`+- **PR:** [#776](https://github.com/Prism-Shadow/penguin-harness/pull/776)++[English](2026-09-17-messaging-outbound-file-errors.md)++回复中提及的文件没能送达消息聊天(飞书、Telegram、QQ 或微信)时,聊天里不再在回复之后出现一条双语提示——+例如 QQ 对每个它收不下的文件都会发出的「文件“xx.md”未能发送到会话」。这些失败改为在该 Session 所属的+Project 下记为错误记录,每条回复按原因各记一条,显示在成本中心的异常表中。入站图片与文件下载失败的提示、+以及审批提醒,仍照常发到聊天里。++## 细节++- 移除了四种出站提示:上传失败、机器人应用缺少上传权限、文件超过单张图片 10MB 或单个文件 30MB 的上限、+ 超出每条回复随附 5 个文件的部分。+- 每条回复按原因各记一条错误记录,写明其涵盖的每个文件、渠道与原因——各文件原因不同时每个文件占一行:+ 被拒绝的上传记 `messaging_file_send_failed`,渠道根本无法承载的上传、缺少权限(所需权限与控制台授权链接+ 只列一次,取代渠道对每个文件给出的原因)与其余拒绝各记一条;超过上限的文件记新增的+ `messaging_file_too_large`,逐个写明其上限;超出数量的部分记新增的 `messaging_files_skipped`。单个文件的+ 记录写作 `"<file>" was not sent to the <channel> chat: <reason>`。每条消息(包括超出数量的那条)都控制在+ 记录器 500 字符的上限之内,超出时先截短文件列表,截去的部分以 `…` 标明。+- QQ 拒绝外发文件时的原因不再点名文件,于是同一条回复里被拒的文件共用一行原因:`QQ cannot receive files:+ sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide`。+- 类型:超过上限的文件、超出数量的文件、以及渠道根本无法承载的上传(QQ 上的任何文件)记为 `expected`;+ 缺少上传权限与其余被拒的上传记为 `unexpected`,因为聊天里已不再有人拿到解决办法。已写入的记录保持原有类型。+- 在 QQ 上,被拒的文件不再为一条提示占用一次被动回复额度。+- 服务端 API 参考的中英两份都写明了这些情况记在哪里。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 9a81eac8..ca4b8bf8 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -461,7 +461,7 @@ A Session can be connected to a messaging bot — Feishu, Telegram, QQ and WeCha| POST | /messaging/wechat/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its handle is forgotten now rather than at the sweep || POST | /messaging/wechat/test-message | Send a short fixed text to the last known chat; 409 `wechat_no_chat` until the bot has been messaged once in WeChat |-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three 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. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows); WeChat reads Markdown itself, so rendering SUBTRACTS rather than translates — what the client will not show keeps its words and loses its markers (headings past the fourth level, emphasis around CJK, and inline images, which become links). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. 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), and WeChat's is the bot id the scan returns. 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 on those two channels — 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. WeChat is the exception, and only because the platform does the work itself: it ships its own transcription with a voice message, and a video arrives as an ordinary file. 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.+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three 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. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows); WeChat reads Markdown itself, so rendering SUBTRACTS rather than translates — what the client will not show keeps its words and loses its markers (headings past the fourth level, emphasis around CJK, and inline images, which become links). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. 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), and WeChat's is the bot id the scan returns. 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 on those two channels — 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. WeChat is the exception, and only because the platform does the work itself: it ships its own transcription with a voice message, and a video arrives as an ordinary file. 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). None of the ways a mentioned file does not arrive is posted in the chat. They are filed as error records under the Project, where the Cost Center's errors table shows them, one record per reply for each cause, naming every file it covers, the channel and the reason: `messaging_file_too_large` for the files over a cap, `messaging_files_skipped` for those past the count cap, and `messaging_file_send_failed` for uploads that were refused — one record for uploads the channel can never carry (any file on QQ), one for a missing permission (the scopes to grant and the console link listed once, in place of the channel's reason for each file) and one for any other refusal. The first two and the uploads a channel can never carry are `expected`; a missing permission and every other refusal are `unexpected`. A name that matches no file in the Workspace is only logged, and a file the run did not write 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, and a `renderMarkdown` send the platform refuses spends a second slot on its plain-text retry. `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.**WeChat carries direct chats only, and the most media of the four.** The claw bot channel has no group inbound at all: a message addressed to the bot in a group never reaches this API, so a binding that answers a direct chat perfectly is silent in a group by design rather than by misconfiguration. In exchange it is the only channel here that carries text, images and files in BOTH directions — a reply's pictures and attachments are uploaded to the platform's CDN (AES-128-ECB under a per-file key) and arrive as real images and files rather than being refused. Two inbound kinds are folded: a voice message is relayed as WeChat's own transcription of it, and a video arrives as a file; a recording the platform could not transcribe reaches the chat as the shared not-supported notice.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 2246a924..f46e195d 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -460,7 +460,7 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr| POST | /messaging/wechat/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其句柄,而不是等待过期清扫 || POST | /messaging/wechat/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在微信里给机器人发过消息之前返回 409 `wechat_no_chat` |-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出);微信自己就读 Markdown,因此渲染是**做减法**而不是翻译——客户端不会呈现的部分保留文字、去掉标记(四级以上的标题、CJK 两侧的强调,以及内联图片,后者改为链接)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变),微信则是扫码返回的机器人 id。读取与两个测试接口对任意 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` 且毫无报错。+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出);微信自己就读 Markdown,因此渲染是**做减法**而不是翻译——客户端不会呈现的部分保留文字、去掉标记(四级以上的标题、CJK 两侧的强调,以及内联图片,后者改为链接)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变),微信则是扫码返回的机器人 id。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。在这两个渠道上,视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。微信是例外,且仅仅因为解码由平台自己完成:语音消息随附它自己的转写文本,视频则作为普通文件到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件没送到时,聊天里不会出现任何说明。它们记为该 Project 下的错误记录,显示在成本中心的异常表中:每条回复按原因各记一条,写明其涵盖的每个文件、渠道与原因——超过上限的文件记 `messaging_file_too_large`,超出数量上限的记 `messaging_files_skipped`,被拒绝的上传记 `messaging_file_send_failed`,其中渠道根本无法承载的上传(QQ 上的任何文件)、缺少权限(所需权限与控制台授权链接只列一次,取代渠道对每个文件给出的原因)与其余拒绝各记一条。前两种与渠道无法承载的上传记为 `expected`;缺少权限与其余拒绝记为 `unexpected`。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;被平台拒绝的 `renderMarkdown` 发送,其纯文本重试会再占用一次额度。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。**微信只承载单聊,但媒体能力是四个渠道里最全的。** 该机器人渠道完全不接收群消息:在群里 @机器人的消息根本不会到达本 API,因此单聊正常、群聊沉默是渠道形态而非配置错误。作为交换,它是这里唯一能**双向**传输文字、图片与文件的渠道——回复中的图片与附件会上传到平台 CDN(每个文件一把 AES-128-ECB 密钥),以真正的图片和文件到达,而不是被拒绝。两类入站消息被折叠处理:语音消息按微信自带的语音转文字结果进入对话,视频按文件到达;微信没能转写的语音则以共用的「不支持」提示回到聊天。diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex 1ee3d45e..d5b66b65 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -67,8 +67,10 @@* reply-files.ts): path-like tokens that resolve inside the Workspace and actually exist,* pictures sent as pictures and everything else as attachments. Not "every file the run* wrote": the Agent's own words are what say which output was the point, and a chat window- * is a bad place to receive a directory. What the caps drop is named in the chat rather- * than dropped quietly.+ * is a bad place to receive a directory. What the caps drop and what the channel refuses is+ * filed as error records under the Session's Project, one per cause for the whole reply,+ * rather than dropped quietly, and none of it is posted into the chat (see+ * messagingFilesNotSentRecords).*/import { imageUrlMessage, scratchpadDir, userText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";@@ -79,6 +81,7 @@ 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 { MESSAGE_MAX } from "../error-recorder.js";import type { ErrorSink } from "../error-recorder.js";import { recallStoreOf } from "../session-manager.js";import type { RecallStore } from "../session-manager.js";@@ -92,7 +95,13 @@ import type {} from "./connector.js";import { messagingErrorKind } from "./error-kind.js";import { chunkMarkdown } from "./markdown.js";-import { MessagingMediaTooLargeError, MessagingPermissionError, isImageFileName } from "./media.js";+import {+ MessagingMediaTooLargeError,+ MessagingOutboundCapError,+ MessagingPermissionError,+ MessagingUnsupportedError,+ isImageFileName,+} from "./media.js";import { replyFileMentions } from "./reply-files.js";import { Component, Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";import type { Slot, ClassCtx } from "@prismshadow/penguin-core/kernel";@@ -297,8 +306,8 @@ export const MESSAGING_TEST_MESSAGE =** The count is not anyone's API limit but a judgement about the medium: a reply naming more* than a handful of files is reporting on work rather than delivering it, and a chat is the- * wrong place to receive twenty attachments. The remainder is counted in a notice, never- * silently dropped — the Web App still has all of them.+ * wrong place to receive twenty attachments. The remainder is counted in an error record+ * (`messaging_files_skipped`), never silently dropped — the Web App still has all of them.*/export const MESSAGING_OUTBOUND_IMAGE_MAX_BYTES = 10 * 1024 * 1024;export const MESSAGING_OUTBOUND_FILE_MAX_BYTES = 30 * 1024 * 1024;@@ -314,33 +323,240 @@ export const MESSAGING_OUTBOUND_FILE_MAX_COUNT = 5;*/const MESSAGING_OUTBOUND_MTIME_GRACE_MS = 2_000;-/** One file a ceiling refused, named so the user knows which one to go and fetch. */-export function messagingFileTooLargeNotice(fileName: string, maxBytes: number): string {- const mb = Math.floor(maxBytes / (1024 * 1024));- return `"${fileName}" is over this channel's ${mb}MB limit and was not sent. 文件“${fileName}”超过该渠道 ${mb}MB 的上限,未发送。`;+/** A mentioned file's name: the tail of `rel`, which is always "/"-joined (toWorkspaceRelative). */+function baseNameOf(rel: string): string {+ return rel.slice(rel.lastIndexOf("/") + 1);+}++/** A mentioned file held back at an outbound ceiling, and the ceiling (see deliverOneFile). */+export interface OversizeOutboundFile {+ fileName: string;+ maxBytes: number;+ asImage: boolean;+}++/** A mentioned file the read or the channel refused, and what was thrown. */+export interface RefusedOutboundFile {+ fileName: string;+ err: unknown;+}++/** One error record to file: the capture point's code and the error it carries. */+export interface MessagingErrorRecord {+ code: string;+ err: Error;}/**- * One file the channel would not take, with its own reason.+ * The error records for the files of one reply that did not go out: ONE per cause, naming every+ * file that cause held back — never one per file.+ *+ * Per reply rather than per file because the recorder keeps a single record per code and+ * Project inside a two-second window (see error-recorder.ts), and a reply's files fail within+ * milliseconds of each other: filed one by one, five files QQ refused would surface as the+ * first alone. None of them is posted into the chat, so these records are the only place any+ * of it is said. The causes, in the order they are returned:*- * Every other way a file does not arrive is named in the chat — over the byte cap, past the- * count cap, an inbound refusal. A failed upload reached `error_records` and nothing else,- * which the person in the chat cannot open, so the feature simply looked broken.+ * - `messaging_file_send_failed`, in up to three records by what was thrown: a missing+ * permission (unexpected), any other refusal (unexpected), and a refusal the channel repeats+ * for every file (expected — any file on QQ), the one record that keeps the type thrown,+ * because error-kind.ts reads its kind off it. The permission record names the files, then+ * lists the scopes and console links once, and quotes nothing that was thrown: Feishu's+ * refusal carries the same scopes and link and ends in a log_id that is new on every request,+ * so quoting it would give each file its own line repeating the fix — and nobody needs a+ * log_id to grant a scope. The three share a code, so a reply failing for two of these+ * causes at once reaches the recorder's window twice and keeps only the first record: the+ * causes somebody has to act on are therefore the ones that come first.+ * - `messaging_file_too_large`, the files over an outbound ceiling, each with its limit+ * (expected).+ *+ * The files past the per-reply count are recorded apart from these (see filesSkippedError).*/-export function messagingFileFailedNotice(fileName: string, reason: string): string {- return `"${fileName}" could not be sent to the chat. 文件“${fileName}”未能发送到会话。(${noticeReason(reason)})`;+export function messagingFilesNotSentRecords(+ channel: string,+ oversize: readonly OversizeOutboundFile[],+ refused: readonly RefusedOutboundFile[],+): MessagingErrorRecord[] {+ const permission: Array<{ fileName: string; err: MessagingPermissionError }> = [];+ const other: RefusedOutboundFile[] = [];+ const unsupported: RefusedOutboundFile[] = [];+ for (const file of refused) {+ if (file.err instanceof MessagingPermissionError) {+ permission.push({ fileName: file.fileName, err: file.err });+ } else if (file.err instanceof MessagingUnsupportedError) {+ unsupported.push(file);+ } else {+ other.push(file);+ }+ }+ const records: MessagingErrorRecord[] = [];+ if (permission.length > 0) {+ const scopes = [...new Set(permission.flatMap((file) => file.err.scopes))];+ const grantUrls = [+ ...new Set(+ permission.flatMap((file) => (file.err.grantUrl === null ? [] : [file.err.grantUrl])),+ ),+ ];+ const fix = ["this bot's app is missing a permission.", scopes.join(", "), ...grantUrls].join(+ "\n",+ );+ records.push({+ code: "messaging_file_send_failed",+ err: new Error(+ filesNotSentMessage(+ channel,+ permission.map((file) => ({ fileName: file.fileName, reason: fix })),+ VERBATIM,+ ),+ ),+ });+ }+ if (other.length > 0) {+ records.push({+ code: "messaging_file_send_failed",+ err: new Error(filesNotSentMessage(channel, other.map(thrownReason), VERBATIM)),+ });+ }+ if (unsupported.length > 0) {+ records.push({+ code: "messaging_file_send_failed",+ err: new MessagingUnsupportedError(+ filesNotSentMessage(channel, unsupported.map(thrownReason), VERBATIM),+ ),+ });+ }+ if (oversize.length > 0) {+ const overLimit = oversize.map((file) => ({+ fileName: file.fileName,+ reason: `larger than the ${Math.floor(file.maxBytes / (1024 * 1024))}MB limit for ${file.asImage ? "a picture" : "a file"}`,+ }));+ records.push({+ code: "messaging_file_too_large",+ err: new MessagingOutboundCapError(filesNotSentMessage(channel, overLimit, OVER_LIMIT)),+ });+ }+ return records;}-/** One file this bot's app is not permitted to upload — the fixable half of the above. */-export function messagingFilePermissionNotice(- fileName: string,- scopes: readonly string[],- grantUrl: string | null,+/** One file's part in a record: its name, and why it did not go out. */+interface FileReason {+ fileName: string;+ reason: string;+}++/** A refused file's reason: what the read or the channel said. */+function thrownReason(file: { fileName: string; err: unknown }): FileReason {+ return {+ fileName: file.fileName,+ reason: file.err instanceof Error ? file.err.message : String(file.err),+ };+}++/** How a record's reason reads after a lone file's head, and as the one reason several files share. */+interface ReasonWording {+ lone(reason: string): string;+ shared(reason: string): string;+}++/** A reason that reads the same either way: a refusal as it was thrown, or a permission's fix. */+const VERBATIM: ReasonWording = { lone: (reason) => reason, shared: (reason) => reason };++/** A ceiling, which reads as a property of the file, or of each file, it held back. */+const OVER_LIMIT: ReasonWording = {+ lone: (reason) => `it is ${reason}`,+ shared: (reason) => `each is ${reason}`,+};++/**+ * The head of a record about one file: which file, and which channel it was going to.+ *+ * The record has to read on its own in the cost center's error table, where nothing else on the+ * row names the file or the channel. `channel` is the binding's discriminant, the same name the+ * bridge's log lines use.+ */+function fileNotSentHead(channel: string, fileName: string): string {+ return `"${fileName}" was not sent to the ${channel} chat`;+}++/**+ * The message of one record covering `files`, fitted under the recorder's MESSAGE_MAX.+ *+ * A lone file reads `"<file>" was not sent to the <channel> chat: <reason>`. Several read+ * `<n> files were not sent to the <channel> chat: "<a>", "<b>"`, then the reason they share —+ * or, when their reasons differ, one `"<file>": <reason>` line each.+ *+ * Fitted here rather than left to the recorder, which cuts from the end, where the reasons are.+ * The list of names gives way first, down to "…": a reason is worth more than the fifth name,+ * and a line per file names its own file anyway. Only then are the reasons cut, all of them+ * alike, so each keeps its file's name and the start of what went wrong.+ */+function filesNotSentMessage(+ channel: string,+ files: readonly FileReason[],+ wording: ReasonWording,): string {- return `"${fileName}" could not be sent: this bot's app is missing a permission. 文件“${fileName}”未能发送:机器人应用缺少所需权限。\n${permissionDetail(scopes, grantUrl)}`;+ const first = files[0]!;+ if (files.length === 1) {+ return clip(+ `${fileNotSentHead(channel, first.fileName)}: ${wording.lone(first.reason)}`,+ MESSAGE_MAX,+ );+ }+ const head = (list: string): string =>+ `${files.length} files were not sent to the ${channel} chat: ${list}`;+ const lines = files.every((file) => file.reason === first.reason)+ ? [wording.shared(first.reason)]+ : files.map((file) => `"${file.fileName}": ${file.reason}`);+ const body = `\n${lines.join("\n")}`;+ const names = files.map((file) => file.fileName);+ const listRoom = MESSAGE_MAX - head("").length - body.length;+ if (listRoom >= 1) return head(quotedNames(names, listRoom)) + body;+ // One "\n" goes in front of each line.+ const lineRoom = MESSAGE_MAX - head("…").length - lines.length;+ const fitted = fitLines(lines, lineRoom).map((line) => `\n${line}`);+ return clip(head("…") + fitted.join(""), MESSAGE_MAX);+}++/** The names quoted and joined, as many as fit in `max` characters, the rest marked "…". */+function quotedNames(names: readonly string[], max: number): string {+ const quoted = names.map((name) => `"${name}"`);+ const all = quoted.join(", ");+ if (all.length <= max) return all;+ let shown = "";+ for (const name of quoted) {+ const next = shown === "" ? name : `${shown}, ${name}`;+ if (next.length + ", …".length > max) break;+ shown = next;+ }+ return shown === "" ? "…" : `${shown}, …`;}-/** How many names one drop notice lists before it stops: a signal, not an inventory. */+/**+ * `lines` cut to share `room` characters alike: a line shorter than an equal share stays whole,+ * and what it leaves over goes to the longer ones.+ */+function fitLines(lines: readonly string[], room: number): string[] {+ const out = [...lines];+ const shortestFirst = lines.map((_, i) => i).sort((a, b) => lines[a]!.length - lines[b]!.length);+ let left = room;+ shortestFirst.forEach((index, done) => {+ out[index] = clip(lines[index]!, Math.floor(left / (shortestFirst.length - done)));+ left -= out[index]!.length;+ });+ return out;+}++/** `text` cut to at most `max` characters, the cut marked "…", never between a surrogate pair. */+function clip(text: string, max: number): string {+ if (text.length <= max) return text;+ if (max < 1) return "";+ let end = max - 1;+ const last = text.charCodeAt(end - 1);+ if (last >= 0xd800 && last <= 0xdbff) end -= 1;+ return `${text.slice(0, end)}…`;+}++/** How many names a line about dropped files lists before it stops: a signal, not an inventory. */const MESSAGING_NOTICE_NAMES_MAX = 5;/**@@ -354,9 +570,9 @@ const MESSAGING_NOTICE_NAMES_MAX = 5;* failed, and announcing them puts an error-shaped line under replies that were entirely* correct — with no move for the reader to make, because nothing was ever going to arrive.*- * Contrast `noteFileFailure`, which does reach the chat: there the file exists and its upload- * failed, so something the reply promised is genuinely missing and silence would read as the- * feature being broken.+ * Contrast messagingFilesNotSentRecords: there the files exist and did not go out, so something+ * the reply promised is genuinely missing, and that is filed as an error record under the+ * Session's Project. Neither reaches the chat.** Still recorded, because "it mentioned a file and I never got it" is a real question someone* will ask, and the server log answers it without charging every other reader for it.@@ -367,9 +583,24 @@ export function messagingFilesMissingLog(names: readonly string[]): string {return `[messaging] reply named files the Workspace does not have, nothing sent: ${list}`;}-/** The tail of a batch the count cap cut off. */-export function messagingFilesSkippedNotice(skipped: number): string {- return `${skipped} more mentioned file(s) were not sent — at most ${MESSAGING_OUTBOUND_FILE_MAX_COUNT} ride along with one reply. 另有 ${skipped} 个提及的文件未发送——每条回复最多附带 ${MESSAGING_OUTBOUND_FILE_MAX_COUNT} 个。`;+/**+ * The error record for the tail of a batch the count cap cut off — one per reply, however many+ * files it holds: how many, the cap, and which. The names are quoted like every other record's+ * and give way to "…" where the whole list would run past the recorder's MESSAGE_MAX, which+ * would otherwise cut it mid-name, closing bracket and all.+ */+function filesSkippedError(+ channel: string,+ fileNames: readonly string[],+): MessagingOutboundCapError {+ const n = fileNames.length;+ const files =+ n === 1 ? "1 more file the reply mentioned was" : `${n} more files the reply mentioned were`;+ const message = (list: string): string =>+ `${files} not sent to the ${channel} chat: at most ${MESSAGING_OUTBOUND_FILE_MAX_COUNT} ride along with one reply (${list})`;+ return new MessagingOutboundCapError(+ message(quotedNames(fileNames, MESSAGE_MAX - message("").length)),+ );}/**@@ -1041,11 +1272,12 @@ export class MessagingBridge {err,code,// Classified here rather than left to the recorder's default: its fallback for a- // non-HTTP source is `unexpected`, which files a scope the app was never granted and a- // file the platform cannot carry as defects. `code` goes in with the error because the- // same refusal means different things at different capture points — on an image- // download the chat is handed the fix, on a send it hears nothing at all, and only the- // first of those is routine (see error-kind.ts for the rule).+ // non-HTTP source is `unexpected`, which files an inbound image the app was never granted+ // the scope to download, and a file the platform cannot carry, as defects. `code` goes in+ // with the error because the same refusal means different things at different capture+ // points — on an image download the chat is handed the fix, on a send or an upload it+ // hears nothing at all, and only the first of those is routine (see error-kind.ts for+ // the rule).kind: messagingErrorKind(err, code),ctx: {sessionId,@@ -1693,9 +1925,12 @@ export class MessagingBridge {* A file the run did not write is dropped SILENTLY, and so is a name matching no file at* all: the rule reads prose, so a reply that mentions the config it read — or describes a* `hello-world.md` it never wrote — is the ordinary case, and announcing those puts an- * error-shaped line under correct answers. Both are logged instead. What IS named in the- * chat is a file that exists and whose upload failed: there the reply promised something- * that then did not arrive, which is the one case where silence reads as broken.+ * error-shaped line under correct answers. Both are logged instead. What IS recorded is a+ * file that exists and still did not go out — over a ceiling, past the count cap, or+ * refused on the way: the reply promised something that then did not arrive, so it is filed+ * under the Session's Project, once the batch is done, in one record per cause naming every+ * file it held back (see messagingFilesNotSentRecords). None of it is posted into the chat,+ * which carries the reply and its files and nothing about the ones that stayed behind.** Always plain sends, never a threaded reply: a run that mentions a file has by* definition already sent the text that mentions it, and that message took the group's@@ -1731,17 +1966,31 @@ export class MessagingBridge {}if (produced.length === 0 && missing.length === 0) return;const client = await this.clientFor(entry.sessionId, row);+ const oversize: OversizeOutboundFile[] = [];+ const refused: RefusedOutboundFile[] = [];for (const rel of produced.slice(0, MESSAGING_OUTBOUND_FILE_MAX_COUNT)) {try {- await this.deliverOneFile(client, chatId, session.workspace, rel);+ const heldBack = await this.deliverOneFile(client, chatId, session.workspace, rel);+ if (heldBack !== null) oversize.push(heldBack);} catch (err) {- this.recordError(entry.sessionId, err, "messaging_file_send_failed");- await this.noteFileFailure(client, chatId, rel, err);+ refused.push({ fileName: baseNameOf(rel), err });}}- const skipped = produced.length - MESSAGING_OUTBOUND_FILE_MAX_COUNT;- if (skipped > 0) {- await client.sendText(chatId, messagingFilesSkippedNotice(skipped));+ // Filed only once the batch is done, and one record per cause rather than per file: the+ // recorder would keep only the first of several same-code records filed this close+ // together (see messagingFilesNotSentRecords).+ for (const record of messagingFilesNotSentRecords(entry.channel, oversize, refused)) {+ this.recordError(entry.sessionId, record.err, record.code);+ }+ // One record for the whole tail, not one per file: the cap is a single decision about+ // this reply, and a row per file would read as that many separate failures.+ const skipped = produced.slice(MESSAGING_OUTBOUND_FILE_MAX_COUNT);+ if (skipped.length > 0) {+ this.recordError(+ entry.sessionId,+ filesSkippedError(entry.channel, skipped.map(baseNameOf)),+ "messaging_files_skipped",+ );}// Logged, never sent: a name in a reply is not a promise of a file (see// messagingFilesMissingLog).@@ -1752,43 +2001,17 @@ export class MessagingBridge {}/**- * Names one file that did not make it, in the chat.- *- * Every other way a file does not arrive is already visible there — over the byte cap,- * past the count cap, an inbound refusal. A failed upload reached `error_records` alone,- * which the person in the chat cannot open, so the feature just looked broken. A missing- * permission gets its own wording: it is the one failure they can fix themselves, in- * about ten seconds, given the scope name and the console link.- *- * Its own try/catch: a chat that will not take the notice must not take the rest of the- * batch down with it, and the upload failure behind it is already recorded.+ * One mirrored file: read under the outer ceiling, then sent as a picture or an attachment.+ * Resolves null once the file went out. A file over the ceiling for its kind is not sent and+ * resolves to that ceiling instead; a read or a send the channel refused throws. The caller+ * records both (see messagingFilesNotSentRecords).*/- private async noteFileFailure(- client: MessagingClient,- chatId: string,- rel: string,- err: unknown,- ): Promise<void> {- // `rel` is always "/"-joined (see toWorkspaceRelative), so its base name is its tail.- const fileName = rel.slice(rel.lastIndexOf("/") + 1);- const text =- err instanceof MessagingPermissionError- ? messagingFilePermissionNotice(fileName, err.scopes, err.grantUrl)- : messagingFileFailedNotice(fileName, err instanceof Error ? err.message : String(err));- try {- await client.sendText(chatId, text);- } catch {- // A channel that will not take the notice either is one problem, not two.- }- }-- /** One mirrored file: read under the outer ceiling, then sent as a picture or an attachment. */private async deliverOneFile(client: MessagingClient,chatId: string,workspace: string,rel: string,- ): Promise<void> {+ ): Promise<OversizeOutboundFile | null> {// Read first, classify second. `rel` is the path the REPLY spelled, and the canonical// file behind it may not share its extension: an in-Workspace `report.png -> report.pdf`// (the everyday "latest" symlink) classified by the mention would go to the image@@ -1803,13 +2026,11 @@ export class MessagingBridge {const maxBytes = asImage? MESSAGING_OUTBOUND_IMAGE_MAX_BYTES: MESSAGING_OUTBOUND_FILE_MAX_BYTES;- if (file.data.length > maxBytes) {- await client.sendText(chatId, messagingFileTooLargeNotice(file.fileName, maxBytes));- return;- }+ if (file.data.length > maxBytes) return { fileName: file.fileName, maxBytes, asImage };const outbound = { fileName: file.fileName, data: file.data };if (asImage) await client.sendImage(chatId, outbound);else await client.sendFile(chatId, outbound);+ return null;}/** One-line notice (approval waiting) to the last known chat; silent before one exists. */diff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.tsindex 1c57c55b..758f2d8d 100644--- a/packages/server/src/runtime/messaging/error-kind.ts+++ b/packages/server/src/runtime/messaging/error-kind.ts@@ -2,12 +2,13 @@* Which messaging failures need a human, and which are the system working as designed.** Every failure the bridge catches used to reach `error-recorder.ts` with no `kind`, and its- * default for a non-HTTP source is `unexpected` — so a Feishu app that has simply not been- * granted a scope yet, and a file QQ structurally cannot accept, both filed as "shouldn't- * happen, needs a human". They are neither. The recorder's own criterion is **"does a human- * need to step in"**, not "did something fail", and by that rule these are `expected`: they- * are anticipated, they have a defined handling path, and the path ends with the one person- * who can act already being told, in the chat, exactly what to do.+ * default for a non-HTTP source is `unexpected` — so an inbound picture a Feishu app had simply+ * not been granted the scope to download, and a file QQ structurally cannot accept, both filed+ * as "shouldn't happen, needs a human". They are neither. The recorder's own criterion is+ * **"does a human need to step in"**, not "did something fail", and by that rule a refusal is+ * `expected` when it is anticipated, has a defined handling path, and leaves nobody anything to+ * do: the one person who can act has already been told, in the chat, exactly what to do — or+ * there is nothing anyone could do at all.** That distinction is load-bearing rather than cosmetic. The cost center highlights unexpected* errors, so a channel that files its ordinary refusals there points that highlight at nothing@@ -16,11 +17,13 @@* It takes the capture point's `code` as well as the error, because the type alone cannot* answer the question: it says what went wrong, not whether anyone was told. Feishu throws the* SAME scope denial (code 99991672) from every call — the inbound image download, the outbound- * upload, and the plain text send — and only the first two are followed by a notice into the- * chat. On a text send there is nothing to be told with: the message that would carry the- * notice is the message being refused. An app granted "receive" but not `im:message:send_as_bot`- * then receives every question and answers none of them, silently, which is the worst state- * this feature has — and this record is the only place it surfaces.+ * upload, and the plain text send — and only the first is followed by a notice into the chat.+ * The other two tell the chat nothing: a reply's file that did not go out is said in its error+ * record and nowhere else, and on a text send there is nothing to be told with at all, because+ * the message that would carry the notice is the message being refused. An app granted+ * "receive" but not `im:message:send_as_bot` then receives every question and answers none of+ * them, silently, which is the worst state this feature has — and this record is the only place+ * it surfaces.** The rule is deliberately a small allowlist of TYPED failures at NAMED capture points rather* than a message match, plus one typed failure that arrives carrying its own verdict — a@@ -32,6 +35,7 @@import type { ErrorKind } from "../error-recorder.js";import {MessagingMediaTooLargeError,+ MessagingOutboundCapError,MessagingPermissionError,MessagingUnsupportedError,} from "./media.js";@@ -41,11 +45,10 @@ import { MessagingConnectionClosedError } from "./qq-api.js";* The capture points that put the refusal in front of the person in the chat.** `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.+ * chat it came from (see messagingImagePermissionNotice and its siblings). Every other code+ * fails with the chat hearing nothing at all — a reply that never went out, a reply's file that+ * did not (see ROUTINE_OUTBOUND_FILE_REFUSALS), an inbound message whose Task never started, a+ * connection that will not come up — so the dashboard is where it has to be noticed.** A Markdown send the channel refuses adds no code here, and that is deliberate. The* connector retries it as plain text (see the three renderers' fallback), so the ordinary@@ -58,49 +61,84 @@ import { MessagingConnectionClosedError } from "./qq-api.js";const CODES_EXPLAINED_IN_CHAT = new Set(["messaging_image_fetch_failed","messaging_file_fetch_failed",- "messaging_file_send_failed",+]);++/** A typed refusal's class, as `instanceof` takes it. */+type RefusalType = new (message: string) => Error;++/**+ * The outbound file capture points, each with the one type it files as routine.+ *+ * The chat is told nothing at any of them — a reply's files that did not go out are recorded and+ * never posted (see the bridge's messagingFilesNotSentRecords) — so `expected` here cannot mean+ * "the person who can act was told". It means nobody has anything to do:+ *+ * - `messaging_file_send_failed` + {@link MessagingUnsupportedError} — the channel structurally+ * cannot carry a file (QQ's rich-media path needs a publicly reachable URL this server does+ * not have). It will refuse the next one identically; there is no fault to chase and no fix+ * to deploy.+ * - `messaging_file_too_large` and `messaging_files_skipped` + {@link MessagingOutboundCapError}+ * — the bridge's own per-file ceiling and per-reply count. Known limits: nothing is broken,+ * and the Web App still has every file.+ *+ * A missing permission on an upload is deliberately NOT routine. The same+ * {@link MessagingPermissionError} is `expected` on an inbound download, where the chat is+ * handed the scope names and the console link; on an upload nobody is handed anything, so a+ * human still has to grant the scope and this record is the only place that says so. Every+ * other upload failure stays `unexpected` with it.+ */+const ROUTINE_OUTBOUND_FILE_REFUSALS: ReadonlyMap<string, RefusalType> = new Map([+ ["messaging_file_send_failed", MessagingUnsupportedError],+ ["messaging_file_too_large", MessagingOutboundCapError],+ ["messaging_files_skipped", MessagingOutboundCapError],]);/*** How one messaging failure should be filed.*- * `expected` needs both halves: a failure this code understands, caught somewhere the chat is- * told about it. The three understood types, and why each is one:+ * `expected` needs both halves: a failure this code understands, caught at a capture point+ * where that failure leaves nobody anything to do. At the two inbound downloads, three types+ * are understood, and why each is one:** - {@link MessagingPermissionError} — the channel refused because the bot's app lacks a scope.- * The chat receives the scope names and the console link to grant them, so the person who- * can fix it has already been handed the fix; an operator reading the dashboard can do- * nothing this notice has not already done.+ * The chat receives the scope names and the console link, so the person who can fix it has+ * already been handed the fix; an operator reading the dashboard can do nothing this notice+ * has not already done.* - {@link MessagingMediaTooLargeError} — a transfer over the cap. The sender fixes it by* sending something smaller, and the chat says so. Nothing is broken.* - {@link MessagingUnsupportedError} — the channel structurally cannot carry this, and says* why. It will refuse the next one identically; there is no fault to chase and no fix to* deploy, so recording it as a defect would only teach people to ignore the count.*+ * The outbound file capture points understand less, for the reason+ * ROUTINE_OUTBOUND_FILE_REFUSALS gives: the structural refusal and the bridge's own caps, and+ * never a missing permission.+ ** Everything else — a network failure, a 5xx from the platform, a bug here — is `unexpected`- * and keeps its place on the dashboard, and so is any of the three caught where the chat hears- * nothing: a refusal nobody was told about is still a refusal somebody has to notice.+ * and keeps its place on the dashboard, and so is any understood type caught anywhere not named+ * above: a refusal nobody was told about, and that somebody could still fix, is a refusal+ * somebody has to notice.*- * {@link MessagingConnectionClosedError} is the one `expected` case the chat is NOT told- * about, and it answers the criterion the other way round: nobody needs telling, because- * nothing stayed broken. A platform that expires a long-lived socket, or hits its own- * internal error, is answered by the connector's next handshake within the backoff, and the- * only trace is a record nobody can act on. It is `expected` only when the connector says the- * close is one of those — `recovers` is decided where the reconnect is, and a close that- * leaves the binding down until a credential or a console setting changes reports- * `recovers: false` and stays a defect.+ * {@link MessagingConnectionClosedError} is classified wherever it is caught, and answers the+ * criterion from its own verdict rather than a capture point: nobody needs telling, because+ * nothing stayed broken. A platform that expires a long-lived socket, or hits its own internal+ * error, is answered by the connector's next handshake within the backoff, and the only trace+ * is a record nobody can act on. It is `expected` only when the connector says the close is one+ * of those — `recovers` is decided where the reconnect is, and a close that leaves the binding+ * down until a credential or a console setting changes reports `recovers: false` and stays a+ * defect.*/export function messagingErrorKind(err: unknown, code: string): ErrorKind {if (err instanceof MessagingConnectionClosedError) {return err.recovers ? "expected" : "unexpected";}- if (!CODES_EXPLAINED_IN_CHAT.has(code)) return "unexpected";- if (- err instanceof MessagingPermissionError ||- err instanceof MessagingMediaTooLargeError ||- err instanceof MessagingUnsupportedError- ) {- return "expected";+ if (CODES_EXPLAINED_IN_CHAT.has(code)) {+ return err instanceof MessagingPermissionError ||+ err instanceof MessagingMediaTooLargeError ||+ err instanceof MessagingUnsupportedError+ ? "expected"+ : "unexpected";}- return "unexpected";+ const routine = ROUTINE_OUTBOUND_FILE_REFUSALS.get(code);+ return routine !== undefined && err instanceof routine ? "expected" : "unexpected";}diff --git a/packages/server/src/runtime/messaging/media.ts b/packages/server/src/runtime/messaging/media.tsindex abce02f2..4d9028cc 100644--- a/packages/server/src/runtime/messaging/media.ts+++ b/packages/server/src/runtime/messaging/media.ts@@ -133,7 +133,8 @@ export class MessagingPermissionError extends Error {** It matters beyond the wording: `error-kind.ts` files it as `expected`, so a channel refusing* what it was never able to do stops being counted among the errors that need someone to look.- * `message` must say what could not be carried and why, because that text reaches the chat.+ * `message` must say what could not be carried and why, because that text is what the error+ * record says about it.*/export class MessagingUnsupportedError extends Error {constructor(message: string) {@@ -142,6 +143,23 @@ export class MessagingUnsupportedError extends Error {}}+/**+ * A file a reply mentioned that the bridge held back at one of its OWN outbound caps — the+ * per-file byte ceiling or the per-reply count — rather than one the channel refused.+ *+ * Its own class so `error-kind.ts` can file it as `expected` by type at the two capture points+ * that record it (`messaging_file_too_large`, `messaging_files_skipped`): the caps are known+ * limits, nothing is broken, and the Web App still has every file. `message` must name the+ * files (or how many), the channel and the cap, because that text is the whole of what the+ * error record says — none of it is posted into the chat.+ */+export class MessagingOutboundCapError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "MessagingOutboundCapError";+ }+}+/*** Reads a download into memory, refusing at the byte that crosses `maxBytes`.*diff --git a/packages/server/src/runtime/messaging/qq-connector.ts b/packages/server/src/runtime/messaging/qq-connector.tsindex 85f161d0..d0316997 100644--- a/packages/server/src/runtime/messaging/qq-connector.ts+++ b/packages/server/src/runtime/messaging/qq-connector.ts@@ -169,25 +169,30 @@ interface QQOutboundFile {* platform lists a file type and does not open it. And any such message would spend a slot* from the same passive-reply budget the text is already rationing.*- * So the honest answer is a refusal that names the reason. The bridge records one error per- * undeliverable file and the reply's text still arrives — quietly resolving would tell it a- * picture reached a chat that never received one. It is a `MessagingUnsupportedError` rather- * than a bare one so that record is filed as expected: this refusal is the platform's shape,- * identical every time, and nothing an operator reads a dashboard to find (see error-kind.ts).+ * So the honest answer is a refusal that names the reason. The bridge files the refusals of one+ * reply as one error record naming every file, and the reply's text still arrives — quietly+ * resolving would tell it a picture reached a chat that never received one. It is a+ * `MessagingUnsupportedError` rather than a bare one so that record is filed as expected: this+ * refusal is the platform's shape, identical every time, and nothing an operator reads a+ * dashboard to find (see error-kind.ts).+ *+ * The text names no file, and that is deliberate: the record's head names every file it covers,+ * and a refusal that reads the same for each is what lets them share the one reason line (see+ * the bridge's messagingFilesNotSentRecords) instead of repeating it once per file.** The passive-reply-window refusal in `enqueue` deliberately stays a BARE `Error`, and the- * split is the point rather than an oversight: this one costs nothing, since the chat gets the- * reply text carrying its own explanation of the missing file, while that one IS the reply —- * the text is dropped and the chat cannot be told, because the message that would carry the- * reason is the message being refused. Somebody therefore does have to notice it, which is- * what `unexpected` is for; and `MessagingUnsupportedError` promises the opposite in its own- * contract ("`message` must say what could not be carried and why, because that text reaches- * the chat"), which for a send outside the window it cannot keep.+ * split is the point rather than an oversight: this one costs nothing, since the reply text+ * still reaches the chat and the record names the file that did not follow it, while that one+ * IS the reply — the text is dropped and the chat cannot be told, because the message that+ * would carry the reason is the message being refused. Somebody therefore does have to notice+ * it, which is what `unexpected` is for; and `MessagingUnsupportedError` promises the opposite+ * in its own contract (a refusal the platform repeats identically, with no fault to chase and+ * no fix to deploy), which a reply lost to an expired window does not keep.*/-function refuseMedia(file: QQOutboundFile): Promise<never> {+function refuseMedia(): Promise<never> {return Promise.reject(new MessagingUnsupportedError(- `QQ cannot receive "${file.fileName}": sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide`,+ "QQ cannot receive files: sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide",),);}@@ -346,8 +351,8 @@ export class QQConnector implements MessagingChannelConnector {const { kind, openid } = chatOfReplyRef(ref);return this.enqueue(creds, bot, kind, openid, text, opts?.markdown === true);},- sendImage: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),- sendFile: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),+ sendImage: (_chatId: string, _file: QQOutboundFile) => refuseMedia(),+ sendFile: (_chatId: string, _file: QQOutboundFile) => refuseMedia(),};return client;}diff --git a/packages/server/test/messaging-error-kind.test.ts b/packages/server/test/messaging-error-kind.test.tsindex dca070d3..1f67fb8b 100644--- a/packages/server/test/messaging-error-kind.test.ts+++ b/packages/server/test/messaging-error-kind.test.ts@@ -3,16 +3,18 @@** The rule under test is the recorder's own criterion — "does a human need to step in" — and* it answers from the error's type AND the capture point's code, because the same refusal is- * routine where the chat was told about it and a silent outage where it was not. The cost+ * routine where the chat was handed the fix and waits for a human where nobody was. The cost* center highlights the unexpected count, so getting either half wrong points that highlight* at nothing, or hides the one failure worth an alert.** Only the two halves live here; that the classification reaches `error_records` this way is- * proved end to end in messaging.test.ts.+ * proved end to end in messaging.test.ts and messaging-qq.test.ts.*/import { describe, expect, it } from "vitest";import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import {+ MessagingMediaTooLargeError,+ MessagingOutboundCapError,MessagingPermissionError,MessagingUnsupportedError,} from "../src/runtime/messaging/media.js";@@ -26,28 +28,79 @@ const scopeDenial = (): MessagingPermissionError =>"Access denied. One of the following scopes is required (code 99991672)",);+/** QQ's refusal of any outbound file, which the platform repeats identically every time. */+const qqFileRefusal = (): MessagingUnsupportedError =>+ new MessagingUnsupportedError('QQ cannot receive "chart.png": requires a public URL');+describe("messagingErrorKind", () => {- it("files a typed refusal as expected only where the chat was told about it", () => {- // The inbound download answers into the chat with the scope names and the console link,- // 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.+ it("files a typed refusal as expected on an inbound download, where the chat was told", () => {+ // The inbound download answers into the chat with the scope names and the console link:+ // it has 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'),- "messaging_file_send_failed",- ),- ).toBe("expected");// The same denial on a send, which is the ordinary half-configured app: nothing reaches// the chat, because the message that would carry the notice is the one being refused.expect(messagingErrorKind(scopeDenial(), "messaging_send_failed")).toBe("unexpected");expect(messagingErrorKind(scopeDenial(), "messaging_inbound_failed")).toBe("unexpected");});+ it("files an outbound file refusal as expected only when nobody has anything to fix", () => {+ // A reply's file that did not go out is recorded and never posted into the chat, so+ // nobody is told anything there. What stays routine is what nobody could act on: a+ // channel that can never carry a file...+ expect(messagingErrorKind(qqFileRefusal(), "messaging_file_send_failed")).toBe("expected");+ // ...and the bridge's own caps, per file and per reply.+ expect(+ messagingErrorKind(+ new MessagingOutboundCapError('"huge.png" was not sent: over the 10MB limit'),+ "messaging_file_too_large",+ ),+ ).toBe("expected");+ expect(+ messagingErrorKind(+ new MessagingOutboundCapError("2 more files were not sent: at most 5 per reply"),+ "messaging_files_skipped",+ ),+ ).toBe("expected");+ // A missing permission on the upload is NOT: the same denial is routine on an inbound+ // download because the chat is handed the fix there, while here nobody is handed+ // anything, and a human still has to grant the scope.+ expect(messagingErrorKind(scopeDenial(), "messaging_file_send_failed")).toBe("unexpected");+ // Nor anything else the upload throws.+ expect(messagingErrorKind(new Error("upload rejected"), "messaging_file_send_failed")).toBe(+ "unexpected",+ );+ expect(+ messagingErrorKind(+ new MessagingMediaTooLargeError("The file", 30 * 1024 * 1024),+ "messaging_file_send_failed",+ ),+ ).toBe("unexpected");+ });++ it("holds each outbound type to its own capture point", () => {+ // The allowlist pairs a type with a code. The cap error is routine where the bridge files+ // it and nowhere else, and the structural refusal is not routine at the caps' codes.+ expect(+ messagingErrorKind(new MessagingOutboundCapError("over a cap"), "messaging_send_failed"),+ ).toBe("unexpected");+ expect(+ messagingErrorKind(new MessagingOutboundCapError("over a cap"), "messaging_file_send_failed"),+ ).toBe("unexpected");+ expect(messagingErrorKind(qqFileRefusal(), "messaging_file_too_large")).toBe("unexpected");+ // And a plain Error at the caps' own codes is still unclassified: the type is half the rule.+ expect(messagingErrorKind(new Error("over a cap"), "messaging_file_too_large")).toBe(+ "unexpected",+ );+ expect(messagingErrorKind(new Error("over a cap"), "messaging_files_skipped")).toBe(+ "unexpected",+ );+ });+it("leaves everything it has not been taught about unexpected, wording included", () => {// The safe direction: a real fault miscounted as routine is invisible, while routine noise// miscounted as a fault is merely loud. A plain Error repeating a permission error's words@@ -66,9 +119,9 @@ describe("messagingErrorKind", () => {});it("a platform close is read from its own verdict, not from the capture point", () => {- // The one expected case the chat is never told about, and the one that crosses a capture- // point the set above deliberately excludes: nobody needs telling because the connector's- // next handshake already put the connection back.+ // Classified by its own verdict wherever it is caught, including capture points the sets+ // above deliberately exclude: nobody needs telling because the connector's next handshake+ // already put the connection back.expect(messagingErrorKind(new MessagingConnectionClosedError("gateway connection closed (code 4009)", 4009, true),diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.tsindex 1b51a473..72ed83fe 100644--- a/packages/server/test/messaging-qq.test.ts+++ b/packages/server/test/messaging-qq.test.ts@@ -13,9 +13,12 @@* exactly four sends for a run that completed six messages, the last carrying the* remainder; `msg_seq` increasing without repeating; the approval notice taking the* reserved slot rather than being lost behind it; one-message-per-line clamped to the- * budget instead of the channel-neutral 20; and a send with nothing to reply to failing- * loudly rather than pretending. No test opens a socket.+ * budget instead of the channel-neutral 20; a reply's files, which QQ cannot take, filed as one+ * error record without spending a slot; and a send with nothing to reply to failing loudly+ * rather than pretending. No test opens a socket.*/+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 type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";@@ -723,6 +726,77 @@ describe("qq binding routes and the passive reply budget", () => {]);});+ // —— Outbound files ——————————————————————————————————————————————————————++ it("a file the reply mentions is filed as an expected error record and spends no reply slot", async () => {+ const ws = await fs.mkdtemp(path.join(t.root, "ws-"));+ const row = sessionRowOf(SID2, projectId);+ row.workspace = ws;+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["The notes are in xx.md."]));+ await bindEnabled(SID2, APP_ID, { renderMarkdown: false });+ // Written just before the run, so it counts as the run's own output.+ await fs.writeFile(path.join(ws, "xx.md"), "notes");+ await fake.lastGateway().fire(c2cText("write the notes", "msg_file"));+ await waitFor(() =>+ t.deps.errorsRepo.recent(projectId).some((r) => r.code === "messaging_file_send_failed"),+ );+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ // The reply alone, in the first slot. QQ counts every message against the passive-reply+ // budget, and nothing about the refused file is sent into the chat.+ expect(fake.allSends().map((s) => [s.content, s.msgSeq])).toEqual([+ ["The notes are in xx.md.", 1],+ ]);+ // The refusal is filed under the Project instead, naming the file, the channel and QQ's+ // own reason — expected, because the platform will refuse the next file identically and+ // nobody has anything to fix.+ expect(+ t.deps.errorsRepo+ .recent(projectId)+ .map(({ code, kind, message }) => ({ code, kind, message })),+ ).toEqual([+ {+ code: "messaging_file_send_failed",+ kind: "expected",+ message:+ '"xx.md" was not sent to the qq chat: QQ cannot receive files: sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide',+ },+ ]);+ });++ it("three files in one reply are ONE expected record naming all three, and QQ hears only the reply", async () => {+ const ws = await fs.mkdtemp(path.join(t.root, "ws-"));+ const row = sessionRowOf(SID2, projectId);+ row.workspace = ws;+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["Wrote a.md, b.md and c.md."]));+ await bindEnabled(SID2, APP_ID, { renderMarkdown: false });+ for (const name of ["a.md", "b.md", "c.md"]) await fs.writeFile(path.join(ws, name), name);+ await fake.lastGateway().fire(c2cText("write three notes", "msg_files"));+ await waitFor(() =>+ t.deps.errorsRepo.recent(projectId).some((r) => r.code === "messaging_file_send_failed"),+ );+ await new Promise((r) => setTimeout(r, TAIL_MS * 3));+ expect(fake.allSends().map((s) => [s.content, s.msgSeq])).toEqual([+ ["Wrote a.md, b.md and c.md.", 1],+ ]);+ // QQ refuses every file with the same sentence, so the three share one reason line under a+ // head naming them all — one record, rather than three racing the recorder's window.+ expect(+ t.deps.errorsRepo+ .recent(projectId)+ .map(({ code, kind, message }) => ({ code, kind, message })),+ ).toEqual([+ {+ code: "messaging_file_send_failed",+ kind: "expected",+ message:+ '3 files were not sent to the qq chat: "a.md", "b.md", "c.md"\n' ++ "QQ cannot receive files: sending a file to QQ requires a publicly reachable URL for it, which this server has no way to provide",+ },+ ]);+ });+// —— Nothing to reply to ——————————————————————————————————————————————————it("a send with no repliable message fails loudly instead of pretending", async () => {@@ -777,7 +851,7 @@ describe("the QQ client's media half", () => {const media = client as unknown as MediaHalf;const file = { fileName: "chart.png", data: Buffer.from("x") };await expect(media.sendImage(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toThrow(- /chart\.png/,+ /QQ cannot receive files/,);await expect(media.sendFile(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toThrow(/publicly reachable URL/,@@ -787,6 +861,20 @@ describe("the QQ client's media half", () => {await expect(media.sendImage(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toBeInstanceOf(MessagingUnsupportedError,);+ // The same sentence for every file, naming none: the bridge's record names the files+ // itself, and a reason that reads alike for each is what lets one reply's refusals share+ // one line.+ const refusal = async (fileName: string): Promise<string> => {+ try {+ await media.sendFile(qqChatIdOf("c2c", USER_OPENID), { fileName, data: Buffer.from("x") });+ } catch (err) {+ return (err as Error).message;+ }+ throw new Error(`the upload of ${fileName} was not refused`);+ };+ const first = await refusal("a.md");+ expect(await refusal("b.md")).toBe(first);+ expect(first).not.toContain("a.md");});it("refuses a text send before the bot has ever been messaged in that chat", async () => {diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 0cfcba0c..f774c3ba 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -18,12 +18,13 @@* 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* only, pictures as pictures, capped by count and by size, escapes refused by the Workspace- * file service), an approval_request sends the one-line notice behind whatever is already- * going out, a binding with `linePerMessage` set delivers a reply one message per- * non-blank line — paced, and with a refused message costing only itself — while an unset- * one is byte-for-byte the original single message, and a binding with `finalReplyOnly` set- * relays a run's last completed message alone, at the run's end, files included. No test- * opens real network.+ * file service, and whatever does not go out filed as an error record under the Project+ * rather than announced in the chat), an approval_request sends the one-line notice behind+ * whatever is already going out, a binding with `linePerMessage` set delivers a reply one+ * message per non-blank line — paced, and with a refused message costing only itself — while+ * an unset one is byte-for-byte the original single message, and a binding with+ * `finalReplyOnly` set relays a run's last completed message alone, at the run's end, files+ * included. No test opens real network.*/import fs from "node:fs/promises";import path from "node:path";@@ -43,9 +44,11 @@ import type { FeishuBindingResponse, FeishuTestResponse } from "../src/api/typesimport type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import { INLINE_IMAGE_MAX_BYTES, toAttachmentLimits } from "../src/services/attachment-limits.js";+import { MESSAGE_MAX } from "../src/runtime/error-recorder.js";import {MESSAGING_APPROVAL_NOTICE,MESSAGING_MAX_LINE_MESSAGES,+ MESSAGING_OUTBOUND_FILE_MAX_BYTES,MESSAGING_OUTBOUND_FILE_MAX_COUNT,MESSAGING_OUTBOUND_IMAGE_MAX_BYTES,MESSAGING_TEST_MESSAGE,@@ -53,11 +56,8 @@ import {MESSAGING_UNSUPPORTED_NOTICE,MessagingBridge,chunkMessagingText,- messagingFileFailedNotice,- messagingFilePermissionNotice,- messagingFileTooLargeNotice,messagingFilesMissingLog,- messagingFilesSkippedNotice,+ messagingFilesNotSentRecords,messagingImageBudgetNotice,messagingImageFailedNotice,messagingImagePermissionNotice,@@ -75,11 +75,13 @@ import type {MessagingInboundImage,MessagingInboundMessage,} from "../src/runtime/messaging/connector.js";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";import { FeishuConnector } from "../src/runtime/messaging/feishu-connector.js";import type { FeishuCard } from "../src/runtime/messaging/feishu-card.js";import { FeishuApiError } from "../src/runtime/messaging/feishu-sdk.js";import {MessagingPermissionError,+ MessagingUnsupportedError,collectUnderCap,imageMimeOfName,isImageFileName,@@ -639,6 +641,204 @@ describe("messaging media helpers", () => {});});+describe("messagingFilesNotSentRecords", () => {+ /** The console link Feishu hands out for `scopes`, on an app id of real length. */+ const grantUrl = (scopes: readonly string[]) =>+ `https://open.feishu.cn/app/cli_a5f8b2c3d4e6f00b/auth?q=${scopes.join(",")}&op_from=openapi&token_type=tenant`;+ /**+ * Feishu's scope denial for an upload, as larkFailure builds it off the wire (see+ * messaging-wire.test.ts): Feishu's own bilingual `msg`, verbatim, which already names the+ * scopes and the console link, then the code and a log_id that is new on every request.+ */+ const uploadDenied = (logId: number, scopes = ["im:resource:upload", "im:resource"]) =>+ new MessagingPermissionError(+ scopes,+ grantUrl(scopes),+ `Access denied. One of the following scopes is required: [${scopes.join(", ")}]. ` ++ `应用尚未开通所需的应用身份权限:[${scopes.join(", ")}],点击链接申请并开通任一权限即可:` ++ `${grantUrl(scopes)} (code 99991672, log_id 2026091710101${logId}ABCDEF0123456789ABCD)`,+ );+ const picture = (fileName: string) => ({+ fileName,+ maxBytes: MESSAGING_OUTBOUND_IMAGE_MAX_BYTES,+ asImage: true,+ });++ it("files one record per cause, not per file, each under its own kind", () => {+ const records = messagingFilesNotSentRecords(+ "feishu",+ [picture("huge.png")],+ [+ { fileName: "a.md", err: new MessagingUnsupportedError("This channel takes no files") },+ { fileName: "b.md", err: new Error("socket hang up") },+ { fileName: "c.png", err: uploadDenied(1) },+ { fileName: "d.md", err: new MessagingUnsupportedError("This channel takes no files") },+ ],+ );+ // The causes somebody has to act on come first: the three send failures share a code, and+ // the recorder keeps only the first same-code record inside its window.+ expect(+ records.map((record) => [+ record.code,+ messagingErrorKind(record.err, record.code),+ record.err.message,+ ]),+ ).toEqual([+ [+ "messaging_file_send_failed",+ "unexpected",+ '"c.png" was not sent to the feishu chat: this bot\'s app is missing a permission.\n' ++ "im:resource:upload, im:resource\n" ++ grantUrl(["im:resource:upload", "im:resource"]),+ ],+ [+ "messaging_file_send_failed",+ "unexpected",+ '"b.md" was not sent to the feishu chat: socket hang up',+ ],+ [+ "messaging_file_send_failed",+ "expected",+ '2 files were not sent to the feishu chat: "a.md", "d.md"\nThis channel takes no files',+ ],+ [+ "messaging_file_too_large",+ "expected",+ '"huge.png" was not sent to the feishu chat: it is larger than the 10MB limit for a picture',+ ],+ ]);+ });++ it("names every file once, then the reason they share, or a line each where it differs", () => {+ const messages = (+ oversize: Parameters<typeof messagingFilesNotSentRecords>[1],+ refused: Parameters<typeof messagingFilesNotSentRecords>[2],+ ): string[] =>+ messagingFilesNotSentRecords("telegram", oversize, refused).map(+ (record) => record.err.message,+ );+ expect(+ messages(+ [],+ ["a.md", "b.md", "c.md"].map((fileName) => ({+ fileName,+ err: new Error("upload rejected"),+ })),+ ),+ ).toEqual([+ '3 files were not sent to the telegram chat: "a.md", "b.md", "c.md"\nupload rejected',+ ]);+ expect(+ messages(+ [],+ [+ { fileName: "a.md", err: new Error("Request Entity Too Large") },+ { fileName: "b.md", err: new Error("socket hang up") },+ ],+ ),+ ).toEqual([+ '2 files were not sent to the telegram chat: "a.md", "b.md"\n' ++ '"a.md": Request Entity Too Large\n' ++ '"b.md": socket hang up',+ ]);+ expect(messages([picture("a.png"), picture("b.png")], [])).toEqual([+ '2 files were not sent to the telegram chat: "a.png", "b.png"\n' ++ "each is larger than the 10MB limit for a picture",+ ]);+ // A picture and a document are held back by different ceilings, so each names its own.+ expect(+ messages(+ [+ picture("chart.png"),+ { fileName: "dump.csv", maxBytes: MESSAGING_OUTBOUND_FILE_MAX_BYTES, asImage: false },+ ],+ [],+ ),+ ).toEqual([+ '2 files were not sent to the telegram chat: "chart.png", "dump.csv"\n' ++ '"chart.png": larger than the 10MB limit for a picture\n' ++ '"dump.csv": larger than the 30MB limit for a file',+ ]);+ });++ it("names every file a permission held back, then lists its scopes and console links once", () => {+ const files = ["chart.png", "notes.md", "data.csv"];+ const [record] = messagingFilesNotSentRecords(+ "feishu",+ [],+ [+ { fileName: "chart.png", err: uploadDenied(1) },+ { fileName: "notes.md", err: uploadDenied(2) },+ { fileName: "data.csv", err: uploadDenied(3, ["im:resource"]) },+ ],+ );+ const text = record!.err.message;+ // Nothing Feishu said is quoted: its sentence repeats the fix and its log_id differs on every+ // request, so quoting it gave each file its own line and ran the record into the cap.+ expect(text).toBe(+ '3 files were not sent to the feishu chat: "chart.png", "notes.md", "data.csv"\n' ++ "this bot's app is missing a permission.\n" ++ "im:resource:upload, im:resource\n" ++ `${grantUrl(["im:resource:upload", "im:resource"])}\n` ++ grantUrl(["im:resource"]),+ );+ expect(text.length).toBeLessThanOrEqual(MESSAGE_MAX);+ const occurrences = (part: string): number => text.split(part).length - 1;+ expect(occurrences("im:resource:upload, im:resource")).toBe(1);+ expect(occurrences(grantUrl(["im:resource:upload", "im:resource"]))).toBe(1);+ expect(occurrences(grantUrl(["im:resource"]))).toBe(1);+ for (const fileName of files) expect(occurrences(`"${fileName}"`)).toBe(1);+ });++ it("stays under the recorder's cap, giving up names before any reason", () => {+ // The recorder cuts a long message from its end, which is where the reasons are.+ const names = ["a", "b", "c", "d", "e"].map((letter) => `${letter.repeat(120)}.md`);+ const [shared] = messagingFilesNotSentRecords(+ "wechat",+ [],+ names.map((fileName) => ({ fileName, err: new Error("upload rejected") })),+ );+ const sharedText = shared!.err.message;+ expect(sharedText.length).toBeLessThanOrEqual(MESSAGE_MAX);+ // The reason whole; the list cut short, and marked as cut.+ expect(sharedText.endsWith('", …\nupload rejected')).toBe(true);+ expect(sharedText).toContain(`"${names[0]}", `);+ expect(sharedText).not.toContain(names[4]);++ // Reasons too long to fit even without the list are cut alike, so every file keeps its+ // line, its name and the start of its reason.+ const files = ["chart.png", "notes.md", "data.csv", "report.pdf", "summary.md"];+ const [perFile] = messagingFilesNotSentRecords(+ "feishu",+ [],+ files.map((fileName, i) => ({+ fileName,+ err: new Error(+ `Upload failed (log_id ${i}): ${"The platform answered 502 Bad Gateway. ".repeat(6)}`,+ ),+ })),+ );+ const perFileText = perFile!.err.message;+ expect(perFileText.length).toBeLessThanOrEqual(MESSAGE_MAX);+ expect(perFileText.startsWith("5 files were not sent to the feishu chat: …\n")).toBe(true);+ for (const fileName of files) {+ expect(perFileText).toContain(`\n"${fileName}": Upload failed (log_id `);+ }++ // A lone file has no list to give up: its reason is cut, and marked as cut.+ const [lone] = messagingFilesNotSentRecords(+ "telegram",+ [],+ [{ fileName: "a.md", err: new Error("x".repeat(600)) }],+ );+ expect(lone!.err.message.length).toBeLessThanOrEqual(MESSAGE_MAX);+ expect(lone!.err.message.startsWith('"a.md" was not sent to the telegram chat: xxx')).toBe(+ true,+ );+ expect(lone!.err.message.endsWith("x…")).toBe(true);+ });+});+describe("replyFileMentions", () => {const WS = "/data/ws";/** Just the deliverable half: the resolvable mentions, in order. */@@ -2526,6 +2726,38 @@ describe("messaging binding routes and bridge", () => {.prepare("SELECT code, kind FROM error_records WHERE source = 'messaging' ORDER BY id").all() as Array<{ code: string; kind: string }>;+ /** One messaging error record in full, attribution included. */+ type FiledError = {+ code: string;+ kind: string;+ message: string;+ projectId: string | null;+ agentId: string | null;+ sessionId: string | null;+ };++ /** Every messaging record filed so far, oldest first — the whole row a cost center reads. */+ const messagingErrorRecords = (): FiledError[] =>+ t.deps.db+ .prepare(+ `SELECT code, kind, message, project_id AS projectId, agent_id AS agentId,+ session_id AS sessionId+ FROM error_records WHERE source = 'messaging' ORDER BY id`,+ )+ .all() as FiledError[];++ /**+ * A record as the second Session files it: under that Session's Project and Agent, which is+ * what lets the cost center serve it to an ordinary member — a record with no Project reaches+ * admins only.+ */+ const filedBySid2 = (record: Pick<FiledError, "code" | "kind" | "message">): FiledError => ({+ ...record,+ projectId,+ agentId: "default_agent",+ sessionId: SID2,+ });+let asks = 0;/** Message the bound Session from the chat, and wait for the run to start AND finish. */const askAndSettle = async (): Promise<void> => {@@ -2565,6 +2797,9 @@ describe("messaging binding routes and bridge", () => {{ kind: "image", target: "oc_chat_files", fileName: "chart.png", bytes: IMAGE_BYTES.length },{ kind: "file", target: "oc_chat_files", fileName: "notes.md", bytes: 5 },]);+ // A batch that went out whole files nothing.+ await settle(80);+ expect(messagingErrorRecords()).toEqual([]);});it("delivers a file the reply names in a plain sentence, with no inline code", async () => {@@ -2706,52 +2941,98 @@ describe("messaging binding routes and bridge", () => {});});- it("names an upload the app has no permission for, with the scopes and the grant link", async () => {+ it("files an upload the app has no permission for with the scopes and the grant link, and tells the chat nothing", async () => {const ws = await makeWorkspace();await fs.writeFile(path.join(ws, "notes.md"), "hi");await bindWithWorkspace(ws, "Written up in `notes.md`.", "cli_scope");// The live failure: an app that receives messages happily is refused the upload until- // a resource scope is granted. That reached `error_records` and nowhere the person in- // the chat could look, so the feature simply appeared not to work.+ // a resource scope is granted.fake.failMediaSendWith = new MessagingPermissionError(["im:resource:upload", "im:resource"],"https://open.feishu.cn/app/cli_scope/auth?q=im:resource:upload","Access denied (code 99991672)",);await askAndSettle();- await waitFor(() => fake.allSends().length === 2);- const notice = fake.allTexts().at(-1)!.text;- expect(notice).toBe(- messagingFilePermissionNotice(- "notes.md",- ["im:resource:upload", "im:resource"],- "https://open.feishu.cn/app/cli_scope/auth?q=im:resource:upload",- ),- );- // Both halves are what the user acts on: what to grant, and where.- expect(notice).toContain("im:resource:upload");- expect(notice).toContain("https://open.feishu.cn/app/cli_scope/auth");+ await waitFor(() => messagingErrorRecords().length === 1);+ await settle(80);+ // The reply and nothing after it: no line about the file reaches the chat.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "Written up in `notes.md`." },+ ]);+ // One record that names the file and the channel, then what to grant and where, and none of+ // the channel's own sentence, which says the same and adds a log_id nobody needs to grant a+ // scope. UNEXPECTED, where the same denial on an inbound download is expected: nobody in the+ // chat is handed the fix any more, so a human still has to grant the scope, and the cost+ // center's highlight is how they find out.+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_send_failed",+ kind: "unexpected",+ message:+ '"notes.md" was not sent to the feishu chat: this bot\'s app is missing a permission.\n' ++ "im:resource:upload, im:resource\n" ++ "https://open.feishu.cn/app/cli_scope/auth?q=im:resource:upload",+ }),+ ]);});- it("caps the batch by count and names how many were left behind", async () => {+ it("caps the batch by count and files ONE record naming how many were left behind", async () => {const names = ["a.md", "b.md", "c.md", "d.md", "e.md", "f.md", "g.md"];const ws = await makeWorkspace();for (const name of names) await fs.writeFile(path.join(ws, name), name);- await bindWithWorkspace(ws, `Wrote ${names.map((n) => `\`${n}\``).join(", ")}.`, "cli_many");+ const reply = `Wrote ${names.map((n) => `\`${n}\``).join(", ")}.`;+ await bindWithWorkspace(ws, reply, "cli_many");await askAndSettle();- await waitFor(() => fake.allSends().length === MESSAGING_OUTBOUND_FILE_MAX_COUNT + 2);+ await waitFor(() => messagingErrorRecords().length === 1);+ await settle(80);const sent = fake.allSends().filter((s): s is SentMedia => s.kind === "file");- expect(sent).toHaveLength(MESSAGING_OUTBOUND_FILE_MAX_COUNT);expect(sent.map((s) => s.fileName)).toEqual(names.slice(0, MESSAGING_OUTBOUND_FILE_MAX_COUNT));- // The remainder is counted in the chat — a cap that drops things quietly is a bug.- expect(fake.allSends().at(-1)).toEqual({- kind: "send",- target: "oc_chat_files",- text: messagingFilesSkippedNotice(names.length - MESSAGING_OUTBOUND_FILE_MAX_COUNT),- });+ // The reply and the files that fit, and not a word about the rest in the chat.+ expect(fake.allTexts().map((s) => s.text)).toEqual([reply]);+ expect(fake.allSends()).toHaveLength(1 + MESSAGING_OUTBOUND_FILE_MAX_COUNT);+ // The remainder is still counted — a cap that drops things quietly is a bug — in one+ // record for the whole tail rather than one per file, naming how many, the cap and which.+ // Expected: the cap is a judgement about the medium, nothing is broken, and the Web App+ // still has both files.+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_files_skipped",+ kind: "expected",+ message:+ '2 more files the reply mentioned were not sent to the feishu chat: at most 5 ride along with one reply ("f.md", "g.md")',+ }),+ ]);+ });++ it("fits a skipped tail of long names under the recorder's cap, the list cut and marked as cut", async () => {+ const sent = ["a.md", "b.md", "c.md", "d.md", "e.md"];+ // Five names of about a hundred characters: listed whole, the record runs past MESSAGE_MAX,+ // and the recorder cuts it mid-name with no "…" and no closing bracket.+ const skipped = [1, 2, 3, 4, 5].map(+ (n) =>+ `quarterly-revenue-breakdown-by-region-and-product-line-2026-q3-final-reviewed-by-finance-v${n}.xlsx`,+ );+ const ws = await makeWorkspace();+ for (const name of [...sent, ...skipped]) await fs.writeFile(path.join(ws, name), name);+ const reply = `Wrote ${[...sent, ...skipped].map((n) => `\`${n}\``).join(", ")}.`;+ await bindWithWorkspace(ws, reply, "cli_many_long");+ await askAndSettle();+ await waitFor(() => messagingErrorRecords().length === 1);+ await settle(80);+ const [record] = messagingErrorRecords();+ expect([record!.code, record!.kind]).toEqual(["messaging_files_skipped", "expected"]);+ const { message } = record!;+ expect(message.length).toBeLessThanOrEqual(MESSAGE_MAX);+ expect(message).toMatch(+ /^5 more files the reply mentioned were not sent to the feishu chat: at most 5 ride along with one reply \("/,+ );+ // Quoted like every other record's names, as many as fit, and the rest marked as cut.+ expect(message).toContain(`("${skipped[0]}", "${skipped[1]}", `);+ expect(message.endsWith(", …)")).toBe(true);+ expect(message).not.toContain(skipped[4]);});- it("names an oversize file instead of sending it, and keeps sending the rest", async () => {+ it("files an oversize file instead of sending it, keeps sending the rest, and tells the chat nothing", async () => {const ws = await makeWorkspace();await fs.writeFile(path.join(ws, "huge.png"),@@ -2760,22 +3041,25 @@ describe("messaging binding routes and bridge", () => {await fs.writeFile(path.join(ws, "small.md"), "ok");await bindWithWorkspace(ws, "Both `huge.png` and `small.md` are ready.", "cli_huge");await askAndSettle();- await waitFor(() => fake.allSends().length === 3);- expect(fake.allSends()[1]).toEqual({- kind: "send",- target: "oc_chat_files",- text: messagingFileTooLargeNotice("huge.png", MESSAGING_OUTBOUND_IMAGE_MAX_BYTES),- });- // One refusal does not cancel the batch behind it.- expect(fake.allSends()[2]).toEqual({- kind: "file",- target: "oc_chat_files",- fileName: "small.md",- bytes: 2,- });+ await waitFor(() => fake.allSends().length === 2 && messagingErrorRecords().length === 1);+ await settle(80);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "Both `huge.png` and `small.md` are ready." },+ // One refusal does not cancel the batch behind it.+ { kind: "file", target: "oc_chat_files", fileName: "small.md", bytes: 2 },+ ]);+ // Named with the ceiling that held it back, and expected: a known limit, nothing broken.+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_too_large",+ kind: "expected",+ message:+ '"huge.png" was not sent to the feishu chat: it is larger than the 10MB limit for a picture',+ }),+ ]);});- it("a failing upload is recorded, not thrown, and the next file still goes", async () => {+ it("a failing upload is recorded, not thrown or announced, and the next file still goes", async () => {const ws = await makeWorkspace();await fs.writeFile(path.join(ws, "one.md"), "1");await fs.writeFile(path.join(ws, "two.md"), "2");@@ -2783,23 +3067,104 @@ describe("messaging binding routes and bridge", () => {// Only the first upload fails: the batch behind it must carry on rather than unwind.fake.failMediaSends = 1;await askAndSettle();- await waitFor(() => fake.allSends().length === 3);+ await waitFor(() => fake.allSends().length === 2 && messagingErrorRecords().length === 1);await settle(80);- // The failure is named in the chat, with the channel's own reason: `error_records` is- // not somewhere the person in the chat can look, so an upload that failed was the one- // drop they could not see at all.- expect(fake.allSends()[1]).toEqual({- kind: "send",- target: "oc_chat_files",- text: messagingFileFailedNotice("one.md", "upload rejected"),- });- // And the batch behind it carries on rather than unwinding.- expect(fake.allSends()[2]).toEqual({- kind: "file",- target: "oc_chat_files",- fileName: "two.md",- bytes: 1,- });+ // The reply, then the file behind the failed one — and no line about the failure between+ // them.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "`one.md` and `two.md`." },+ { kind: "file", target: "oc_chat_files", fileName: "two.md", bytes: 1 },+ ]);+ // The record says which file, where it was going, and the channel's own reason. A failure+ // this code does not understand stays unexpected: somebody has to look at it.+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_send_failed",+ kind: "unexpected",+ message: '"one.md" was not sent to the feishu chat: upload rejected',+ }),+ ]);+ });++ it("a file the channel can never carry is filed as expected, and the chat hears only the reply", async () => {+ const ws = await makeWorkspace();+ await fs.writeFile(path.join(ws, "chart.png"), IMAGE_BYTES);+ await bindWithWorkspace(ws, "The chart is `chart.png`.", "cli_unsupported");+ // A structural refusal, typed as one (QQ's is the real case; see messaging-qq.test.ts for+ // it end to end): the platform will refuse the next file identically.+ fake.failMediaSendWith = new MessagingUnsupportedError(+ 'This channel cannot receive "chart.png": it takes no pictures',+ );+ await askAndSettle();+ await waitFor(() => messagingErrorRecords().length === 1);+ await settle(80);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "The chart is `chart.png`." },+ ]);+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_send_failed",+ kind: "expected",+ message:+ '"chart.png" was not sent to the feishu chat: This channel cannot receive "chart.png": it takes no pictures',+ }),+ ]);+ // And it is where the Project's cost center reads its errors from, for an ordinary member.+ const res = await api.get(`/api/projects/${projectId}/usage/errors`);+ expect(res.status).toBe(200);+ const page = (await res.json()) as { items: Array<{ code: string; kind: string }> };+ expect(page.items.map((item) => [item.code, item.kind])).toEqual([+ ["messaging_file_send_failed", "expected"],+ ]);+ });++ it("three uploads refused in one reply file ONE record naming all three, and the chat hears only the reply", async () => {+ const ws = await makeWorkspace();+ for (const name of ["a.md", "b.md", "c.md"]) await fs.writeFile(path.join(ws, name), name);+ await bindWithWorkspace(ws, "Wrote `a.md`, `b.md` and `c.md`.", "cli_upload_burst");+ // Every upload refused within milliseconds of the last. Filed one per file, the recorder+ // keeps the first record of a code inside its two-second window and drops the other two.+ fake.failMediaSends = 3;+ await askAndSettle();+ await waitFor(() => messagingErrorRecords().length === 1);+ await settle(80);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "Wrote `a.md`, `b.md` and `c.md`." },+ ]);+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_send_failed",+ kind: "unexpected",+ message:+ '3 files were not sent to the feishu chat: "a.md", "b.md", "c.md"\nupload rejected',+ }),+ ]);+ });++ it("two oversized files in one reply file ONE record naming both, and the rest still goes", async () => {+ const ws = await makeWorkspace();+ const oversize = Buffer.alloc(MESSAGING_OUTBOUND_IMAGE_MAX_BYTES + 1);+ await fs.writeFile(path.join(ws, "huge.png"), oversize);+ await fs.writeFile(path.join(ws, "vast.png"), oversize);+ await fs.writeFile(path.join(ws, "small.md"), "ok");+ const reply = "See `huge.png`, `vast.png` and `small.md`.";+ await bindWithWorkspace(ws, reply, "cli_huge_pair");+ await askAndSettle();+ await waitFor(() => fake.allSends().length === 2 && messagingErrorRecords().length === 1);+ await settle(80);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: reply },+ { kind: "file", target: "oc_chat_files", fileName: "small.md", bytes: 2 },+ ]);+ expect(messagingErrorRecords()).toEqual([+ filedBySid2({+ code: "messaging_file_too_large",+ kind: "expected",+ message:+ '2 files were not sent to the feishu chat: "huge.png", "vast.png"\n' ++ "each is larger than the 10MB limit for a picture",+ }),+ ]);});it("under finalReplyOnly the files follow the ONE message that reached the chat", async () => {