A local-first multi-agent app development platform, built on PenguinHarness
Relay only a run's final reply, per messaging binding (#512)
Yaowei Zheng5607c28b0f54
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.md b/changelog/unreleased/2026-08-27-backward-compatibility.mdindex 9a2c4478..3c5be5c6 100644--- a/changelog/unreleased/2026-08-27-backward-compatibility.md+++ b/changelog/unreleased/2026-08-27-backward-compatibility.md@@ -3,20 +3,22 @@- **Date:** 2026-08-27- **Type:** process- **Scope:** `server`, `web`-- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508), [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)- **Breaking:** yes — on downgrade only: a Telegram binding whose last message was written in a forum topic sends nothing on a build from before this change until its next inbound message[中文版](2026-08-27-backward-compatibility.zh.md)-This batch touched three things that outlive a release.+This batch touched four things that outlive a release.[Scoping browser-persisted UI state to its data root](2026-08-26-install-scoped-local-state.md)added a file in the data root, `<root>/install-id`, and a `localStorage` entry,-`penguin.installId`; and+`penguin.installId`;[a Telegram reply carrying the forum topic it was asked in](2026-08-26-telegram-forum-topics.md)changed what `messaging_bindings.last_chat_id` means on an existing `web.db`, without adding or-dropping a column or rewriting a row. Only the browser side and the column needed a decision; the-file and the key are recorded here too, so a reader looking for "does my install need anything?"-finds every answer in one place.+dropping a column or rewriting a row; and+[relaying a run's final reply only](2026-08-27-messaging-final-reply-only.md) added a column,+`messaging_bindings.final_reply_only`. Only the browser side and the `last_chat_id` change needed+a decision; the file, the key and the new column are recorded here too, so a reader looking for+"does my install need anything?" finds every answer in one place.## The browser that has keys but no recorded id@@ -87,6 +89,21 @@ every ordinary group and every forum's General topic writes one on every messageparse is the format, so nothing ever stops writing the bare form and nothing ever removes the codethat reads it. `chatRefOf` in `telegram-connector.ts` carries the same note.+## The added `final_reply_only` column++[Relaying a run's final reply only](2026-08-27-messaging-final-reply-only.md) added+`messaging_bindings.final_reply_only INTEGER NOT NULL DEFAULT 0`, ALTERed in on open by the+`ensureColumn` list that exists for exactly this — the same shape `line_per_message` took one+batch earlier. It is purely additive and needs no decision: the default reproduces the delivery+every existing binding already had — every completed assistant message of a run, mirrored as it+completes — so no binding changes behaviour, nothing is rewritten, and the user does nothing. The+`ensureColumn` entry stays for as long as a `web.db` formed before this release can be opened, on+the same terms as the rest of that list.++A downgrade is invisible in both directions. What the column does is done by the bridge, so an+older server ignores a column it has never heard of and relays every message again — the setting+is still on disk, and an upgrade back honours it without the user re-saving anything.+## CompatibilityNo action is required on upgrade or on downgrade. The single manual step, for a user who wipeddiff --git a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md b/changelog/unreleased/2026-08-27-backward-compatibility.zh.mdindex c70318ff..21b15eee 100644--- a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md+++ b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md@@ -3,17 +3,19 @@- **Date:** 2026-08-27- **Type:** process- **Scope:** `server`, `web`-- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508), [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)- **Breaking:** yes — 仅在降级时:最后一条消息写在论坛话题里的 Telegram 绑定,在此改动之前的构建上会一直发不出消息,直到下一条入站消息到来[English](2026-08-27-backward-compatibility.md)-本批改动动到了三样会跨越版本存活的东西。[把浏览器持久化的 UI 状态按数据根划定作用域](2026-08-26-install-scoped-local-state.zh.md)+本批改动动到了四样会跨越版本存活的东西。[把浏览器持久化的 UI 状态按数据根划定作用域](2026-08-26-install-scoped-local-state.zh.md)新增了数据根里的文件 `<root>/install-id` 与 `localStorage` 条目 `penguin.installId`;[让 Telegram 的回复带上提问所在的论坛话题](2026-08-26-telegram-forum-topics.zh.md)则改变了存量-`web.db` 上 `messaging_bindings.last_chat_id` 的含义——不增删任何列,也不重写任何行。需要做决定的-只有浏览器一侧与这一列;那个文件和那个键也一并记在这里,方便有人来查「我这套安装需要做什么吗?」时,-在同一处找到全部答案。+`web.db` 上 `messaging_bindings.last_chat_id` 的含义——不增删任何列,也不重写任何行;+[只转发一次运行的最终回复](2026-08-27-messaging-final-reply-only.zh.md)新增了一列+`messaging_bindings.final_reply_only`。需要做决定的只有浏览器一侧与 `last_chat_id` 的含义变化;那个+文件、那个键和这个新列也一并记在这里,方便有人来查「我这套安装需要做什么吗?」时,在同一处找到全部+答案。## 有键、但从未记录过 id 的浏览器@@ -70,6 +72,18 @@本身就是这个格式,所以裸形式永远会继续被写入,读取它的代码也永远不会被删除。`telegram-connector.ts` 里的 `chatRefOf` 写有同样的说明。+## 新增的 `final_reply_only` 列++[只转发一次运行的最终回复](2026-08-27-messaging-final-reply-only.zh.md)新增了+`messaging_bindings.final_reply_only INTEGER NOT NULL DEFAULT 0`,由既有的 `ensureColumn` 清单在打+开时 ALTER 补上——那份清单正是为此存在,形状与上一批的 `line_per_message` 完全相同。它纯属新增,无需+任何决策:默认值复现了每份存量绑定原本的送达方式——一次运行中每条完成的助手消息在完成时逐条转发——因+此没有任何绑定的行为改变,没有任何数据被改写,用户也无需做任何事。该 `ensureColumn` 条目的保留期与+「本次发布之前形成的 `web.db` 仍可被打开」等长,与该清单中其余条目同一口径。++降级在两个方向上都看不出来。这一列的效果由 bridge 实现,因此旧构建会忽略一个它从未听说过的列,重新+逐条转发;设置本身仍留在磁盘上,再升级回来时无需用户重新保存即可继续生效。+## 兼容性升级与降级都不需要做任何操作。对在本版本之前清空过数据根的用户而言,唯一需要手动执行的一步在上文。diff --git a/changelog/unreleased/2026-08-27-messaging-final-reply-only.md b/changelog/unreleased/2026-08-27-messaging-final-reply-only.mdnew file mode 100644index 00000000..a0344e02--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-final-reply-only.md@@ -0,0 +1,67 @@+# A messaging binding can relay a run's final reply only++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)++[中文版](2026-08-27-messaging-final-reply-only.zh.md)++Every completed assistant message of a run was mirrored to the chat the moment it completed, so+a run that writes working notes between tool calls sent each note as its own message. A+per-binding option now holds those back and delivers the run's LAST completed assistant text+alone, when the run ends — the answer without the work. Off by default, and off is byte-for-byte+the previous behaviour.++## Details++- The option is stored as `messaging_bindings.final_reply_only`, a column beside `enabled` and+ `line_per_message` for the same reason that one is there: `config_json` is the channel's own+ credential document, owned by its connector, while this means the same thing on every channel.+ It is `INTEGER NOT NULL DEFAULT 0`, ALTERed into an existing database on open by the standing+ `ensureColumn` list — the added-column convention described under+ [backward compatibility](2026-08-27-backward-compatibility.md), which needs nothing of the+ user: the default reproduces the delivery every existing binding already had.+- `finalReplyOnly` joined `FeishuBindingInfo` / `TelegramBindingInfo` / `QQBindingInfo` and all+ three PUT bodies, alongside `linePerMessage` and on the same terms — an ordinary form field+ applied on Save, no route of its own, an omitted value keeping the stored one, and a new+ binding starting with it off.+- What is held is one message: each completed assistant text replaces the one the run was+ already holding, and the survivor is delivered on the run's `task_state` → `idle` edge,+ through the same path every relayed message takes. Chunking, the per-line split, the pacing,+ the group's single reply-to and the send chain's ordering are the ones already there.+- A held reply is addressed where its run was ASKED, not where the chat has since moved. The+ chat ref and the message its first chunk quotes are captured on the run's `task_state` →+ `running` edge, because this is the one delivery that leaves at the far end of a run: a second+ person writing in another Telegram forum topic meanwhile would otherwise take delivery of a+ whole answer to a question they never asked, quoted onto their own message. The files that+ follow the held reply go to the same place. A message relayed as it completes is unchanged —+ it goes to the chat the row names then, which is where the conversation actually is.+- The two delivery options compose in one direction: `finalReplyOnly` picks which text is sent+ and `linePerMessage` decides how that one text is split, so a binding with both on sends the+ final reply one message per line.+- The files a run's reply mentions follow the words that actually REACHED THE CHAT. With the+ option on, that is the final message alone: a file named only in a held-back working note has+ nothing in the chat to say why it arrived, and the mention is the whole reason this feature+ knows which output was the point.+- On QQ the option cuts both ways. It spends the least of that platform's passive-reply+ budget a run can spend — one message — but a passive reply is accepted only for a few+ minutes after the inbound message that funds it, and holding the reply until the run ends+ spends that window on the run: a run that outlives it delivers nothing, where the+ every-message relay would have sent whatever completed inside it. That is a different+ outcome rather than a shade of the same one — silence on the other two channels, lost+ output here — so on QQ it is said twice rather than left to these notes: appended to the+ option's explanation, for the reader deciding, and stood under the row as a warning strip+ while the switch is actually on. `linePerMessage` needs no such warning: QQ clamps the split+ to its own budget and the reply still arrives.+- The `approval_request` notice is not an assistant message and is unaffected — a run blocked on+ approval is exactly when the chat has to hear something. The other fixed notices and the test+ message are unaffected for the same reason, compaction output is still skipped before any of+ this, and a connection that joins mid-run still relays nothing from that run.+- A binding that holds a reply and never sees the run end — the process stops, or a state toggle+ or credential save rebuilds the connection mid-run — delivers nothing of what it held. The+ every-message path loses only the remainder of that run.+- In the binding editor the two options close the form as a pair of `Switch` rows, identical on+ all three channels, saved by the existing Save action, each with its explanation behind the+ "?" beside its label. They are ordered as they take effect: which messages are sent, then how+ each one is split.diff --git a/changelog/unreleased/2026-08-27-messaging-final-reply-only.zh.md b/changelog/unreleased/2026-08-27-messaging-final-reply-only.zh.mdnew file mode 100644index 00000000..4d611e3d--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-final-reply-only.zh.md@@ -0,0 +1,51 @@+# 消息绑定可以只转发一次运行的最终回复++- **Date:** 2026-08-27+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)++[English](2026-08-27-messaging-final-reply-only.md)++此前一次运行中每条完成的助手消息都会在完成的那一刻转发到聊天,因此在工具调用之间写下过程记录+的运行,会把每条记录都作为一条消息发出去。现在每份绑定多了一个选项,可以把这些消息扣下,只在运+行结束时发出该次运行**最后**完成的那段助手文本——只要结论,不要过程。默认关闭,关闭时的行为与此+前逐字节一致。++## 细节++- 该选项存为 `messaging_bindings.final_reply_only` 列,与 `enabled`、`line_per_message` 并列,理+ 由和后者当初一样:`config_json` 是渠道自己的凭据文档、由其连接器拥有,而这个选项在每个渠道上+ 含义相同。它是 `INTEGER NOT NULL DEFAULT 0`,由既有的 `ensureColumn` 清单在打开存量数据库时+ ALTER 补上——即[向后兼容](2026-08-27-backward-compatibility.zh.md)中记述的新增列惯例,用户无需+ 做任何事:默认值复现了每份存量绑定原本的送达方式。+- `finalReplyOnly` 加入 `FeishuBindingInfo` / `TelegramBindingInfo` / `QQBindingInfo` 与三个 PUT+ 请求体,与 `linePerMessage` 并列、口径相同——随 Save 生效的普通表单字段,没有独立路由,省略则+ 保持已存值,新建的绑定默认关闭。+- 扣下的始终只有一条:每条完成的助手文本覆盖该次运行此前扣下的那条,留到最后的那条在运行的+ `task_state` → `idle` 边沿发出,走的是每条转发消息都走的同一条路径。长度分段、按行拆分、发送+ 节奏、群聊中唯一的一次回复引用、发送链的顺序,都沿用现有的那一套。+- 被扣下的回复发往**提问所在的那个会话**,而不是聊天此后移动到的那个。会话引用与首段所引用的那条入+ 站消息,都在该次运行的 `task_state` → `running` 边沿取下:只有这一条消息是在运行的另一端才发出+ 的,否则期间在另一个 Telegram 论坛话题里发言的第二个人,会收到一份自己从未提过的问题的完整回答,+ 还被引用在他自己的消息上。跟随这条回复的文件发往同一处。完成即转发的消息不受影响——它仍然发往行上+ 当时记录的会话,那里才是对话正在进行的地方。+- 两个送达选项按一个方向叠加:`finalReplyOnly` 决定发哪一段文本,`linePerMessage` 决定这段文本+ 怎么拆,因此同时开启时,最终回复按行逐条发出。+- 随回复发送的文件,跟随**真正到达聊天的那些文字**。选项开启时就是那条最终消息:只在被扣下的过程+ 记录中提到的文件,在聊天里找不到任何一句话解释它为何出现,而「被提及」正是这个功能判断哪个产+ 物才是交付物的全部依据。+- 在 QQ 上该选项有利有弊:它把一次运行对该平台被动回复额度的消耗压到最低——只发一条;但被动回复+ 只在为其提供额度的入站消息之后几分钟内被接受,而把回复扣到运行结束才发,等于把这个窗口花在了运+ 行本身上:运行时长超过窗口时什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。+ 这与另外两个渠道是不同的结果,而不是同一件事的程度差别——那边的代价是安静,这边是输出丢失——所以在+ QQ 上这句提醒说了两遍,而不是只留在这份记录里:既附在该选项的说明中供正在做决定的人读到,也在开关+ 真正打开时以警示条的形式立在该行下面。「每行一条消息」不需要类似的提醒:QQ 会把拆分收敛到自己的额+ 度内,回复仍然会到达。+- `approval_request` 提醒不属于助手消息,不受影响——运行卡在审批上,恰恰是聊天必须听到动静的时+ 候。其余固定提示与测试消息同理不受影响;压缩输出仍在这一切之前就被跳过;中途接入的连接依旧不+ 转发该次运行的任何内容。+- 扣着回复却始终没等到运行结束的绑定——进程结束,或运行中途的启用开关、凭证保存重建了连接——扣下+ 的内容不会发出。逐条转发的路径在同样的情况下只损失该次运行的剩余部分。+- 绑定编辑器中,两个选项以一对 `Switch` 行收尾表单,三个渠道完全一致,由既有的 Save 保存,各自的+ 说明放在标签旁的「?」之后。两行按生效顺序排列:先决定发哪些消息,再决定每条怎么拆。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 8a68cc75..71eee425 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -297,21 +297,21 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th| Method | Path | Description || --- | --- | --- |-| GET | /messaging | Channel-agnostic read: EVERY saved channel config (`channel` discriminant, secrets masked, per-row `enabled` intent + `linePerMessage` + runtime status + `lastChatKnown`). The channel-aware binding editor loads this one |+| GET | /messaging | Channel-agnostic read: EVERY saved channel config (`channel` discriminant, secrets masked, per-row `enabled` intent + `linePerMessage` + `finalReplyOnly` + runtime status + `lastChatKnown`). The channel-aware binding editor loads this one || GET | /messaging/feishu | The Feishu config in a `{binding, status}` envelope (null when not saved) |-| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?}`. An omitted/blank `appSecret` keeps the stored one; `clearAppSecret: true` drops it (a typed secret wins; 409 `messaging_disable_before_clear` while enabled — the cleared config keeps its row and non-secret fields); `baseDomain` defaults to `https://open.feishu.cn`. No connection side effect — except that an **enabled** binding's connector restarts with the new credentials, so stored config and live connection never diverge. A save never conflicts across Sessions, with one exception that follows from that restart: re-pointing an **enabled** binding at an account ANOTHER Session has enabled answers 409 `account_enabled_elsewhere`, because the restart would otherwise carry a second live connection onto it without passing the enable gate |+| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?}`. An omitted/blank `appSecret` keeps the stored one; `clearAppSecret: true` drops it (a typed secret wins; 409 `messaging_disable_before_clear` while enabled — the cleared config keeps its row and non-secret fields); `baseDomain` defaults to `https://open.feishu.cn`. No connection side effect — except that an **enabled** binding's connector restarts with the new credentials, so stored config and live connection never diverge. A save never conflicts across Sessions, with one exception that follows from that restart: re-pointing an **enabled** binding at an account ANOTHER Session has enabled answers 409 `account_enabled_elsewhere`, because the restart would otherwise carry a second live connection onto it without passing the enable gate || POST | /messaging/feishu/state | The connection toggle: `{enabled}` — enabling connects with the STORED credentials, disabling terminates. 409 `another_channel_enabled` while the Session's other channel is enabled, 409 `account_enabled_elsewhere` while ANOTHER Session has the same account enabled (both mean: turn that one off first — the second names nothing about the holder, which may sit in a Project the caller cannot see); 400 `feishu_secret_required` when the stored config has no secret. New configs start disabled; server startup connects only enabled ones || DELETE | /messaging/feishu | Remove this channel's config entirely (App Secret included; the other channel is untouched). API completeness only — the web UI's removal affordance is the clear flag || POST | /messaging/feishu/test | Credential probe with the request's draft values, each falling back to the stored config → `{ok, latencyMs?, error?}` (a rejected credential is `ok: false`, not an HTTP error) || POST | /messaging/feishu/test-message | Send a short fixed text to the last known chat; 409 `feishu_no_chat` until the bot has been messaged once in Feishu || GET | /messaging/telegram | The Telegram config in the same envelope (`botId`, `botTokenMasked`) |-| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?, linePerMessage?}` — the whole credential is the one `<bot id>:<secret>` token from @BotFather (omitted/blank keeps the stored one; 400 `telegram_token_invalid` when the numeric id cannot be read; the clear flag works like Feishu's and the cleared config keeps its bot identity). Same save/enable split, the same 409 `account_enabled_elsewhere` when an enabled binding's token is swapped for one another Session has enabled, and otherwise the same absence of a cross-Session conflict on save |+| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?}` — the whole credential is the one `<bot id>:<secret>` token from @BotFather (omitted/blank keeps the stored one; 400 `telegram_token_invalid` when the numeric id cannot be read; the clear flag works like Feishu's and the cleared config keeps its bot identity). Same save/enable split, the same 409 `account_enabled_elsewhere` when an enabled binding's token is swapped for one another Session has enabled, and otherwise the same absence of a cross-Session conflict on save || POST | /messaging/telegram/state | Same contract as the Feishu toggle (400 `telegram_token_required` without a stored token) || DELETE | /messaging/telegram | Remove this channel's config entirely (Bot Token included). API completeness only || POST | /messaging/telegram/test | Credential probe (`getMe`) with the draft token falling back to the stored one → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}` — success names the bot the token signs in as, and reports `groupPrivacy: true` when @BotFather's Group Privacy is on (the default), under which the bot receives no ordinary message in any group it does not administer || POST | /messaging/telegram/test-message | Send a short fixed text to the last known chat; 409 `telegram_no_chat` until the bot has been messaged once in Telegram || GET | /messaging/qq | The QQ config in the same envelope (`appId`, `appSecretMasked`) |-| PUT | /messaging/qq | Save the credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?}` — the App ID and App Secret from the QQ open platform's development settings. Same keep-on-blank, clear flag and save/enable split as the Feishu PUT, the same 409 `account_enabled_elsewhere` when an enabled binding's App ID is swapped for one another Session has enabled, and no cross-Session conflict on save otherwise; there is no domain field, because API v2 has one host |+| PUT | /messaging/qq | Save the credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?}` — the App ID and App Secret from the QQ open platform's development settings. Same keep-on-blank, clear flag and save/enable split as the Feishu PUT, the same 409 `account_enabled_elsewhere` when an enabled binding's App ID is swapped for one another Session has enabled, and no cross-Session conflict on save otherwise; there is no domain field, because API v2 has one host || POST | /messaging/qq/state | Same contract as the other toggles (400 `qq_secret_required` without a stored secret) || DELETE | /messaging/qq | Remove this channel's config entirely (App Secret included). API completeness only || 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 |@@ -320,9 +320,9 @@ A Session can be connected to a messaging bot — Feishu, Telegram and QQ are th| POST | /messaging/qq/scan/cancel | `{taskId}` — drop a scan the user walked away from, so its key is forgotten now rather than at the sweep || POST | /messaging/qq/test-message | Send a short fixed text to the last known chat; 409 `qq_no_chat` until the bot has been messaged once in QQ, and 502 `qq_send_failed` when no recent QQ message can be replied to (see below) |-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` 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. Inbound processing accepts text and images: an image becomes an ordinary `image_url` input part (a PHOTO's caption is that message's text; a caption on any other media kind is not, since its bytes are never delivered and running the model on the caption alone answers about a file it never received), capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, and none of them runs half a message; a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` and `finalReplyOnly` are the two saved fields that are not credentials. With `linePerMessage` set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs. Inbound processing accepts text and images: an image becomes an ordinary `image_url` input part (a PHOTO's caption is that message's text; a caption on any other media kind is not, since its bytes are never delivered and running the model on the caption alone answers about a file it never received), capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, and none of them runs half a message; a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.-**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.+**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20. `finalReplyOnly` cuts both ways here: it spends the least budget a run can spend — one reply — but the passive-reply window is only a few minutes wide, and holding the reply until the run ends spends that window on the run, so a run that outlives it delivers nothing at all where an every-message relay would have sent whatever completed inside it. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.**Scan-to-connect never shows the browser the key.** The AES key that decrypts the App Secret is generated, held, used and dropped on the server; the client is given only a task handle, a URL to draw, and a status. Tasks live in memory, are scoped to the Session that started them, are bounded per Session so one caller's scans cannot evict another's, and are claimed by the poll that resolves them — so both a replay and a second concurrent poll of one task read as 404 rather than as a second bind. Every scan route is owner-only, because the flow ends in a stored credential however little of it the caller types.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 9a9c3309..f8233733 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -296,21 +296,21 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr| 方法 | 路径 | 说明 || --- | --- | --- |-| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |+| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + `finalReplyOnly` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 || GET | /messaging/feishu | `{binding, status}` 形态下的飞书配置(未保存时为 null) |-| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?}`。`appSecret` 省略或留空则保持已存值;`clearAppSecret: true` 清除已存密钥(新输入的密钥优先于清除标记;启用中返回 409 `messaging_disable_before_clear`——清除后配置行与非密钥字段保留);`baseDomain` 默认 `https://open.feishu.cn`。不带连接副作用——唯一例外:**已启用**绑定的连接器会用新凭据重启,保证存储配置与在线连接永不背离。保存不会与其他 Session 冲突,唯一例外正源于这次重启:把**已启用**的绑定改指到另一个 Session 已启用的账号上,返回 409 `account_enabled_elsewhere`,否则那次重启就会绕过启用闸门、把第二条在线连接接到同一账号上 |+| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?}`。`appSecret` 省略或留空则保持已存值;`clearAppSecret: true` 清除已存密钥(新输入的密钥优先于清除标记;启用中返回 409 `messaging_disable_before_clear`——清除后配置行与非密钥字段保留);`baseDomain` 默认 `https://open.feishu.cn`。不带连接副作用——唯一例外:**已启用**绑定的连接器会用新凭据重启,保证存储配置与在线连接永不背离。保存不会与其他 Session 冲突,唯一例外正源于这次重启:把**已启用**的绑定改指到另一个 Session 已启用的账号上,返回 409 `account_enabled_elsewhere`,否则那次重启就会绕过启用闸门、把第二条在线连接接到同一账号上 || POST | /messaging/feishu/state | 连接开关:`{enabled}`——启用即用**已存凭据**建立连接,停用即断开。该 Session 另一渠道已启用时返回 409 `another_channel_enabled`,同一账号已在**其他 Session** 上启用时返回 409 `account_enabled_elsewhere`(两者都是「先停用那一个」——后者不透露持有方的任何信息,它可能位于调用方看不到的 Project);已存配置没有密钥时返回 400 `feishu_secret_required`。新配置默认停用;服务端启动只连接已启用的配置 || DELETE | /messaging/feishu | 整体删除该渠道的配置(含 App Secret;另一渠道不受影响)。仅为 API 完整性保留——Web 界面的移除入口是清除标记 || POST | /messaging/feishu/test | 用请求携带的草稿值做凭据探测,缺省字段回落到已存配置 → `{ok, latencyMs?, error?}`(凭据被拒是 `ok: false`,不是 HTTP 错误) || POST | /messaging/feishu/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在飞书里给机器人发过消息之前返回 409 `feishu_no_chat` || GET | /messaging/telegram | 同一形态下的 Telegram 配置(`botId`、`botTokenMasked`) |-| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?, linePerMessage?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 |+| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 || POST | /messaging/telegram/state | 与飞书开关同一契约(无已存 Token 时返回 400 `telegram_token_required`) || DELETE | /messaging/telegram | 整体删除该渠道的配置(含 Bot Token)。仅为 API 完整性保留 || POST | /messaging/telegram/test | 凭据探测(`getMe`),草稿 Token 缺省回落到已存值 → `{ok, latencyMs?, botUsername?, groupPrivacy?, error?}`——成功时报出 Token 登录到的机器人;当 @BotFather 的 Group Privacy 处于开启状态(默认如此,此时机器人在它不担任管理员的群里收不到任何普通消息)时报出 `groupPrivacy: true` || POST | /messaging/telegram/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 Telegram 里给机器人发过消息之前返回 409 `telegram_no_chat` || GET | /messaging/qq | 同一形态下的 QQ 配置(`appId`、`appSecretMasked`) |-| PUT | /messaging/qq | 保存凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?}`——QQ 开放平台「开发设置」页的 App ID 与 App Secret。留空保持、清除标记、保存与启用分离都与飞书 PUT 同口径;把一条已启用绑定的 App ID 换成另一个 Session 已启用的账号时,同样返回 409 `account_enabled_elsewhere`,此外保存不会跨 Session 冲突;没有域名字段,因为 API v2 只有一个接口域名 |+| PUT | /messaging/qq | 保存凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?}`——QQ 开放平台「开发设置」页的 App ID 与 App Secret。留空保持、清除标记、保存与启用分离都与飞书 PUT 同口径;把一条已启用绑定的 App ID 换成另一个 Session 已启用的账号时,同样返回 409 `account_enabled_elsewhere`,此外保存不会跨 Session 冲突;没有域名字段,因为 API v2 只有一个接口域名 || POST | /messaging/qq/state | 与其他开关同一契约(无已存密钥时返回 400 `qq_secret_required`) || DELETE | /messaging/qq | 整体删除该渠道的配置(含 App Secret)。仅为 API 完整性保留 || POST | /messaging/qq/test | 凭据探测(换取 app access token)→ `{ok, latencyMs?, error?}`。不报出账号名:平台没有能识别机器人身份的接口 |@@ -319,9 +319,9 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 || 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 会连带删除其全部渠道配置。入站处理文本与图片:图片按普通 `image_url` 输入部分送入(**图片**消息的说明文字即该消息的文本;其他媒体类型的说明文字不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈),单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示,且都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 与 `finalReplyOnly` 是仅有的两个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本与图片:图片按普通 `image_url` 输入部分送入(**图片**消息的说明文字即该消息的文本;其他媒体类型的说明文字不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈),单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示,且都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。-**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。+**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。**扫码连接不会把密钥交给浏览器。** 解密 App Secret 的 AES 密钥在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放与对同一任务的并发轮询得到的都是 404,而不是第二次绑定。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex ae902e0e..b7f0bbb3 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1698,6 +1698,13 @@ export interface FeishuBindingInfo {* message per reply. Off by default; off is the original one-message-per-reply behaviour.*/linePerMessage: boolean;+ /**+ * Relay only the LAST completed assistant message of a run, delivered when the run ends,+ * instead of mirroring each completed message as it completes. Off by default; off is the+ * original every-message behaviour. Independent of `linePerMessage`, which then applies to+ * that one final message. The approval notice is not a reply and is unaffected.+ */+ finalReplyOnly: boolean;/*** Whether an inbound Feishu chat is known (the bot has been messaged at least once).* Replies and test messages target that chat; until it exists nothing can be sent.@@ -1726,6 +1733,13 @@ export interface TelegramBindingInfo {* message per reply. Off by default; off is the original one-message-per-reply behaviour.*/linePerMessage: boolean;+ /**+ * Relay only the LAST completed assistant message of a run, delivered when the run ends,+ * instead of mirroring each completed message as it completes. Off by default; off is the+ * original every-message behaviour. Independent of `linePerMessage`, which then applies to+ * that one final message. The approval notice is not a reply and is unaffected.+ */+ finalReplyOnly: boolean;/*** Whether an inbound Telegram chat is known (the bot has been messaged at least once).* Replies and test messages target that chat; until it exists nothing can be sent.@@ -1756,6 +1770,20 @@ export interface QQBindingInfo {* far fewer messages here than on the other channels.*/linePerMessage: boolean;+ /**+ * Relay only the LAST completed assistant message of a run, delivered when the run ends,+ * instead of mirroring each completed message as it completes. Off by default; off is the+ * original every-message behaviour. Independent of `linePerMessage`, which then applies to+ * that one final message. The approval notice is not a reply and is unaffected.+ *+ * On QQ it cuts both ways, which is worth knowing before setting it here. It spends the+ * least of the platform's passive-reply budget a run can spend — one message, where an+ * every-message relay spends one per completed message. But a passive reply is accepted+ * only for a few minutes after the inbound message that funds it, and holding the reply+ * to the run's end spends that window on the run: a run that outlives it delivers nothing+ * at all, where the every-message relay would have sent whatever completed inside it.+ */+ finalReplyOnly: boolean;/*** Whether an inbound QQ chat is known (the bot has been messaged at least once).* Weaker than it looks on this channel: QQ accepts only replies to a recent message, so a@@ -1824,6 +1852,11 @@ export interface FeishuBindingPutRequest {* value; a binding created without it starts with it off.*/linePerMessage?: boolean;+ /**+ * Delivery preference (see `FeishuBindingInfo.finalReplyOnly`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ finalReplyOnly?: boolean;}/**@@ -1846,6 +1879,11 @@ export interface TelegramBindingPutRequest {* value; a binding created without it starts with it off.*/linePerMessage?: boolean;+ /**+ * Delivery preference (see `TelegramBindingInfo.finalReplyOnly`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ finalReplyOnly?: boolean;}/**@@ -1868,6 +1906,11 @@ export interface QQBindingPutRequest {* value; a binding created without it starts with it off.*/linePerMessage?: boolean;+ /**+ * Delivery preference (see `QQBindingInfo.finalReplyOnly`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ finalReplyOnly?: boolean;}/**diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.tsindex a29f56df..4d6d91c6 100644--- a/packages/server/src/db/database.ts+++ b/packages/server/src/db/database.ts@@ -56,6 +56,7 @@ export function openDatabase(dbPath: string): DatabaseSync {ensureColumn(db, "auth_sessions", "via", "TEXT");ensureColumn(db, "trace_files", "page_stats", "TEXT");ensureColumn(db, "messaging_bindings", "line_per_message", "INTEGER NOT NULL DEFAULT 0");+ ensureColumn(db, "messaging_bindings", "final_reply_only", "INTEGER NOT NULL DEFAULT 0");ensureColumn(db, "messaging_bindings", "last_inbound_message_id", "TEXT");// Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on// this database: the old index is a strict prefix of it, so every query it served isdiff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.tsindex 96fa37ba..bc22777e 100644--- a/packages/server/src/db/repos/messaging-bindings.ts+++ b/packages/server/src/db/repos/messaging-bindings.ts@@ -15,9 +15,10 @@* `findEnabledByAccount` to see it. One account has one event stream, so two live* connections on it are meaningless; two saved configs are not.*- * `line_per_message` is a delivery preference rather than credentials, which is why it is a- * column beside `enabled` and not a key inside `config`: that document is the channel's own- * shape, owned by its connector, and this applies to every channel identically.+ * `line_per_message` and `final_reply_only` are delivery preferences rather than credentials,+ * which is why they are columns beside `enabled` and not keys inside `config`: that document+ * is the channel's own shape, owned by its connector, and these apply to every channel+ * identically.** `config` is the channel-specific credential/config document, stored as JSON. Secrets* inside it are plaintext at rest (same trade-off as the proxy address in@@ -51,6 +52,14 @@ export interface MessagingBindingRow {* original behaviour exactly. Ordinary saved state — the PUT owns it, like the config.*/linePerMessage: boolean;+ /**+ * DELIVERY preference: relay only the LAST completed assistant message of a run, sent when+ * the run ends, instead of mirroring each of them as it completes. Off by default, and off+ * reproduces the original behaviour exactly. Independent of `linePerMessage`: with both set+ * that one final message is what gets split per line. Ordinary saved state, like the field+ * above.+ */+ finalReplyOnly: boolean;/*** Most recent inbound chat (null until the bot is messaged once). The channel's connector* mints this string and is the only thing that may read it: Telegram encodes the forum@@ -88,6 +97,7 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {config,enabled: Number(r.enabled) === 1,linePerMessage: Number(r.line_per_message) === 1,+ finalReplyOnly: Number(r.final_reply_only) === 1,lastChatId: (r.last_chat_id as string | null) ?? null,lastChatIsDirect: Number(r.last_chat_is_direct) === 1,lastInboundMessageId: (r.last_inbound_message_id as string | null) ?? null,@@ -149,8 +159,9 @@ export class MessagingBindingsRepo {/*** Create or replace the Session's config for one channel — credentials/config only:* `enabled` is intent state the state toggle owns, so an insert starts disabled and an- * update keeps the stored value. `linePerMessage` is an ordinary saved field this write- * does own, and an omitted one keeps the stored value (a fresh row starts with it off).+ * update keeps the stored value. `linePerMessage` and `finalReplyOnly` are ordinary saved+ * fields this write does own, and an omitted one keeps the stored value (a fresh row starts+ * with both off).* It cannot fail on another Session: the same account saved elsewhere is none of this* write's business, since only enabling is exclusive.* Re-saving a Session's own binding keeps its last-chat memory, so a settings edit never@@ -163,6 +174,7 @@ export class MessagingBindingsRepo {accountId: string;config: Record<string, unknown>;linePerMessage?: boolean;+ finalReplyOnly?: boolean;}): MessagingBindingRow {const now = new Date().toISOString();const configJson = JSON.stringify(args.config);@@ -171,8 +183,8 @@ export class MessagingBindingsRepo {this.db.prepare(`INSERT INTO messaging_bindings- (session_id, channel, account_id, config_json, line_per_message, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?)`,+ (session_id, channel, account_id, config_json, line_per_message, final_reply_only, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,).run(args.sessionId,@@ -180,6 +192,7 @@ export class MessagingBindingsRepo {args.accountId,configJson,args.linePerMessage === true ? 1 : 0,+ args.finalReplyOnly === true ? 1 : 0,now,now,);@@ -190,6 +203,7 @@ export class MessagingBindingsRepo {`UPDATE messaging_bindingsSET account_id = ?, config_json = ?,line_per_message = COALESCE(?, line_per_message),+ final_reply_only = COALESCE(?, final_reply_only),last_chat_id = CASE WHEN ? THEN last_chat_id ELSE NULL END,last_chat_is_direct = CASE WHEN ? THEN last_chat_is_direct ELSE 1 END,last_inbound_message_id = CASE WHEN ? THEN last_inbound_message_id ELSE NULL END,@@ -201,6 +215,7 @@ export class MessagingBindingsRepo {configJson,// NULL = the caller said nothing about it, and COALESCE keeps what is stored.args.linePerMessage === undefined ? null : args.linePerMessage ? 1 : 0,+ args.finalReplyOnly === undefined ? null : args.finalReplyOnly ? 1 : 0,keepChat ? 1 : 0,keepChat ? 1 : 0,keepChat ? 1 : 0,diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex b3161dff..4fc46446 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -137,6 +137,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channelconfig_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle doesline_per_message INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = every non-blank line of a relayed assistant reply is sent as its own message (a reply written as spoken lines arrives as spoken lines), 0 = one message per reply. Channel-agnostic, so it lives here rather than in config_json, which each connector owns+ final_reply_only INTEGER NOT NULL DEFAULT 0, -- delivery preference: 1 = a run's intermediate assistant messages are held and only its LAST completed one is sent, at the run's end, 0 = every completed assistant message mirrors the moment it completes. Channel-agnostic like the column above and independent of it: with both set, that one final text is the one split per linelast_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it); CONNECTOR-OPAQUE, not necessarily a bare chat id — telegram appends the forum topic (see telegram-connector.ts chatRefOf), so only that channel's connector may interpret itlast_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)last_inbound_message_id TEXT, -- channel id of the most recently PROCESSED inbound message (NULL until one arrives); the durable half of the bridge's redelivery guard, so a channel replaying an event this server already turned into a Task after a restart does not run it twicediff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsindex 4ba05065..b0490af4 100644--- a/packages/server/src/http/routes/messaging.ts+++ b/packages/server/src/http/routes/messaging.ts@@ -26,9 +26,11 @@* code, and the App ID that came back — the same never-round-trip-the-secret rule the PUT* handlers follow, applied to a secret that arrives from outside instead of from the user.*- * A PUT also carries `linePerMessage`, the one saved field that is not a credential: whether- * a relayed reply is delivered one message per non-blank line. It is an ordinary form field- * applied on Save — omitted keeps the stored value — and it never touches the connection.+ * A PUT also carries the two saved fields that are not credentials: `linePerMessage` (whether+ * a relayed reply is delivered one message per non-blank line) and `finalReplyOnly` (whether a+ * run relays only its last completed assistant message, at the run's end, instead of each one+ * as it completes). Both are ordinary form fields applied on Save — omitted keeps the stored+ * value — and neither touches the connection.** Round-trip rule for secrets: GET only ever returns the masked value, and a PUT whose* secret (feishu `appSecret`, telegram `botToken`, qq `appSecret`) is omitted or blank keeps the stored@@ -115,6 +117,7 @@ function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {baseDomain: fields.baseDomain,enabled: row.enabled,linePerMessage: row.linePerMessage,+ finalReplyOnly: row.finalReplyOnly,lastChatKnown: row.lastChatId !== null,createdAt: row.createdAt,updatedAt: row.updatedAt,@@ -130,6 +133,7 @@ function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {...(botToken !== "" ? { botTokenMasked: maskApiKey(botToken) } : {}),enabled: row.enabled,linePerMessage: row.linePerMessage,+ finalReplyOnly: row.finalReplyOnly,lastChatKnown: row.lastChatId !== null,createdAt: row.createdAt,updatedAt: row.updatedAt,@@ -145,6 +149,7 @@ function toQQInfo(row: MessagingBindingRow): QQBindingInfo {...(fields.appSecret !== "" ? { appSecretMasked: maskApiKey(fields.appSecret) } : {}),enabled: row.enabled,linePerMessage: row.linePerMessage,+ finalReplyOnly: row.finalReplyOnly,lastChatKnown: row.lastChatId !== null,createdAt: row.createdAt,updatedAt: row.updatedAt,@@ -318,6 +323,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {const clearSecret = (body as { clearAppSecret?: unknown }).clearAppSecret === true;const baseDomain = parseBaseDomain(optionalString(body, "baseDomain", { maxLen: 500 }));const linePerMessage = optionalBoolean(body, "linePerMessage");+ const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");const existing = deps.messagingRepo.find(row.sessionId, "feishu");const typed = secretInput !== undefined && secretInput !== "" ? secretInput : undefined;// Blank keeps the stored secret; the clear flag (models idiom — a typed secret wins@@ -353,6 +359,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {accountId: appId,config: { appId, appSecret, baseDomain },...(linePerMessage !== undefined ? { linePerMessage } : {}),+ ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),});// Save persists credentials only and never flips the connection — with one deliberate// exception: an ENABLED binding's connector restarts with the new credentials, so the@@ -458,6 +465,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {const tokenInput = optionalString(body, "botToken", { maxLen: 200 })?.trim();const clearToken = (body as { clearBotToken?: unknown }).clearBotToken === true;const linePerMessage = optionalBoolean(body, "linePerMessage");+ const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");const existing = deps.messagingRepo.find(row.sessionId, "telegram");const typed = tokenInput !== undefined && tokenInput !== "" ? tokenInput : undefined;// Same ladder as the Feishu PUT: typed wins, then the clear flag (disable first),@@ -503,6 +511,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {accountId: botId,config: { botToken },...(linePerMessage !== undefined ? { linePerMessage } : {}),+ ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),});// Same save/enable split as Feishu: only an enabled binding restarts its connector.if (saved.enabled) await deps.messaging.sync(row.sessionId);@@ -603,6 +612,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {const secretInput = optionalString(body, "appSecret", { maxLen: 500 })?.trim();const clearSecret = (body as { clearAppSecret?: unknown }).clearAppSecret === true;const linePerMessage = optionalBoolean(body, "linePerMessage");+ const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");const existing = deps.messagingRepo.find(row.sessionId, "qq");const typed = secretInput !== undefined && secretInput !== "" ? secretInput : undefined;// The same ladder as the other two channels: typed wins, then the clear flag (disable@@ -635,6 +645,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {accountId: appId,config: { appId, appSecret },...(linePerMessage !== undefined ? { linePerMessage } : {}),+ ...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),});if (saved.enabled) await deps.messaging.sync(row.sessionId);return c.json(qqResponse(row.sessionId));diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex e4a4f0f1..501b5ad4 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -27,27 +27,33 @@* marked.** Outbound (Session → channel): the bridge subscribes to the Session's in-process channel- * and relays each of the main conversation's completed assistant messages on its own, the- * moment it completes — a run that writes working notes between tool calls before its- * answer reaches the chat as that same sequence of messages, so the chat follows the run- * as it happens. Each is sent to the last known chat, chunked under the channel's- * text-size limits — or, when the binding's `linePerMessage` is set, split into one message- * per non-blank line first, each of those chunked and the resulting burst paced — and the- * outbound traffic of one entry is serialised through a promise chain:+ * and relays the main conversation's completed assistant messages — by default each of them+ * on its own, the moment it completes: a run that writes working notes between tool calls+ * before its answer reaches the chat as that same sequence of messages, so the chat follows+ * the run as it happens. A binding with `finalReplyOnly` set holds them back instead and+ * delivers the run's LAST completed assistant text alone, at the run's end: the answer+ * without the working notes, at the cost of the chat hearing nothing while the run works.+ * Either way delivery is the same path — sent to the last known chat (a held reply to the chat+ * its run was ASKED in, captured at the run's start: it leaves late enough for another message+ * to have moved the conversation elsewhere), chunked under the channel's text-size limits, or,+ * when the binding's `linePerMessage` is set, split into one message per non-blank line first,+ * each of those chunked and the resulting burst paced (the two options compose: a binding with+ * both sends that final reply one message per line) — and the outbound traffic of one entry is+ * serialised through a promise chain:* several messages completing in quick succession must reach the chat in the order they* completed. In a group chat the run's FIRST outbound message threads onto the inbound* one and everything after it is a plain send — one reply-to anchors the exchange, where* repeating it per message would stack a quote header over each of them; a direct chat is- * plain sends throughout. EVERY completed assistant message mirrors once a chat is known- * — web-initiated turns included; before the first inbound message no chat is known and- * nothing is sent. Compaction output (the summary the model streams between compaction- * events) is not a reply and is skipped, and- * a connection joining mid-run relays nothing from that run rather than mirroring half a+ * plain sends throughout. Mirroring needs a known chat — web-initiated turns included;+ * before the first inbound message no chat is known and nothing is sent. Compaction output+ * (the summary the model streams between compaction events) is not a reply and is skipped,+ * and a connection joining mid-run relays nothing from that run rather than mirroring half a* reply. An `approval_request` additionally sends a one-line notice that a tool call is* waiting in the web UI — on the same chain, so it lands between replies instead of inside- * one.+ * one. That notice is not an assistant message, so `finalReplyOnly` never holds it: a run+ * blocked on approval is exactly when the chat must hear something.*- * When the run ends, the files its reply MENTIONED follow the text into the chat (see+ * When the run ends, the files ITS DELIVERED TEXT mentioned follow it into the chat (see* reply-files.ts): path-like tokens that resolve inside the Workspace and actually exist,* pictures sent as pictures and everything else as attachments. Not "every file the run* wrote": the Agent's own words are what say which output was the point, and a chat window@@ -496,6 +502,18 @@ export interface MessagingBridgeDeps {inboundImageBudgetBytes?: number;}+/**+ * Where one outbound reply is addressed: the chat ref, whether that chat is direct, and the+ * inbound message its first chunk quotes (null in a direct chat, where nothing is quoted).+ * All three move together when a user writes from somewhere new, which is why they travel+ * as one value rather than being read from two places at delivery time.+ */+interface ReplyTarget {+ chatId: string;+ isDirect: boolean;+ inboundMessageId: string | null;+}+/** One connected (or connecting/errored) binding's in-memory state. */interface BridgeEntry {sessionId: string;@@ -553,12 +571,35 @@ interface BridgeEntry {* cut-off for "a file this run produced" — see deliverFiles.*/runStartedAt: number;+ /**+ * Where the run in progress was asked, captured on the same edge as `runStartedAt` and null+ * while no chat is known. Only the run's END delivers anything through it: a message relayed+ * as it completes is addressed live, because the chat it goes to is where the conversation+ * currently is, whereas a held reply is the whole answer to a question asked before another+ * user could move the row's chat and this entry's reply anchor (see deliverReply).+ */+ runTarget: ReplyTarget | null;/*** What this run has relayed so far, joined at the run's end to find the files the reply* mentions. Only text that actually mirrored is collected: a connection joined mid-run- * relays none of that run's messages and must not send its files either.+ * relays none of that run's messages and must not send its files either, and a message+ * `finalReplyOnly` held back never arrives here — the one held reply joins it at the run's+ * end, in the same step that delivers it.*/replyText: string[];+ /**+ * The run's last completed assistant text, held instead of sent, for a binding with+ * `finalReplyOnly` set. Each later message overwrites it: only the last one is the answer,+ * and everything before it is the working note the option exists to suppress. Null when+ * nothing is held — the option is off, or the run has produced no assistant text yet — and+ * cleared at the run's end by the delivery it feeds.+ *+ * Memory only, and only as long as the entry: a run whose idle edge this connection never+ * sees (the process ends, or a state toggle / credential save mid-run rebuilds the entry)+ * delivers nothing of what it held. The same event costs the every-message path only the+ * remainder of that run, which is the price of holding the answer back.+ */+ heldReply: string | null;/*** Tail of this entry's outbound sends. Every relayed message AND every notice is appended* rather than started on its own, so outbound traffic completing in quick succession cannot@@ -761,7 +802,9 @@ export class MessagingBridge {inCompaction: false,threadedThisRun: false,runStartedAt: 0,+ runTarget: null,replyText: [],+ heldReply: null,sendChain: Promise.resolve(),};this.entries.set(row.sessionId, entry);@@ -1126,19 +1169,65 @@ export class MessagingBridge {}/**- * Queues one completed assistant message for the bound chat. Appended to the entry's- * send chain rather than started here: a run can complete several messages within- * milliseconds, and two sends racing would reach the chat in the wrong order. Returns- * immediately either way, so a slow channel never blocks the Session's stream handling.+ * Queues one completed assistant message for the bound chat — or holds it back.+ *+ * Appended to the entry's send chain rather than started here: a run can complete several+ * messages within milliseconds, and two sends racing would reach the chat in the wrong+ * order. Returns immediately either way, so a slow channel never blocks the Session's+ * stream handling.+ *+ * A binding with `finalReplyOnly` set sends nothing from here: the message replaces+ * whatever this run was already holding, and the last one standing is delivered at the+ * run's idle edge (see onTaskState). The preference is read per message off the stored row,+ * as every delivery preference is, and no run ever sees it change: each of the three PUT+ * handlers calls `sync` on an enabled binding, `sync` reconnects, and `connect` opens with a+ * disconnect and a fresh entry — so a save made mid-run discards whatever was held at that+ * moment along with the rest of this entry's memory (see heldReply).*/private relay(entry: BridgeEntry, text: string): void {if (!entry.armed) return; // joined mid-run: this run's messages are not a replyconst body = text.trim();if (body === "") return;+ if (this.finalReplyOnly(entry)) {+ entry.heldReply = body;+ return;+ }entry.replyText.push(body);entry.sendChain = entry.sendChain.then(() => this.deliverReply(entry, body));}+ /**+ * Whether this binding holds a run's intermediate messages back. A row that cannot be read+ * at all is deliberately not decided here: relaying is the default, and the same read+ * inside deliverReply then records the failure rather than letting it pass as a preference.+ */+ private finalReplyOnly(entry: BridgeEntry): boolean {+ try {+ return this.deps.repo.find(entry.sessionId, entry.channel)?.finalReplyOnly === true;+ } catch {+ return false;+ }+ }++ /**+ * Where this entry's traffic would go right now: null before any chat is known, and null+ * when the row cannot be read at all — a caller holding null falls back to reading it again+ * at delivery time, which is where a failure to read is recorded rather than swallowed.+ */+ private replyTargetOf(entry: BridgeEntry): ReplyTarget | null {+ try {+ const row = this.deps.repo.find(entry.sessionId, entry.channel);+ if (!row || row.lastChatId === null) return null;+ return {+ chatId: row.lastChatId,+ isDirect: row.lastChatIsDirect,+ inboundMessageId: entry.lastInboundMessageId,+ };+ } catch {+ return null;+ }+ }+private onTaskState(entry: BridgeEntry, state: string): void {if (state === "running") {// A fresh run observed from its start gets one thread reply again. Only a real@@ -1149,26 +1238,64 @@ export class MessagingBridge {// The cut-off the run's own output is judged against. Taken on the same edge, so a// task_state republished mid-run cannot move it forward past files already written.entry.runStartedAt = this.now();+ // Where this run was asked, for what it delivers at its END. Taken here for the same+ // reason: a task_state republished mid-run must not move it either.+ entry.runTarget = this.replyTargetOf(entry);}} else if (state === "idle") {// A run joined midway ends here; from the next one on its messages mirror.entry.armed = true;- // The run's files ride behind its text on the same chain — the reply first, then what- // it produced. Taken and cleared here, so a task_state republished at idle cannot- // send the same batch twice and the next run starts from nothing.- const replyText = entry.replyText.join("\n\n");+ // The run's text and then its files ride the same chain, in that order. Both sources+ // are taken and cleared here, so a task_state republished at idle cannot send either+ // twice and the next run starts from nothing.+ const relayed = entry.replyText;+ const held = entry.heldReply;const since = entry.runStartedAt;+ // Read on this edge with the rest, before the next run's `running` edge can replace it.+ const askedAt = entry.runTarget;entry.replyText = [];+ entry.heldReply = null;+ if (held !== null) {+ // All of `finalReplyOnly`, in one place: the run's last completed assistant text, and+ // only it, goes out at the end — through the same deliverReply as any relayed+ // message, so chunking, the per-line split, pacing, group threading and the chain's+ // ordering are the ones the other path already has. Addressed where the run was+ // ASKED: this is the one delivery whose whole text was written before an inbound+ // message from someone else could move the chat out from under it.+ relayed.push(held);+ entry.sendChain = entry.sendChain.then(() => this.deliverReply(entry, held, askedAt));+ }+ // The files follow the words that actually REACHED THE CHAT, not everything the run+ // said. With `finalReplyOnly` on, the messages this run held back were never delivered,+ // and a file named only in one of them would land in a chat with nothing there naming+ // it — so `relayed` carries exactly the texts deliverReply was handed, the held one+ // included, and never the ones that were dropped.+ const replyText = relayed.join("\n\n");if (replyText !== "") {- entry.sendChain = entry.sendChain.then(() => this.deliverFiles(entry, replyText, since));+ // ...and the files go wherever those words went, which is the held reply's chat when+ // there was one and the live chat otherwise — the every-message path's texts left as+ // they completed, so the live chat is the only answer that fits all of them.+ entry.sendChain = entry.sendChain.then(() =>+ this.deliverFiles(entry, replyText, since, held !== null ? askedAt : null),+ );}}entry.active = state;}/**- * Sends one completed assistant message to the last known chat, in chunks under the- * channel's cap; a send failure is recorded, never thrown, so the chain behind it keeps+ * Sends one relayed assistant message to the bound chat, in chunks under the channel's cap.+ * Which messages arrive here is the caller's business — every completed message of the run,+ * or its last one alone when the binding holds the rest (`finalReplyOnly`) — and nothing+ * below is affected by the difference.+ *+ * `at` is where to put it. A message relayed as it completes passes none and goes to the+ * chat the row names now, which is where the conversation is. A held reply passes the target+ * captured when its run started (see onTaskState), because it leaves at the run's END: a+ * second user writing in another forum topic meanwhile would otherwise take delivery of a+ * whole answer to a question they never asked, quoted onto their own message.+ *+ * A send failure is recorded, never thrown, so the chain behind it keeps* moving — and so do the messages behind it in THIS reply: one refused message (a 429 on* the third line of twelve) must not abandon the rest, which would leave a reply stopping* mid-sentence with nothing in the chat to say why. A binding with `linePerMessage` set@@ -1182,17 +1309,28 @@ export class MessagingBridge {* answered, and one of them says it — repeating it per message and per chunk stacks quote* headers over the whole conversation.*/- private async deliverReply(entry: BridgeEntry, text: string): Promise<void> {- // Both halves of the target are snapshotted together, ahead of every await: this line runs- // before sendTarget, which reads the chat ref off the row synchronously before its own.- // An inbound message arriving mid-delivery moves them independently, and a reply whose+ private async deliverReply(+ entry: BridgeEntry,+ text: string,+ at: ReplyTarget | null = null,+ ): Promise<void> {+ // Both halves of the LIVE target are snapshotted together, ahead of every await: this line+ // runs before sendTarget, which reads the chat ref off the row synchronously before its+ // own. An inbound message arriving mid-delivery moves them independently, and a reply whose// first chunk threaded onto the new message while the rest went to the chat the row// still named would be split across two places — two forum topics, on a channel that// packs one into the chat ref.- const inboundMessageId = entry.lastInboundMessageId;+ const liveInboundMessageId = entry.lastInboundMessageId;const target = await this.sendTarget(entry);if (target === null) return;- const { row, chatId, client } = target;+ const { row, client } = target;+ // The caller's target when it named one, the live one otherwise. The ROW is read fresh+ // either way: WHERE a reply goes belongs to the run, HOW it is split to the binding.+ const to: ReplyTarget = at ?? {+ chatId: target.chatId,+ isDirect: row.lastChatIsDirect,+ inboundMessageId: liveInboundMessageId,+ };// One body per outbound message: the whole reply, or one per non-blank line when the// binding asked for that. Everything below is untouched by the choice.const bodies = row.linePerMessage@@ -1204,15 +1342,15 @@ export class MessagingBridge {// about one a second, so they go out at that pace rather than back to back.if (i > 0 && row.linePerMessage) await this.pace();const threadOnto =- !row.lastChatIsDirect && inboundMessageId !== null && !entry.threadedThisRun- ? inboundMessageId+ !to.isDirect && to.inboundMessageId !== null && !entry.threadedThisRun+ ? to.inboundMessageId: null;try {if (threadOnto !== null) {entry.threadedThisRun = true;this.noteSend(entry, await client.replyText(threadOnto, chunk));} else {- this.noteSend(entry, await client.sendText(chatId, chunk));+ this.noteSend(entry, await client.sendText(to.chatId, chunk));}} catch (err) {this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");@@ -1223,6 +1361,15 @@ export class MessagingBridge {/*** Sends the files THIS RUN produced and its reply mentioned, after its text.*+ * `replyText` is what the run actually SENT, not everything it said: a binding with+ * `finalReplyOnly` set delivered one message, so that message is the whole of what this+ * scans (see onTaskState). A file named only in a held-back working note has nothing in+ * the chat to explain its arrival.+ *+ * `at` is where those words went, for the one caller whose text is not addressed to the live+ * chat (again the held reply). Files follow their words: a picture landing in a forum topic+ * where nothing named it is the same defect as one arriving unmentioned.+ ** Two filters, and both are load-bearing. The reply having said the name is what picks* the one output that was the point out of the dozen a run writes. The file being newer* than the run's start is what keeps that from becoming an exfiltration primitive: the@@ -1241,10 +1388,16 @@ export class MessagingBridge {* one reply-to. Nothing here throws — a batch that fails is recorded, and a single file* that fails does not stop the ones behind it.*/- private async deliverFiles(entry: BridgeEntry, replyText: string, since: number): Promise<void> {+ private async deliverFiles(+ entry: BridgeEntry,+ replyText: string,+ since: number,+ at: ReplyTarget | null = null,+ ): Promise<void> {try {const row = this.deps.repo.find(entry.sessionId, entry.channel);if (!row || row.lastChatId === null) return; // no chat known yet: nothing mirrors+ const chatId = at?.chatId ?? row.lastChatId;const session = this.deps.sessions.findById(entry.sessionId);if (session === null) return; // deleted mid-runconst mentions = replyFileMentions(replyText, session.workspace);@@ -1265,18 +1418,18 @@ export class MessagingBridge {const client = await this.clientFor(entry.sessionId, row);for (const rel of produced.slice(0, MESSAGING_OUTBOUND_FILE_MAX_COUNT)) {try {- await this.deliverOneFile(client, row.lastChatId, session.workspace, rel);+ await this.deliverOneFile(client, chatId, session.workspace, rel);} catch (err) {this.recordError(entry.sessionId, err, "messaging_file_send_failed");- await this.noteFileFailure(client, row.lastChatId, rel, err);+ await this.noteFileFailure(client, chatId, rel, err);}}const skipped = produced.length - MESSAGING_OUTBOUND_FILE_MAX_COUNT;if (skipped > 0) {- await client.sendText(row.lastChatId, messagingFilesSkippedNotice(skipped));+ await client.sendText(chatId, messagingFilesSkippedNotice(skipped));}if (missing.length > 0) {- await client.sendText(row.lastChatId, messagingFilesMissingNotice(missing));+ await client.sendText(chatId, messagingFilesMissingNotice(missing));}} catch (err) {this.recordError(entry.sessionId, err, "messaging_send_failed");diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.tsindex 3a1a6099..43081f06 100644--- a/packages/server/test/db-upgrade.test.ts+++ b/packages/server/test/db-upgrade.test.ts@@ -414,14 +414,19 @@ describe("openDatabase table and index upgrades", () => {});/**- * Seeds a database in the shape it had before messaging_bindings.line_per_message existed:- * today's schema with that column dropped. Same derivation rule as the helpers around it.+ * Seeds a database in the shape it had before one of messaging_bindings' delivery-preference+ * columns existed: today's schema with that column dropped. Same derivation rule as the+ * helpers around it — a hand-copied DDL replica forks silently from the schema it imitates.*/- function seedPreLinePerMessageDb(dbPath: string, seed: (db: DatabaseSync) => void): void {+ function seedPreDeliveryColumnDb(+ dbPath: string,+ column: string,+ seed: (db: DatabaseSync) => void,+ ): void {const db = new sqlite.DatabaseSync(dbPath);try {db.exec(SCHEMA_SQL);- db.exec("ALTER TABLE messaging_bindings DROP COLUMN line_per_message");+ db.exec(`ALTER TABLE messaging_bindings DROP COLUMN ${column}`);seed(db);} finally {db.close();@@ -431,7 +436,7 @@ describe("openDatabase table and index upgrades", () => {it("adds line_per_message to a messaging_bindings formed before it, existing rows off", () => {const dbPath = path.join(dir, "web.db");const ts = "2026-01-01T00:00:00.000Z";- seedPreLinePerMessageDb(dbPath, (old) => {+ seedPreDeliveryColumnDb(dbPath, "line_per_message", (old) => {old.prepare(`INSERT INTO messaging_bindings@@ -477,6 +482,47 @@ describe("openDatabase table and index upgrades", () => {}});+ it("adds final_reply_only to a messaging_bindings formed before it, existing rows off", () => {+ const dbPath = path.join(dir, "web.db");+ const ts = "2026-01-01T00:00:00.000Z";+ seedPreDeliveryColumnDb(dbPath, "final_reply_only", (old) => {+ old+ .prepare(+ `INSERT INTO messaging_bindings+ (session_id, channel, account_id, config_json, enabled, line_per_message, created_at, updated_at)+ VALUES ('session-old', 'telegram', '12345', '{"botToken":"t"}', 1, 1, ?, ?)`,+ )+ .run(ts, ts);+ });++ const db = openDatabase(dbPath);+ try {+ const repo = new MessagingBindingsRepo(db);+ const row = repo.find("session-old", "telegram");+ // The default reproduces the delivery the row already had — every completed message+ // mirrored as it completed — so the upgrade cannot change how a binding behaves.+ expect(row?.finalReplyOnly).toBe(false);+ // The rest of the row is untouched, the OTHER delivery preference included: the two+ // are separate columns, and reading a new one must not reset the one beside it.+ expect(row?.linePerMessage).toBe(true);+ expect(row?.enabled).toBe(true);+ expect(row?.config.botToken).toBe("t");+ // Writable immediately: an ALTERed column with no backing code path would look+ // identical until something tried to set it.+ expect(+ repo.upsert({+ sessionId: "session-old",+ channel: "telegram",+ accountId: "12345",+ config: { botToken: "t" },+ finalReplyOnly: true,+ }).finalReplyOnly,+ ).toBe(true);+ } finally {+ db.close();+ }+ });+/*** Seeds a database in the shape it had while a bot account belonged to ONE Session forever:* today's schema with the by-account index swapped back to the UNIQUE one it used to be.diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex efa3b51a..39eb8e17 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -632,6 +632,22 @@ describe("telegram binding routes and connector loop", () => {expect(t.deps.messagingRepo.find(SID, "telegram")?.linePerMessage).toBe(true);});+ it("the final-reply-only flag rides the same PUT, defaults off, and is its own field", async () => {+ // Same split as the flag above: the bridge's holding back is channel-agnostic (pinned in+ // messaging.test.ts), and what is per-channel is the route wiring this asserts.+ await api.put(BASE(SID), { botToken: TOKEN });+ expect(t.deps.messagingRepo.find(SID, "telegram")?.finalReplyOnly).toBe(false);+ const on = await api.put(BASE(SID), { finalReplyOnly: true });+ expect(on.status).toBe(200);+ const saved = (await on.json()) as TelegramBindingResponse;+ expect(saved.binding?.finalReplyOnly).toBe(true);+ // Two independent columns: saving one never carries the other along.+ expect(saved.binding?.linePerMessage).toBe(false);+ expect(t.deps.messagingRepo.find(SID, "telegram")?.config.botToken).toBe(TOKEN);+ await api.put(BASE(SID), {});+ expect(t.deps.messagingRepo.find(SID, "telegram")?.finalReplyOnly).toBe(true);+ });+it("the account is the bot id: a rotated secret saves freely and collides only on enable", async () => {t.deps.sessionsRepo.insert(sessionRowOf(SID2, projectId));await bindEnabled(SID);@@ -1077,6 +1093,59 @@ describe("telegram binding routes and connector loop", () => {expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe(`${FORUM_CHAT}:77`);});+ it("a held reply answers into the topic its run was ASKED in, not the one the chat moved to", async () => {+ // `finalReplyOnly` delivers at the run's END, which is long after the chat can move: a+ // second person writing in another topic meanwhile takes over both `last_chat_id` and the+ // reply anchor. Addressed at delivery time, the WHOLE answer to the first question would+ // land in their topic, quoted onto their message — the every-message relay can misplace+ // the tail of a reply that way, never the entire thing.+ const row = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["working on it", "the answer"], gate));+ expect((await api.put(BASE(SID2), { botToken: TOKEN, finalReplyOnly: true })).status).toBe(200);+ expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(200);+ await waitFor(() => t.deps.messaging.statusOf(SID2, "telegram").state === "connected");++ // The bridge subscribed to this channel before this listener did, so a message seen here+ // is one it has already handled — and the run's `running` edge came before it.+ let seen = 0;+ const off = t.deps.channels.get(SID2).subscribe((evt) => {+ const msg = JSON.parse(evt.data) as { type?: string; payload?: { role?: string } };+ if (msg.type === "model_msg" && msg.payload?.role === "assistant") seen += 1;+ });+ fake.push(forumText("what is it?", 201, TOPIC));+ await waitFor(() => seen === 1);+ off();++ // Bob, in another topic, while the run is parked on its last message. A sticker rather+ // than text so nothing queues behind the run: what matters is only that the chat moved.+ fake.push({+ message_id: 202,+ chat: { id: FORUM_CHAT, type: "supergroup", is_forum: true },+ message_thread_id: 77,+ is_topic_message: true,+ from: { first_name: "Bob" },+ });+ await waitFor(() => fake.allSends().length === 1);+ expect(t.deps.messagingRepo.find(SID2, "telegram")?.lastChatId).toBe(`${FORUM_CHAT}:77`);++ release();+ await waitFor(() => fake.allSends().length === 2);+ const sends = fake.allTexts();+ // Bob's message got its notice where Bob wrote it — the live target is right for that.+ expect(sends[0]).toMatchObject({+ text: MESSAGING_TEXT_ONLY_NOTICE,+ threadId: 77,+ replyTo: 202,+ });+ // ...and the answer went back to the topic that asked, quoting the message that asked it.+ expect(sends[1]).toMatchObject({ text: "the answer", threadId: TOPIC, replyTo: 201 });+ });+it("sends the approval notice and the test message into the remembered topic", async () => {const row = sessionRowOf(SID2, projectId);// The approval only becomes an event when something is actually asked.diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 2b79c69a..62d2fd27 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -15,9 +15,11 @@* the inbound message in groups), the files the reply MENTIONED follow it (existing ones* only, pictures as pictures, capped by count and by size, escapes refused by the Workspace* file service), an approval_request sends the one-line notice behind whatever is already- * going out, and a binding with `linePerMessage` set delivers a reply one message per+ * going out, a binding with `linePerMessage` set delivers a reply one message per* non-blank line — paced, and with a refused message costing only itself — while an unset- * one is byte-for-byte the original single message. No test opens real network.+ * one is byte-for-byte the original single message, and a binding with `finalReplyOnly` set+ * relays a run's last completed message alone, at the run's end, files included. No test+ * opens real network.*/import fs from "node:fs/promises";import path from "node:path";@@ -1289,6 +1291,138 @@ describe("messaging binding routes and bridge", () => {expect(t.deps.messagingRepo.find(SID, "feishu")?.linePerMessage).toBe(false);});+ // —— finalReplyOnly: the run's last word, and only it ——————————————————————++ /** A run that thinks out loud: two working notes before the answer. */+ const THINKING_ALOUD = ["working on it", "still going", "here is the answer"];++ /** SID2 running one multi-message run, bound and connected. `gate` holds its LAST message. */+ const bindThinkingAloud = async (put: Record<string, unknown>, gate?: Promise<void>) => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, THINKING_ALOUD, gate));+ await bindEnabled(SID2, { ...PUT_BODY, ...put });+ };++ /**+ * Counts the completed assistant messages of SID2 as the CHANNEL publishes them, which is+ * what makes "nothing was sent" mean something: a held message produces no send to wait+ * for, and the bridge subscribed to this channel before this listener did, so a message+ * this listener has seen is one the bridge has already handled.+ */+ const countAssistantMessages = (): { seen: () => number; off: () => void } => {+ let seen = 0;+ const off = t.deps.channels.get(SID2).subscribe((evt) => {+ const msg = JSON.parse(evt.data) as { type?: string; payload?: { role?: string } };+ if (msg.type === "model_msg" && msg.payload?.role === "assistant") seen += 1;+ });+ return { seen: () => seen, off };+ };++ it("finalReplyOnly off (the default) mirrors every completed message of a run", async () => {+ await bindThinkingAloud({ appId: "cli_final_off" });+ // The default is off, on a binding whose PUT never mentioned the field.+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.finalReplyOnly).toBe(false);+ await messageBot("oc_final_off");+ await waitFor(() => fake.allSends().length === 3);+ expect(fake.allTexts().map((s) => s.text)).toEqual(THINKING_ALOUD);+ });++ it("finalReplyOnly on sends the run's LAST message only, and only once the run ends", async () => {+ let release!: () => void;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ await bindThinkingAloud({ appId: "cli_final_on", finalReplyOnly: true }, gate);+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.finalReplyOnly).toBe(true);+ const notes = countAssistantMessages();+ await messageBot("oc_final_on");+ // Both working notes have completed and the run is still running. With the option off+ // they would already be in the chat (the test above); here the chat has heard nothing.+ await waitFor(() => notes.seen() === 2);+ notes.off();+ expect(t.deps.manager.statusOf(SID2)).toBe("running");+ expect(fake.allSends()).toEqual([]);+ release();+ await waitFor(() => fake.allSends().length === 1);+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ // One message, carrying the answer whole: the notes were dropped, not merged into it.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_final_on", text: "here is the answer" },+ ]);+ });++ it("a run whose only message is its last one delivers identically either way", async () => {+ // The everyday single-answer run. The option is about what a run says ON THE WAY, so a+ // run that says nothing on the way must not be able to tell the two settings apart —+ // byte for byte the array the linePerMessage-off test asserts for the same reply.+ await bindReplying(SPOKEN, { appId: "cli_final_single", finalReplyOnly: true });+ await messageBot("oc_final_single");+ await waitFor(() => fake.allSends().length > 0);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_final_single", text: SPOKEN.trim() },+ ]);+ });++ it("with linePerMessage too, the final reply is the one split per line", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, ["a note held back", SPOKEN]));+ await bindEnabled(SID2, {+ ...PUT_BODY,+ appId: "cli_final_lines",+ finalReplyOnly: true,+ linePerMessage: true,+ });+ await messageBot("oc_final_lines");+ await waitFor(() => fake.allSends().length === 3);+ // The two compose in one direction: finalReplyOnly picks WHICH text is sent, and+ // linePerMessage decides how that one text is split. The held note is in neither.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_final_lines", text: "Line one." },+ { kind: "send", target: "oc_final_lines", text: " Line two." },+ { kind: "send", target: "oc_final_lines", text: "Line three." },+ ]);+ });++ it("the approval notice is not an assistant message: it arrives while the run is held", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ row2.approvalMode = "always-ask";+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, replyThenApprovalFakeSession(SID2, "the answer"));+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_final_approve", finalReplyOnly: true });+ await messageBot("oc_final_approve");+ // The run has completed one assistant message and parked on the approval. Holding the+ // reply must not hold the one line that says the run is waiting on the user.+ await waitFor(() => fake.allSends().length === 1);+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_final_approve", text: MESSAGING_APPROVAL_NOTICE },+ ]);+ t.deps.manager.decideApproval(SID2, "tc-lines", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ await waitFor(() => fake.allSends().length === 2);+ // And the held message goes out at the run's end, behind the notice on the same chain.+ expect(fake.allTexts().map((s) => s.text)).toEqual([MESSAGING_APPROVAL_NOTICE, "the answer"]);+ });++ it("PUT saves finalReplyOnly, keeps an omitted one, and leaves the other option alone", async () => {+ await api.put(BASE(SID), { ...PUT_BODY, finalReplyOnly: true });+ expect(t.deps.messagingRepo.find(SID, "feishu")?.finalReplyOnly).toBe(true);+ // The masked read carries it, so the editor can render the switch from the GET — and the+ // two preferences are separate columns: saving one says nothing about the other.+ const read = (await (await api.get(BASE(SID))).json()) as FeishuBindingResponse;+ expect(read.binding?.finalReplyOnly).toBe(true);+ expect(read.binding?.linePerMessage).toBe(false);+ // A credentials-only save says nothing about it, and it stays where it was.+ await api.put(BASE(SID), { appId: PUT_BODY.appId });+ expect(t.deps.messagingRepo.find(SID, "feishu")?.finalReplyOnly).toBe(true);+ // Turning it off is an ordinary save, and the other option is still its own field.+ await api.put(BASE(SID), { ...PUT_BODY, finalReplyOnly: false, linePerMessage: true });+ const both = t.deps.messagingRepo.find(SID, "feishu");+ expect(both?.finalReplyOnly).toBe(false);+ expect(both?.linePerMessage).toBe(true);+ });+it("the streamed compaction summary is not a reply and never reaches the chat", async () => {const row2 = sessionRowOf(SID2, projectId);t.deps.sessionsRepo.insert(row2);@@ -2264,6 +2398,39 @@ describe("messaging binding routes and bridge", () => {});});+ it("under finalReplyOnly the files follow the ONE message that reached the chat", async () => {+ const ws = await makeWorkspace();+ await fs.writeFile(path.join(ws, "draft.md"), "wip");+ await fs.writeFile(path.join(ws, "final.md"), "done");+ const row = sessionRowOf(SID2, projectId);+ row.workspace = ws;+ t.deps.sessionsRepo.insert(row);+ t.deps.manager.adopt(+ row,+ multiMessageFakeSession(SID2, [+ "Working — see `draft.md` for now.",+ "Done — the write-up is `final.md`.",+ ]),+ );+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_final_files", finalReplyOnly: true });+ await fake.lastConnection().fire({+ chatId: "oc_chat_files",+ chatType: "p2p",+ messageId: "om_files_final",+ messageType: "text",+ content: JSON.stringify({ text: "do the thing" }),+ });+ await waitFor(() => fake.allSends().length === 2);+ await settle(20);+ // `draft.md` was named only by the message the option held back. A file arriving in a+ // chat where nothing named it is worse than the file not arriving: the mention is the+ // whole reason this feature knows which output was the point.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_chat_files", text: "Done — the write-up is `final.md`." },+ { kind: "file", target: "oc_chat_files", fileName: "final.md", bytes: 4 },+ ]);+ });+// —— Inbound deduplication ————————————————————————————————————————————————// A channel can hand the bridge the same message twice: a Feishu long connection// replays across a reconnect, and any connector that resumes an unconfirmed stream candiff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex e8b287b2..91157a3e 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -50,7 +50,7 @@ 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 { toneInk, toneStrip, type Tone } from "../../lib/tone";import { Button } from "../../components/ui/button";import { FieldLabel } from "../../components/ui/field";import { HelpFold } from "../../components/ui/help-fold";@@ -68,6 +68,7 @@ import {formTestable,formToPut,formToTest,+ type MessagingDeliveryFields,type MessagingFormErrors,type MessagingFormState,} from "./messaging-binding-form";@@ -565,15 +566,49 @@ function StoredSecretRow({);}+/**+ * One saved delivery preference: a label, its semantics behind the label's "?", and the+ * switch. What the option does to a reply is meaning rather than formatting, which is what+ * puts the sentence in a popover instead of under the row — a standing line of explanation+ * is read once and stepped over on every later visit.+ */+function DeliveryOptionRow({+ label,+ help,+ checked,+ onChange,+}: {+ label: string;+ /**+ * The semantics behind the "?". A node rather than a string because one channel's answer+ * needs a second paragraph, and the popover's panel does not preserve newlines — a `\n\n`+ * inside a string would collapse to a space and read as one run-on sentence.+ */+ help: ReactNode;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <div className="flex items-center justify-between gap-3">+ <span className="flex items-center gap-1.5">+ <FieldLabel block={false}>{label}</FieldLabel>+ <InfoPopover label={label}>{help}</InfoPopover>+ </span>+ <Switch aria-label={label} checked={checked} onChange={onChange} />+ </div>+ );+}+/*** The editor's body, top to bottom: the channel selector, the connection controls (enable* toggle + live status, then the two probes, then the hint naming what gates the switch),* then the selected channel's credential fields (credential-source link at the credential- * field's corner, models-style stored-secret row), and last the one saved field that is not a- * credential — the one-message-per-line delivery option, which Save persists like the rest. Only the selector and the controls sit above the- * fields, and everything above the fields is channel-independent in height, so the toggle- * and the probes hold one vertical position no matter which channel is selected. Hosts- * place their own Save action after it and `MessagingBindingHelp` below that.+ * field's corner, models-style stored-secret row), and last the saved fields that are not+ * credentials — the two delivery options, which Save persists like the rest. Only the+ * selector and the controls sit above the fields, and everything above the fields is+ * channel-independent in height, so the toggle and the probes hold one vertical position no+ * matter which channel is selected. Hosts place their own Save action after it and+ * `MessagingBindingHelp` below that.*/export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }) {const { form } = b;@@ -581,6 +616,19 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })const channel = form.channel;const facts = b.channels[channel];const links = CHANNEL_LINKS[channel];+ // The delivery preferences of the selected channel, and the patch that writes one back.+ // All three sub-states carry the same two, so resolving the channel once here keeps the+ // rows at the bottom free of a selector they have nothing to say about.+ const delivery =+ channel === "telegram" ? form.telegram : channel === "qq" ? form.qq : form.feishu;+ const patchDelivery = (patch: Partial<MessagingDeliveryFields>) =>+ b.patchForm(+ channel === "telegram"+ ? { telegram: { ...form.telegram, ...patch } }+ : channel === "qq"+ ? { qq: { ...form.qq, ...patch } }+ : { feishu: { ...form.feishu, ...patch } },+ );return (<div className="space-y-3">{/* Channel first — each channel's config is saved independently, so the selector@@ -886,37 +934,50 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })/></>)}- {/* The one saved field that is not a credential, so it closes the form rather than- sitting among them. Its explanation is semantics — what the option does to a- reply — and therefore rides the "?" beside its label instead of a line the reader- steps over on every later visit. */}- <div className="flex items-center justify-between gap-3">- <span className="flex items-center gap-1.5">- <FieldLabel block={false}>{S.messaging.linePerMessage}</FieldLabel>- <InfoPopover label={S.messaging.linePerMessage}>- {S.messaging.linePerMessageHelp}- </InfoPopover>- </span>- <Switch- aria-label={S.messaging.linePerMessage}- checked={- channel === "telegram"- ? form.telegram.linePerMessage- : channel === "qq"- ? form.qq.linePerMessage- : form.feishu.linePerMessage- }- onChange={(v) =>- b.patchForm(- channel === "telegram"- ? { telegram: { ...form.telegram, linePerMessage: v } }- : channel === "qq"- ? { qq: { ...form.qq, linePerMessage: v } }- : { feishu: { ...form.feishu, linePerMessage: v } },- )- }- />- </div>+ {/* The saved fields that are not credentials, so they close the form rather than+ sitting among them. Both rows are offered on every channel, and their explanations+ sit behind the label's "?" — see DeliveryOptionRow. Order is the order they take+ effect in: which messages are sent, then how each one is split.++ The one place a channel changes the answer rather than shading it: on QQ every send+ is a passive reply anchored to an inbound message, and that anchor expires, so+ holding the reply to the run's end loses a long run's output entirely instead of+ merely delaying it. That is a different outcome, not a nuance of the same one, so it+ is said twice — appended to the explanation, for the reader deciding, and stood on+ screen under the row while the switch is on, for the one who already has. Left to+ the "?" alone, the user learns it from an empty chat. `linePerMessage` needs nothing+ similar: QQ clamps the split to its own budget and the reply still arrives. */}+ <DeliveryOptionRow+ label={S.messaging.finalReplyOnly}+ help={+ channel === "qq" ? (+ <>+ <p>{S.messaging.finalReplyOnlyHelp}</p>+ <p className="mt-2">{S.messaging.finalReplyOnlyQQWarning}</p>+ </>+ ) : (+ S.messaging.finalReplyOnlyHelp+ )+ }+ checked={delivery.finalReplyOnly}+ onChange={(v) => patchDelivery({ finalReplyOnly: v })}+ />+ {/* Rendered by the state it describes, so it is on screen exactly while the loss it+ names is possible and nowhere else. */}+ {channel === "qq" && delivery.finalReplyOnly && (+ <p+ role="alert"+ className={`rounded-md border px-2.5 py-1.5 text-xs ${toneStrip.attention}`}+ >+ {S.messaging.finalReplyOnlyQQWarning}+ </p>+ )}+ <DeliveryOptionRow+ label={S.messaging.linePerMessage}+ help={S.messaging.linePerMessageHelp}+ checked={delivery.linePerMessage}+ onChange={(v) => patchDelivery({ linePerMessage: v })}+ /></div>);}diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.tsindex 5cf46c8c..7746dcac 100644--- a/packages/web/src/features/messaging/messaging-binding-form.ts+++ b/packages/web/src/features/messaging/messaging-binding-form.ts@@ -8,9 +8,10 @@* QQ's sub-state mirrors Feishu's minus the domain field: the platform has one host, so* there is nothing for a domain to switch between.*- * Not every field is a credential: `linePerMessage` is a per-binding delivery preference- * (send a reply one message per non-blank line) that rides the same Save as the rest, which- * is why it lives in the form state rather than behind a toggle of its own.+ * Not every field is a credential: `linePerMessage` (send a reply one message per non-blank+ * line) and `finalReplyOnly` (send only a run's last reply, when the run ends) are per-binding+ * delivery preferences that ride the same Save as the rest, which is why they live in the form+ * state rather than behind toggles of their own.** Secrets never round-trip: `bindingToForm` always leaves the secret field empty (the* server only ever returns a masked value), and `formToPut` omits a blank one so the@@ -34,34 +35,40 @@ export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";/** The token shape @BotFather issues — mirrors the server's identity rule, for immediate feedback. */const TELEGRAM_TOKEN_RE = /^\d+:[A-Za-z0-9_-]{5,}$/;-export interface FeishuFormFields {+/**+ * The delivery preferences every channel carries — the two saved fields that are not+ * credentials, identical in meaning on every channel, which is what lets one row render each+ * of them whichever channel is selected.+ */+export interface MessagingDeliveryFields {+ /** Deliver a reply as one message per non-blank line. */+ linePerMessage: boolean;+ /** Deliver only a run's LAST completed reply, at the run's end, instead of each as it completes. */+ finalReplyOnly: boolean;+}++export interface FeishuFormFields extends MessagingDeliveryFields {appId: string;/** Always starts empty; a non-empty value replaces the stored secret on save. */appSecret: string;baseDomain: string;/** The stored-secret clear checkbox (models idiom): applied on save, a typed secret wins over it. */clearSecret: boolean;- /** Deliver a reply as one message per non-blank line (saved, not a connection setting). */- linePerMessage: boolean;}-export interface QQFormFields {+export interface QQFormFields extends MessagingDeliveryFields {appId: string;/** Always starts empty; a non-empty value replaces the stored secret on save. */appSecret: string;/** The stored-secret clear checkbox (models idiom): applied on save, a typed secret wins over it. */clearSecret: boolean;- /** Deliver a reply as one message per non-blank line (saved, not a connection setting). */- linePerMessage: boolean;}-export interface TelegramFormFields {+export interface TelegramFormFields extends MessagingDeliveryFields {/** Always starts empty; a non-empty value replaces the stored token on save. */botToken: string;/** The stored-token clear checkbox (models idiom): applied on save, a typed token wins over it. */clearToken: boolean;- /** Deliver a reply as one message per non-blank line (saved, not a connection setting). */- linePerMessage: boolean;}/** Editable state backing the binding editor: the selected channel plus every channel's fields. */@@ -99,9 +106,16 @@ export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagbaseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,+ },+ telegram: { botToken: "", clearToken: false, linePerMessage: false, finalReplyOnly: false },+ qq: {+ appId: "",+ appSecret: "",+ clearSecret: false,+ linePerMessage: false,+ finalReplyOnly: false,},- telegram: { botToken: "", clearToken: false, linePerMessage: false },- qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },};}@@ -122,6 +136,7 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormSbaseDomain: info.baseDomain,clearSecret: false,linePerMessage: info.linePerMessage,+ finalReplyOnly: info.finalReplyOnly,};} else if (info.channel === "qq") {form.qq = {@@ -129,11 +144,17 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormSappSecret: "",clearSecret: false,linePerMessage: info.linePerMessage,+ finalReplyOnly: info.finalReplyOnly,};} else {// Telegram's only credential field is the secret itself, so its sub-state loads empty- // apart from the delivery preference, which is not a credential.- form.telegram = { botToken: "", clearToken: false, linePerMessage: info.linePerMessage };+ // apart from the delivery preferences, which are not credentials.+ form.telegram = {+ botToken: "",+ clearToken: false,+ linePerMessage: info.linePerMessage,+ finalReplyOnly: info.finalReplyOnly,+ };}}return form;@@ -174,8 +195,9 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M...(botToken !== "" ? { botToken } : {}),...(clearing ? { clearBotToken: true } : {}),// Always sent, unlike the credential fields: an omitted flag means "keep", which- // would make turning the option back off impossible.+ // would make turning either option back off impossible.linePerMessage: form.telegram.linePerMessage,+ finalReplyOnly: form.telegram.finalReplyOnly,},};}@@ -195,6 +217,7 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M...(clearing ? { clearAppSecret: true } : {}),// Always sent, for the same reason as the other channels': an omitted flag means "keep".linePerMessage: form.qq.linePerMessage,+ finalReplyOnly: form.qq.finalReplyOnly,},};}@@ -216,6 +239,7 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): MbaseDomain,// Always sent, for the same reason as Telegram's: an omitted flag means "keep".linePerMessage: form.feishu.linePerMessage,+ finalReplyOnly: form.feishu.finalReplyOnly,},};}@@ -256,14 +280,17 @@ export function formToTest(form: MessagingFormState): MessagingTestRequestByChan/*** Unsaved edits on the selected channel: any field differing from the loaded baseline (a- * typed secret always counts — it always loads empty — and so does a checked clear box).+ * typed secret always counts — it always loads empty — and so does a checked clear box, and+ * so does either delivery preference, which are the only edits a Telegram form can otherwise+ * have nothing to show for).*/export function formDirty(form: MessagingFormState, baseline: MessagingFormState): boolean {if (form.channel === "telegram") {return (form.telegram.botToken.trim() !== "" ||form.telegram.clearToken ||- form.telegram.linePerMessage !== baseline.telegram.linePerMessage+ form.telegram.linePerMessage !== baseline.telegram.linePerMessage ||+ form.telegram.finalReplyOnly !== baseline.telegram.finalReplyOnly);}if (form.channel === "qq") {@@ -271,7 +298,8 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormStateform.qq.appId !== baseline.qq.appId ||form.qq.appSecret.trim() !== "" ||form.qq.clearSecret ||- form.qq.linePerMessage !== baseline.qq.linePerMessage+ form.qq.linePerMessage !== baseline.qq.linePerMessage ||+ form.qq.finalReplyOnly !== baseline.qq.finalReplyOnly);}return (@@ -279,7 +307,8 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormStateform.feishu.baseDomain !== baseline.feishu.baseDomain ||form.feishu.appSecret.trim() !== "" ||form.feishu.clearSecret ||- form.feishu.linePerMessage !== baseline.feishu.linePerMessage+ form.feishu.linePerMessage !== baseline.feishu.linePerMessage ||+ form.feishu.finalReplyOnly !== baseline.feishu.finalReplyOnly);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 8ac34777..0c12b368 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1935,6 +1935,22 @@ Scenarios:/** Its disclosure, beside the label: what the option does to a reply, and its two edges. */linePerMessageHelp:"Each non-blank line of a reply is sent as its own message and blank lines are dropped, so an answer written as several spoken lines arrives as several messages. Past a per-reply limit the remaining lines are combined into one last message rather than dropped, and a line longer than the channel allows is still split. The messages go out about a second apart, the pace a chat platform allows.",+ /** The saved delivery option: hold a run's working notes, send its last reply only. */+ finalReplyOnly: "Final reply only",+ /** Its disclosure, beside the label: what the option changes, and what it costs. */+ finalReplyOnlyHelp:+ "Only the last thing the assistant says in a run is sent, when the run ends. The notes it writes between tool calls stay in the web app instead of arriving as their own messages, so the chat receives the answer rather than the work — at the cost of hearing nothing while a long run is under way. The approval reminder is not a reply and still arrives immediately. With one message per line also on, that final reply is the one that is split.",+ /**+ * QQ only, and said twice there: appended to the option's explanation for the reader+ * deciding, and stood under the row as a warning strip while the switch is on. Not a+ * nuance of the same trade but a different outcome: QQ can only send a passive reply+ * anchored to an inbound message, and that anchor expires. On the other two channels the+ * cost of holding the reply is silence; here a run that outlasts the window delivers+ * nothing at all — too much to rest on a "?" the user need never open, which would leave+ * them to discover it from an empty chat.+ */+ finalReplyOnlyQQWarning:+ "On QQ this needs a second thought: QQ only accepts a passive reply anchored to an inbound message, and that anchor expires after about five minutes. Holding the reply until the run ends means a run that outlasts the window delivers nothing at all — with this off, at least whatever finished inside the window arrives.",/** Enabled-row indicator's tooltip / sr text (the small per-channel glyph on the session row). */enabledIndicator: {feishu: "Feishu connection enabled",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex fd3aea0b..ace8430a 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1890,6 +1890,22 @@ Benchmark:/** Its disclosure, beside the label: what the option does to a reply, and its two edges. */linePerMessageHelp:"开启后,回复中的每个非空行各自作为一条消息发出,空行忽略——写成多句台词的回复就按台词逐条到达。行数超过每条回复的上限时,余下的行合并为最后一条,内容不会丢失;过长的单行仍按渠道长度上限分段。多条消息之间相隔约一秒发出,这是聊天平台允许的速率。",+ /** The saved delivery option: hold a run's working notes, send its last reply only. */+ finalReplyOnly: "只发送最终回复",+ /** Its disclosure, beside the label: what the option changes, and what it costs. */+ finalReplyOnlyHelp:+ "开启后,一次运行中只有助手最后说的那段话会发出,且在运行结束时发送。它在工具调用之间写下的过程记录留在网页端,不再各自作为一条消息到达——聊天里收到的是结论而非过程,代价是长时间运行期间聊天中一片安静。审批提醒不属于回复,仍会立即到达。若同时开启「每行一条消息」,被拆分的就是这条最终回复。",+ /**+ * QQ only, and said twice there: appended to the option's explanation for the reader+ * deciding, and stood under the row as a warning strip while the switch is on. Not a+ * nuance of the same trade but a different outcome: QQ can only send a passive reply+ * anchored to an inbound message, and that anchor expires. On the other two channels the+ * cost of holding the reply is silence; here a run that outlasts the window delivers+ * nothing at all — too much to rest on a "?" the user need never open, which would leave+ * them to discover it from an empty chat.+ */+ finalReplyOnlyQQWarning:+ "在 QQ 上要多想一步:QQ 只接受锚定在某条入站消息上的被动回复,且该锚点约五分钟后失效。把回复押到运行结束,意味着运行超过这个窗口时一条也发不出去——关闭本开关时,至少窗口内完成的那几条能送达。",/** Enabled-row indicator's tooltip / sr text (the small per-channel glyph on the session row). */enabledIndicator: {feishu: "飞书连接已启用",diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex 45452e26..939d4d79 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -177,14 +177,17 @@ describe("MessagingBindingBody", () => {expect(html).toContain(`title="${lastError}"`);});- it('closes the form with the delivery option, its explanation behind the label\'s "?"', () => {+ it('closes the form with the delivery options, each explanation behind its label\'s "?"', () => {for (const channel of ["feishu", "telegram", "qq"] as MessagingChannel[]) {const html = render(stateOf(channel));- // Both channels carry it: it is a delivery preference, not a credential.+ // Every channel carries both: they are delivery preferences, not credentials.expect(html).toContain(S.messaging.linePerMessage);- // Semantics disclose — the sentence is in the popover panel, which renders collapsed.+ expect(html).toContain(S.messaging.finalReplyOnly);+ // Semantics disclose — each sentence is in a popover panel, which renders collapsed.expect(html).toContain(S.common.moreInfoAbout(S.messaging.linePerMessage));+ expect(html).toContain(S.common.moreInfoAbout(S.messaging.finalReplyOnly));expect(html).not.toContain(S.messaging.linePerMessageHelp);+ expect(html).not.toContain(S.messaging.finalReplyOnlyHelp);// After the credential fields, not among them.const fieldAt = html.indexOf(channel === "telegram"@@ -194,10 +197,30 @@ describe("MessagingBindingBody", () => {: S.feishu.appId,);expect(fieldAt).toBeGreaterThanOrEqual(0);- expect(html.indexOf(S.messaging.linePerMessage)).toBeGreaterThan(fieldAt);+ expect(html.indexOf(S.messaging.finalReplyOnly)).toBeGreaterThan(fieldAt);+ // In the order the two take effect: which messages are sent, then how each is split.+ expect(html.indexOf(S.messaging.linePerMessage)).toBeGreaterThan(+ html.indexOf(S.messaging.finalReplyOnly),+ );}});+ it("renders each delivery switch from its own form field", () => {+ // One row per option, both fed from the SELECTED channel's sub-state: a row wired to the+ // wrong field renders a switch that is on while the form says off, which no type checker+ // and no snapshot of the default state would catch.+ const form = emptyMessagingForm("telegram");+ form.telegram.finalReplyOnly = true;+ const html = render(stateOf("telegram", {}, { form }));+ const finalAt = html.indexOf(S.messaging.finalReplyOnly);+ const lineAt = html.indexOf(S.messaging.linePerMessage);+ expect(finalAt).toBeGreaterThanOrEqual(0);+ expect(lineAt).toBeGreaterThan(finalAt);+ // Exactly one switch is checked, and it is the one under the label that was flipped.+ expect(html.slice(finalAt, lineAt)).toContain('aria-checked="true"');+ expect(html.slice(lineAt)).toContain('aria-checked="false"');+ });+it("states QQ's replies-only rule on screen, not in a collapsed fold", () => {// The one piece of channel copy that cannot wait to be unfolded. QQ delivers only// replies to messages sent from QQ, so a user who binds it and then works in the web appdiff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.tsindex b8ed67de..4d3fcda8 100644--- a/packages/web/test/messaging-binding-form.test.ts+++ b/packages/web/test/messaging-binding-form.test.ts@@ -4,9 +4,10 @@* always load empty, an empty submit keeps the stored secret (the PUT body omits it), and* only a first bind requires one — the models-idiom clear checkbox (applied on save, a* typed secret wins over it), the per-channel submit routing (only the selected channel's- * fields are validated and sent), the blank-domain-means-default fallback, and the one saved- * field that is not a credential — `linePerMessage`, which loads per channel and is always sent- * (an omitted flag would mean "keep", leaving no way to turn the option back off).+ * fields are validated and sent), the blank-domain-means-default fallback, and the two saved+ * fields that are not credentials — `linePerMessage` and `finalReplyOnly`, which load per+ * channel and are always sent (an omitted flag would mean "keep", leaving no way to turn either+ * option back off).*/import { describe, expect, it } from "vitest";import type {@@ -32,6 +33,7 @@ const STORED_FEISHU: FeishuBindingInfo = {baseDomain: "https://open.larksuite.com",enabled: false,linePerMessage: false,+ finalReplyOnly: false,lastChatKnown: true,createdAt: "2026-08-25T00:00:00.000Z",updatedAt: "2026-08-25T00:00:00.000Z",@@ -45,6 +47,7 @@ const STORED_TELEGRAM: TelegramBindingInfo = {enabled: true,// Set on one fixture only, so a per-channel load cannot pass by copying the other channel.linePerMessage: true,+ finalReplyOnly: false,lastChatKnown: false,createdAt: "2026-08-26T00:00:00.000Z",updatedAt: "2026-08-26T00:00:00.000Z",@@ -57,6 +60,8 @@ const STORED_QQ: QQBindingInfo = {appSecretMasked: "qq-a…1234",enabled: false,linePerMessage: false,+ // The other flag, set on a different fixture: neither can pass by riding the other.+ finalReplyOnly: true,lastChatKnown: true,createdAt: "2026-08-27T00:00:00.000Z",updatedAt: "2026-08-27T00:00:00.000Z",@@ -72,9 +77,16 @@ describe("emptyMessagingForm / bindingsToForm", () => {baseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,+ },+ telegram: { botToken: "", clearToken: false, linePerMessage: false, finalReplyOnly: false },+ qq: {+ appId: "",+ appSecret: "",+ clearSecret: false,+ linePerMessage: false,+ finalReplyOnly: false,},- telegram: { botToken: "", clearToken: false, linePerMessage: false },- qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },});});@@ -90,17 +102,28 @@ describe("emptyMessagingForm / bindingsToForm", () => {baseDomain: "https://open.larksuite.com",clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,},- // Each channel's delivery preference comes from its own stored config.- telegram: { botToken: "", clearToken: false, linePerMessage: true },+ // Each channel's delivery preferences come from its own stored config.+ telegram: { botToken: "", clearToken: false, linePerMessage: true, finalReplyOnly: false },// An unsaved channel keeps its empty sub-state, so switching to it shows a blank form.- qq: { appId: "", appSecret: "", clearSecret: false, linePerMessage: false },+ qq: {+ appId: "",+ appSecret: "",+ clearSecret: false,+ linePerMessage: false,+ finalReplyOnly: false,+ },});// All three coexist: every saved channel loads its own non-secret fields.const all = bindingsToForm([STORED_FEISHU, STORED_TELEGRAM, STORED_QQ]);expect(all.feishu.appId).toBe("cli_abc");expect(all.qq.appId).toBe("102000001");expect(all.qq.appSecret).toBe("");+ // Each flag loads from the channel that stored it, and from nowhere else.+ expect(all.qq.finalReplyOnly).toBe(true);+ expect(all.telegram.finalReplyOnly).toBe(false);+ expect(all.feishu.linePerMessage).toBe(false);// No enabled channel: the first saved one is selected; nothing saved: Feishu.expect(bindingsToForm([STORED_FEISHU]).channel).toBe("feishu");expect(bindingsToForm([STORED_QQ]).channel).toBe("qq");@@ -114,7 +137,12 @@ describe("formToPut (feishu)", () => {expect(res).toEqual({ok: true,channel: "feishu",- body: { appId: "cli_abc", baseDomain: "https://open.larksuite.com", linePerMessage: false },+ body: {+ appId: "cli_abc",+ baseDomain: "https://open.larksuite.com",+ linePerMessage: false,+ finalReplyOnly: false,+ },});});@@ -145,6 +173,7 @@ describe("formToPut (feishu)", () => {clearAppSecret: true,baseDomain: "https://open.larksuite.com",linePerMessage: false,+ finalReplyOnly: false,},});// The models idiom: a typed replacement wins over a stale checked box.@@ -155,6 +184,7 @@ describe("formToPut (feishu)", () => {appSecret: "replacement-secret",baseDomain: "https://open.larksuite.com",linePerMessage: false,+ finalReplyOnly: false,});// Without a stored secret there is nothing to clear: the flag never reaches the body.const nothingStored = emptyMessagingForm();@@ -174,6 +204,7 @@ describe("formToPut (feishu)", () => {baseDomain: " ",clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,};const blankDomain = formToPut(form, false);expect(blankDomain.ok && blankDomain.channel === "feishu" && blankDomain.body.baseDomain).toBe(@@ -193,7 +224,11 @@ describe("formToPut (telegram)", () => {expect(formToPut(form, false)).toEqual({ok: true,channel: "telegram",- body: { botToken: "7000000001:secret-token-AAAA", linePerMessage: false },+ body: {+ botToken: "7000000001:secret-token-AAAA",+ linePerMessage: false,+ finalReplyOnly: false,+ },});// With a stored token an empty field means "keep it": the body omits the token — but not// the delivery flag, which is a plain field and always carries its current value.@@ -201,7 +236,7 @@ describe("formToPut (telegram)", () => {expect(formToPut(form, true)).toEqual({ok: true,channel: "telegram",- body: { linePerMessage: false },+ body: { linePerMessage: false, finalReplyOnly: false },});// A first bind must carry one.expect(formToPut(form, false)).toEqual({ ok: false, errors: { botToken: "required" } });@@ -213,13 +248,14 @@ describe("formToPut (telegram)", () => {expect(formToPut(form, true)).toEqual({ok: true,channel: "telegram",- body: { clearBotToken: true, linePerMessage: false },+ body: { clearBotToken: true, linePerMessage: false, finalReplyOnly: false },});form.telegram.botToken = "7000000001:replacement-token";const typed = formToPut(form, true);expect(typed.ok && typed.channel === "telegram" && typed.body).toEqual({botToken: "7000000001:replacement-token",linePerMessage: false,+ finalReplyOnly: false,});});@@ -243,12 +279,41 @@ describe("formToPut (telegram)", () => {baseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,};feishuSide.telegram.botToken = "garbage";expect(formToPut(feishuSide, false).ok).toBe(true);});});+describe("the delivery flags", () => {+ it("sends both on every channel, whatever their values, so either can be turned back off", () => {+ // The rule that makes them work at all: an omitted flag means "keep the stored value",+ // so a body that drops the ones currently off can never turn an option off again.+ for (const [form, channel] of [+ [emptyMessagingForm("feishu"), "feishu"],+ [emptyMessagingForm("telegram"), "telegram"],+ [emptyMessagingForm("qq"), "qq"],+ ] as const) {+ form.feishu.appId = "cli_x";+ form.qq.appId = "102000001";+ form.telegram.botToken = "7000000001:secret-token-AAAA";+ for (const values of [+ { linePerMessage: false, finalReplyOnly: false },+ { linePerMessage: true, finalReplyOnly: false },+ { linePerMessage: false, finalReplyOnly: true },+ { linePerMessage: true, finalReplyOnly: true },+ ]) {+ Object.assign(form[channel], values);+ const res = formToPut(form, true);+ expect(res.ok).toBe(true);+ expect(res.ok && res.body.linePerMessage).toBe(values.linePerMessage);+ expect(res.ok && res.body.finalReplyOnly).toBe(values.finalReplyOnly);+ }+ }+ });+});+describe("formToTest", () => {it("carries only the selected channel's filled-in fields, so blanks fall back to the stored binding server-side", () => {// The fresh form prefills the default domain, and a prefilled value is a filled value.@@ -266,6 +331,7 @@ describe("formToTest", () => {baseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,linePerMessage: false,+ finalReplyOnly: false,};expect(formToTest(feishu)).toEqual({channel: "feishu",@@ -305,20 +371,27 @@ describe("formDirty / formTestable", () => {expect(formDirty(tg, tgBaseline)).toBe(true);});- it("counts the delivery flag as an edit on both channels", () => {- // Telegram is the one that would silently break: before this field its only dirty signals- // were the token and the clear box, so flipping a switch would have left Save disabled.+ it("counts either delivery flag as an edit on every channel", () => {+ // Telegram is the one that would silently break: without these fields its only dirty+ // signals are the token and the clear box, so flipping a switch would leave Save disabled.const tgBaseline = bindingsToForm([STORED_TELEGRAM]);const tg = bindingsToForm([STORED_TELEGRAM]);tg.telegram.linePerMessage = !tg.telegram.linePerMessage;expect(formDirty(tg, tgBaseline)).toBe(true);+ const tgFinal = bindingsToForm([STORED_TELEGRAM]);+ tgFinal.telegram.finalReplyOnly = true;+ expect(formDirty(tgFinal, tgBaseline)).toBe(true);const baseline = bindingsToForm([STORED_FEISHU]);const feishu = bindingsToForm([STORED_FEISHU]);feishu.feishu.linePerMessage = true;expect(formDirty(feishu, baseline)).toBe(true);- // The unselected channel's flag is not the selected channel's business.+ const feishuFinal = bindingsToForm([STORED_FEISHU]);+ feishuFinal.feishu.finalReplyOnly = true;+ expect(formDirty(feishuFinal, baseline)).toBe(true);+ // The unselected channel's flags are not the selected channel's business.const otherChannel = bindingsToForm([STORED_FEISHU]);otherChannel.telegram.linePerMessage = true;+ otherChannel.telegram.finalReplyOnly = true;expect(formDirty(otherChannel, baseline)).toBe(false);});@@ -349,6 +422,9 @@ describe("the QQ channel", () => {expect(form.qq.appId).toBe("102000001");expect(form.qq.appSecret).toBe("");expect(form.qq.clearSecret).toBe(false);+ // Both delivery preferences load from the stored config, each on its own.+ expect(form.qq.finalReplyOnly).toBe(true);+ expect(form.qq.linePerMessage).toBe(false);});it("submits the pair, omits a blank secret, and always sends the delivery flag", () => {@@ -359,14 +435,19 @@ describe("the QQ channel", () => {channel: "qq",// No `appSecret` key at all: an omitted secret is what tells the server to keep the// stored one, and the masked value must never round-trip.- body: { appId: "102000001", linePerMessage: false },+ body: { appId: "102000001", linePerMessage: false, finalReplyOnly: true },});form.qq.appSecret = " fresh-secret ";expect(formToPut(form, true)).toEqual({ok: true,channel: "qq",- body: { appId: "102000001", appSecret: "fresh-secret", linePerMessage: false },+ body: {+ appId: "102000001",+ appSecret: "fresh-secret",+ linePerMessage: false,+ finalReplyOnly: true,+ },});});@@ -382,14 +463,24 @@ describe("the QQ channel", () => {expect(formToPut(stored, true)).toEqual({ok: true,channel: "qq",- body: { appId: "102000001", clearAppSecret: true, linePerMessage: false },+ body: {+ appId: "102000001",+ clearAppSecret: true,+ linePerMessage: false,+ finalReplyOnly: true,+ },});// A typed secret wins over a stale clear checkbox (the models idiom).stored.qq.appSecret = "typed";expect(formToPut(stored, true)).toEqual({ok: true,channel: "qq",- body: { appId: "102000001", appSecret: "typed", linePerMessage: false },+ body: {+ appId: "102000001",+ appSecret: "typed",+ linePerMessage: false,+ finalReplyOnly: true,+ },});});@@ -401,6 +492,9 @@ describe("the QQ channel", () => {expect(formDirty(form, baseline)).toBe(false);form.qq.linePerMessage = true;expect(formDirty(form, baseline)).toBe(true);+ const qqFinal = bindingsToForm([STORED_QQ]);+ qqFinal.qq.finalReplyOnly = !qqFinal.qq.finalReplyOnly;+ expect(formDirty(qqFinal, baseline)).toBe(true);// A stored secret is testable as-is; a draft needs both halves.expect(formTestable(emptyMessagingForm("qq"), true)).toBe(true);