A local-first multi-agent app development platform, built on PenguinHarness
Messaging stops reporting what is not a problem (#511)
Yaowei Zheng9d215d561899
diff --git a/changelog/unreleased/2026-08-27-messaging-error-kinds.md b/changelog/unreleased/2026-08-27-messaging-error-kinds.mdnew file mode 100644index 00000000..3babae27--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-error-kinds.md@@ -0,0 +1,50 @@+# A messaging refusal the chat already explained is no longer counted as a defect++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#511](https://github.com/Prism-Shadow/penguin-harness/pull/511)++[中文版](2026-08-27-messaging-error-kinds.zh.md)++Every failure the messaging bridge caught was written to `error_records` without a `kind`, and the+recorder's default for a non-HTTP source is `unexpected`. So two things that are neither surprising+nor anyone's bug were filed as "shouldn't happen, needs a human":++- a Feishu app that has not been granted `im:message` / `im:message.history:readonly` yet, whose+ refusal (code 99991672) already reaches the chat complete with the scope names and the console+ link to grant them;+- a file sent to QQ, which the platform can only accept behind a publicly reachable https URL that+ this server has no way to provide — a refusal it will repeat identically every time.++Both became `expected`. The recorder's criterion is **"does a human need to step in"**, and in both+cases the answer is no: the one person who can act has already been handed the fix in the chat, or+there is no fix to apply.++## Details++- `runtime/messaging/error-kind.ts` was added to carry the rule, with the reasoning for each case+ written beside it. It was built as a small allowlist of TYPED failures at NAMED capture points+ rather than a message match: anything the connectors had not classified was left `unexpected`,+ which is the safe direction — a real fault miscounted as routine is invisible, while routine+ noise miscounted as a fault is merely loud. Deciding by type rather than by wording also keeps+ the count from depending on how a platform phrases its refusal.+- Three failure types were allowed through: `MessagingPermissionError` (a scope to grant, already+ named in the chat), `MessagingMediaTooLargeError` (the sender fixes it by sending something+ smaller) and the new `MessagingUnsupportedError` (the channel structurally cannot carry it).+ QQ's outbound media refusal was changed to throw the last of these instead of a bare `Error`.+- The capture point counts as much as the type, because Feishu throws the same scope denial from+ every call it makes. Only the inbound image download and the outbound file upload answer that+ refusal with a notice in the chat, so only those two were allowed to file it as `expected`. A+ send, an inbound message whose Task never started and a connection that never came up were left+ `unexpected` whatever they threw: the chat hears nothing there, and an app granted the receive+ scopes but not `im:message:send_as_bot` would otherwise take every question and answer none of+ them without raising anything anywhere.+- The records were left unchanged in every other respect, including still being written at all: a+ scope nobody grants is still worth finding on the dashboard, it is simply not a defect.++## Compatibility++Error records already written keep the classification they were written with — nothing rewrites+history. A Feishu scope denial recorded before this change stays `unexpected` until it ages out of+the view, so an existing "unexpected errors" count does not drop on upgrade.diff --git a/changelog/unreleased/2026-08-27-messaging-error-kinds.zh.md b/changelog/unreleased/2026-08-27-messaging-error-kinds.zh.mdnew file mode 100644index 00000000..97bd597c--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-error-kinds.zh.md@@ -0,0 +1,26 @@+# 消息通道里已经在聊天中解释过的拒绝,不再计为缺陷++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#511](https://github.com/Prism-Shadow/penguin-harness/pull/511)++[English](2026-08-27-messaging-error-kinds.md)++消息桥接捕获的每一个失败写入 `error_records` 时都没有带 `kind`,而记录器对非 HTTP 来源的默认值是 `unexpected`。于是两件既不意外、也不是谁的 bug 的事被归成了「不该发生、需要人介入」:++- 尚未开通 `im:message` / `im:message.history:readonly` 的飞书应用,其拒绝(错误码 99991672)本就会连同所需权限名与开通链接一起送到聊天里;+- 发往 QQ 的文件——该平台只接受挂在公网可达 https URL 后面的媒体,而本服务端无法提供这样的地址,因此每次都会得到完全相同的拒绝。++两者都改归为 `expected`。记录器的判据是**「是否需要人介入」**,而这两种情况的答案都是否:唯一能处理的人已经在聊天里拿到了办法,或者根本没有办法可施。++## 细节++- 新增 `runtime/messaging/error-kind.ts` 承载这条规则,并把每一种情况的理由写在旁边。它被写成一份按**类型**、且限定**捕获位置**的小白名单,而不是文案匹配:连接器未分类的一切都保留为 `unexpected`——这是安全的方向,真实故障被误计为常态会隐形,而常态噪声被误计为故障只是吵。按类型而非措辞判定,也让计数不依赖各平台如何遣词。+- 三种失败类型被放行:`MessagingPermissionError`(待开通的权限,聊天里已点名)、`MessagingMediaTooLargeError`(发送方换个更小的文件即可)以及新增的 `MessagingUnsupportedError`(该通道在结构上就承载不了)。QQ 的出站媒体拒绝改为抛出后者,而不再是裸 `Error`。+- 捕获位置与类型同样要紧,因为飞书的每一个调用抛出的都是同一种权限拒绝。只有入站图片下载与出站文件上传会把这条拒绝以通知的形式送进聊天,因此也只有这两处被允许记为 `expected`。发送、任务没能起来的入站消息、以及始终建不起来的连接,无论抛出什么都保留为 `unexpected`:那些位置上聊天什么也听不到,否则一个开通了接收权限、却没有 `im:message:send_as_bot` 的应用,会照单全收每一个问题、一个也不回答,而任何地方都不会有提示。+- 记录本身在其他方面全部照旧,包括仍然被写入:没人去开通的权限依然值得在看板上被发现,只是它不是缺陷。++## 兼容性++已经写入的错误记录保持写入时的分类——不会改写历史。本次改动之前记录的飞书权限拒绝仍是 `unexpected`,直到它随时间移出视图,因此升级后既有的「未预期错误」计数不会立刻下降。diff --git a/changelog/unreleased/2026-08-27-messaging-mention-no-file.md b/changelog/unreleased/2026-08-27-messaging-mention-no-file.mdnew file mode 100644index 00000000..30ca72b3--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-mention-no-file.md@@ -0,0 +1,27 @@+# A mention that names no file is no longer announced in the chat++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#511](https://github.com/Prism-Shadow/penguin-harness/pull/511)++[中文版](2026-08-27-messaging-mention-no-file.zh.md)++The reply-file feature scans a reply's prose for path-like tokens and sends the ones that resolve+inside the Workspace. Names that resolved to nothing were announced in the chat — *"Named in the+reply but not sent — no such file inside this Session's Workspace: hello-world.md"* — on the+reasoning that a promised file which never arrives, with nothing to say why, reads as broken. That+notice was dropped, and the names were sent to the server log instead.++## Details++- The reasoning behind the notice holds only when something was promised. The rule reads prose, and+ prose names files for reasons that have nothing to do with delivery: a model describing a+ `hello-world.md` it went on not to write, or quoting a path out of a document it read. Announcing+ those put an error-shaped line under replies that were entirely correct, and left the reader no+ move to make.+- `messagingFilesMissingNotice` became `messagingFilesMissingLog`, and the name change is the+ point: a chat notice and a log line answer to different readers, and only one of them is charged+ for a name the reply merely mentioned.+- A file that exists and whose upload failed is still named in the chat. There the reply promised+ something that then did not arrive, which is the one case where silence reads as broken.diff --git a/changelog/unreleased/2026-08-27-messaging-mention-no-file.zh.md b/changelog/unreleased/2026-08-27-messaging-mention-no-file.zh.mdnew file mode 100644index 00000000..1e19b1c2--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-mention-no-file.zh.md@@ -0,0 +1,16 @@+# 回复里提到但并不存在的文件名,不再发进聊天++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#511](https://github.com/Prism-Shadow/penguin-harness/pull/511)++[English](2026-08-27-messaging-mention-no-file.md)++回复文件功能会扫描回复正文里像路径的词,把能在 Workspace 中解析到的发出去。解析不到的名字原先会被播报进聊天——*「回复中提及但未发送——该会话 Workspace 内没有这些文件:hello-world.md」*——理由是:承诺过的文件没到、又没有任何说明,会让人觉得功能坏了。本次改动去掉了这条通知,改为把这些名字写进服务端日志。++## 细节++- 那条理由只在「确实承诺过」时成立。该规则读的是自然语言,而自然语言提到文件名的原因常常与投递无关:模型描述了一个它最终并没有写的 `hello-world.md`,或者引用了它读过的文档里的某个路径。把这些播报出来,等于在完全正确的回复下面加一行像报错的字,而读到的人无事可做。+- `messagingFilesMissingNotice` 改名为 `messagingFilesMissingLog`,改名本身就是重点:聊天通知与日志面对的是不同的读者,而只有其中一方需要为回复顺口提到的一个名字买单。+- **确实存在**但上传失败的文件仍然会在聊天里点名。那种情况下回复承诺了某样东西却没送到,正是沉默会被读成「坏了」的唯一情形。diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex 501b5ad4..519666c4 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -77,6 +77,7 @@ import type {MessagingInboundMessage,MessagingSendNote,} from "./connector.js";+import { messagingErrorKind } from "./error-kind.js";import { MessagingMediaTooLargeError, MessagingPermissionError, isImageFileName } from "./media.js";import { replyFileMentions } from "./reply-files.js";@@ -263,17 +264,27 @@ export function messagingFilePermissionNotice(const MESSAGING_NOTICE_NAMES_MAX = 5;/**- * Files the reply named that the Workspace has nothing to send for — a path that resolves- * outside it, a `~` path, or one that simply is not there.+ * The LOG line for files the reply named that the Workspace has nothing to send for — a path+ * resolving outside it, a `~` path, or one that simply is not there.*- * One notice for the batch, quoting the reply's own spelling. The two causes share a- * sentence because they share the user's next move (look at the path) and share one true- * statement: there is no such file in this Session's Workspace.+ * **Deliberately not a chat notice.** The mention rule is a heuristic over prose, and prose+ * names files for reasons that have nothing to do with delivery: a model writes+ * `hello-world.md` while describing what it would do, quotes a path out of a document it read,+ * or names a file the run decided in the end not to write. None of those is a delivery that+ * 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.+ *+ * 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.*/-export function messagingFilesMissingNotice(names: readonly string[]): string {+export function messagingFilesMissingLog(names: readonly string[]): string {const shown = names.slice(0, MESSAGING_NOTICE_NAMES_MAX);const list = shown.join(", ") + (names.length > shown.length ? ", …" : "");- return `Named in the reply but not sent — no such file inside this Session's Workspace: ${list}. 回复中提及但未发送——该会话 Workspace 内没有这些文件:${list}。`;+ return `[messaging] reply named files the Workspace does not have, nothing sent: ${list}`;}/** The tail of a batch the count cap cut off. */@@ -891,6 +902,13 @@ export class MessagingBridge {source: "messaging",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).+ kind: messagingErrorKind(err, code),ctx: {sessionId,...(row !== null ? { projectId: row.projectId, agentId: row.agentId } : {}),@@ -1378,10 +1396,12 @@ export class MessagingBridge {* declined to paste it. Containment (the Workspace and nothing narrower) lives in the* file service either way — see MessagingWorkspaceFiles.*- * A file the run did not write is dropped SILENTLY: a reply that mentions the config it- * read is the ordinary case, and announcing every one of those would bury the notices- * that matter. A file that could not be delivered at all is named, because a mention the- * chat never receives with nothing to say why is how this feature reads as broken.+ * 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.** 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@@ -1428,9 +1448,9 @@ export class MessagingBridge {if (skipped > 0) {await client.sendText(chatId, messagingFilesSkippedNotice(skipped));}- if (missing.length > 0) {- await client.sendText(chatId, messagingFilesMissingNotice(missing));- }+ // Logged, never sent: a name in a reply is not a promise of a file (see+ // messagingFilesMissingLog).+ if (missing.length > 0) this.log(messagingFilesMissingLog(missing));} catch (err) {this.recordError(entry.sessionId, err, "messaging_send_failed");}diff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.tsnew file mode 100644index 00000000..bca359ec--- /dev/null+++ b/packages/server/src/runtime/messaging/error-kind.ts@@ -0,0 +1,81 @@+/**+ * 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.+ *+ * 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+ * anyone can fix — and buries the failures that genuinely do need looking at.+ *+ * 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.+ *+ * The rule is deliberately a small allowlist of TYPED failures at NAMED capture points rather+ * than a message match. Anything the connectors have not classified stays `unexpected`, which+ * is the safe direction: a real fault miscounted as routine is invisible, while routine noise+ * miscounted as a fault is merely loud.+ */+import type { ErrorKind } from "../error-recorder.js";+import {+ MessagingMediaTooLargeError,+ MessagingPermissionError,+ MessagingUnsupportedError,+} from "./media.js";++/**+ * The capture points that put the refusal in front of the person in the chat.+ *+ * `messaging_image_fetch_failed` answers the sender in the chat it came from (see+ * messagingImagePermissionNotice and its siblings), and `messaging_file_send_failed` names the+ * file that did not make it and why (see noteFileFailure). Every other code fails with the chat+ * hearing nothing at all — a reply that never went out, an inbound message whose Task never+ * started, a connection that will not come up — so the dashboard is where it has to be noticed.+ */+const CODES_EXPLAINED_IN_CHAT = new Set([+ "messaging_image_fetch_failed",+ "messaging_file_send_failed",+]);++/**+ * 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:+ *+ * - {@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.+ * - {@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.+ *+ * 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.+ */+export function messagingErrorKind(err: unknown, code: string): ErrorKind {+ if (!CODES_EXPLAINED_IN_CHAT.has(code)) return "unexpected";+ if (+ err instanceof MessagingPermissionError ||+ err instanceof MessagingMediaTooLargeError ||+ err instanceof MessagingUnsupportedError+ ) {+ return "expected";+ }+ return "unexpected";+}diff --git a/packages/server/src/runtime/messaging/media.ts b/packages/server/src/runtime/messaging/media.tsindex 066c7798..f0aac435 100644--- a/packages/server/src/runtime/messaging/media.ts+++ b/packages/server/src/runtime/messaging/media.ts@@ -112,6 +112,26 @@ export class MessagingPermissionError extends Error {}}+/**+ * A transfer the channel cannot carry at all — a permanent shape of the platform, not a fault.+ *+ * Its own class because it is the one failure here that nothing will ever clear: no permission+ * to grant, no smaller file to send, no retry that behaves differently. QQ's outbound media is+ * the case it exists for — the platform's rich-media path registers bytes against a PUBLICLY+ * REACHABLE https URL, which is the same requirement that ruled webhook mode out, and this+ * server has no such address to offer.+ *+ * 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.+ */+export class MessagingUnsupportedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "MessagingUnsupportedError";+ }+}+/*** 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 47a3b551..bf707082 100644--- a/packages/server/src/runtime/messaging/qq-connector.ts+++ b/packages/server/src/runtime/messaging/qq-connector.ts@@ -73,6 +73,7 @@* refused with a reason — see refuseMedia, which explains what QQ would require.*/import { chunkMessagingText } from "./bridge.js";+import { MessagingUnsupportedError } from "./media.js";import type {MessagingChannelConnector,MessagingClient,@@ -162,11 +163,22 @@ interface QQOutboundFile {** 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.+ * 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 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.*/function refuseMedia(file: QQOutboundFile): Promise<never> {return Promise.reject(- new Error(+ 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`,),);@@ -474,6 +486,10 @@ export class QQConnector implements MessagingChannelConnector {// `async` so this is a rejection rather than a synchronous throw: the seam's methods// are typed as promises, and a caller that only attaches `.catch` — as any caller// reasonably may — would never see a throw raised before the promise exists.+ //+ // A bare Error on purpose, unlike the media refusal next door: this one drops text the+ // chat was meant to receive and has no way to say so, so the error record is the only+ // place it can be noticed (see refuseMedia).throw new Error("QQ only accepts replies to a message sent from QQ, within a few minutes of it — send the bot a message in QQ and it will answer",);diff --git a/packages/server/test/messaging-error-kind.test.ts b/packages/server/test/messaging-error-kind.test.tsnew file mode 100644index 00000000..fd4630d9--- /dev/null+++ b/packages/server/test/messaging-error-kind.test.ts@@ -0,0 +1,62 @@+/**+ * Which messaging failures the dashboard counts as needing a human.+ *+ * 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+ * 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.+ */+import { describe, expect, it } from "vitest";+import { messagingErrorKind } from "../src/runtime/messaging/error-kind.js";+import {+ MessagingPermissionError,+ MessagingUnsupportedError,+} from "../src/runtime/messaging/media.js";++/** Feishu's 99991672, which every one of its calls throws alike — the point of the code half. */+const scopeDenial = (): MessagingPermissionError =>+ new MessagingPermissionError(+ ["im:message", "im:message.history:readonly"],+ "https://open.feishu.cn/app/cli_x/auth?q=im:message",+ "Access denied. One of the following scopes is required (code 99991672)",+ );++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.+ expect(messagingErrorKind(scopeDenial(), "messaging_image_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("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+ // is still unclassified — matching on wording would make the count depend on how a+ // platform phrases its refusal.+ expect(messagingErrorKind(new Error("socket hang up"), "messaging_image_fetch_failed")).toBe(+ "unexpected",+ );+ expect(+ messagingErrorKind(+ new Error("Access denied (code 99991672)"),+ "messaging_image_fetch_failed",+ ),+ ).toBe("unexpected");+ expect(messagingErrorKind(undefined, "messaging_connect_failed")).toBe("unexpected");+ });+});diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.tsindex 09865a8f..007b04b0 100644--- a/packages/server/test/messaging-qq.test.ts+++ b/packages/server/test/messaging-qq.test.ts@@ -32,6 +32,7 @@ import {MESSAGING_TEXT_ONLY_NOTICE,} from "../src/runtime/messaging/bridge.js";import type { MessagingClient } from "../src/runtime/messaging/connector.js";+import { MessagingUnsupportedError } from "../src/runtime/messaging/media.js";import type {QQBotClient,QQCredentials,@@ -699,6 +700,11 @@ describe("the QQ client's media half", () => {await expect(media.sendFile(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toThrow(/publicly reachable URL/,);+ // Typed, not bare: the bridge files a refusal the platform will repeat identically as an+ // expected error rather than a defect (see error-kind.ts), and the type is what says so.+ await expect(media.sendImage(qqChatIdOf("c2c", USER_OPENID), file)).rejects.toBeInstanceOf(+ MessagingUnsupportedError,+ );});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 62d2fd27..27fef133 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -49,7 +49,7 @@ import {messagingFileFailedNotice,messagingFilePermissionNotice,messagingFileTooLargeNotice,- messagingFilesMissingNotice,+ messagingFilesMissingLog,messagingFilesSkippedNotice,messagingImageBudgetNotice,messagingImageFailedNotice,@@ -138,6 +138,7 @@ class FakeClient implements FeishuApiClient {return null;}async sendText(chatId: string, text: string): Promise<void> {+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);this.sdk.noteSend();this.record({ kind: "send", target: chatId, text });@@ -229,6 +230,8 @@ class FakeSdk implements FeishuSdk {botIdentityLookups = 0;/** Non-null makes every outbound sendText throw with this message. */failSend: string | null = null;+ /** Non-null makes every outbound sendText throw THIS — for the failure shapes that carry data. */+ failSendWith: Error | null = null;/*** Non-null holds every createClient until it resolves, which is what makes the bridge's* one await between reading the binding row and its first send observable to a test.@@ -1565,8 +1568,14 @@ describe("messaging binding routes and bridge", () => {),);// Still an error record: somebody has to grant it, and the dashboard is where that is- // noticed when nobody is watching the chat.+ // noticed when nobody is watching the chat. Filed as EXPECTED, though — the one person+ // who can fix it has just been handed the scope names and the console link, so nothing+ // is pending for an operator, and the cost center's unexpected count stays a count of+ // things that need looking at.expect(imageFetchErrors()).toHaveLength(1);+ expect(messagingErrorKinds()).toEqual([+ { code: "messaging_image_fetch_failed", kind: "expected" },+ ]);expect(runs).toHaveLength(0);});@@ -1842,7 +1851,13 @@ describe("messaging binding routes and bridge", () => {it("a reply that never went out is reported on the status and filed under the Project", async () => {await bindEnabled(SID);- fake.failSend = "Bad Request: have no rights to send a message";+ // The half-configured first run: an app granted the receive scopes but never+ // `im:message:send_as_bot`. Typed, because the type is what the classification below reads.+ fake.failSendWith = new MessagingPermissionError(+ ["im:message:send_as_bot"],+ "https://open.feishu.cn/app/cli_x/auth?q=im:message:send_as_bot",+ "Access denied. One of the following scopes is required: [im:message:send_as_bot] (code 99991672)",+ );await fake.lastConnection().fire({chatId: "oc_chat_1",chatType: "p2p",@@ -1859,12 +1874,18 @@ describe("messaging binding routes and bridge", () => {// says which end failed, because the two send the user to different places.expect(failed.lastInboundAt).toBeDefined();expect(failed.lastDeliveryError?.stage).toBe("send");- expect(failed.lastDeliveryError?.detail).toContain("have no rights to send a message");+ expect(failed.lastDeliveryError?.detail).toContain("im:message:send_as_bot");// And the error record is attributed, which is what makes it reachable at all: the// project errors query serves unattributed records to admins only.const recorded = t.deps.errorsRepo.recent(projectId);expect(recorded.map((r) => r.code)).toContain("messaging_send_failed");+ // UNEXPECTED, even though the same refusal on the image download is expected: there the+ // chat is handed the scope names and the console link, here it is handed nothing — the+ // message that would carry them is the one being refused. A bot that receives every+ // question and answers none of them is the worst state this feature has, and this record+ // is the only place it shows (see error-kind.ts).+ expect(messagingErrorKinds()).toEqual([{ code: "messaging_send_failed", kind: "unexpected" }]);});it("keeps a delivery failure on the status after a later message goes through", async () => {@@ -2122,6 +2143,12 @@ describe("messaging binding routes and bridge", () => {.all().map((r) => r.message as string);+ /** How the messaging failures recorded so far were classified, newest last (see error-kind.ts). */+ const messagingErrorKinds = (): Array<{ code: string; kind: string }> =>+ t.deps.db+ .prepare("SELECT code, kind FROM error_records WHERE source = 'messaging' ORDER BY id")+ .all() as Array<{ code: string; kind: string }>;+let asks = 0;/** Message the bound Session from the chat, and wait for the run to start AND finish. */const askAndSettle = async (): Promise<void> => {@@ -2196,20 +2223,19 @@ describe("messaging binding routes and bridge", () => {]);});- it("names a mentioned path that does not exist rather than dropping it in silence", async () => {+ it("says nothing in the chat about a mentioned path that matches no file", async () => {await bindWithWorkspace(await makeWorkspace(),"I would have written `out/missing.png`, but the run failed.","cli_ghost",);await askAndSettle();- await waitFor(() => fake.allSends().length === 2);await settle(80);- // Existence is still the rule and nothing exists, so no file goes. What changed is- // that the chat is told: a name in the reply that never arrives, with nothing anywhere- // to say why, is how this feature reads as broken.- expect(fake.allSends().map((s) => s.kind)).toEqual(["send", "send"]);- expect(fake.allTexts().at(-1)!.text).toBe(messagingFilesMissingNotice(["out/missing.png"]));+ // The reply, and nothing after it. A name in a reply is not a promise of a file: the rule+ // reads prose, so a path the model merely described would otherwise put an error-shaped+ // line under a correct answer. The fact is logged instead — messagingFilesMissingLog.+ expect(fake.allSends().map((s) => s.kind)).toEqual(["send"]);+ expect(messagingFilesMissingLog(["out/missing.png"])).toContain("out/missing.png");});it("says nothing at all about a reply that named no file", async () => {@@ -2267,16 +2293,17 @@ describe("messaging binding routes and bridge", () => {"cli_escape",);await askAndSettle();- await waitFor(() => fake.allSends().length === 2);await settle(80);- // Nothing leaves the Workspace; the escapes are reported as what they are here — paths- // with no file behind them — in the reply's own spelling, never a normalization of it.- expect(fake.allSends().map((s) => s.kind)).toEqual(["send", "send"]);- // Both escapes are named, in the reply's own spelling: the lexical one, which never- // resolves, and the symlink, which resolves to a name the file service then refuses.- // (`/etc/hostname` carries no extension, so it is never a candidate in the first place.)- expect(fake.allTexts().at(-1)!.text).toContain("../outside.txt");- expect(fake.allTexts().at(-1)!.text).toContain("linked.txt");+ // The property under test: nothing leaves the Workspace. The reply goes out and NO file+ // follows it — not the lexical escape, which never resolves, and not the symlink, which+ // resolves to a name the file service then refuses. (`/etc/hostname` carries no+ // extension, so it is never a candidate in the first place.)+ expect(fake.allSends().map((s) => s.kind)).toEqual(["send"]);+ // Both escapes reach the log in the reply's own spelling, never a normalization of it —+ // a normalized path in a log line about containment would hide which name was tried.+ const logged = messagingFilesMissingLog(["../outside.txt", "linked.txt"]);+ expect(logged).toContain("../outside.txt");+ expect(logged).toContain("linked.txt");});it("classifies by the file the read reached, not by the name the reply spelled", async () => {