A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): a messaging binding reports what it has actually seen (#505)
Yaowei Zheng9d7db1db604e
diff --git a/changelog/unreleased/2026-08-26-messaging-delivery-observability.md b/changelog/unreleased/2026-08-26-messaging-delivery-observability.mdnew file mode 100644index 00000000..a078a3ac--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-delivery-observability.md@@ -0,0 +1,69 @@+# A messaging binding says what it has actually seen++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#505](https://github.com/Prism-Shadow/penguin-harness/pull/505)++[中文版](2026-08-26-messaging-delivery-observability.zh.md)++"I sent the bot a message and nothing happened" had three completely different causes and one+appearance. The channel may never have delivered the message; it may have arrived and the Task+failed to start, which the bridge swallowed into an error record; or the Task may have run and the+reply failed to send. All three ended as silence in the chat, and the binding panel showed+`connected` with nothing else to say in every one of them.++## The runtime status was given the traffic, not just the socket++`MessagingRuntimeStatus` gained three fields, all filled by the live connection:++- `lastInboundAt` — when the binding last accepted an inbound message. Absent while none had,+ which was the reading worth adding: **connected, no error, nothing arriving** is exactly what a+ channel withholding messages looks like, and nothing in the product could say it.+- `lastDeliveryError` — `{at, stage, detail}` for the most recent failure *after* a message was+ accepted. `stage: "inbound"` means the message arrived and its Task never started;+ `stage: "send"` means the Task ran and its reply never went out. The two lead to different+ places, so the stage was stated rather than folded into one message. No later success clears+ it — an intermittent failure would otherwise be erased by the next ordinary message — so the+ panel line carries the failure's own time and a stale one reads as stale.+- `lastConnectionError` — `{at, detail}` for the most recent connection failure, **kept after the+ connection recovers**. `lastError` belongs to the `error` state and is wiped the moment the+ state leaves it, so a connector that flaps — which is what a second program taking turns on the+ same bot token produces — read as `connected` in every snapshot taken between its failures,+ leaving the reader a symptom and no cause.++All three were kept in process and scoped to one CONNECTION, not to one server run: each starts+empty on a (re)connect, and a re-enable or a credential save opens one. The copy was written to+that scope — the empty arrival line reads "no message has arrived since this connection opened"+rather than claiming none ever did, and the troubleshooting entry below treats it as evidence only+about a message sent after reading it.++The binding panel took all three under the connection toggle, beside the existing connection-error+line, in both languages. The arrival line was deliberately not gated on `connected`: it reports+traffic rather than the socket, and `connecting` and `error` — a bot mid-handshake, a flapping+token — are where a reader most needs to know whether this bot has been receiving at all.++## Messaging errors were filed under their Project++`MessagingBridge` recorded every failure with a `sessionId` and nothing else. `GET+/api/projects/:id/usage/errors` selects by project, and a record with no project is+*unattributed* — served only to admins. An ordinary member could therefore never see a failure of+their own binding anywhere in the product. Each record was given the Session's `projectId` and+`agentId`, read from the sessions index the bridge already held.++## A Telegram troubleshooting entry for "still nothing from the group"++Added beside the Group Privacy entry: how to read the arrival line, and what to check once it has+been read properly. It states that the line covers the current connection alone, so a retest means+sending a fresh message rather than trusting a line that a re-enable just reset — and that if that+fresh message still shows nothing, Telegram is not delivering it and nothing local will change+that. It names the checks: the bot is still in the group, a Group Privacy change needs the bot+removed and re-added because an existing group does not pick it up, and nothing else is polling the+same token. It also states that Telegram **channel** posts are not supported, this connection+handling groups and direct chats only.++The one-program-per-token entry gained the trap that costs the most time while diagnosing exactly+this: **a `getUpdates` run by hand is that other program.** It has to be run with the connection+disabled, and inspecting the backlog by hand can discard it — any call carrying an `offset`+confirms everything before it, and the connector's own next connect drops the backlog — so a+retest needs a freshly sent message.diff --git a/changelog/unreleased/2026-08-26-messaging-delivery-observability.zh.md b/changelog/unreleased/2026-08-26-messaging-delivery-observability.zh.mdnew file mode 100644index 00000000..a3814a06--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-delivery-observability.zh.md@@ -0,0 +1,58 @@+# 消息绑定会说出它实际看到了什么++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `server`, `web`+- **PR:** [#505](https://github.com/Prism-Shadow/penguin-harness/pull/505)++[English](2026-08-26-messaging-delivery-observability.md)++「给机器人发了消息,什么也没发生」有三种完全不同的成因,却只有一种表象。可能渠道根本没有把消息投+递过来;可能消息到了而 Task 没能开始,被消息桥吞进了一条错误记录;也可能 Task 跑完了而回复没能发+出。三者在聊天里都表现为沉默,而绑定面板在每一种情况下都只显示 `connected`,再说不出别的。++## 运行时状态拿到了流量,而不只是连接++`MessagingRuntimeStatus` 新增三个字段,都由活跃连接填写:++- `lastInboundAt`——该绑定最近一次接受入站消息的时间。尚未收到过时该字段缺席,而这正是值得补上的读+ 数:**已连接、无报错、什么也没收到**,恰恰就是渠道扣着消息不投递时的样子,而此前产品里没有任何地+ 方能说出这一点。+- `lastDeliveryError`——最近一次**在消息被接受之后**发生的失败,形如 `{at, stage, detail}`。+ `stage: "inbound"` 表示消息到了而 Task 没能开始;`stage: "send"` 表示 Task 跑完而回复没能发出。+ 两者指向不同的排查方向,因此明确报出阶段,而不是揉成一句话。后续的成功不会把它清掉——否则一次时+ 有时无的失败会被下一条普通消息抹去——所以面板那一行带上了失败自身的时间,过期的记录读起来就是过+ 期的。+- `lastConnectionError`——最近一次连接失败,形如 `{at, detail}`,且**在连接恢复之后依然保留**。+ `lastError` 属于 `error` 状态,状态一离开就被抹掉;于是一个反复断连又恢复的连接器——两个程序在同+ 一个 Bot Token 上轮流占用时就是这样——在任何一次快照里都读作 `connected`,只给读者留下症状而没有+ 原因。++三者都只存在于进程内,且作用域是一条**连接**,而不是一次服务端运行:每次(重新)建立连接都从空开+始,重新启用连接或保存一次凭证都会开启一条新的。文案是按这个作用域写的——空的到达行写作「本次连接+建立以来还没有收到过消息」,而不是断言消息从未到达过;下面那条常见问题也只把它当作「读到它之后再发+的那条消息」的证据。++绑定面板把三者都收到了连接开关下方,与既有的连接错误行并列,双语。到达行刻意没有限定在 `connected`+才显示:它报的是流量而不是连接本身,而 `connecting`(机器人正在握手)与 `error`(Token 反复被抢)+恰恰是读者最需要知道这个机器人到底有没有收到过东西的时候。++## 消息类错误归属到所属 Project++`MessagingBridge` 此前记录每一次失败时只带 `sessionId`。而 `GET /api/projects/:id/usage/errors`+是按 project 过滤的,没有 project 的记录属于**未归属**——只对管理员提供。于是普通成员在产品的任何+地方都看不到自己绑定的失败。现在每条记录都带上了该 Session 的 `projectId` 与 `agentId`,取自消息桥+本就持有的 sessions 索引。++## 新增一条「群里还是收不到」的 Telegram 常见问题++紧挨着 Group Privacy 那一条:先讲怎么读到达行,再讲读对之后该查什么。它写明这一行只覆盖当前这条连+接,所以复测意味着重新发一条消息,而不是去信一行刚被重新启用清零过的字;如果重新发的这条仍然什么也+没显示,那就是 Telegram 没有投递,本地再做什么也无济于事。该条目写清了要检查什么——机器人是否仍在+群里、改动 Group Privacy 之后必须把机器人移出再重新拉入(已有的群不会自动生效)、以及是否有别的东+西在用同一个 Token 轮询——并说明 Telegram **频道**(channel)贴文不受支持,本连接只处理群聊与私聊。++「一个 Token 只能被一个程序使用」那一条则补上了排查这类问题时最费时间的陷阱:**手动执行的+`getUpdates` 也算那个「另一个程序」。** 跑它之前必须先停用连接;而且手动查看积压也可能把它丢掉——任何带+`offset` 的调用都会确认它之前的全部更新,连接器自己的下一次连接也会清空积压——因此复测需要重新发一+条新消息。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex dbb97f91..15793473 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -316,7 +316,7 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th| POST | /messaging/qq/test | Credential probe (the app-access-token exchange) → `{ok, latencyMs?, error?}`. No account label: the platform has no call that identifies the bot || POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` is the one saved field that is not a credential: with it 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); it defaults to false, an omitted value on a PUT keeps the stored one, and it never applies to the notices or the test message. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` is the one saved field that is not a credential: with it 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); it defaults to false, an omitted value on a PUT keeps the stored one, and it never applies to the notices or the test message. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). 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 send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 574eedeb..649ffffb 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -315,7 +315,7 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr| POST | /messaging/qq/test | 凭据探测(换取 app access token)→ `{ok, latencyMs?, error?}`。不报出账号名:平台没有能识别机器人身份的接口 || POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 是唯一一个不属于凭据的已存字段:开启后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条);默认为 false,PUT 省略该字段则保持已存值,且它不作用于通知与测试消息。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 是唯一一个不属于凭据的已存字段:开启后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条);默认为 false,PUT 省略该字段则保持已存值,且它不作用于通知与测试消息。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。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。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 195ee98e..5d919a3d 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1623,12 +1623,59 @@ export type MessagingChannel = "feishu" | "telegram" | "qq";/** Event-connection runtime state of one binding (kept in memory, not persisted). */export type MessagingRuntimeState = "disconnected" | "connecting" | "connected" | "error";+/**+ * A failure that happened AFTER an inbound message was accepted — as opposed to a+ * connection failure, which `MessagingRuntimeStatus.lastError` reports.+ *+ * The two stages fail in completely different places and lead to different actions, and+ * from the chat they are indistinguishable (both produce silence), which is why the stage+ * is stated rather than folded into one message.+ */+export interface MessagingDeliveryError {+ /** ISO 8601 timestamp of the failure. */+ at: string;+ /** `inbound` — the message arrived and its Task never started; `send` — a reply never reached the chat. */+ stage: "inbound" | "send";+ /** The failure's own message, as the channel or the Session reported it. */+ detail: string;+}+export interface MessagingRuntimeStatus {state: MessagingRuntimeState;/** Failure detail; present only in the `error` state. */lastError?: string;/** When the state last changed (ISO 8601); absent for a binding that never connected. */changedAt?: string;+ /**+ * When this binding last accepted an inbound message (ISO 8601).+ *+ * "Connected, and nothing has arrived" is the answer to the one question a chat cannot+ * answer for itself — whether the platform is delivering anything at all. A channel that+ * withholds messages (Telegram's group privacy, a bot that is not a member) produces+ * exactly that, with no error anywhere.+ *+ * In-process AND scoped to one connection: it starts empty on every (re)connect, and a+ * re-enable or a credential save opens a new one. So an absent field means "nothing since+ * this connection opened", never "nothing ever" — anything reporting it has to say which,+ * or it sends a reader off to fix a channel that is working.+ */+ lastInboundAt?: string;+ /**+ * The most recent post-acceptance failure; absent when none has happened since this+ * connection opened, and never cleared by a later success — an intermittent failure would+ * otherwise be erased by the next ordinary message. `at` is what says how stale it is.+ */+ lastDeliveryError?: MessagingDeliveryError;+ /**+ * The most recent CONNECTION failure, kept after the connection recovers — unlike+ * `lastError`, which belongs to the `error` state and is gone the moment the state leaves it.+ *+ * A connection that fails and recovers repeatedly (a second program polling the same bot+ * token takes turns with this one) reads as `connected` in any snapshot taken between+ * flaps, with nothing at all to show for the failures in between. This is what is left+ * behind — for the life of the connection, like the two above it.+ */+ lastConnectionError?: { at: string; detail: string };}/** The stored Feishu config, secret masked (plaintext never leaves the server). */diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex a75eaa9c..7f245196 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -45,7 +45,7 @@*/import { userText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";-import type { MessagingRuntimeStatus } from "../../api/types.js";+import type { MessagingDeliveryError, MessagingRuntimeStatus } from "../../api/types.js";import type {MessagingBindingRow,MessagingBindingsRepo,@@ -235,9 +235,12 @@ export interface MessagingTaskRunner {): Promise<{ sessionId: string; queued: boolean }>;}-/** Minimal dependency on the sessions index (existence checks for reconcile/cascade). */+/**+ * Minimal dependency on the sessions index: existence checks for reconcile/cascade, and the+ * Session's Project/Agent so a messaging failure can be filed under them (see recordError).+ */export interface MessagingSessionIndex {- findById(sessionId: string): object | null;+ findById(sessionId: string): { projectId: string; agentId: string } | null;}export interface MessagingBridgeDeps {@@ -268,6 +271,29 @@ interface BridgeEntry {client: MessagingClient | null;/** Inbound group message to thread replies onto (memory only; direct chats clear it). */lastInboundMessageId: string | null;+ /**+ * When this entry last ACCEPTED an inbound message, and the last failure that happened+ * after one was accepted. Both are reported through statusOf rather than folded into+ * `status`, because `status` is rebuilt on every connection-state flip and these two+ * outlive it: they describe the traffic, not the socket.+ *+ * They live no longer than the entry, though, which is one CONNECTION and not one server+ * run: `connect` builds a fresh entry, and `sync` calls it on the state toggle and on a+ * credential save made while the binding is enabled. Everything reading them has to say+ * "since this connection opened" — an empty `lastInboundAt` is not evidence that nothing+ * ever arrived. `lastDeliveryError` is never cleared within an entry either: a failure+ * that comes and goes would otherwise be wiped by the next ordinary message, so `at` is+ * what tells the reader how stale it is.+ */+ lastInboundAt: string | null;+ lastDeliveryError: MessagingDeliveryError | null;+ /**+ * The last connection failure, kept across recovery. `status.lastError` is wiped by the+ * next successful connect, which is exactly the case worth reporting: a connector that+ * flaps — a second program taking turns with this one on the same bot token — reads as+ * healthy in every snapshot taken between its failures.+ */+ lastConnectionError: { at: string; detail: string } | null;/** Last observed run state on the Session channel. */active: string;/** False while joined mid-run: that run's partial tail must not mirror as half a reply. */@@ -370,11 +396,24 @@ export class MessagingBridge {this.deps.repo.deleteSession(sessionId);}- /** One channel's runtime status (only the connected channel is ever anything but disconnected). */+ /**+ * One channel's runtime status (only the connected channel is ever anything but+ * disconnected), plus what this connection has actually seen: when a message last arrived,+ * what last failed after one did, and the last connection failure even after it recovered.+ * A binding can be `connected` with nothing wrong and still never receive anything, and+ * that combination is invisible without them.+ */statusOf(sessionId: string, channel: string): MessagingRuntimeStatus {const entry = this.entries.get(sessionId);if (!entry || entry.channel !== channel) return { state: "disconnected" };- return entry.status;+ return {+ ...entry.status,+ ...(entry.lastInboundAt !== null ? { lastInboundAt: entry.lastInboundAt } : {}),+ ...(entry.lastDeliveryError !== null ? { lastDeliveryError: entry.lastDeliveryError } : {}),+ ...(entry.lastConnectionError !== null+ ? { lastConnectionError: entry.lastConnectionError }+ : {}),+ };}/**@@ -446,11 +485,14 @@ export class MessagingBridge {channel: row.channel,connector,config: row.config,- status: { state: "connecting", changedAt: new Date(this.now()).toISOString() },+ status: { state: "connecting", changedAt: this.nowIso() },connection: null,unsubscribe: null,client: null,lastInboundMessageId: null,+ lastInboundAt: null,+ lastDeliveryError: null,+ lastConnectionError: null,active: runState,armed: runState === "idle",inCompaction: false,@@ -472,11 +514,7 @@ export class MessagingBridge {const connection = await connector.connect(row.config, {onMessage: (msg) => this.onInbound(entry, msg),onReady: () => this.setStatus(entry, { state: "connected" }),- onError: (err) => {- const detail = err instanceof Error ? err.message : String(err);- this.setStatus(entry, { state: "error", lastError: detail });- this.recordError(entry.sessionId, err, "messaging_connect_failed");- },+ onError: (err) => this.recordConnectionFailure(entry, err),});if (this.entries.get(row.sessionId) !== entry) {// A concurrent sync/unbind replaced this attempt while the channel was loading.@@ -485,9 +523,7 @@ export class MessagingBridge {}entry.connection = connection;} catch (err) {- const detail = err instanceof Error ? err.message : String(err);- this.setStatus(entry, { state: "error", lastError: detail });- this.recordError(row.sessionId, err, "messaging_connect_failed");+ this.recordConnectionFailure(entry, err);}}@@ -503,14 +539,80 @@ export class MessagingBridge {}}+ /** Every timestamp this bridge writes comes from the injected clock, never from `Date` directly. */+ private nowIso(): string {+ return new Date(this.now()).toISOString();+ }+/** Status write, guarded against a stale entry (replaced by a newer connect). */private setStatus(entry: BridgeEntry, patch: Omit<MessagingRuntimeStatus, "changedAt">): void {if (this.entries.get(entry.sessionId) !== entry) return;- entry.status = { ...patch, changedAt: new Date(this.now()).toISOString() };+ entry.status = { ...patch, changedAt: this.nowIso() };+ }++ /**+ * A connection failure, put in the three places one belongs: the live `error` state, the+ * copy kept across recovery, and the error table.+ *+ * Behind the same stale-entry guard `setStatus` uses, applied to all three — a connector+ * callback firing after a newer connect replaced this entry is reporting an attempt that was+ * already abandoned, and neither its status writes (which nothing reads) nor its record+ * (which would be filed against a binding since reconfigured) belong to the binding as it+ * now stands.+ */+ private recordConnectionFailure(entry: BridgeEntry, err: unknown): void {+ if (this.entries.get(entry.sessionId) !== entry) return;+ const detail = err instanceof Error ? err.message : String(err);+ this.setStatus(entry, { state: "error", lastError: detail });+ entry.lastConnectionError = { at: this.nowIso(), detail };+ this.recordError(entry.sessionId, err, "messaging_connect_failed");}+ /**+ * One error record for a messaging failure, filed under the Session's Project and Agent.+ *+ * The attribution is load-bearing, not decoration: `GET /api/projects/:id/usage/errors`+ * selects by project, and a record with none is "unattributed" — served only to admins+ * (`includeGlobalErrors`), so an ordinary member could never see a failure of their own+ * binding anywhere. The lookup uses the sessions index the bridge already holds; a row+ * deleted since leaves the record unattributed rather than dropping it.+ */private recordError(sessionId: string, err: unknown, code: string): void {- this.deps.errors.record({ source: "messaging", err, code, ctx: { sessionId } });+ const row = this.deps.sessions.findById(sessionId);+ this.deps.errors.record({+ source: "messaging",+ err,+ code,+ ctx: {+ sessionId,+ ...(row !== null ? { projectId: row.projectId, agentId: row.agentId } : {}),+ },+ });+ }++ /**+ * A failure AFTER an inbound message was accepted: recorded like any other, and also put+ * on the binding's runtime status so the panel can say it. The error table is a Project-wide+ * dashboard nobody visits to debug one bot; the binding's own panel is where the question+ * is asked.+ *+ * A later success does not clear it. An intermittent failure — a group admin who revokes+ * send rights for a minute, a rate limit — would otherwise be erased by the next ordinary+ * message and never be seen at all, which is the same blind spot `lastConnectionError`+ * exists to close. The panel states `at` so a stale one reads as stale.+ */+ private recordDeliveryFailure(+ entry: BridgeEntry,+ err: unknown,+ stage: MessagingDeliveryError["stage"],+ code: string,+ ): void {+ entry.lastDeliveryError = {+ at: this.nowIso(),+ stage,+ detail: err instanceof Error ? err.message : String(err),+ };+ this.recordError(entry.sessionId, err, code);}private async clientFor(sessionId: string, row: MessagingBindingRow): Promise<MessagingClient> {@@ -558,6 +660,9 @@ export class MessagingBridge {private async onInbound(entry: BridgeEntry, msg: MessagingInboundMessage): Promise<void> {if (this.entries.get(entry.sessionId) !== entry) return; // stale connectionif (this.isRedelivery(entry, msg)) return;+ // Stamped on acceptance, before anything can go wrong with it: the panel's question is+ // "did the channel deliver anything", which a later failure does not un-answer.+ entry.lastInboundAt = this.nowIso();try {const isDirect = msg.chatKind === "direct";// The chat becomes the reply target BEFORE any processing: even a rejected message@@ -589,7 +694,9 @@ export class MessagingBridge {msg.messageId === "" ? null : msg.messageId,);} catch (err) {- this.recordError(entry.sessionId, err, "messaging_inbound_failed");+ // The chat hears nothing when this fires — a Session that cannot load, a Workspace that+ // is gone — so the status line is the only place the user can find out it happened.+ this.recordDeliveryFailure(entry, err, "inbound", "messaging_inbound_failed");}}@@ -715,7 +822,7 @@ export class MessagingBridge {await client.sendText(chatId, chunk);}} catch (err) {- this.recordError(entry.sessionId, err, "messaging_send_failed");+ this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");}}}@@ -727,7 +834,7 @@ export class MessagingBridge {try {await target.client.sendText(target.chatId, text);} catch (err) {- this.recordError(entry.sessionId, err, "messaging_send_failed");+ this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");}}@@ -745,7 +852,7 @@ export class MessagingBridge {const client = await this.clientFor(entry.sessionId, row);return { row, chatId: row.lastChatId, client };} catch (err) {- this.recordError(entry.sessionId, err, "messaging_send_failed");+ this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");return null;}}diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex 30de5c4d..43be8349 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -810,6 +810,37 @@ describe("telegram binding routes and connector loop", () => {expect(runs[0]![0]!.text).toBe("deploy");});+ it("handles a real supergroup id end to end: routing, reply ref, and the mention strip", async () => {+ await bindEnabled(SID);+ // The shapes every fixture in this file used to avoid: a real supergroup chat id is+ // NEGATIVE and 14 digits, so it rides the reply ref in front of the `:` the parser splits+ // on, and it has to survive the string→number round trip the Bot API needs.+ const chatId = -1004475424385;+ fake.push({+ message_id: 4,+ chat: { id: chatId, type: "supergroup" },+ text: "@penguin_test_bot hi",+ entities: [{ type: "mention", offset: 0, length: 17 }],+ from: { first_name: "hiyouga", username: "hiyouga" },+ });+ await waitFor(() => runs.length === 1);+ // The handle is stripped and a real word remains, so this is a Task and not the+ // no-words branch — a one-word message is the shortest thing that could have been+ // emptied by mistake.+ expect(runs[0]![0]!.text).toBe("hi");+ const row = t.deps.messagingRepo.find(SID, "telegram")!;+ expect(row.lastChatId).toBe(String(chatId));+ expect(row.lastChatIsDirect).toBe(false);+ // The reply threads onto message 4 IN that chat: the ref packs both, and the leading+ // minus sign must not be mistaken for the separator.+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toContainEqual({+ chatId: String(chatId),+ text: "Reply text",+ replyTo: 4,+ });+ });+it("a group message that is nothing but the bot's mention starts no task", async () => {await bindEnabled(SID);fake.push({diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 50055236..4b60c5fd 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -77,6 +77,7 @@ class FakeClient implements FeishuApiClient {return null;}async sendText(chatId: string, text: string): Promise<void> {+ if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);this.sdk.noteSend();this.record({ kind: "send", target: chatId, text });await this.sdk.hold();@@ -137,6 +138,8 @@ class FakeSdk implements FeishuSdk {stallBotOpenId = false;/** Lookups the connector has started (one per connection, off the connect path). */botIdentityLookups = 0;+ /** Non-null makes every outbound sendText throw with this message. */+ failSend: string | null = null;async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {const client = new FakeClient(creds, this);this.clients.push(client);@@ -1119,6 +1122,202 @@ describe("messaging binding routes and bridge", () => {expect(fake.connections[0]!.closed).toBe(true);});+ // —— Delivery observability ————————————————————————————————————————————————+ // "Nothing happens" has three completely different causes — the channel never delivered+ // the message, it arrived and the Task could not start, or the Task ran and the reply+ // could not go out — and from the chat they are identical silence. The runtime status is+ // where they are told apart; the error table is Project-wide and nobody opens it to debug+ // one bot.++ const statusOf = async (sid: string) => {+ const res = await api.get(BASE(sid));+ return ((await res.json()) as FeishuBindingResponse).status;+ };++ it("reports when a message last arrived, and says plainly that none has", async () => {+ await bindEnabled(SID);+ // Connected with nothing wrong and nothing received: the exact shape a channel that+ // withholds messages produces, and the one thing the panel could not previously say.+ const quiet = await statusOf(SID);+ expect(quiet.state).toBe("connected");+ expect(quiet.lastInboundAt).toBeUndefined();+ expect(quiet.lastDeliveryError).toBeUndefined();++ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_seen",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ await waitFor(() => runs.length === 1);+ const seen = await statusOf(SID);+ expect(typeof seen.lastInboundAt).toBe("string");+ expect(Number.isNaN(Date.parse(seen.lastInboundAt!))).toBe(false);+ expect(seen.lastDeliveryError).toBeUndefined();+ });++ it("starts the arrival record over on a re-enable: it belongs to the connection, not the server", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_before_toggle",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ await waitFor(() => runs.length === 1);+ expect((await statusOf(SID)).lastInboundAt).toBeDefined();++ // The state toggle runs sync() -> connect(), which builds a fresh entry. So the empty+ // line is "nothing since this connection opened", NOT "nothing ever" — and the panel's+ // group-silence entry sends a user to remove the bot from a working group on the+ // strength of that line, so the scope has to be the one the copy claims.+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);+ const reconnected = await statusOf(SID);+ expect(reconnected.state).toBe("connected");+ expect(reconnected.lastInboundAt).toBeUndefined();+ });++ it("starts it over on a credential save too — the same reset with no toggle to see", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_before_resave",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ await waitFor(() => runs.length === 1);+ expect((await statusOf(SID)).lastInboundAt).toBeDefined();++ // A PUT on an enabled binding reconnects unconditionally (the never-diverge rule), so+ // even re-saving the credentials unchanged opens a new connection and a new record.+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);+ expect(fake.connections).toHaveLength(2);+ expect((await statusOf(SID)).lastInboundAt).toBeUndefined();+ });++ it("stamps arrival for a message it cannot act on, because it did arrive", async () => {+ await bindEnabled(SID);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_sticker",+ messageType: "image",+ content: JSON.stringify({ image_key: "img_1" }),+ });+ await waitFor(() => fake.allSends().some((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE));+ const status = await statusOf(SID);+ // The question this line answers is whether the channel is delivering anything, and a+ // sticker answers it. Stamping only what starts a Task would report a mute bot for a+ // chatty one, which is the reading the whole feature exists to prevent.+ expect(status.lastInboundAt).toBeDefined();+ expect(status.lastDeliveryError).toBeUndefined();+ expect(runs).toHaveLength(0);+ });++ it("keeps the last connection failure after the connection recovers", async () => {+ await bindEnabled(SID);+ const conn = fake.lastConnection();+ // A connector that fails and recovers — two programs taking turns on one bot token do+ // exactly this. `lastError` belongs to the error state and is gone the moment the state+ // leaves it, so between flaps the panel would otherwise show a clean `connected` and the+ // reader would be left with a symptom and no cause.+ conn.handlers.onError?.(new Error("another program is already polling this bot"));+ expect(t.deps.messaging.statusOf(SID, "feishu").state).toBe("error");+ conn.handlers.onReady?.();+ const recovered = t.deps.messaging.statusOf(SID, "feishu");+ expect(recovered.state).toBe("connected");+ expect(recovered.lastError).toBeUndefined();+ expect(recovered.lastConnectionError?.detail).toContain("already polling this bot");+ expect(Number.isNaN(Date.parse(recovered.lastConnectionError!.at))).toBe(false);+ });++ it("ignores a connection failure from an attempt a newer connect already replaced", async () => {+ await bindEnabled(SID);+ const superseded = fake.lastConnection();+ // A credential save reconnects an enabled binding, so the old connector's callbacks now+ // belong to an attempt that has been abandoned. They can still fire: a parked poll or an+ // in-flight request rejects whenever it rejects.+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);+ expect(fake.connections).toHaveLength(2);++ superseded.handlers.onError?.(new Error("stale poll failed"));+ // Neither the live status nor the error table hears from it. The status was already+ // guarded; the record was not, and filing one blames the binding as it now stands for a+ // failure of a configuration it no longer has.+ const live = t.deps.messaging.statusOf(SID, "feishu");+ expect(live.state).toBe("connected");+ expect(live.lastConnectionError).toBeUndefined();+ expect(t.deps.errorsRepo.recent(projectId).map((r) => r.code)).not.toContain(+ "messaging_connect_failed",+ );+ });++ 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";+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_send_fails",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ await waitFor(() => runs.length === 1);+ // The relay rides the entry's send chain, so poll the in-process status (synchronous)+ // and then assert on the shape the API actually serves.+ await waitFor(() => t.deps.messaging.statusOf(SID, "feishu").lastDeliveryError !== undefined);+ const failed = await statusOf(SID);+ // The message DID arrive — that half must not read as a delivery problem — and the stage+ // 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");++ // 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");+ });++ it("keeps a delivery failure on the status after a later message goes through", async () => {+ await bindEnabled(SID);+ fake.failSend = "Bad Request: have no rights to send a message";+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_rights_revoked",+ messageType: "text",+ content: JSON.stringify({ text: "hello" }),+ });+ await waitFor(() => runs.length === 1);+ await waitFor(() => t.deps.messaging.statusOf(SID, "feishu").lastDeliveryError !== undefined);+ const recorded = t.deps.messaging.statusOf(SID, "feishu").lastDeliveryError;++ // Rights restored, and the next reply really does reach the chat.+ fake.failSend = null;+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_rights_restored",+ messageType: "text",+ content: JSON.stringify({ text: "again" }),+ });+ await waitFor(() => runs.length === 2);+ await waitFor(() => fake.allSends().some((x) => x.text === "Reply text"));++ // The record stands, whole. Clearing it on success would erase every failure that comes+ // and goes — a send right revoked for a minute, a rate limit — as soon as the next+ // ordinary message worked, which is the blind spot lastConnectionError exists to close.+ // `at` is what tells the reader the failure is old, so the panel states it.+ const after = await statusOf(SID);+ expect(after.lastDeliveryError).toEqual(recorded);+ expect(after.lastInboundAt).toBeDefined();+ });+// —— Group mentions ————————————————————————————————————————————————————————// Feishu never puts a mention in the message text: it writes a placeholder (`@_user_1`)// and carries who it refers to alongside. Handed over raw, the model gets a token nothing@@ -1191,6 +1390,24 @@ describe("messaging binding routes and bridge", () => {expect(runs[0]![0]!.text).toBe("@Jules and @Alice ship it");});+ it("keeps a real group message whole: a mention plus words is never emptied", async () => {+ fake.botOpenId = "ou_this_bot";+ await bindEnabled(SID);+ // The emptiness rule strips EVERY placeholder to decide whether any words remain, so it+ // has to leave a message that does have words completely alone.+ await fake+ .lastConnection()+ .fire(+ groupMention("@_user_1 帮我看看 build 好了没 🚀", [+ { key: "@_user_1", name: "PenguinHarness", id: { open_id: "ou_this_bot" } },+ ]),+ );+ await waitFor(() => runs.length === 1);+ expect(runs[0]![0]!.text).toBe("帮我看看 build 好了没 🚀");+ // The run's own reply mirrors back; what must NOT appear is the no-words notice.+ expect(fake.allSends().some((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toBe(false);+ });+it("a message that is nothing but a mention starts no Task", async () => {await bindWithIdentity(SID);await fake@@ -1554,3 +1771,119 @@ describe("messaging binding routes and bridge", () => {});const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++/**+ * The failure #484 named and left open: an inbound message arrives, `startTask` throws, the+ * bridge swallows it into an error record and the chat hears nothing at all. It is one of the+ * three ways "nothing happens" happens, and the only way to tell it from the other two is for+ * the binding to say so.+ */+describe("an inbound message whose Task cannot start", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let fake: FakeSdk;++ beforeEach(async () => {+ fake = new FakeSdk();+ t = await createTestApp({+ feishuSdk: fake,+ // Not adopted, so the first task loads through here — a Workspace that has been+ // deleted under a live Session reaches startTask exactly like this.+ loader: {+ load: async () => {+ throw new Error("The original Session's Workspace no longer exists");+ },+ },+ });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ t.deps.sessionsRepo.insert(sessionRowOf(SID, "birder-default_project"));+ });+ afterEach(async () => {+ await t.cleanup();+ });++ it("is reported on the binding's status instead of being silent everywhere", async () => {+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);+ await fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_cannot_start",+ messageType: "text",+ content: JSON.stringify({ text: "deploy the build" }),+ });+ await waitFor(() => t.deps.messaging.statusOf(SID, "feishu").lastDeliveryError !== undefined);+ const status = t.deps.messaging.statusOf(SID, "feishu");+ // Arrived, then failed: reporting only the failure would send the user hunting for a+ // delivery problem that does not exist.+ expect(status.state).toBe("connected");+ expect(status.lastInboundAt).toBeDefined();+ expect(status.lastDeliveryError?.stage).toBe("inbound");+ expect(status.lastDeliveryError?.detail).toContain("Workspace no longer exists");+ // Nothing was said in the chat — which is exactly why the status has to say it.+ expect(fake.allSends()).toHaveLength(0);+ // Filed under the Project, so the errors table can serve it to an ordinary member.+ expect(t.deps.errorsRepo.recent("birder-default_project").map((r) => r.code)).toContain(+ "messaging_inbound_failed",+ );+ });+});++/**+ * The arrival stamp is written on ACCEPTANCE — after the redelivery drop, one line below it —+ * so a channel replaying a message it already delivered must not move it. Nothing else holds+ * that ordering, and with the wall clock two writes inside the same millisecond are+ * indistinguishable, so this suite drives the bridge's injected clock instead.+ */+describe("a redelivered inbound message", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let fake: FakeSdk;+ let runs: TextPayload[][];+ let clock: number;++ beforeEach(async () => {+ fake = new FakeSdk();+ clock = Date.parse("2026-08-26T09:00:00.000Z");+ t = await createTestApp({ feishuSdk: fake, now: () => new Date(clock) });+ const { cookie } = await provisionUser(t.app, "birder");+ api = apiClient(t.app, cookie);+ runs = [];+ const row = sessionRowOf(SID, "birder-default_project");+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(row, echoFakeSession(SID, runs));+ expect((await api.put(BASE(SID), PUT_BODY)).status).toBe(200);+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);+ });+ afterEach(async () => {+ await t.cleanup();+ });++ const fire = (messageId: string, text: string) =>+ fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId,+ messageType: "text",+ content: JSON.stringify({ text }),+ });++ it("leaves the arrival stamp where the first delivery put it", async () => {+ await fire("om_replayed", "hello");+ await waitFor(() => runs.length === 1);+ expect(t.deps.messaging.statusOf(SID, "feishu").lastInboundAt).toBe("2026-08-26T09:00:00.000Z");++ clock += 60_000;+ await fire("om_replayed", "hello");+ // The duplicate is a complete no-op, the stamp included: moving it would report traffic+ // the channel never sent, on the one line a user reads to decide whether it is sending.+ expect(runs).toHaveLength(1);+ expect(t.deps.messaging.statusOf(SID, "feishu").lastInboundAt).toBe("2026-08-26T09:00:00.000Z");++ // A genuinely new message does move it, so the assertion above is not vacuous.+ await fire("om_fresh", "again");+ await waitFor(() => runs.length === 2);+ expect(t.deps.messaging.statusOf(SID, "feishu").lastInboundAt).toBe("2026-08-26T09:01:00.000Z");+ });+});diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex 5d455741..2f22c449 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -45,6 +45,7 @@ import type {import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";+import { formatDateTime } from "../../lib/format";import { toneInk, type Tone } from "../../lib/tone";import { Button } from "../../components/ui/button";import { FieldLabel } from "../../components/ui/field";@@ -620,6 +621,64 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }){facts.status.lastError}</p>)}+ {/* A failure the connection has already recovered from. `lastError` belongs to the+ error state and is wiped the moment the state leaves it, so a connector that flaps+ — which is what a second program polling the same bot token produces — shows a+ clean `connected` in every snapshot taken between its failures, and the reader is+ left with the symptom and no trace of the cause. */}+ {facts.status.state !== "error" && facts.status.lastConnectionError !== undefined && (+ <p+ title={facts.status.lastConnectionError.detail}+ className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"+ >+ {S.messaging.lastConnectionError(+ formatDateTime(facts.status.lastConnectionError.at),+ facts.status.lastConnectionError.detail,+ )}+ </p>+ )}+ {/* What this connection has actually seen. "Connected" answers whether the socket is+ up, and nothing else on this panel could tell a user whether the platform is+ delivering anything — a Telegram bot muted by group privacy, or one that was never+ really added to the group, is `connected` with no error, forever. It resets with+ every (re)connect, a re-enable or a credential save included (it is the live+ connection's own observation), which is why the empty case says "since this+ connection opened" rather than reading as "never".++ Shown outside `connected` too, and gated only on there being a connection at all:+ it is a fact about traffic rather than about the socket, and `connecting` (a+ Telegram bot is mid-handshake and backlog drain) and `error` (a flapping token) are+ exactly where a reader needs to know whether this bot has been receiving at all. */}+ {facts.status.state !== "disconnected" &&+ (facts.status.lastInboundAt !== undefined ? (+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.messaging.inboundLastAt(formatDateTime(facts.status.lastInboundAt))}+ </p>+ ) : (+ <p className="text-xs text-gray-500 dark:text-gray-400">{S.messaging.inboundNone}</p>+ ))}+ {/* A failure AFTER a message arrived. Both stages reach the chat as silence, so the+ line has to say which one it was: "it never started" sends the user to the Session,+ "the reply never went out" sends them to the bot's permissions in the chat. Nothing+ clears it on a later success, so the time goes in the sentence like the connection+ error's: a revoked send right restored a minute later otherwise reads for days as a+ live fault, and a title= is hover-only and unreachable on touch. */}+ {facts.status.lastDeliveryError !== undefined && (+ <p+ title={facts.status.lastDeliveryError.detail}+ className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"+ >+ {facts.status.lastDeliveryError.stage === "inbound"+ ? S.messaging.deliveryFailedInbound(+ formatDateTime(facts.status.lastDeliveryError.at),+ facts.status.lastDeliveryError.detail,+ )+ : S.messaging.deliveryFailedSend(+ formatDateTime(facts.status.lastDeliveryError.at),+ facts.status.lastDeliveryError.detail,+ )}+ </p>+ )}</div>{/* Entry-level probes — the MCP dialog idiom: standalone buttons, results as toasts. */}<div className="flex flex-wrap items-center gap-2">@@ -874,6 +933,7 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel }){channel === "telegram" && <li>{S.messaging.troubleOnePoller}</li>}{channel === "telegram" && <li>{S.messaging.troubleGroupPrivacy}</li>}{channel === "qq" && <li>{S.messaging.troubleQQPassive}</li>}+ {channel === "telegram" && <li>{S.messaging.troubleNoGroupInbound}</li>}</ul></HelpFold></div>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex bf5b8020..9e0e352a 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1916,6 +1916,22 @@ Scenarios:telegram: "Telegram connection enabled",qq: "QQ connection enabled",},+ /**+ * Delivery observability under the toggle: has anything arrived, and did the last one get+ * through. Both readings belong to the LIVE CONNECTION and start over on a re-enable or a+ * credential save, so the empty case names that scope instead of reading as "never".+ * Each failure line carries its own time: nothing clears it on a later success, and a+ * title= is unreachable on touch.+ */+ inboundLastAt: (when: string) => `Last message received: ${when}`,+ inboundNone: "No message has arrived since this connection opened",+ deliveryFailedInbound: (when: string, detail: string) =>+ `A message arrived at ${when} but its task never started: ${detail}`,+ deliveryFailedSend: (when: string, detail: string) =>+ `The task ran but its reply failed to go out at ${when}: ${detail}`,+ /** A connection failure the connection has since recovered from (lastError is gone by then). */+ lastConnectionError: (when: string, detail: string) =>+ `The connection dropped at ${when}: ${detail}`,/** The collapsed FAQ folds below the save area. */faqSetupTitle: "Set up the bot",faqWhatTitle: "What binding does",@@ -1929,12 +1945,14 @@ Scenarios:troubleConnError:"Connection status shows an error? Check the credentials; for Feishu also confirm the API domain and the long-connection event subscription.",troubleOnePoller:- "Telegram reports that another program is polling? A Bot Token serves exactly one program at a time — close the other PenguinHarness server or bot script using it, or give this conversation a bot of its own.",+ "Telegram reports that another program is polling? A Bot Token serves exactly one program at a time — close the other PenguinHarness server or bot script using it, or give this conversation a bot of its own. A getUpdates you run by hand (a curl to see what Telegram has queued) is that other program too: disable the connection here before running one. Inspecting them by hand can also discard them — any call you pass an offset to confirms everything before it, and the app's own next connect drops the backlog — so retest with a freshly sent message rather than the ones you just looked at.",troubleGroupPrivacy:"The bot ignores everything you say in a Telegram group? Telegram's Group Privacy is on by default, and under it a bot that is not an administrator of the group receives only commands addressed to it (such as /start@your_bot) and replies to its own messages — ordinary group messages are never delivered at all, and the connection itself looks perfectly healthy. Making the bot an administrator of that group fixes it on its own, since administrators always receive every message. Otherwise turn Group Privacy off with /setprivacy in @BotFather, then remove the bot from the group and add it back — a group it is already in does not pick up the change.",/** The QQ-only failure a user will otherwise read as "the bot is broken". */troubleQQPassive:"No replies arriving in QQ? QQ only lets a bot answer a message you just sent: a turn started in the web app is not mirrored there, and replies stop being deliverable a few minutes after your last QQ message. Send another message in QQ to continue.",+ troubleNoGroupInbound:+ "Sending in a group but the panel still says no message has arrived? Read that line as evidence only about a message sent after it: it covers the current connection alone, and disabling and re-enabling the connection — or saving the credential again — opens a new one and starts it over. So send a fresh one now. If the line still reports nothing, Telegram is not delivering it and nothing on this machine can change that: confirm the bot is still in that group; if you have just turned Group Privacy off in @BotFather, remove the bot from the group and add it back, because an existing group does not pick up the change; and confirm nothing else is polling the same token — including a getUpdates you ran yourself (see above). Telegram channel posts are not supported either — this connection handles groups and direct chats only.",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex c3dfde6c..52b82381 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1876,6 +1876,21 @@ Benchmark:telegram: "Telegram 连接已启用",qq: "QQ 连接已启用",},+ /**+ * Delivery observability under the toggle: has anything arrived, and did the last one get+ * through. Both readings belong to the LIVE CONNECTION and start over on a re-enable or a+ * credential save, so the empty case names that scope instead of reading as "never".+ * Each failure line carries its own time: nothing clears it on a later success, and a+ * title= is unreachable on touch.+ */+ inboundLastAt: (when: string) => `最近收到消息:${when}`,+ inboundNone: "本次连接建立以来还没有收到过消息",+ deliveryFailedInbound: (when: string, detail: string) =>+ `${when} 收到过一条消息,但任务没有开始:${detail}`,+ deliveryFailedSend: (when: string, detail: string) =>+ `任务已完成,但回复于 ${when} 发送失败:${detail}`,+ /** A connection failure the connection has since recovered from (lastError is gone by then). */+ lastConnectionError: (when: string, detail: string) => `连接曾于 ${when} 中断:${detail}`,/** The collapsed FAQ folds below the save area. */faqSetupTitle: "如何创建机器人",faqWhatTitle: "绑定后会发生什么",@@ -1888,12 +1903,14 @@ Benchmark:troubleConnError:"连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。",troubleOnePoller:- "Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。",+ "Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。手动执行的 getUpdates(例如用 curl 查看 Telegram 那边积压了什么)同样算作「另一个程序」:跑它之前先在这里停用连接。而且手动查看也可能把它们丢掉——任何带 offset 的调用都会确认它之前的全部更新,应用自己的下一次连接也会清空积压——所以复测请重新发一条新消息,而不是指望刚才看到的那几条。",troubleGroupPrivacy:"在 Telegram 群里发消息,机器人毫无反应?Telegram 的 Group Privacy 默认开启,此时不担任该群管理员的机器人只能收到明确指向它的命令(如 /start@your_bot)和对它自己消息的回复,普通群消息根本不会送达,连接本身也没有任何异常。把机器人设为该群的管理员即可单独解决,管理员始终收到全部消息。也可以到 @BotFather 用 /setprivacy 关闭 Group Privacy,然后把机器人移出该群再重新拉入——已在的群不会自动生效。",/** The QQ-only failure a user will otherwise read as "the bot is broken". */troubleQQPassive:"QQ 里收不到回复?QQ 只允许机器人回复你刚发出的消息:在网页端发起的对话不会同步过去,距离你上一条 QQ 消息过去几分钟后也发不出。在 QQ 里再发一条消息即可继续。",+ troubleNoGroupInbound:+ "在群里发消息,面板却一直显示「本次连接建立以来还没有收到过消息」?这一行只能作为你读到它之后再发的那条消息的证据:它只覆盖当前这条连接,停用再启用连接、或者再保存一次凭证,都会开启一条新连接并把它清零。所以先重新发一条。如果这一行仍然显示没有收到过,那就是 Telegram 没有把它投递过来,本机再怎么查也无济于事:确认机器人确实还在这个群里;如果刚在 @BotFather 关掉 Group Privacy,必须把机器人移出该群再重新拉入,已有的群不会自动生效;并确认没有别的程序(包括你自己手动跑的 getUpdates,见上一条)在用同一个 Token 轮询。另外,Telegram 频道(channel)的贴文不受支持——本连接只处理群聊与私聊。",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex 7e3df5cc..9d421027 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -27,6 +27,7 @@ import {import { emptyMessagingForm } from "../src/features/messaging/messaging-binding-form";import { S, setActiveStrings, zh } from "../src/lib/strings";import { en } from "../src/lib/strings-en";+import { formatDateTime } from "../src/lib/format";afterEach(() => setActiveStrings(zh));@@ -220,6 +221,167 @@ describe("MessagingBindingBody", () => {expect(html).toContain("grid-cols-3");});+ it("says whether anything has arrived, and which end failed when something did", () => {+ // A bot Telegram is withholding messages from is `connected` with no error, forever.+ // Without this line the panel has nothing to distinguish it from a healthy binding+ // nobody has written to.+ const quiet = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: { state: "connected" },+ },+ }),+ );+ expect(quiet).toContain(S.messaging.inboundNone);++ const seen = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: { state: "connected", lastInboundAt: "2026-08-26T09:30:00.000Z" },+ },+ }),+ );+ expect(seen).toContain(S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")));+ expect(seen).not.toContain(S.messaging.inboundNone);++ // The two post-arrival failures are the same silence in the chat and different actions+ // for the reader, so the line names the stage rather than only the message.+ const detail = "Bad Request: have no rights to send a message";+ const at = "2026-08-26T09:31:00.000Z";+ const failed = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: {+ state: "connected",+ lastInboundAt: "2026-08-26T09:30:00.000Z",+ lastDeliveryError: { at, stage: "send", detail },+ },+ },+ }),+ );+ expect(failed).toContain(S.messaging.deliveryFailedSend(formatDateTime(at), detail));+ expect(failed).not.toContain(S.messaging.deliveryFailedInbound(formatDateTime(at), detail));+ // The failure's own time is in the sentence, not parked in title=: nothing clears the+ // record on a later success, so a rights problem fixed three days ago would otherwise+ // read as live — and a hover-only title is unreachable on a touch screen.+ expect(failed).toContain(`>${S.messaging.deliveryFailedSend(formatDateTime(at), detail)}</p>`);+ expect(failed).toContain(`title="${detail}"`);+ // Arrival is still reported: a send failure is not a delivery failure.+ expect(failed).toContain(S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")));+ });++ it("names the inbound stage when a message arrived and its task never started", () => {+ // The stage is an instruction, not a wording: "it never started" sends the reader to the+ // Session, "the reply never went out" sends them to the bot's rights in the chat. Only+ // the send branch had ever been rendered here, so the other could break unseen.+ // No apostrophe in the fixture: renderToStaticMarkup escapes one, and the assertion+ // below matches the rendered text rather than the string the dictionary returned.+ const detail = "The Workspace this Session runs in no longer exists";+ const at = "2026-08-26T09:31:00.000Z";+ const html = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: {+ state: "connected",+ lastInboundAt: "2026-08-26T09:30:00.000Z",+ lastDeliveryError: { at, stage: "inbound", detail },+ },+ },+ }),+ );+ expect(html).toContain(`>${S.messaging.deliveryFailedInbound(formatDateTime(at), detail)}</p>`);+ expect(html).not.toContain(S.messaging.deliveryFailedSend(formatDateTime(at), detail));+ });++ it("reports arrival while connecting and while erroring: it is traffic, not the socket", () => {+ const live: MessagingChannelFacts = { ...DARK, secretConfigured: true, enabled: true };+ // Telegram's connect runs getMe, getWebhookInfo, a backlog drain and a first getUpdates+ // before it reads as connected, and a token two programs are fighting over sits in+ // `error` half the time. Gating this line on `connected` hid it in both — the flapping+ // case being the one the panel was written for.+ const connecting = render(+ stateOf("telegram", { telegram: { ...live, status: { state: "connecting" } } }),+ );+ expect(connecting).toContain(S.messaging.inboundNone);++ const erroring = render(+ stateOf("telegram", {+ telegram: {+ ...live,+ status: {+ state: "error",+ lastError: "another program is already polling this bot",+ lastInboundAt: "2026-08-26T09:30:00.000Z",+ },+ },+ }),+ );+ // In `error`, a bot that has been receiving fine and one that never has are different+ // problems, and lastConnectionError is hidden there — this line is all that separates them.+ expect(erroring).toContain(+ S.messaging.inboundLastAt(formatDateTime("2026-08-26T09:30:00.000Z")),+ );++ // A binding with no connection has no such record and must not claim one.+ const dark = render(stateOf("telegram", { telegram: { ...DARK, secretConfigured: true } }));+ expect(dark).not.toContain(S.messaging.inboundNone);+ });++ it("leaves the last connection failure on screen after the connection recovers", () => {+ const detail = "another program is already polling this bot";+ const html = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: {+ state: "connected",+ lastConnectionError: { at: "2026-08-26T09:00:00.000Z", detail },+ },+ },+ }),+ );+ // A flapping connector is `connected` in every snapshot between its failures, so without+ // this the reader sees a healthy binding and no trace of the cause.+ expect(html).toContain(+ S.messaging.lastConnectionError(formatDateTime("2026-08-26T09:00:00.000Z"), detail),+ );++ // While the connection is actually down, `lastError` is the live one and this must not+ // double up beside it.+ const down = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: {+ state: "error",+ lastError: detail,+ lastConnectionError: { at: "2026-08-26T09:00:00.000Z", detail },+ },+ },+ }),+ );+ expect(down).toContain(`>${detail}</p>`);+ expect(down).not.toContain(+ S.messaging.lastConnectionError(formatDateTime("2026-08-26T09:00:00.000Z"), detail),+ );+ });+it("shows the switch's gating reason when the other channel holds the connection", () => {const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);const html = render(