A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): deliver a messaging reply one message per line (#494)
Yaowei Zheng50d780830302
diff --git a/changelog/unreleased/2026-08-26-backward-compatibility.md b/changelog/unreleased/2026-08-26-backward-compatibility.mdindex 7f2ef74f..2405f9f3 100644--- a/changelog/unreleased/2026-08-26-backward-compatibility.md+++ b/changelog/unreleased/2026-08-26-backward-compatibility.md@@ -3,14 +3,16 @@- **Date:** 2026-08-26- **Type:** process- **Scope:** `server`-- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)- **Breaking:** yes — one-way for the database: after two Sessions have saved the same bot account, a build from before this change can no longer open that `web.db`[中文版](2026-08-26-backward-compatibility.zh.md)-This batch touches one piece of existing state: the `idx_messaging_account` unique index on-`messaging_bindings`, carried by every `web.db` that has opened a build with messaging bindings in-it (0.2.5 and later).+This batch touches two things on an existing `web.db`, both on `messaging_bindings`: the+`idx_messaging_account` unique index it carries (every database that has opened a build with+messaging bindings in it — 0.2.5 and later), and one added column. Only the first needs a+decision; the second is recorded so a reader looking here for "does my database need anything?"+finds both answers in one place.## The retired unique account index@@ -47,6 +49,16 @@ per open. It is removed only in a release that is allowed to break existing `webshould be removed together with the `idx_usage_session` drop that sits beside it, since both arethe same kind of debt.+## The added `line_per_message` column++[One message per line](2026-08-26-messaging-line-per-message.md) added+`messaging_bindings.line_per_message INTEGER NOT NULL DEFAULT 0`, ALTERed in on open by the+`ensureColumn` list that exists for exactly this. It is purely additive and needs no decision:+the default reproduces the delivery every existing binding already had — one message per reply —+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. An older build simply ignores a column it has never heard of.+## CompatibilityNo action is required. The first open of an updated build drops the index; bindings, credentialsdiff --git a/changelog/unreleased/2026-08-26-backward-compatibility.zh.md b/changelog/unreleased/2026-08-26-backward-compatibility.zh.mdindex 97bf53b5..bba2d4c1 100644--- a/changelog/unreleased/2026-08-26-backward-compatibility.zh.md+++ b/changelog/unreleased/2026-08-26-backward-compatibility.zh.md@@ -3,13 +3,14 @@- **Date:** 2026-08-26- **Type:** process- **Scope:** `server`-- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490)+- **PR:** [#490](https://github.com/Prism-Shadow/penguin-harness/pull/490), [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)- **Breaking:** yes — 对数据库是单向的:一旦两个 Session 保存了同一个机器人账号,本次改动之前的构建就再也打不开那个 `web.db`[English](2026-08-26-backward-compatibility.md)-本批改动触及一处存量状态:`messaging_bindings` 上的 `idx_messaging_account` 唯一索引——凡是打开-过带消息绑定的构建(0.2.5 及以后)的 `web.db` 都带有它。+本批改动在存量 `web.db` 上触及两处,都在 `messaging_bindings` 上:它携带的 `idx_messaging_account`+唯一索引(凡是打开过带消息绑定的构建——0.2.5 及以后——的数据库都有),以及新增的一列。只有前者需要+决策;后者记在这里,是为了让来这里查「我的数据库需要做什么吗」的读者在同一处拿到两个答案。## 退役的账号唯一索引@@ -40,6 +41,15 @@限期保留,代价是每次打开多执行一条空操作语句。它只在允许破坏存量 `web.db` 的版本中移除,并且应当与紧挨着它的 `idx_usage_session` 删除语句一并清理,两者属于同一类债务。+## 新增的 `line_per_message` 列++[每行一条消息](2026-08-26-messaging-line-per-message.zh.md)新增了+`messaging_bindings.line_per_message INTEGER NOT NULL DEFAULT 0`,由既有的 `ensureColumn` 列表在打+开时 ALTER 进来——那份列表正是为此存在。它纯属新增,无需任何决策:默认值复现了每份存量绑定原本的送+达方式——每条回复一条消息——因此没有任何绑定的行为改变,没有任何数据被改写,用户也无需做任何事。该+`ensureColumn` 条目的保留期与「本次发布之前形成的 `web.db` 仍可被打开」等长,与该列表中其余条目同一+口径。旧构建则直接忽略一个它从未听说过的列。+## 兼容性无需任何操作。升级后第一次打开即删除该索引;绑定、凭证与记住的会话都不受影响,从不把同一个机器diff --git a/changelog/unreleased/2026-08-26-messaging-line-per-message.md b/changelog/unreleased/2026-08-26-messaging-line-per-message.mdnew file mode 100644index 00000000..924ac478--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-line-per-message.md@@ -0,0 +1,42 @@+# A messaging reply can arrive one message per line++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)++[中文版](2026-08-26-messaging-line-per-message.zh.md)++A relayed assistant reply reached the chat as one message, however it was written. A per-binding+option now delivers it as one message per non-blank line instead — the shape a role-play answer+written as several spoken lines is meant to arrive in. Off by default, and off is byte-for-byte+the previous behaviour.++## Details++- The option is stored as `messaging_bindings.line_per_message`, a column beside `enabled` rather+ than a key inside `config_json`: that document is the channel's own credential shape, owned by+ its connector, while this applies to every channel identically.+- `linePerMessage` joined `FeishuBindingInfo` / `TelegramBindingInfo` and both PUT bodies. It is+ an ordinary form field applied on Save — no route of its own — and an omitted value keeps the+ stored one; a new binding starts with it off.+- Splitting is deliberately literal: every non-blank line becomes its own message, fenced code+ blocks included; blank lines and trailing whitespace are dropped, and leading indentation is+ kept — an indented code block arrives runnable. Each resulting message still goes through the+ channel's size chunking, so a single line over the cap is split rather than rejected.+- One reply may become at most `MESSAGING_MAX_LINE_MESSAGES` (20) messages, a number taken from+ the tightest channel's per-chat burst allowance — Telegram answers 429 to roughly 20 messages a+ minute in one chat. The budget counts outbound messages rather than line bodies, the size+ chunking included, so a long answer cannot slip past it; past the budget the remaining lines+ ride one combined body rather than being dropped. The messages of such a reply go out a second+ apart, the pace that same allowance describes.+- Delivery is order-safe and failure-safe: the approval notice is queued behind whatever is+ already going out instead of landing between two lines of a reply, and a message the channel+ refuses costs only itself — it is recorded as an error while the rest of the reply still+ arrives.+- The group-chat rule is unchanged: the run's first outbound message threads onto the inbound one+ and everything after it is a plain send, so many lines do not become many quote headers. The+ option applies only to relayed assistant replies — never to the approval notice, the text-only+ notice or the test message.+- In the binding editor the option closes the form as a `Switch` for both channels, saved by the+ existing Save action, with its explanation behind the "?" beside its label.diff --git a/changelog/unreleased/2026-08-26-messaging-line-per-message.zh.md b/changelog/unreleased/2026-08-26-messaging-line-per-message.zh.mdnew file mode 100644index 00000000..318a11c1--- /dev/null+++ b/changelog/unreleased/2026-08-26-messaging-line-per-message.zh.md@@ -0,0 +1,33 @@+# 消息回复可以每行一条送达++- **Date:** 2026-08-26+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **PR:** [#494](https://github.com/Prism-Shadow/penguin-harness/pull/494)++[English](2026-08-26-messaging-line-per-message.md)++转发的助手回复此前无论怎么写都以一条消息抵达聊天。现在每份绑定多了一个选项,可以改为每个非+空行各自一条消息——写成多句台词的角色扮演回复本该以这种形态到达。默认关闭,关闭时的行为与此+前逐字节一致。++## 细节++- 该选项存为 `messaging_bindings.line_per_message` 列,与 `enabled` 并列,而不是塞进+ `config_json`:后者是渠道自己的凭据文档、由其连接器拥有,而这个选项对每个渠道的含义完全+ 相同。+- `linePerMessage` 加入 `FeishuBindingInfo` / `TelegramBindingInfo` 与两个 PUT 请求体。它是随+ Save 生效的普通表单字段,没有独立路由;省略则保持已存值,新建的绑定默认关闭。+- 拆分刻意保持字面:每个非空行成为一条消息,代码围栏之内同样如此;空行与行尾空白一并丢弃,行+ 首缩进保留——缩进的代码块到达时仍然可运行。拆出的每条消息仍走渠道的长度分段,因此超长的单行+ 会被分段而不是被拒绝。+- 一条回复最多拆成 `MESSAGING_MAX_LINE_MESSAGES`(20)条消息,这个数取自最紧的渠道的单聊突发+ 额度——Telegram 对同一会话每分钟约 20 条以上就会返回 429。这份额度按真正发出的消息计,含长度+ 分段在内,而不是按行计,长回复因此无法绕过它;超出额度的行合并为最后一条,而不是被丢弃。这样+ 一条回复的各条消息之间相隔一秒发出,正是同一份额度描述的速率。+- 送达的顺序与失败都有兜底:审批提醒排在已在发送的内容之后,不会插进一条回复的两行之间;被渠道+ 拒绝的那条消息只损失它自己——错误会被记录,回复的其余部分照常送达。+- 群聊规则不变:一次运行的第一条外发消息回复到入站消息,其余为普通发送,因此多行不会变成多个+ 引用头。该选项只作用于转发的助手回复——审批提醒、「仅支持文本」提示与测试消息都不受影响。+- 绑定编辑器中,该选项以 `Switch` 收尾表单,两个渠道通用,由既有的 Save 保存,说明放在标签旁+ 的「?」之后。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 45baa283..11a088ab 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -295,21 +295,21 @@ A Session can be connected to a messaging bot — Feishu and Telegram are the ch| Method | Path | Description || --- | --- | --- |-| GET | /messaging | Channel-agnostic read: EVERY saved channel config (`channel` discriminant, secrets masked, per-row `enabled` intent + 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` + 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?}`. 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?}`. 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?}` — 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?}` — 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?, error?}` — success names the bot the token signs in as || 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 |-Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage` is the one saved field that is not a credential: with it set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap); it defaults to false, an omitted value on a PUT keeps the stored one, and it never applies to the notices or the test message. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs, and inbound processing accepts text messages only (other types get a bilingual "text only" reply). Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone.### Preview on a separate origindiff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 6a86f330..08087fc5 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -294,21 +294,21 @@ Session 可以接入消息软件机器人——目前的渠道是飞书与 Teleg| 方法 | 路径 | 说明 || --- | --- | --- |-| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |+| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 || GET | /messaging/feishu | `{binding, status}` 形态下的飞书配置(未保存时为 null) |-| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?}`。`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?}`。`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?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 |+| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?, linePerMessage?}`——整份凭据就是 @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?, error?}`——成功时报出 Token 登录到的机器人 || POST | /messaging/telegram/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 Telegram 里给机器人发过消息之前返回 409 `telegram_no_chat` |-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 是唯一一个不属于凭据的已存字段:开启后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条);默认为 false,PUT 省略该字段则保持已存值,且它不作用于通知与测试消息。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置;入站仅处理文本消息(其他类型收到双语的“仅支持文本”回复)。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。### 独立源预览diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 852c2d89..40b849b2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1631,6 +1631,11 @@ export interface FeishuBindingInfo {baseDomain: string;/** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */enabled: boolean;+ /**+ * Send each non-blank line of a relayed assistant reply as its own message instead of one+ * message per reply. Off by default; off is the original one-message-per-reply behaviour.+ */+ linePerMessage: 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.@@ -1654,6 +1659,11 @@ export interface TelegramBindingInfo {botTokenMasked?: string;/** Connection INTENT (the state toggle's value); new bindings start disabled, and at most one of a Session's channels is enabled. */enabled: boolean;+ /**+ * Send each non-blank line of a relayed assistant reply as its own message instead of one+ * message per reply. Off by default; off is the original one-message-per-reply behaviour.+ */+ linePerMessage: 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.@@ -1710,6 +1720,11 @@ export interface FeishuBindingPutRequest {* it). Refused with 409 `messaging_disable_before_clear` while the binding is enabled.*/clearAppSecret?: boolean;+ /**+ * Delivery preference (see `FeishuBindingInfo.linePerMessage`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ linePerMessage?: boolean;}/**@@ -1727,6 +1742,11 @@ export interface TelegramBindingPutRequest {* `messaging_disable_before_clear` while the binding is enabled.*/clearBotToken?: boolean;+ /**+ * Delivery preference (see `TelegramBindingInfo.linePerMessage`). Omitted keeps the stored+ * value; a binding created without it starts with it off.+ */+ linePerMessage?: boolean;}/**diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 899807b8..152b3956 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -213,6 +213,8 @@ export interface BuildDepsOverrides {telegramTransport?: TelegramTransport;/** Test hook: the Telegram connector's poll backoff (tests collapse it to zero). */telegramRetryDelayMs?: (failures: number) => number;+ /** Test hook: the bridge's pace between a per-line reply's messages (tests collapse it to zero). */+ messagingLineDelayMs?: number;/*** Test double: scrypt work factor for password hashes written through this app.* Omitted in production, where the KDF runs at full strength.@@ -747,6 +749,9 @@ export function buildAppDeps(errors,log,...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),+ ...(overrides.messagingLineDelayMs !== undefined+ ? { lineDelayMs: overrides.messagingLineDelayMs }+ : {}),});const sessionService = new SessionService({root: config.root,diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.tsindex dbb7b72f..177983aa 100644--- a/packages/server/src/db/database.ts+++ b/packages/server/src/db/database.ts@@ -33,6 +33,7 @@ export function openDatabase(dbPath: string): DatabaseSync {ensureColumn(db, "sessions", "thinking_level", "TEXT");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");// 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 is// served identically. Dropping is safe — an index is derived, never data.diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.tsindex 8696f1cc..c80c4fb4 100644--- a/packages/server/src/db/repos/messaging-bindings.ts+++ b/packages/server/src/db/repos/messaging-bindings.ts@@ -15,6 +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.+ ** `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* server_settings) and must be masked at every API surface — nothing here ever masks,@@ -41,6 +45,12 @@ export interface MessagingBindingRow {* route-enforced).*/enabled: boolean;+ /**+ * DELIVERY preference: send each non-blank line of a relayed assistant reply as its own+ * message instead of one message per reply. Off by default, and off reproduces the+ * original behaviour exactly. Ordinary saved state — the PUT owns it, like the config.+ */+ linePerMessage: boolean;/** Most recent inbound chat (null until the bot is messaged once). */lastChatId: string | null;/** Whether that chat is a direct chat; group chats prefer reply-to-message. */@@ -65,6 +75,7 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {accountId: r.account_id as string,config,enabled: Number(r.enabled) === 1,+ linePerMessage: Number(r.line_per_message) === 1,lastChatId: (r.last_chat_id as string | null) ?? null,lastChatIsDirect: Number(r.last_chat_is_direct) === 1,createdAt: r.created_at as string,@@ -125,8 +136,10 @@ 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. It cannot fail on another Session: the same account- * saved elsewhere is none of this write's business, since only enabling is exclusive.+ * 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).+ * 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* loses the reply target — unless the account changed, whose chats are unrelated: the* remembered chat is dropped so replies can never land in the old bot's conversation.@@ -136,6 +149,7 @@ export class MessagingBindingsRepo {channel: string;accountId: string;config: Record<string, unknown>;+ linePerMessage?: boolean;}): MessagingBindingRow {const now = new Date().toISOString();const configJson = JSON.stringify(args.config);@@ -144,16 +158,25 @@ export class MessagingBindingsRepo {this.db.prepare(`INSERT INTO messaging_bindings- (session_id, channel, account_id, config_json, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?)`,+ (session_id, channel, account_id, config_json, line_per_message, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?)`,)- .run(args.sessionId, args.channel, args.accountId, configJson, now, now);+ .run(+ args.sessionId,+ args.channel,+ args.accountId,+ configJson,+ args.linePerMessage === true ? 1 : 0,+ now,+ now,+ );} else {const keepChat = existing.accountId === args.accountId;this.db.prepare(`UPDATE messaging_bindingsSET account_id = ?, config_json = ?,+ line_per_message = COALESCE(?, line_per_message),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,updated_at = ?@@ -162,6 +185,8 @@ export class MessagingBindingsRepo {.run(args.accountId,configJson,+ // NULL = the caller said nothing about it, and COALESCE keeps what is stored.+ args.linePerMessage === undefined ? null : args.linePerMessage ? 1 : 0,keepChat ? 1 : 0,keepChat ? 1 : 0,now,diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex b615f8dc..ffc70f9b 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -128,6 +128,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channelaccount_id TEXT NOT NULL, -- channel-scoped bot/app identity (feishu: app_id; telegram: the bot token's numeric id); NOT unique — any number of Sessions may keep the same account saved side by side, each with its own config and last-chat memory; only ENABLING is exclusive (route-enforced, 409 account_enabled_elsewhere: one account has one event stream, two live connections on it would race)config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken); 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 does+ line_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 ownslast_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)last_chat_is_direct INTEGER NOT NULL DEFAULT 1, -- 1 = direct chat (reply by chat id), 0 = group chat (prefer reply-to-message)created_at TEXT NOT NULL,diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.tsindex 043accdb..cb155f40 100644--- a/packages/server/src/http/routes/messaging.ts+++ b/packages/server/src/http/routes/messaging.ts@@ -20,6 +20,10 @@* and run the two tests; the secret-mutating writes — PUT, the state toggle and DELETE —* are Project-owner-only.*+ * 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.+ ** Round-trip rule for secrets: GET only ever returns the masked value, and a PUT whose* secret (feishu `appSecret`, telegram `botToken`) is omitted or blank keeps the stored* one (the same never-round-trip-masked-keys convention as the models test endpoint), so@@ -50,7 +54,13 @@ import { FEISHU_DEFAULT_DOMAIN, feishuConfigOf } from "../../runtime/messaging/fimport { telegramBotIdOf } from "../../runtime/messaging/telegram-connector.js";import { maskApiKey } from "../../services/project-config-service.js";import { HttpError } from "../errors.js";-import { badRequest, optionalString, readJson, requireString } from "../validate.js";+import {+ badRequest,+ optionalBoolean,+ optionalString,+ readJson,+ requireString,+} from "../validate.js";import type { AppDeps } from "../../app.js";/** The stored feishu config, tolerated loosely (a malformed document reads as blanks). */@@ -84,6 +94,7 @@ function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {...(fields.appSecret !== "" ? { appSecretMasked: maskApiKey(fields.appSecret) } : {}),baseDomain: fields.baseDomain,enabled: row.enabled,+ linePerMessage: row.linePerMessage,lastChatKnown: row.lastChatId !== null,createdAt: row.createdAt,updatedAt: row.updatedAt,@@ -98,6 +109,7 @@ function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {botId: row.accountId,...(botToken !== "" ? { botTokenMasked: maskApiKey(botToken) } : {}),enabled: row.enabled,+ linePerMessage: row.linePerMessage,lastChatKnown: row.lastChatId !== null,createdAt: row.createdAt,updatedAt: row.updatedAt,@@ -252,6 +264,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 baseDomain = parseBaseDomain(optionalString(body, "baseDomain", { maxLen: 500 }));+ const linePerMessage = optionalBoolean(body, "linePerMessage");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@@ -286,6 +299,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {channel: "feishu",accountId: appId,config: { appId, appSecret, baseDomain },+ ...(linePerMessage !== undefined ? { linePerMessage } : {}),});// 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@@ -390,6 +404,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {const body = await readJson(c);const tokenInput = optionalString(body, "botToken", { maxLen: 200 })?.trim();const clearToken = (body as { clearBotToken?: unknown }).clearBotToken === true;+ const linePerMessage = optionalBoolean(body, "linePerMessage");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),@@ -434,6 +449,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {channel: "telegram",accountId: botId,config: { botToken },+ ...(linePerMessage !== undefined ? { linePerMessage } : {}),});// Same save/enable split as Feishu: only an enabled binding restarts its connector.if (saved.enabled) await deps.messaging.sync(row.sessionId);diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex 501192f4..86a9f4b9 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -25,7 +25,9 @@* 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, and the sends of one entry are serialised through a promise chain:+ * 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:* 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@@ -36,7 +38,8 @@* 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.+ * waiting in the web UI — on the same chain, so it lands between replies instead of inside+ * one.*/import { userText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";@@ -62,6 +65,35 @@ import type {*/export const MESSAGING_TEXT_CHUNK_CHARS = 4000;+/**+ * How many messages one reply may become under a binding's `linePerMessage`, and why this+ * particular number.+ *+ * The ceiling is a rate limit, not a size limit. Telegram's documented per-chat allowance is+ * about one message a second, with a burst to a single group tolerated up to roughly 20 a+ * minute before it starts answering 429; Feishu's IM send limit is counted per app and is far+ * looser, so Telegram sets the number. 20 spends the tightest channel's burst allowance for+ * one chat on a single reply — enough that an answer written as spoken lines arrives as spoken+ * lines, low enough that one long reply cannot spend several minutes of budget at once.+ *+ * It bounds OUTBOUND MESSAGES, not lines: the budget is spent in chunks, so a line over the+ * size cap costs as many messages as it chunks into (see splitReplyLines). Past it the+ * remaining lines are COMBINED into one final body rather than dropped: silently losing the+ * tail of a reply is the worst failure available here. The one reply that still exceeds the+ * ceiling is one long enough to need more messages than this unchunked — which it would have+ * needed with the option off too.+ */+export const MESSAGING_MAX_LINE_MESSAGES = 20;++/**+ * The wait between the messages of one per-line reply. The cap above bounds a single reply's+ * burst; this paces it, because the tightest channel's per-chat allowance is about one message+ * a second and 20 sends fired back to back is exactly the shape that draws a 429. Only a+ * per-line reply is paced: with the option off a reply is one message (or the handful its size+ * chunks into), which was never a burst.+ */+export const MESSAGING_LINE_DELAY_MS = 1000;+// The three fixed outbound notices are user-facing chat content, deliberately bilingual// like the rest of the product's user-facing copy (the server has no locale for an// external chat, so both languages ride each notice).@@ -135,6 +167,47 @@ export function chunkMessagingText(text: string, max = MESSAGING_TEXT_CHUNK_CHARreturn out;}+/**+ * Splits a relayed reply into one message per non-blank line, for a binding that asked for it.+ *+ * Deliberately literal: every non-blank line becomes its own message — inside a fenced code+ * block included — with blank lines dropped. The whole value of the option is that its+ * behaviour is predictable, which any "smart" grouping (holding a code fence together, merging+ * short lines) would trade away. Only trailing whitespace goes (a CR from a CRLF reply with+ * it); leading indentation is content, and a code block that arrives unindented does not run.+ *+ * `max` bounds the outbound MESSAGES, not the lines: each body returned still goes through+ * chunkMessagingText, so the budget is spent in chunks — a line over the channel's cap costs+ * as many messages as it chunks into. Splitting therefore stops while what is left still fits+ * in the remaining budget, and everything from there rides one combined body (chunked like any+ * other), so the reply reaches the chat entire either way.+ */+export function splitReplyLines(text: string, max = MESSAGING_MAX_LINE_MESSAGES): string[] {+ const lines = text+ .split("\n")+ .map((line) => line.trimEnd())+ .filter((line) => line !== "");+ const out: string[] = [];+ let used = 0;+ for (let i = 0; i < lines.length; i += 1) {+ const line = lines[i]!;+ const lineCost = chunkMessagingText(line).length;+ const rest = lines.slice(i + 1);+ const restCost = rest.length === 0 ? 0 : chunkMessagingText(rest.join("\n")).length;+ if (used + lineCost + restCost > max) {+ // Splitting this line off would put the reply over the budget. The rest rides one+ // combined body instead, keeping its own line breaks so the message reads as the lines+ // it was made of. (The loop cannot run past `max` rounds: every emitted line spends at+ // least one message.)+ out.push(lines.slice(i).join("\n"));+ return out;+ }+ out.push(line);+ used += lineCost;+ }+ return out;+}+/** Dedupe scope: one binding, i.e. a Session's config for one channel. */function inboundKey(sessionId: string, channel: string): string {return `${sessionId}:${channel}`;@@ -165,6 +238,8 @@ export interface MessagingBridgeDeps {errors: ErrorSink;log?: (line: string) => void;now?: () => number;+ /** Test hook: the pace between a per-line reply's messages (default MESSAGING_LINE_DELAY_MS; tests collapse it to zero). */+ lineDelayMs?: number;}/** One connected (or connecting/errored) binding's in-memory state. */@@ -190,10 +265,11 @@ interface BridgeEntry {/** The run in progress already threaded its first outbound message onto the inbound one. */threadedThisRun: boolean;/**- * Tail of this entry's outbound sends. Each relayed message is appended rather than- * started on its own, so messages completing in quick succession cannot race each other- * into the chat out of order. It never rejects — deliverReply records its own failures —- * so one slow or failing send delays this Session's later messages and nothing else.+ * 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+ * race into the chat out of order — an approval notice must not land between the messages of+ * a reply. It never rejects — deliverReply and deliverNotice record their own failures — so+ * one slow or failing send delays this Session's later messages and nothing else.*/sendChain: Promise<void>;}@@ -213,11 +289,13 @@ export class MessagingBridge {private readonly connectors: ReadonlyMap<string, MessagingChannelConnector>;private readonly now: () => number;private readonly log: (line: string) => void;+ private readonly lineDelayMs: number;constructor(private readonly deps: MessagingBridgeDeps) {this.connectors = new Map(deps.connectors.map((c) => [c.channel, c]));this.now = deps.now ?? (() => Date.now());this.log = deps.log ?? (() => {});+ this.lineDelayMs = deps.lineDelayMs ?? MESSAGING_LINE_DELAY_MS;}/**@@ -488,7 +566,13 @@ export class MessagingBridge {if (event.type === "task_state" && typeof event.state === "string") {this.onTaskState(entry, event.state);} else if (event.type === "approval_request") {- void this.deliverNotice(entry, MESSAGING_APPROVAL_NOTICE);+ // Queued behind whatever is already going out, like a reply: a reply the binding+ // splits per line holds the client for many sequential sends, and a notice started+ // beside that chain would land between two of its lines. deliverNotice never+ // throws, so it cannot break the chain.+ entry.sendChain = entry.sendChain.then(() =>+ this.deliverNotice(entry, MESSAGING_APPROVAL_NOTICE),+ );}return;}@@ -536,42 +620,80 @@ export class MessagingBridge {/*** 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- * moving. In a group the run's first outbound chunk threads onto the inbound message and+ * 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+ * sends one message per non-blank line instead of one per reply (see splitReplyLines),+ * paced MESSAGING_LINE_DELAY_MS apart so the burst stays inside the channel's per-chat+ * allowance — chunking, threading and ordering are identical either way, and with the flag+ * off the send sequence is unchanged. In a group the run's+ * first outbound chunk threads onto the inbound message and* everything after it is a plain send: the reply-to relation names which message is being* 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> {- try {- const row = this.deps.repo.find(entry.sessionId, entry.channel);- if (!row || row.lastChatId === null) return; // no chat known yet: nothing mirrors- const client = await this.clientFor(entry.sessionId, row);- for (const chunk of chunkMessagingText(text)) {- const threadOnto =- !row.lastChatIsDirect && entry.lastInboundMessageId !== null && !entry.threadedThisRun- ? entry.lastInboundMessageId- : null;+ const target = await this.sendTarget(entry);+ if (target === null) return;+ const { row, chatId, client } = target;+ // 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 ? splitReplyLines(text) : [text];+ const messages = bodies.flatMap((body) => chunkMessagingText(body));+ for (const [i, chunk] of messages.entries()) {+ // The messages of a per-line reply are a burst; the channel's per-chat allowance is+ // 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 && entry.lastInboundMessageId !== null && !entry.threadedThisRun+ ? entry.lastInboundMessageId+ : null;+ try {if (threadOnto !== null) {entry.threadedThisRun = true;await client.replyText(threadOnto, chunk);} else {- await client.sendText(row.lastChatId, chunk);+ await client.sendText(chatId, chunk);}+ } catch (err) {+ this.recordError(entry.sessionId, err, "messaging_send_failed");}- } catch (err) {- this.recordError(entry.sessionId, err, "messaging_send_failed");}}/** One-line notice (approval waiting) to the last known chat; silent before one exists. */private async deliverNotice(entry: BridgeEntry, text: string): Promise<void> {+ const target = await this.sendTarget(entry);+ if (target === null) return;+ try {+ await target.client.sendText(target.chatId, text);+ } catch (err) {+ this.recordError(entry.sessionId, err, "messaging_send_failed");+ }+ }++ /**+ * Where this entry's outbound traffic goes, with a client for it: null when no chat is+ * known yet (nothing mirrors before the first inbound message) and null when the binding+ * or its client could not be read at all, which is recorded like the send it stands in for.+ */+ private async sendTarget(+ entry: BridgeEntry,+ ): Promise<{ row: MessagingBindingRow; chatId: string; client: MessagingClient } | null> {try {const row = this.deps.repo.find(entry.sessionId, entry.channel);- if (!row || row.lastChatId === null) return;+ if (!row || row.lastChatId === null) return null;const client = await this.clientFor(entry.sessionId, row);- await client.sendText(row.lastChatId, text);+ return { row, chatId: row.lastChatId, client };} catch (err) {this.recordError(entry.sessionId, err, "messaging_send_failed");+ return null;}}++ /** The pace between a per-line reply's messages; zero (tests) waits for nothing. */+ private pace(): Promise<void> {+ if (this.lineDelayMs <= 0) return Promise.resolve();+ return new Promise((resolve) => setTimeout(resolve, this.lineDelayMs));+ }}diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.tsindex 663f14a9..beb0c5e9 100644--- a/packages/server/test/db-upgrade.test.ts+++ b/packages/server/test/db-upgrade.test.ts@@ -5,8 +5,9 @@* pre-existing database.** The last two suites cover the other two directions a released build meets on disk: a table- * that did not exist when the database was formed (and, in the same suite, an index that has- * since been retired — the one shape openDatabase removes rather than adds), and a database+ * that did not exist when the database was formed, a column added to it afterwards, and an+ * index that has since been retired — the one shape openDatabase removes rather than adds — and+ * a database* written by a *newer* build than the one opening it (a user who updates, dislikes it, and* reinstalls the previous release). Nothing records a schema version, so both properties rest* on every schema change staying additive — and the downgrade one on more than that, which the@@ -369,6 +370,70 @@ 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.+ */+ function seedPreLinePerMessageDb(dbPath: 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");+ seed(db);+ } finally {+ db.close();+ }+ }++ 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) => {+ old+ .prepare(+ `INSERT INTO messaging_bindings+ (session_id, channel, account_id, config_json, enabled, created_at, updated_at)+ VALUES ('session-old', 'telegram', '12345', '{"botToken":"t"}', 1, ?, ?)`,+ )+ .run(ts, ts);+ });+ const before = new sqlite.DatabaseSync(dbPath);+ let columnsBefore: { name: string }[];+ try {+ columnsBefore = before.prepare("PRAGMA table_info(messaging_bindings)").all() as {+ name: string;+ }[];+ } finally {+ before.close();+ }+ expect(columnsBefore.map((c) => c.name)).not.toContain("line_per_message");++ const db = openDatabase(dbPath);+ try {+ const repo = new MessagingBindingsRepo(db);+ const row = repo.find("session-old", "telegram");+ // The column arrives with a default that reproduces the behaviour the row already had —+ // one message per reply — so the upgrade cannot change how an existing binding delivers.+ expect(row?.linePerMessage).toBe(false);+ // And the rest of the row is untouched, including the connection intent.+ expect(row?.enabled).toBe(true);+ expect(row?.config.botToken).toBe("t");+ // It is 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" },+ linePerMessage: true,+ }).linePerMessage,+ ).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/helpers.ts b/packages/server/test/helpers.tsindex abb0e02d..1b3f40b5 100644--- a/packages/server/test/helpers.ts+++ b/packages/server/test/helpers.ts@@ -82,7 +82,14 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestAif (beforeSeed) await beforeSeed(root);const deps = await bootAppDeps({ ...testConfig(root), ...config },- { log: () => {}, passwordHashCost: TEST_PASSWORD_HASH_COST, ...overrides },+ {+ log: () => {},+ passwordHashCost: TEST_PASSWORD_HASH_COST,+ // The bridge's per-line pace is a real wait in production; every test but the one+ // about the pacing itself collapses it to nothing.+ messagingLineDelayMs: 0,+ ...overrides,+ },);// Consistent with the startup entrypoint: seed the built-in admin (owning default_project),// keeping the password it returns (only null if a beforeSeed hook ever pre-created users).diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex a8767778..996e8ce9 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -432,6 +432,20 @@ describe("telegram binding routes and connector loop", () => {expect((await api.post(`${BASE(SID2)}/state`, { enabled: true })).status).toBe(409);});+ it("the delivery flag rides the token PUT on this channel too, and defaults off", async () => {+ // The bridge's splitting is channel-agnostic (messaging.test.ts pins the behaviour); what+ // is per-channel is the route wiring, which is what this asserts.+ await api.put(BASE(SID), { botToken: TOKEN });+ expect(t.deps.messagingRepo.find(SID, "telegram")?.linePerMessage).toBe(false);+ const on = await api.put(BASE(SID), { linePerMessage: true });+ expect(on.status).toBe(200);+ expect(((await on.json()) as TelegramBindingResponse).binding?.linePerMessage).toBe(true);+ // The token was untouched by that save, and an omitted flag keeps the stored value.+ expect(t.deps.messagingRepo.find(SID, "telegram")?.config.botToken).toBe(TOKEN);+ await api.put(BASE(SID), {});+ expect(t.deps.messagingRepo.find(SID, "telegram")?.linePerMessage).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);diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex 084efa5f..a4985f12 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -9,8 +9,10 @@* exactly as if typed in the composer (no marker, no special sender; queueIfBusy),* non-text gets the bilingual text-only reply, each completed assistant message mirrors on* its own to the last known chat as soon as it completes (the run's first one threaded onto- * the inbound message in groups), and an approval_request sends the one-line notice. No- * test opens real network.+ * the inbound message in groups), 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 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.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import {@@ -26,9 +28,12 @@ import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import {MESSAGING_APPROVAL_NOTICE,+ MESSAGING_MAX_LINE_MESSAGES,MESSAGING_TEST_MESSAGE,+ MESSAGING_TEXT_CHUNK_CHARS,MESSAGING_TEXT_ONLY_NOTICE,chunkMessagingText,+ splitReplyLines,} from "../src/runtime/messaging/bridge.js";import type {FeishuApiClient,@@ -38,7 +43,7 @@ import type {FeishuSdk,} from "../src/runtime/messaging/feishu-sdk.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";-import type { TestApp } from "./helpers.js";+import type { TestApp, TestAppOptions } from "./helpers.js";const SID = "session-2026-08-25-10-00-00-fe15aa01";const SID2 = "session-2026-08-25-10-00-01-fe15aa02";@@ -56,6 +61,8 @@ interface SentText {class FakeClient implements FeishuApiClient {readonly sends: SentText[] = [];+ /** When each send was recorded, parallel to `sends`: what the pacing test measures. */+ readonly sentAt: number[] = [];checks = 0;constructor(readonly creds: FeishuCredentials,@@ -67,10 +74,18 @@ class FakeClient implements FeishuApiClient {return null;}async sendText(chatId: string, text: string): Promise<void> {- this.sends.push({ kind: "send", target: chatId, text });+ this.sdk.noteSend();+ this.record({ kind: "send", target: chatId, text });+ await this.sdk.hold();}async replyText(messageId: string, text: string): Promise<void> {- this.sends.push({ kind: "reply", target: messageId, text });+ this.sdk.noteSend();+ this.record({ kind: "reply", target: messageId, text });+ await this.sdk.hold();+ }+ private record(sent: SentText): void {+ this.sends.push(sent);+ this.sentAt.push(Date.now());}async botOpenId(): Promise<string | null> {this.sdk.botIdentityLookups++;@@ -99,6 +114,20 @@ class FakeSdk implements FeishuSdk {readonly connections: FakeConnection[] = [];/** Non-null makes checkCredentials throw with this message. */failCheck: string | null = null;+ /** Non-null makes the send with this 1-based number (counted across clients) throw. */+ failSendAt: number | null = null;+ /** Non-null parks every send on this promise, holding the bridge's send chain open. */+ heldSends: Promise<void> | null = null;+ private sendCount = 0;+ /** Every send passes here first: it counts, and throws for the one a test marked. */+ noteSend(): void {+ this.sendCount += 1;+ if (this.sendCount === this.failSendAt) throw new Error("Too Many Requests: retry after 5");+ }+ /** Awaited after each send: instant unless a test is holding sends open. */+ hold(): Promise<void> {+ return this.heldSends ?? Promise.resolve();+ }/** What `/open-apis/bot/v3/info` reports for this app; null = the identity is unavailable. */botOpenId: string | null = null;/** Makes that lookup never answer, so a test can prove connect() does not wait on it. */@@ -120,6 +149,10 @@ class FakeSdk implements FeishuSdk {allSends(): SentText[] {return this.clients.flatMap((c) => c.sends);}+ /** Their timestamps, in the same order. */+ allSentAt(): number[] {+ return this.clients.flatMap((c) => c.sentAt);+ }lastConnection(): FakeConnection {const conn = this.connections.at(-1);if (!conn) throw new Error("no fake connection was opened");@@ -195,6 +228,28 @@ function multiMessageFakeSession(};}+/**+ * Fake Session that completes one assistant message and then parks on an approval: the+ * window in which a notice could overtake the reply's still-unsent messages.+ */+function replyThenApprovalFakeSession(sessionId: string, text: string): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {+ yield assistantText(text);+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-lines" });+ yield tc;+ yield approvalDecision(await opts.approve(tc), "tc-lines");+ },+ async *compact() {},+ };+}+/** Fake Session that streams a compaction summary mid-run, then the actual answer. */function compactingFakeSession(sessionId: string): RuntimeSession {const bounds = { reason: "context", mode: "summarize" } as const;@@ -248,6 +303,61 @@ describe("chunkMessagingText", () => {});});+describe("splitReplyLines", () => {+ it("makes one message per non-blank line and leaves a single line alone", () => {+ // Trailing whitespace goes with the line break it followed; the indentation in front of+ // a line is content the reader asked for.+ expect(splitReplyLines("one\n\n two \nthree")).toEqual(["one", " two", "three"]);+ expect(splitReplyLines("just one line")).toEqual(["just one line"]);+ // Literal on purpose, fenced code included: the option is worth having because a reader+ // can predict what arrives, and any "smart" grouping would trade that away.+ expect(splitReplyLines("```\ncode()\n```")).toEqual(["```", "code()", "```"]);+ });++ it("keeps the indentation inside a code block and reads a CRLF reply", () => {+ // Stripping the indent would hand the chat Python that does not run — the split is a+ // split, not an edit.+ expect(splitReplyLines("```python\ndef f():\n return 1 \n```")).toEqual([+ "```python",+ "def f():",+ " return 1",+ "```",+ ]);+ // A CRLF reply: the CR is trailing whitespace, and a CRLF blank line is still blank.+ expect(splitReplyLines("a\r\n\r\nb\r\n")).toEqual(["a", "b"]);+ });++ it("combines the tail past the cap rather than dropping it", () => {+ const lines = Array.from({ length: 25 }, (_, i) => `l${i}`);+ const out = splitReplyLines(lines.join("\n"), 5);+ expect(out).toHaveLength(5);+ expect(out.slice(0, 4)).toEqual(["l0", "l1", "l2", "l3"]);+ // Everything from the cap on rides the last message, keeping its own line breaks — so+ // nothing is lost, which is the point of combining instead of truncating.+ expect(out[4]).toBe(lines.slice(4).join("\n"));+ expect(out.join("\n")).toBe(lines.join("\n"));+ // Exactly at the cap nothing is combined.+ expect(splitReplyLines(lines.slice(0, 5).join("\n"), 5)).toEqual(lines.slice(0, 5));+ });++ it("defaults to the documented per-reply message cap", () => {+ const lines = Array.from({ length: MESSAGING_MAX_LINE_MESSAGES + 5 }, (_, i) => `l${i}`);+ expect(splitReplyLines(lines.join("\n"))).toHaveLength(MESSAGING_MAX_LINE_MESSAGES);+ });++ it("spends the cap on outbound MESSAGES, chunking included", () => {+ // An ordinary long answer: every line sits well under the size cap, but the combined+ // tail does not, so counting bodies would promise 20 messages and send 25 — past the+ // rate limit the cap exists to hold.+ const lines = Array.from({ length: 60 }, (_, i) => `${i}`.padEnd(500, "x"));+ const bodies = splitReplyLines(lines.join("\n"));+ const messages = bodies.flatMap((body) => chunkMessagingText(body));+ expect(messages.length).toBeLessThanOrEqual(MESSAGING_MAX_LINE_MESSAGES);+ // And still the whole reply: the budget is spent by combining, never by dropping.+ expect(messages.join("\n")).toBe(lines.join("\n"));+ });+});+describe("messaging binding routes and bridge", () => {let t: TestApp;let api: ReturnType<typeof apiClient>;@@ -261,9 +371,10 @@ describe("messaging binding routes and bridge", () => {expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);};- beforeEach(async () => {+ /** The suite's app, rebuildable: the pacing test needs one whose per-line wait is not zero. */+ const boot = async (opts: TestAppOptions = {}) => {fake = new FakeSdk();- t = await createTestApp({ feishuSdk: fake });+ t = await createTestApp({ feishuSdk: fake, ...opts });const { cookie } = await provisionUser(t.app, "birder");api = apiClient(t.app, cookie);projectId = "birder-default_project";@@ -271,7 +382,9 @@ describe("messaging binding routes and bridge", () => {const row = sessionRowOf(SID, projectId);t.deps.sessionsRepo.insert(row);t.deps.manager.adopt(row, echoFakeSession(SID, runs));- });+ };++ beforeEach(() => boot());afterEach(async () => {await t.cleanup();});@@ -670,6 +783,203 @@ describe("messaging binding routes and bridge", () => {]);});+ // —— linePerMessage: the per-binding delivery option ————————————————————————++ /**+ * A reply written as spoken lines: a blank line between the first two, and a middle line+ * both indented and trailing-padded — the split keeps the indent and drops the padding, so+ * every expectation below spells the middle line with its two leading spaces.+ */+ const SPOKEN = "Line one.\n\n Line two. \nLine three.";++ /** SID2 replying with one fixed text, bound and connected, ready to be messaged. */+ const bindReplying = async (text: string, put: Record<string, unknown>) => {+ const row2 = sessionRowOf(SID2, projectId);+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, multiMessageFakeSession(SID2, [text]));+ await bindEnabled(SID2, { ...PUT_BODY, ...put });+ };++ /** One inbound text into a direct chat, which becomes the reply target. */+ const messageBot = async (chatId: string, chatType: "p2p" | "group" = "p2p") =>+ fake.lastConnection().fire({+ chatId,+ chatType,+ messageId: `om_${chatId}`,+ messageType: "text",+ content: JSON.stringify({ text: "ping" }),+ });++ it("linePerMessage off (the default) delivers a multi-line reply as ONE message", async () => {+ await bindReplying(SPOKEN, { appId: "cli_lines_off" });+ // The default is off, on a binding whose PUT never mentioned the field.+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.linePerMessage).toBe(false);+ await messageBot("oc_off");+ await waitFor(() => fake.allSends().length > 0);+ // Byte for byte what the bridge sent before the option existed: the trimmed reply, whole.+ expect(fake.allSends()).toEqual([{ kind: "send", target: "oc_off", text: SPOKEN.trim() }]);+ });++ it("linePerMessage on delivers one message per non-blank line, in order", async () => {+ await bindReplying(SPOKEN, { appId: "cli_lines_on", linePerMessage: true });+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.linePerMessage).toBe(true);+ await messageBot("oc_on");+ await waitFor(() => fake.allSends().length === 3);+ // Order is the send chain's guarantee, so the whole array is asserted, not its contents:+ // three messages arriving out of order would be a different bug with the same members.+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_on", text: "Line one." },+ { kind: "send", target: "oc_on", text: " Line two." },+ { kind: "send", target: "oc_on", text: "Line three." },+ ]);+ });++ it("a line over the channel's size cap is still chunked rather than rejected", async () => {+ const long = "x".repeat(MESSAGING_TEXT_CHUNK_CHARS + 500);+ await bindReplying(`head\n${long}`, { appId: "cli_lines_long", linePerMessage: true });+ await messageBot("oc_long");+ await waitFor(() => fake.allSends().length === 3);+ // Splitting happens first, chunking after: the long line becomes two messages, and the+ // pieces reassemble into exactly the line that was sent.+ expect(fake.allSends().map((s) => s.text)).toEqual([+ "head",+ long.slice(0, MESSAGING_TEXT_CHUNK_CHARS),+ long.slice(MESSAGING_TEXT_CHUNK_CHARS),+ ]);+ });++ it("past the cap the remaining lines arrive combined, not dropped", async () => {+ const lines = Array.from({ length: MESSAGING_MAX_LINE_MESSAGES + 4 }, (_, i) => `l${i}`);+ await bindReplying(lines.join("\n"), { appId: "cli_lines_cap", linePerMessage: true });+ await messageBot("oc_cap");+ await waitFor(() => fake.allSends().length === MESSAGING_MAX_LINE_MESSAGES);+ const texts = fake.allSends().map((s) => s.text);+ expect(texts.slice(0, -1)).toEqual(lines.slice(0, MESSAGING_MAX_LINE_MESSAGES - 1));+ // The tail rides the last message: the reply reaches the chat entire either way.+ expect(texts.at(-1)).toBe(lines.slice(MESSAGING_MAX_LINE_MESSAGES - 1).join("\n"));+ expect(texts.join("\n")).toBe(lines.join("\n"));+ });++ it("a refused message costs only itself: the rest of the reply still arrives", async () => {+ const lines = Array.from({ length: 6 }, (_, i) => `l${i}`);+ await bindReplying(lines.join("\n"), { appId: "cli_lines_429", linePerMessage: true });+ // What a 429 looks like from here. The reply used to stop at the first one, leaving the+ // chat with an answer cut off mid-sentence and nothing saying why.+ fake.failSendAt = 3;+ await messageBot("oc_429");+ await waitFor(() => fake.allSends().length === 5);+ expect(fake.allSends().map((s) => s.text)).toEqual(["l0", "l1", "l3", "l4", "l5"]);+ // The loss is recorded rather than swallowed (one row: the recorder dedupes a repeat of+ // the same code within its window).+ const errors = t.deps.db+ .prepare("SELECT code FROM error_records WHERE source = 'messaging'")+ .all() as Array<{ code: string }>;+ expect(errors).toEqual([{ code: "messaging_send_failed" }]);+ });++ it("paces the messages of a per-line reply instead of firing them back to back", async () => {+ // The pace is a real wait, so this one test runs on an app with a short one; the rest of+ // the suite collapses it to zero.+ await t.cleanup();+ await boot({ messagingLineDelayMs: 40 });+ await bindReplying(SPOKEN, { appId: "cli_lines_paced", linePerMessage: true });+ await messageBot("oc_paced");+ await waitFor(() => fake.allSends().length === 3);+ // Two waits between three messages. The burst is what draws the channel's 429, so the+ // reply is spread over the per-chat allowance instead of spending it at once.+ const at = fake.allSentAt();+ expect(at[2]! - at[0]!).toBeGreaterThanOrEqual(60);+ });++ it("the approval notice waits behind the reply rather than landing between its lines", async () => {+ const row2 = sessionRowOf(SID2, projectId);+ row2.approvalMode = "always-ask";+ t.deps.sessionsRepo.insert(row2);+ t.deps.manager.adopt(row2, replyThenApprovalFakeSession(SID2, SPOKEN));+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_lines_approve", linePerMessage: true });+ // Hold every send open: the whole reply is then still in flight when the approval fires.+ let release = () => {};+ fake.heldSends = new Promise<void>((resolve) => {+ release = resolve;+ });+ let requested = false;+ const off = t.deps.channels.get(SID2).subscribe((evt) => {+ const data = JSON.parse(evt.data) as { type?: string };+ if (evt.event === "server_event" && data.type === "approval_request") requested = true;+ });+ await messageBot("oc_approve");+ // The bridge subscribed to this channel first, so once this listener has seen the+ // request the bridge has already handled it; the timer then drains the microtasks a+ // notice sent beside the chain would have taken.+ await waitFor(() => requested);+ off();+ await new Promise((resolve) => setTimeout(resolve, 10));+ release();+ await waitFor(() => fake.allSends().length === 4);+ expect(fake.allSends().map((s) => s.text)).toEqual([+ "Line one.",+ " Line two.",+ "Line three.",+ MESSAGING_APPROVAL_NOTICE,+ ]);+ t.deps.manager.decideApproval(SID2, "tc-lines", "allow");+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");+ });++ it("the notices are not replies: linePerMessage never reaches them", async () => {+ await bindReplying(SPOKEN, { appId: "cli_lines_notice", linePerMessage: true });+ await fake.lastConnection().fire({+ chatId: "oc_notice",+ chatType: "p2p",+ messageId: "om_notice",+ messageType: "image",+ content: JSON.stringify({ image_key: "img_1" }),+ });+ await waitFor(() => fake.allSends().length > 0);+ // One send carrying the notice whole. The notices are single-line by construction, so+ // this is asserted from both ends: the text has no line break to split on, and it+ // arrives as one message — a notice routed through the reply path would break the pair.+ expect(MESSAGING_TEXT_ONLY_NOTICE).not.toContain("\n");+ expect(fake.allSends()).toEqual([+ { kind: "send", target: "oc_notice", text: MESSAGING_TEXT_ONLY_NOTICE },+ ]);+ // And the test message, sent through its own path, is one message too.+ const sent = fake.allSends().length;+ expect((await api.post(`/api/sessions/${SID2}/messaging/feishu/test-message`, {})).status).toBe(+ 200,+ );+ expect(fake.allSends().slice(sent)).toEqual([+ { kind: "send", target: "oc_notice", text: MESSAGING_TEST_MESSAGE },+ ]);+ });++ it("in a group, split lines still thread only once", async () => {+ await bindReplying(SPOKEN, { appId: "cli_lines_group", linePerMessage: true });+ await messageBot("oc_lines_group", "group");+ await waitFor(() => fake.allSends().length === 3);+ // The rule the option must not disturb: one reply-to anchors the exchange, and many+ // lines must not become many quote headers.+ expect(fake.allSends()).toEqual([+ { kind: "reply", target: "om_oc_lines_group", text: "Line one." },+ { kind: "send", target: "oc_lines_group", text: " Line two." },+ { kind: "send", target: "oc_lines_group", text: "Line three." },+ ]);+ });++ it("PUT saves the flag and an omitted one keeps the stored value", async () => {+ await api.put(BASE(SID), { ...PUT_BODY, linePerMessage: true });+ expect(t.deps.messagingRepo.find(SID, "feishu")?.linePerMessage).toBe(true);+ // The masked read carries it, so the editor can render the switch from the GET.+ const read = (await (await api.get(BASE(SID))).json()) as FeishuBindingResponse;+ expect(read.binding?.linePerMessage).toBe(true);+ // 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")?.linePerMessage).toBe(true);+ // Turning it off is an ordinary save.+ await api.put(BASE(SID), { ...PUT_BODY, linePerMessage: false });+ expect(t.deps.messagingRepo.find(SID, "feishu")?.linePerMessage).toBe(false);+ });+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);diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex baaa7ff3..0ed099c7 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -46,6 +46,7 @@ import { toneInk, type Tone } from "../../lib/tone";import { Button } from "../../components/ui/button";import { FieldLabel } from "../../components/ui/field";import { HelpFold } from "../../components/ui/help-fold";+import { InfoPopover } from "../../components/ui/info-popover";import { Input } from "../../components/ui/input";import { PasswordInput } from "../../components/ui/password-input";import { Segmented } from "../../components/ui/segmented";@@ -476,7 +477,8 @@ function StoredSecretRow({* 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 (console link at the credential field's- * corner, models-style stored-secret row). Only the selector and the controls sit above the+ * 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.@@ -592,7 +594,9 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })error={errorText(b.fieldErrors.botToken)}value={form.telegram.botToken}onChange={(e) =>- b.patchForm({ telegram: { botToken: e.target.value, clearToken: false } })+ b.patchForm({+ telegram: { ...form.telegram, botToken: e.target.value, clearToken: false },+ })}autoComplete="off"/>@@ -668,6 +672,31 @@ 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 : form.feishu.linePerMessage+ }+ onChange={(v) =>+ b.patchForm(+ channel === "telegram"+ ? { telegram: { ...form.telegram, linePerMessage: v } }+ : { feishu: { ...form.feishu, linePerMessage: v } },+ )+ }+ />+ </div></div>);}diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.tsindex fce75061..b89bc063 100644--- a/packages/web/src/features/messaging/messaging-binding-form.ts+++ b/packages/web/src/features/messaging/messaging-binding-form.ts@@ -5,6 +5,10 @@* selector back and forth never loses what was typed; `channel` names the selected one,* and only its fields are validated or submitted.*+ * 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.+ ** 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* server keeps the stored value. Validation errors come back as codes; the component maps@@ -32,6 +36,8 @@ export interface FeishuFormFields {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 TelegramFormFields {@@ -39,6 +45,8 @@ export interface TelegramFormFields {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 both channels' fields. */@@ -67,8 +75,14 @@ export type MessagingTestRequestByChannel =export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagingFormState {return {channel,- feishu: { appId: "", appSecret: "", baseDomain: FEISHU_DEFAULT_DOMAIN, clearSecret: false },- telegram: { botToken: "", clearToken: false },+ feishu: {+ appId: "",+ appSecret: "",+ baseDomain: FEISHU_DEFAULT_DOMAIN,+ clearSecret: false,+ linePerMessage: false,+ },+ telegram: { botToken: "", clearToken: false, linePerMessage: false },};}@@ -88,9 +102,13 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormSappSecret: "",baseDomain: info.baseDomain,clearSecret: false,+ linePerMessage: info.linePerMessage,};+ } 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 };}- // Telegram's one field is the secret itself, so its sub-state always loads empty.}return form;}@@ -129,6 +147,9 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): Mbody: {...(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.+ linePerMessage: form.telegram.linePerMessage,},};}@@ -148,6 +169,8 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M...(appSecret !== "" ? { appSecret } : {}),...(clearing ? { clearAppSecret: true } : {}),baseDomain,+ // Always sent, for the same reason as Telegram's: an omitted flag means "keep".+ linePerMessage: form.feishu.linePerMessage,},};}@@ -181,13 +204,18 @@ export function formToTest(form: MessagingFormState): MessagingTestRequestByChan*/export function formDirty(form: MessagingFormState, baseline: MessagingFormState): boolean {if (form.channel === "telegram") {- return form.telegram.botToken.trim() !== "" || form.telegram.clearToken;+ return (+ form.telegram.botToken.trim() !== "" ||+ form.telegram.clearToken ||+ form.telegram.linePerMessage !== baseline.telegram.linePerMessage+ );}return (form.feishu.appId !== baseline.feishu.appId ||form.feishu.baseDomain !== baseline.feishu.baseDomain ||form.feishu.appSecret.trim() !== "" ||- form.feishu.clearSecret+ form.feishu.clearSecret ||+ form.feishu.linePerMessage !== baseline.feishu.linePerMessage);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex b89ecc9d..ffb44e05 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1857,6 +1857,11 @@ Scenarios:credentialMissingHint: "Enter and save the credential first, then enable the connection",/** Why the clear checkbox is gated while the channel's connection is enabled. */disableBeforeClearHint: "Disable the connection before clearing the credential",+ /** The saved delivery option: one message per non-blank line of a reply. */+ linePerMessage: "One message per line",+ /** 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.",/** 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 8611e8f0..13442395 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1817,6 +1817,11 @@ Benchmark:credentialMissingHint: "先填写并保存凭证,再启用连接",/** Why the clear checkbox is gated while the channel's connection is enabled. */disableBeforeClearHint: "先停用连接,才能清除凭证",+ /** The saved delivery option: one message per non-blank line of a reply. */+ linePerMessage: "每行一条消息",+ /** Its disclosure, beside the label: what the option does to a reply, and its two edges. */+ linePerMessageHelp:+ "开启后,回复中的每个非空行各自作为一条消息发出,空行忽略——写成多句台词的回复就按台词逐条到达。行数超过每条回复的上限时,余下的行合并为最后一条,内容不会丢失;过长的单行仍按渠道长度上限分段。多条消息之间相隔约一秒发出,这是聊天平台允许的速率。",/** 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 08ab83bf..ffc8b157 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -139,6 +139,21 @@ describe("MessagingBindingBody", () => {expect(html).toContain(`title="${lastError}"`);});+ it('closes the form with the delivery option, its explanation behind the label\'s "?"', () => {+ for (const channel of ["feishu", "telegram"] as MessagingChannel[]) {+ const html = render(stateOf(channel));+ // Both channels carry it: it is a delivery preference, not a credential.+ expect(html).toContain(S.messaging.linePerMessage);+ // Semantics disclose — the sentence is in the popover panel, which renders collapsed.+ expect(html).toContain(S.common.moreInfoAbout(S.messaging.linePerMessage));+ expect(html).not.toContain(S.messaging.linePerMessageHelp);+ // After the credential fields, not among them.+ const fieldAt = html.indexOf(channel === "telegram" ? S.telegram.botToken : S.feishu.appId);+ expect(fieldAt).toBeGreaterThanOrEqual(0);+ expect(html.indexOf(S.messaging.linePerMessage)).toBeGreaterThan(fieldAt);+ }+ });+it("shows the switch's gating reason when the other channel holds the connection", () => {const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);const html = render(diff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.tsindex 0cd4fecc..ca079079 100644--- a/packages/web/test/messaging-binding-form.test.ts+++ b/packages/web/test/messaging-binding-form.test.ts@@ -4,7 +4,9 @@* 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), and the blank-domain-means-default fallback.+ * 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).*/import { describe, expect, it } from "vitest";import type { FeishuBindingInfo, TelegramBindingInfo } from "@prismshadow/penguin-server/api";@@ -25,6 +27,7 @@ const STORED_FEISHU: FeishuBindingInfo = {appSecretMasked: "abcd…wxyz",baseDomain: "https://open.larksuite.com",enabled: false,+ linePerMessage: false,lastChatKnown: true,createdAt: "2026-08-25T00:00:00.000Z",updatedAt: "2026-08-25T00:00:00.000Z",@@ -36,6 +39,8 @@ const STORED_TELEGRAM: TelegramBindingInfo = {botId: "7000000001",botTokenMasked: "7000…1111",enabled: true,+ // Set on one fixture only, so a per-channel load cannot pass by copying the other channel.+ linePerMessage: true,lastChatKnown: false,createdAt: "2026-08-26T00:00:00.000Z",updatedAt: "2026-08-26T00:00:00.000Z",@@ -45,8 +50,14 @@ describe("emptyMessagingForm / bindingsToForm", () => {it("starts empty forms on Feishu with the default domain, both channels blank", () => {expect(emptyMessagingForm()).toEqual({channel: "feishu",- feishu: { appId: "", appSecret: "", baseDomain: FEISHU_DEFAULT_DOMAIN, clearSecret: false },- telegram: { botToken: "", clearToken: false },+ feishu: {+ appId: "",+ appSecret: "",+ baseDomain: FEISHU_DEFAULT_DOMAIN,+ clearSecret: false,+ linePerMessage: false,+ },+ telegram: { botToken: "", clearToken: false, linePerMessage: false },});});@@ -61,8 +72,10 @@ describe("emptyMessagingForm / bindingsToForm", () => {appSecret: "",baseDomain: "https://open.larksuite.com",clearSecret: false,+ linePerMessage: false,},- telegram: { botToken: "", clearToken: false },+ // Each channel's delivery preference comes from its own stored config.+ telegram: { botToken: "", clearToken: false, linePerMessage: true },});// No enabled channel: the first saved one is selected; nothing saved: Feishu.expect(bindingsToForm([STORED_FEISHU]).channel).toBe("feishu");@@ -76,7 +89,7 @@ describe("formToPut (feishu)", () => {expect(res).toEqual({ok: true,channel: "feishu",- body: { appId: "cli_abc", baseDomain: "https://open.larksuite.com" },+ body: { appId: "cli_abc", baseDomain: "https://open.larksuite.com", linePerMessage: false },});});@@ -102,7 +115,12 @@ describe("formToPut (feishu)", () => {expect(formToPut(clearing, true)).toEqual({ok: true,channel: "feishu",- body: { appId: "cli_abc", clearAppSecret: true, baseDomain: "https://open.larksuite.com" },+ body: {+ appId: "cli_abc",+ clearAppSecret: true,+ baseDomain: "https://open.larksuite.com",+ linePerMessage: false,+ },});// The models idiom: a typed replacement wins over a stale checked box.clearing.feishu.appSecret = "replacement-secret";@@ -111,6 +129,7 @@ describe("formToPut (feishu)", () => {appId: "cli_abc",appSecret: "replacement-secret",baseDomain: "https://open.larksuite.com",+ linePerMessage: false,});// Without a stored secret there is nothing to clear: the flag never reaches the body.const nothingStored = emptyMessagingForm();@@ -124,7 +143,13 @@ describe("formToPut (feishu)", () => {it("defaults a blank domain and rejects a non-http(s) one", () => {const form = emptyMessagingForm();- form.feishu = { appId: "cli_x", appSecret: "s", baseDomain: " ", clearSecret: false };+ form.feishu = {+ appId: "cli_x",+ appSecret: "s",+ baseDomain: " ",+ clearSecret: false,+ linePerMessage: false,+ };const blankDomain = formToPut(form, false);expect(blankDomain.ok && blankDomain.channel === "feishu" && blankDomain.body.baseDomain).toBe(FEISHU_DEFAULT_DOMAIN,@@ -143,11 +168,16 @@ describe("formToPut (telegram)", () => {expect(formToPut(form, false)).toEqual({ok: true,channel: "telegram",- body: { botToken: "7000000001:secret-token-AAAA" },+ body: { botToken: "7000000001:secret-token-AAAA", linePerMessage: false },});- // With a stored token an empty field means "keep it": the body omits the token.+ // 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.form.telegram.botToken = "";- expect(formToPut(form, true)).toEqual({ ok: true, channel: "telegram", body: {} });+ expect(formToPut(form, true)).toEqual({+ ok: true,+ channel: "telegram",+ body: { linePerMessage: false },+ });// A first bind must carry one.expect(formToPut(form, false)).toEqual({ ok: false, errors: { botToken: "required" } });});@@ -158,12 +188,13 @@ describe("formToPut (telegram)", () => {expect(formToPut(form, true)).toEqual({ok: true,channel: "telegram",- body: { clearBotToken: true },+ body: { clearBotToken: true, linePerMessage: 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,});});@@ -186,6 +217,7 @@ describe("formToPut (telegram)", () => {appSecret: "s",baseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,+ linePerMessage: false,};feishuSide.telegram.botToken = "garbage";expect(formToPut(feishuSide, false).ok).toBe(true);@@ -208,6 +240,7 @@ describe("formToTest", () => {appSecret: "s",baseDomain: FEISHU_DEFAULT_DOMAIN,clearSecret: false,+ linePerMessage: false,};expect(formToTest(feishu)).toEqual({channel: "feishu",@@ -247,6 +280,23 @@ 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.+ const tgBaseline = bindingsToForm([STORED_TELEGRAM]);+ const tg = bindingsToForm([STORED_TELEGRAM]);+ tg.telegram.linePerMessage = !tg.telegram.linePerMessage;+ expect(formDirty(tg, 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 otherChannel = bindingsToForm([STORED_FEISHU]);+ otherChannel.telegram.linePerMessage = true;+ expect(formDirty(otherChannel, baseline)).toBe(false);+ });+it("allows the probe when the selected channel has a testable draft or a stored secret", () => {// Feishu drafts need both halves of the credential pair.expect(formTestable(emptyMessagingForm(), false)).toBe(false);