Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Relay a reply's Markdown as formatting, per messaging binding (#519)

Yaowei Zheng3d366653e7d2
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.md b/changelog/unreleased/2026-08-27-backward-compatibility.md
index 3c5be5c6..594046d3 100644
--- a/changelog/unreleased/2026-08-27-backward-compatibility.md
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.md
@@ -3,22 +3,24 @@
- **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), [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)
+- **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), [#519](https://github.com/Prism-Shadow/penguin-harness/pull/519)
- **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 four things that outlive a release.
+This batch touched five 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`;
[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; 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.
+[relaying a run's final reply only](2026-08-27-messaging-final-reply-only.md) and
+[relaying a reply's Markdown as formatting](2026-08-27-messaging-markdown.md) each added a column,
+`messaging_bindings.final_reply_only` and `messaging_bindings.render_markdown`. Only the browser
+side, the `last_chat_id` change and the second of those columns needed a decision; the file, the
+key and the purely additive 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
@@ -104,10 +106,35 @@ A downgrade is invisible in both directions. What the column does is done by the
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.
+## The added `render_markdown` column, whose default is not the old behaviour
+
+[Relaying a reply's Markdown as formatting](2026-08-27-messaging-markdown.md) added
+`messaging_bindings.render_markdown INTEGER NOT NULL DEFAULT 1`, ALTERed in on open by the same
+`ensureColumn` list. The mechanics are the ones `line_per_message` and `final_reply_only` already
+took; the DEFAULT is not.
+
+This is the one added flag whose default is the CORRECTED behaviour rather than the previous one,
+and that was the decision. Relaying the model's Markdown as characters — `**bold**`, `## heading`,
+raw code fences — was the defect being fixed, so a default of 0 would have shipped the fix to
+nobody and left every existing binding on the broken side of a switch they would have to go and
+find. **Every existing binding therefore starts rendering Markdown on the first open of an updated
+build.** Nothing is asked of the user and no row is rewritten, but it is a visible change to every
+relayed message, and a user who wants the old bytes turns the switch off in the binding editor —
+off reproduces the previous plain-text relay exactly, on every channel.
+
+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 and the
+connectors, so an older server ignores a column it has never heard of and relays plain text again
+— the setting is still on disk, and an upgrade back honours it without the user re-saving anything.
+
## Compatibility
No action is required on upgrade or on downgrade. The single manual step, for a user who wiped
-a data root before this release, is above.
+a data root before this release, is above. The one thing to expect rather than do: every messaging
+binding starts rendering Markdown, which changes how its relayed messages look until the switch is
+turned off.
Upgrading asks nothing of the user. The first message after the upgrade rewrites the column as
usual, and until then the stored bare id keeps working exactly as it did.
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
index 21b15eee..7ff0f26e 100644
--- a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
@@ -3,19 +3,20 @@
- **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), [#512](https://github.com/Prism-Shadow/penguin-harness/pull/512)
+- **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), [#519](https://github.com/Prism-Shadow/penguin-harness/pull/519)
- **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` 的含义——不增删任何列,也不重写任何行;
-[只转发一次运行的最终回复](2026-08-27-messaging-final-reply-only.zh.md)新增了一列
-`messaging_bindings.final_reply_only`。需要做决定的只有浏览器一侧与 `last_chat_id` 的含义变化;那个
-文件、那个键和这个新列也一并记在这里,方便有人来查「我这套安装需要做什么吗?」时,在同一处找到全部
-答案。
+[只转发一次运行的最终回复](2026-08-27-messaging-final-reply-only.zh.md)与
+[把回复的 Markdown 按排版转发](2026-08-27-messaging-markdown.zh.md)各新增了一列,分别是
+`messaging_bindings.final_reply_only` 与 `messaging_bindings.render_markdown`。需要做决定的只有浏览器
+一侧、`last_chat_id` 的含义变化,以及后一个新列;那个文件、那个键和纯属新增的那一列也一并记在这里,
+方便有人来查「我这套安装需要做什么吗?」时,在同一处找到全部答案。
## 有键、但从未记录过 id 的浏览器
@@ -84,9 +85,30 @@
降级在两个方向上都看不出来。这一列的效果由 bridge 实现,因此旧构建会忽略一个它从未听说过的列,重新
逐条转发;设置本身仍留在磁盘上,再升级回来时无需用户重新保存即可继续生效。
+## 新增的 `render_markdown` 列——它的默认值不是旧行为
+
+[把回复的 Markdown 按排版转发](2026-08-27-messaging-markdown.zh.md)新增了
+`messaging_bindings.render_markdown INTEGER NOT NULL DEFAULT 1`,同样由那份 `ensureColumn` 列表在打
+开时 ALTER 进来。机制与 `line_per_message`、`final_reply_only` 完全一样;默认值不一样。
+
+这是唯一一个默认值取「修正后行为」而非「原行为」的新增标志位,这正是需要拍板的地方。把模型写的
+Markdown 当作字符转发——`**bold**`、`## heading`、裸代码围栏——正是本次要修的缺陷,因此默认值取 0
+等于把修复交付给零个人,并且把每一份存量绑定都留在一个他们还得自己去找的开关的错误一侧。**因此,
+所有存量绑定在升级后第一次打开时即开始渲染 Markdown。** 用户无需做任何事,也没有任何行被改写,但这
+是每条转发消息都可见的变化;想要旧字节的用户,在绑定编辑器里把开关关掉即可——关闭状态在每个渠道上
+都精确复现原先的纯文本转发。
+
+只要当前构建仍需打开本次发布之前形成的 `web.db`,该 `ensureColumn` 条目就保留,与该列表中其余条目
+同一口径。
+
+降级在两个方向上都不可见。该列的作用由消息桥与各连接器实现,因此旧服务端会忽略一个它从未听说过的列,
+重新以纯文本转发——设置仍在磁盘上,再升级回来时无需用户重新保存即可生效。
+
## 兼容性
升级与降级都不需要做任何操作。对在本版本之前清空过数据根的用户而言,唯一需要手动执行的一步在上文。
+唯一需要预期而非动手的一点:所有消息绑定都会开始渲染 Markdown,在关掉该开关之前,其转发消息的样子
+都会改变。
升级对用户没有任何要求。升级后的第一条消息会照常重写该列,在那之前存着的裸 id 与从前一样可用。
diff --git a/changelog/unreleased/2026-08-27-messaging-markdown.md b/changelog/unreleased/2026-08-27-messaging-markdown.md
new file mode 100644
index 00000000..69cce6b4
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-markdown.md
@@ -0,0 +1,84 @@
+# A relayed reply arrives as formatting, not as Markdown source
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#519](https://github.com/Prism-Shadow/penguin-harness/pull/519)
+- **Breaking:** yes — existing bindings start rendering Markdown after the upgrade, which changes how every relayed message looks; the new per-binding switch turns it off
+
+[中文版](2026-08-27-messaging-markdown.zh.md)
+
+The messaging bridge relayed the assistant's reply as plain text on every channel — Telegram
+`sendMessage` with no `parse_mode`, Feishu `msg_type: "text"`, QQ `msg_type: 0` — so the model's
+Markdown reached the chat as literal `**bold**`, `## heading` and raw code fences. A per-binding
+preference, `renderMarkdown`, now renders it in each channel's own markup. It defaults ON: the
+previous behaviour is the thing being corrected, so the corrected one is the default.
+
+## Details
+
+- The option is stored as `messaging_bindings.render_markdown`, a column beside `enabled` and the
+ other two delivery preferences rather than a key inside `config_json`. `renderMarkdown` joined
+ `FeishuBindingInfo` / `TelegramBindingInfo` / `QQBindingInfo` and all three PUT bodies; an
+ omitted value keeps the stored one, and a binding created without an opinion starts with it on.
+- Reading the reply as Markdown and deciding where a long one may be cut are shared
+ (`runtime/messaging/markdown.ts`, beside `media.ts`): which constructs a reply contains is a
+ fact about the text, and a cut through a construct costs it on every channel. The parser is
+ `remark-parse` + `remark-gfm` over `unified`, the stack `packages/web` already renders Markdown
+ with, so a reply reads the same in the transcript and in the chat.
+- The render is per channel, because the three platforms accept three different subsets over two
+ markups and three escaping rules:
+ - **Telegram** (`telegram-html.ts`) sends `parse_mode: "HTML"`. Bold, italic, strikethrough,
+ links, inline code, fenced code with a language and blockquotes render. There is no heading,
+ list or table tag, so a heading becomes a bold line, list markers become literal text
+ (`• `, `1. `, two spaces of indent per level, `☐`/`☑` for task items) and a table becomes a
+ `<pre>` block of its rows.
+ - **Feishu** (`feishu-card.ts`) sends `msg_type: "interactive"` carrying the JSON 2.0 card's
+ `{"tag": "markdown"}` component, which renders headings 1–6, bold, italic, strikethrough,
+ inline and fenced code, nested lists, blockquotes, rules, links and tables. The component
+ shows at most five data rows per table and four tables, so an over-limit table is emitted as
+ a fenced code block instead of losing rows silently.
+ - **QQ** (`qq-markdown.ts`) sends `msg_type: 2` free-form markdown, which is open to every bot
+ in single and group chats. Headings, bold, italic, strikethrough, lists, blockquotes, rules
+ and links render; inline code, fenced code and tables have no syntax at all, so a code block
+ arrives as plain escaped lines and a table as its rows.
+- Text that merely looks like markup arrives as text on every channel: `5 < 6` and `a & b` are
+ entity-escaped for Telegram and Feishu and backslash-escaped for QQ, a `<script>` in a code
+ block stays a `<script>` in a code block, and raw HTML the model typed is shown rather than
+ forwarded. A link whose scheme a chat cannot open keeps its label and loses only its
+ clickability.
+- **A formatted send the channel refuses falls back to a plain-text send of the same message.**
+ Telegram answers 400 for HTML it will not parse, Feishu and QQ answer with their own refusal
+ codes; each connector retries once with the model's own Markdown source, so the setting can
+ cost formatting and never a reply. Only a refusal is retried — a timeout or a reset may already
+ have delivered, and re-sending it would post the reply twice. On QQ the retry additionally
+ spends one more of the four passive replies an inbound message funds, since a repeated
+ `(msg_id, msg_seq)` pair is refused rather than deduplicated; a refusal that was not about the
+ message body is not retried at all.
+- Chunking became format-aware. A reply over `MESSAGING_TEXT_CHUNK_CHARS` is cut between top-level
+ blocks, then inside the one block that is itself too long — between a paragraph's inline runs,
+ along a blockquote's or a list's own lines — and a fenced code block that spans messages is
+ re-opened and re-closed with its language in every piece. `linePerMessage` composes by staying
+ literal: each line is converted on its own, so a line that is not a whole construct arrives as
+ the text it is.
+- `FeishuApiError` and `QQApiError` were added beside the existing `TelegramApiError`, so all
+ three adapters distinguish a refusal the platform answered from a request that never completed
+ — the distinction the fallback turns on.
+- Every step of the bridge's send chain now checks that its entry still holds the Session's
+ connection, the way `observe` already did. A run's last messages and the files behind them are
+ queued on that chain, and a hard stop drops the entry and closes the database while they are
+ still waiting their turn.
+- In the binding editor the option is a third `DeliveryOptionRow` below the other two, with its
+ own explanation per channel behind the label's "?" — what a channel can show is the whole of
+ what the reader needs in order to decide.
+
+## Compatibility
+
+See [backward compatibility](2026-08-27-backward-compatibility.md) for the added column and what
+an upgrade and a downgrade do to it.
+
+Every existing binding starts rendering Markdown on the first open of an updated build. Nothing is
+asked of the user and nothing is rewritten, but it is a visible change to every relayed message:
+a reply that used to arrive as `**bold**` now arrives bold, a heading arrives as a bold line or a
+heading depending on the channel, and a code block arrives monospaced on Telegram and Feishu and
+as plain lines on QQ. Turning the switch off in the binding editor restores the previous
+plain-text relay exactly.
diff --git a/changelog/unreleased/2026-08-27-messaging-markdown.zh.md b/changelog/unreleased/2026-08-27-messaging-markdown.zh.md
new file mode 100644
index 00000000..890de778
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-messaging-markdown.zh.md
@@ -0,0 +1,63 @@
+# 转发的回复以排版到达,而不是 Markdown 源码
+
+- **Date:** 2026-08-27
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#519](https://github.com/Prism-Shadow/penguin-harness/pull/519)
+- **Breaking:** yes — 升级后存量绑定即开始渲染 Markdown,每条转发消息的样子都会改变;新增的按绑定开关可将其关闭
+
+[English](2026-08-27-messaging-markdown.md)
+
+消息桥此前在所有渠道上都以纯文本转发助手回复——Telegram 的 `sendMessage` 不带 `parse_mode`,飞书用
+`msg_type: "text"`,QQ 用 `msg_type: 0`——因此模型写的 Markdown 到达聊天时就是字面的 `**bold**`、
+`## heading` 和裸代码围栏。新增的按绑定偏好 `renderMarkdown` 会将其按各渠道自身的标记语言渲染。它
+**默认开启**:被修正的正是原先的行为,所以修正后的行为才是默认值。
+
+## 细节
+
+- 该选项存为 `messaging_bindings.render_markdown`,与 `enabled` 及另外两个送达偏好并列成列,而不是
+ 放进 `config_json`。`renderMarkdown` 同时加入 `FeishuBindingInfo` / `TelegramBindingInfo` /
+ `QQBindingInfo` 与三个 PUT 请求体;省略该字段保持已存值,未表态创建的绑定即为开启。
+- 「把回复读成 Markdown」与「决定长回复可以从哪里切开」是共享的(`runtime/messaging/markdown.ts`,
+ 与 `media.ts` 并列):一条回复包含哪些构件是文本本身的事实,而切穿构件在每个渠道上都会损失它。
+ 解析器是 `unified` 之上的 `remark-parse` + `remark-gfm`,即 `packages/web` 本就用来渲染 Markdown
+ 的那套,因此同一条回复在网页记录与聊天里读法一致。
+- 渲染则按渠道各自实现,因为三个平台在两种标记语言、三套转义规则之上接受三个不同的子集:
+ - **Telegram**(`telegram-html.ts`)使用 `parse_mode: "HTML"`。粗体、斜体、删除线、链接、行内
+ 代码、带语言的代码块与引用均可渲染。它没有标题、列表和表格标签,因此标题渲染为一行粗体,列表
+ 符号作为文本保留(`• `、`1. `,每层缩进两个空格,任务项用 `☐`/`☑`),表格改用 `<pre>` 块承载
+ 其各行。
+ - **飞书**(`feishu-card.ts`)使用 `msg_type: "interactive"`,承载 JSON 2.0 卡片的
+ `{"tag": "markdown"}` 组件,可渲染 1–6 级标题、粗体、斜体、删除线、行内代码与代码块、嵌套
+ 列表、引用、分割线、链接和表格。该组件每张表最多显示 5 行数据、每条消息最多 4 张表,因此超限的
+ 表格改以代码块发出,而不是静默丢行。
+ - **QQ**(`qq-markdown.ts`)使用 `msg_type: 2` 自定义 markdown,单聊与群聊场景已对全部机器人开放。
+ 标题、粗体、斜体、删除线、列表、引用、分割线和链接均可渲染;行内代码、代码块和表格则完全没有
+ 对应语法,因此代码块按转义后的普通文本行到达,表格按其行到达。
+- 只是「看起来像标记」的文本在每个渠道上都作为文本到达:`5 < 6` 与 `a & b` 在 Telegram 和飞书上转为
+ 实体、在 QQ 上加反斜杠转义,代码块里的 `<script>` 仍然是代码块里的 `<script>`,模型自己写下的裸
+ HTML 只展示、不转发。链接的协议若非聊天可打开的,则保留其文字、仅失去可点击性。
+- **渠道拒绝的格式化发送会退回为同一条消息的纯文本发送。** Telegram 对它无法解析的 HTML 返回 400,
+ 飞书与 QQ 各自返回自己的拒绝码;每个连接器都会用模型自己的 Markdown 源码重试一次,因此该设置只
+ 可能损失排版,绝不会损失回复。只有「被拒绝」才重试——超时或连接中断有可能其实已经送达,重发会让
+ 回复在聊天里出现两次。在 QQ 上,该重试还会额外占用一条入站消息所提供的四条被动回复之一,因为重复
+ 的 `(msg_id, msg_seq)` 组合会被拒绝而非去重;与消息体无关的拒绝则根本不重试。
+- 分段改为随格式变化。超过 `MESSAGING_TEXT_CHUNK_CHARS` 的回复先在顶层块之间切分,再在那个自身过长
+ 的块内部切分——在段落的行内片段之间、沿引用或列表自身的行——而跨消息的代码块会在每一片里重新加上
+ 带语言的开合围栏。`linePerMessage` 通过保持「逐字面」与之共存:每一行各自转换,因此不构成完整
+ 构件的一行就按它本身的文本到达。
+- 在既有的 `TelegramApiError` 之外新增了 `FeishuApiError` 与 `QQApiError`,使三个适配器都能区分
+ 「平台答复的拒绝」与「从未完成的请求」——这正是退回机制所依赖的区分。
+- 消息桥发送链的每一步现在都会先确认自己的条目仍持有该 Session 的连接,与 `observe` 一贯的做法一致。
+ 一次运行的最后几条消息及其随附文件都排在这条链上,而硬停止会在它们还在排队时丢弃条目并关闭数据库。
+- 在绑定编辑器中,该选项是另外两项之下的第三个 `DeliveryOptionRow`,其说明按渠道分别置于标签旁的
+ 「?」之后——某个渠道能显示什么,正是读者做决定所需要知道的全部。
+
+## 兼容性
+
+新增列在升级与降级时的表现见[向后兼容](2026-08-27-backward-compatibility.zh.md)。
+
+升级后第一次打开时,所有存量绑定即开始渲染 Markdown。用户无需做任何事,也没有任何数据被改写,但这是
+每条转发消息都可见的变化:原先以 `**bold**` 到达的回复现在会真的加粗,标题按渠道渲染为一行粗体或真正
+的标题,代码块在 Telegram 与飞书上以等宽呈现、在 QQ 上作为普通文本行到达。在绑定编辑器中关闭该开关,
+即可完全恢复原先的纯文本转发。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 4bd25e08..39e5d236 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -314,21 +314,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` + `finalReplyOnly` + 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` + `renderMarkdown` + 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?, 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 |
+| PUT | /messaging/feishu | Save credentials: `{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`. 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?, 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 |
+| PUT | /messaging/telegram | Save the credential: `{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` — 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?, 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 |
+| PUT | /messaging/qq | Save the credential pair: `{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}` — 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 |
@@ -337,9 +337,8 @@ 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` 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, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
-
-**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.
+Masked secrets are omitted from responses when none is stored (a cleared config), and a config without a secret cannot be enabled. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are the three saved fields that are not credentials. With `linePerMessage` set, every non-blank line of a relayed assistant reply is sent as its own message (blank lines dropped, each line still chunked under the size cap, and the remainder combined into one last message past a per-reply message cap). With `finalReplyOnly` set, a run relays only its LAST completed assistant message, delivered when the run ends, instead of mirroring each one as it completes — the working notes a run writes between tool calls stay in the web app, and the files that follow the reply are then read from that final message alone, since it is the only text the chat received. The two compose: with both set, the final reply is the one split per line. Both default to false, an omitted value on a PUT keeps the stored one, and neither applies to the notices or the test message — the approval reminder in particular is not a reply and arrives immediately whatever `finalReplyOnly` says. `renderMarkdown` renders a relayed reply's Markdown in the channel's own markup instead of sending its characters as written; it **defaults to true**, an omitted value on a PUT keeps the stored one, and it likewise never applies to the notices or the test message. Each channel shows what it can and degrades the rest deliberately rather than leaking the source: Telegram sends `parse_mode: "HTML"` and has no headings, lists or tables (a heading becomes a bold line, list markers become literal text, a table becomes a `<pre>` block); Feishu sends an interactive card carrying the JSON 2.0 rich-text component and renders everything, over-long tables becoming code blocks so no row is silently dropped; QQ sends `msg_type: 2` free-form markdown and has no code formatting and no tables (a fenced block becomes plain escaped lines, a table becomes its rows). Chunking follows the setting, cutting at block boundaries and re-fencing a code block that spans messages, so no message opens a construct it does not close. **A formatted send the channel refuses falls back to a plain-text send of the same message**, so the setting can cost formatting and never a reply. The one cross-Session rule is per bot account per channel and applies to the connection only: one account has one event stream, so at most one Session may have it enabled. Feishu's account identity is the `app_id`, Telegram's is the numeric bot id in front of the token's colon (robust against token rotation). Reads and the two tests are open to any Project member; PUT, the state toggle and DELETE are owner-only (vault semantics — the binding writes carry or act on the secret). Secrets never round-trip. Deleting the Session removes all its configs. Inbound processing accepts text, images and files: an image becomes an ordinary `image_url` input part, capped at the server's inline-image ceiling per image and by a rolling per-binding byte budget in aggregate — an inline image is written verbatim into the Trace, and this path, unlike the composer, has no authentication in front of it. A file becomes the composer's other attachment shape — written into the Session scratchpad and handed to the model as an `[attached file: <path>]` line, so its bytes never enter the conversation — under the same admin-settable per-file and per-message attachment caps an authenticated upload answers to, narrowed further by any tighter ceiling the channel itself has (Telegram serves a bot no file over 20MB). Feishu takes the `file` message type and Telegram the `document` field: a file the sender chose to send AS a file, which is also the only one of Telegram's media fields carrying the sender's own name. Video, audio and voice are deliberately not delivered — nothing downstream decodes or transcribes them, and what a sender wants the Agent to have arrives as a file the moment they attach it as one. The caption of a message whose attachment IS delivered (a photo, a document) is that message's text; a caption on any other media kind is not, since its bytes never arrive and running the model on the caption alone answers about a file it never received. An image over the ceiling, one past the budget and one the channel refuses answer with three different bilingual notices, as do a file over a cap, a batch over the per-message total and a file the channel refuses; none of them runs half a message, and a refusal the bot's own permissions caused names the scopes to grant and carries the channel's console link, which for Feishu is the usual case (receiving messages and downloading their attachments are separate scopes). Every other type still gets the bilingual "not supported" reply. Outbound, a finished run's reply is followed by the files it MENTIONED AND PRODUCED — path-like tokens that resolve inside the Workspace, exist, and were written at or after the run started, wherever in the reply they appear (the mention picks which output was the point; the mtime is what keeps a steerable reply from becoming a read primitive, since a reply that declines to paste a file still names it) — images as images and everything else as attachments, classified by the file the read actually reached rather than by the name the reply spelled, at most 5 per run and at most 10MB per image / 30MB per file (the tighter of each channel's own limits). Every way a mentioned file does not arrive is said in the chat — over a cap, past the count cap, no such file in the Workspace, or an upload the channel refused — except a file the run did not write, which is dropped silently because a reply naming the config it read is the ordinary case. Telegram connects by draining the backlog first: messages sent while no connection existed are skipped, matching Feishu, where missed events are simply gone. A binding's runtime status additionally reports what the live connection has SEEN — `lastInboundAt` (when a message last arrived; absent while none has since this connection opened), `lastDeliveryError` (`{at, stage, detail}`, where `stage` is `inbound` when the message arrived and its Task never started, or `send` when a reply never reached the chat, and which no later success clears) and `lastConnectionError` (`{at, detail}` for the last connection failure, kept after the connection recovers — unlike `lastError`, which belongs to the `error` state and is gone the moment the state leaves it). All three are in-process and reset on every (re)connect — a re-enable or a credential save opens a new one — so an absent `lastInboundAt` means "nothing since this connection opened", never "nothing ever". They exist because a channel that withholds messages produces `connected` with no error at all.
+**QQ is a reply-only channel, and it changes what delivery means.** The platform accepts no push this product may use: every outbound message is a *passive reply* carrying the `msg_id` of an inbound one, valid for a few minutes and capped at 4 replies per message in a single chat (5 in a group). Three consequences are visible through this API. A run that completes more assistant messages than the budget allows has them **coalesced** — the first `budget - 1` go out as they complete and the rest arrive combined in one final message, so nothing is dropped. `linePerMessage` is **clamped to that budget** rather than to the channel-neutral cap of 20, and a `renderMarkdown` send the platform refuses spends a second slot on its plain-text retry. `finalReplyOnly` cuts both ways here: it spends the least budget a run can spend — one reply — but the passive-reply window is only a few minutes wide, and holding the reply until the run ends spends that window on the run, so a run that outlives it delivers nothing at all where an every-message relay would have sent whatever completed inside it. And a send with nothing to reply to — a turn started in the web app, or any reply after the window closed — is **refused rather than pushed**, surfacing as 502 `qq_send_failed` on the test endpoint and as one `messaging_send_failed` error record for a relayed reply. QQ's account identity is the App ID. Outbound files are refused on this channel: the platform's rich-media path requires a publicly reachable URL for the bytes.
**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.md
index 7dd85401..4eb250c7 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -313,21 +313,21 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + `finalReplyOnly` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |
+| GET | /messaging | 渠道无关读取:该 Session **每一份**已保存的渠道配置(`channel` 判别字段、密钥掩码、逐行 `enabled` 意图 + `linePerMessage` + `finalReplyOnly` + `renderMarkdown` + 连接运行状态 + `lastChatKnown`)。渠道感知的绑定编辑器只加载这一个 |
| GET | /messaging/feishu | `{binding, status}` 形态下的飞书配置(未保存时为 null) |
-| 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`,否则那次重启就会绕过启用闸门、把第二条在线连接接到同一账号上 |
+| PUT | /messaging/feishu | 保存凭据:`{appId, appSecret?, baseDomain?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`。`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?, finalReplyOnly?}`——整份凭据就是 @BotFather 签发的一条 `<机器人 id>:<密钥>` Token(省略或留空则保持已存值;读不出数字 id 时返回 400 `telegram_token_invalid`;清除标记与飞书同口径,清除后配置保留其机器人身份)。保存与启用的分离一致;把已启用绑定的 Token 换成另一个 Session 已启用的机器人时,同样返回 409 `account_enabled_elsewhere`,其余情况不存在跨 Session 的保存冲突 |
+| PUT | /messaging/telegram | 保存凭据:`{botToken?, clearBotToken?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`——整份凭据就是 @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?, finalReplyOnly?}`——QQ 开放平台「开发设置」页的 App ID 与 App Secret。留空保持、清除标记、保存与启用分离都与飞书 PUT 同口径;把一条已启用绑定的 App ID 换成另一个 Session 已启用的账号时,同样返回 409 `account_enabled_elsewhere`,此外保存不会跨 Session 冲突;没有域名字段,因为 API v2 只有一个接口域名 |
+| PUT | /messaging/qq | 保存凭据对:`{appId, appSecret?, clearAppSecret?, linePerMessage?, finalReplyOnly?, renderMarkdown?}`——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?}`。不报出账号名:平台没有能识别机器人身份的接口 |
@@ -336,9 +336,8 @@ Session 可以接入消息软件机器人——目前的渠道是飞书、Telegr
| POST | /messaging/qq/scan/cancel | `{taskId}`——用户中途离开时丢弃该任务,立即忘记其密钥,而不是等待过期清扫 |
| POST | /messaging/qq/test-message | 向最近一次收到消息的会话发送一条固定测试文本;在 QQ 里给机器人发过消息之前返回 409 `qq_no_chat`;没有可回复的近期消息时返回 502 `qq_send_failed`(见下) |
-没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage` 与 `finalReplyOnly` 是仅有的两个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
-
-**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。
+没有已存密钥的配置(被清除过的)不返回掩码字段,也无法启用。`linePerMessage`、`finalReplyOnly` 与 `renderMarkdown` 是仅有的三个不属于凭据的已存字段。开启 `linePerMessage` 后,转发的助手回复中每个非空行各自作为一条消息发出(空行忽略,单行仍按长度上限分段,超出每条回复的消息条数上限的部分合并为最后一条)。开启 `finalReplyOnly` 后,一次运行只转发它**最后**完成的那条助手消息,并在运行结束时发送,而不是每完成一条就转发一条——运行过程中在工具调用之间写下的记录留在网页端;随回复发送的文件也只从这条最终消息中读取提及,因为聊天只收到了它。两者可叠加:同时开启时,被按行拆分的就是这条最终回复。两者默认均为 false,PUT 省略则保持已存值,且都不作用于通知与测试消息——审批提醒尤其不属于回复,无论 `finalReplyOnly` 如何都会立即到达。开启 `renderMarkdown` 后,转发回复中的 Markdown 按各渠道自身的标记语言渲染,而不是把字符原样发出;它**默认为 true**,PUT 省略同样保持已存值,同样不作用于通知与测试消息。各渠道各自渲染力所能及的部分,其余按既定方式降级而非泄漏源码:Telegram 使用 `parse_mode: "HTML"`,没有标题、列表和表格(标题渲染为一行粗体,列表符号作为文本保留,表格改用 `<pre>` 块);飞书发送携带 JSON 2.0 富文本组件的交互卡片,全部构件均可渲染,超长表格改为代码块以免整行被静默丢弃;QQ 使用 `msg_type: 2` 自定义 markdown,没有代码格式也没有表格(代码块按转义后的普通文本行发出,表格按其行发出)。分段随该设置改变:在块边界切分,跨消息的代码块会重新加围栏,因此任何一条消息都不会打开一个它没有闭合的构件。**渠道拒绝的格式化发送会退回为同一条消息的纯文本发送**,因此该设置只可能损失排版,绝不会损失回复。唯一的跨 Session 规则按渠道内机器人账号计,且只作用于连接:一个账号只有一条事件流,因此至多一个 Session 能将其启用。飞书的账号身份是 `app_id`,Telegram 是 Token 冒号前的数字机器人 id(换发 Token 也不会改变)。读取与两个测试接口对任意 Project 成员开放;PUT、state 开关与 DELETE 仅限所有者(与 Vault 同口径——绑定写操作携带或作用于密钥)。密钥永不回传。删除 Session 会连带删除其全部渠道配置。入站处理文本、图片与文件:图片按普通 `image_url` 输入部分送入,单张受服务端的内联图片上限约束,总量再受每个绑定一个滚动窗口的字节预算约束——内联图片会原样写入 Trace,而这条路径不像网页输入框,前面没有任何鉴权。文件按输入框的另一种附件形态送入——写进该 Session 的 Scratchpad,并以 `[attached file: <path>]` 行交给模型,其字节不进入对话——上限沿用管理员可设的单个文件与单条消息附件上限(与经过鉴权的上传同一组数值),并再取渠道自身更紧的那个上限(Telegram 不向机器人提供超过 20MB 的文件)。飞书取 `file` 消息类型,Telegram 取 `document` 字段:发送者主动**以文件形式**发出的那一个,也是 Telegram 各媒体字段中唯一携带发送者原始文件名的。视频、音频与语音有意不予送达——下游没有任何环节能解码或转写它们,而发送者真正想交给智能体的东西,只要按文件发送就会到达。附件**确实会被送达**的消息(图片、文件),其说明文字即该消息的文本;其他媒体类型的说明文字则不是——其字节并不会送达,仅凭说明文字运行只会让模型对一个它从未收到的文件侃侃而谈。图片超过单张上限、超出窗口预算与渠道拒绝下载分别回复三种不同的双语提示;文件超过单个上限、一条消息的文件总量超限与渠道拒绝下载同样各有其提示。它们都不会把半条消息交给模型;因机器人自身权限被拒时,提示会点名所需权限并带上渠道给出的授权链接——飞书通常正是此种情况(接收消息与下载其中的附件是两项独立权限)。其余类型仍收到双语的“暂不支持”回复。出站方向,一次运行结束后会在回复文本之后发送该回复**提及且由本次运行产出**的文件——回复中形如路径、能解析到 Workspace 之内、确实存在、且修改时间不早于本次运行开始的片段,出现在回复的任何位置皆可(「提及」挑出这次真正要交付的那个产物;「修改时间」则确保一条可被会话中任何人引导的回复不会变成读取原语——拒绝粘贴某个文件的回复同样会点到它的名字)——图片按图片发送、其余按文件发送,且按**读取时实际拿到的文件名**分类,而非回复中写下的那个名字;每次运行最多 5 个,单个图片上限 10MB、单个文件上限 30MB(取两个渠道各自限制中更紧的一个)。被提及的文件凡是没送到,都会在会话中说明原因——超过上限、超出数量上限、Workspace 内没有该文件、渠道拒绝上传——唯独「本次运行没有写过」是静默跳过的,因为回复中提到自己读过的配置文件属于常态。Telegram 建立连接时先清空积压:无连接期间发来的消息会被跳过,与飞书“错过的事件即消失”同口径。绑定的运行时状态另外报出该连接**实际见到**的情况——`lastInboundAt`(最近一条消息到达的时间;自本次连接建立以来还没有收到过时该字段缺席)、`lastDeliveryError`(`{at, stage, detail}`,`stage` 为 `inbound` 表示消息已到达但其 Task 没能开始,为 `send` 表示回复没能送达聊天;后续的成功不会把它清掉),以及 `lastConnectionError`(`{at, detail}`,最近一次连接失败,并在连接恢复之后依然保留——不同于属于 `error` 状态、状态一离开就被抹掉的 `lastError`)。三者都只存在于进程内,且每次(重新)建立连接都会清空——重新启用连接或再保存一次凭证,都会开启一条新连接——所以 `lastInboundAt` 缺席只意味着「本次连接以来没有收到过」,而不是「从来没有收到过」。它们的存在是因为一个扣着消息不投递的渠道,表现出来正是 `connected` 且毫无报错。
+**QQ 是只能被动回复的渠道,这改变了「送达」的含义。** 平台不提供本产品可用的主动推送:每一条外发消息都是携带入站 `msg_id` 的*被动回复*,有效期只有几分钟,且单聊对同一条消息最多 4 条回复(群聊 5 条)。由此有三点在 API 上可见。一次运行完成的助手消息超过该额度时会被**合并**——前 `budget - 1` 条随完成即时发出,其余合并为最后一条送达,内容不丢。`linePerMessage` 的拆分上限**收敛到该额度**,而不是渠道无关的 20;被平台拒绝的 `renderMarkdown` 发送,其纯文本重试会再占用一次额度。`finalReplyOnly` 在这里有利有弊:它把一次运行的额度消耗压到最低——只发一条;但被动回复的有效期只有几分钟,把回复扣到运行结束才发,等于把这个窗口花在了运行本身上,运行时长超过窗口时将什么都送不出去,而逐条转发至少能把窗口之内完成的部分发出去。而没有可回复对象的发送——在网页端发起的对话,或窗口关闭之后的回复——会被**拒绝而非主动推送**:测试接口上表现为 502 `qq_send_failed`,转发回复则记为一条 `messaging_send_failed` 错误记录。QQ 的账号身份是 App ID。该渠道拒绝外发文件:平台的富媒体接口要求为文件提供公网可达地址。
**扫码连接不会把密钥交给浏览器。** 解密 App Secret 的 AES 密钥在服务端生成、持有、使用并丢弃;客户端只拿到任务句柄、待绘制的 URL 与状态。任务只存在于内存,归属发起它的 Session,按 Session 单独限量(一个调用方的扫码任务挤不掉另一个调用方的),并被「解决它的那一次轮询」认领掉,因此重放与对同一任务的并发轮询得到的都是 404,而不是第二次绑定。所有扫码路由都仅限 Project 所有者——无论调用方实际输入了多少内容,这个流程的终点都是一份存下来的凭据。
diff --git a/packages/server/package.json b/packages/server/package.json
index aff5a61a..2875cdd5 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -73,13 +73,17 @@
"fflate": "^0.8.3",
"hono": "^4.12.34",
"node-pty": "^1.1.0",
+ "remark-gfm": "^4.0.0",
+ "remark-parse": "^11.0.0",
"smol-toml": "^1.3.0",
"tar": "^7.5.21",
"undici": "^7.29.0",
+ "unified": "^11.0.5",
"ws": "^8.18.3",
"yaml": "^2.5.0"
},
"devDependencies": {
+ "@types/mdast": "^4.0.4",
"@types/node": "^24.0.0",
"@types/ws": "^8.18.1",
"tsup": "^8.3.0",
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 131812f1..7e021d2a 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1729,6 +1729,14 @@ export interface FeishuBindingInfo {
* that one final message. The approval notice is not a reply and is unaffected.
*/
finalReplyOnly: boolean;
+ /**
+ * Render a relayed reply's Markdown in this channel's own markup instead of sending its
+ * characters as written. ON by default. Each channel shows what it can — Telegram has no
+ * headings, lists or tables, QQ has no code or tables, Feishu has all of them — and a
+ * rendering the channel refuses falls back to the plain source, so this can cost
+ * formatting and never a message.
+ */
+ renderMarkdown: 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.
@@ -1764,6 +1772,14 @@ export interface TelegramBindingInfo {
* that one final message. The approval notice is not a reply and is unaffected.
*/
finalReplyOnly: boolean;
+ /**
+ * Render a relayed reply's Markdown in this channel's own markup instead of sending its
+ * characters as written. ON by default. Each channel shows what it can — Telegram has no
+ * headings, lists or tables, QQ has no code or tables, Feishu has all of them — and a
+ * rendering the channel refuses falls back to the plain source, so this can cost
+ * formatting and never a message.
+ */
+ renderMarkdown: 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.
@@ -1808,6 +1824,15 @@ export interface QQBindingInfo {
* at all, where the every-message relay would have sent whatever completed inside it.
*/
finalReplyOnly: boolean;
+ /**
+ * Render a relayed reply's Markdown in this channel's own markup instead of sending its
+ * characters as written. ON by default. QQ's own subset is the widest for prose and the
+ * narrowest for code: headings, lists, blockquotes and rules render, while inline code,
+ * fenced code and tables have no syntax at all here — a code block arrives as plain
+ * escaped lines. A rendering the platform refuses falls back to the plain source, at the
+ * cost of one more slot from the passive-reply budget.
+ */
+ renderMarkdown: 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
@@ -1881,6 +1906,11 @@ export interface FeishuBindingPutRequest {
* value; a binding created without it starts with it off.
*/
finalReplyOnly?: boolean;
+ /**
+ * Delivery preference (see `FeishuBindingInfo.renderMarkdown`). Omitted keeps the stored
+ * value; a binding created without it starts with it ON.
+ */
+ renderMarkdown?: boolean;
}
/**
@@ -1908,6 +1938,11 @@ export interface TelegramBindingPutRequest {
* value; a binding created without it starts with it off.
*/
finalReplyOnly?: boolean;
+ /**
+ * Delivery preference (see `TelegramBindingInfo.renderMarkdown`). Omitted keeps the stored
+ * value; a binding created without it starts with it ON.
+ */
+ renderMarkdown?: boolean;
}
/**
@@ -1935,6 +1970,11 @@ export interface QQBindingPutRequest {
* value; a binding created without it starts with it off.
*/
finalReplyOnly?: boolean;
+ /**
+ * Delivery preference (see `QQBindingInfo.renderMarkdown`). Omitted keeps the stored
+ * value; a binding created without it starts with it ON.
+ */
+ renderMarkdown?: boolean;
}
/**
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 4d6d91c6..cfe06dbb 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -18,7 +18,7 @@ const sqlite = process.getBuiltinModule("node:sqlite");
/**
* Opens an EXISTING database for a narrow write, without running any schema work.
*
- * `openDatabase` migrates — CREATE TABLE, six ensureColumn calls, a DROP INDEX and a backfill.
+ * `openDatabase` migrates — CREATE TABLE, several ensureColumn calls, a DROP INDEX and a backfill.
* That is right for the process that owns the database and wrong for a short-lived CLI writing
* one row (`penguin auth token`): after `penguin update` the CLI on disk can be NEWER than the
* running server, and migrating under a live server's prepared statements is not something a
@@ -57,6 +57,11 @@ export function openDatabase(dbPath: string): DatabaseSync {
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");
+ // DEFAULT 1, unlike every other added flag here: this one's default is the CORRECTED
+ // behaviour, not the previous one. Sending the model's Markdown as characters was the
+ // defect, so an existing binding starts rendering it — a visible change to every relayed
+ // message, recorded in the release's backward-compatibility entry.
+ ensureColumn(db, "messaging_bindings", "render_markdown", "INTEGER NOT NULL DEFAULT 1");
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 is
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index bc22777e..6636b798 100644
--- a/packages/server/src/db/repos/messaging-bindings.ts
+++ b/packages/server/src/db/repos/messaging-bindings.ts
@@ -15,10 +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` 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.
+ * `line_per_message`, `final_reply_only` and `render_markdown` 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 — each channel renders what it can of the same request.
*
* `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
@@ -60,6 +60,15 @@ export interface MessagingBindingRow {
* above.
*/
finalReplyOnly: boolean;
+ /**
+ * DELIVERY preference: render a relayed assistant reply's Markdown in the channel's own
+ * markup rather than sending its characters as written. ON by default — the model writes
+ * Markdown, and relaying it raw is what this replaced. What survives differs per channel
+ * (Telegram has no headings, lists or tables; QQ has no code or tables; Feishu has all of
+ * them) and a rendering the channel refuses falls back to the plain source, so the setting
+ * can cost formatting and never a message.
+ */
+ renderMarkdown: 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
@@ -98,6 +107,7 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {
enabled: Number(r.enabled) === 1,
linePerMessage: Number(r.line_per_message) === 1,
finalReplyOnly: Number(r.final_reply_only) === 1,
+ renderMarkdown: Number(r.render_markdown) === 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,
@@ -159,9 +169,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` 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).
+ * update keeps the stored value. `linePerMessage`, `finalReplyOnly` and `renderMarkdown` are
+ * ordinary saved fields this write does own, and an omitted one keeps the stored value (a
+ * fresh row starts with the first two off and the third ON, matching the column defaults).
* 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
@@ -175,6 +185,7 @@ export class MessagingBindingsRepo {
config: Record<string, unknown>;
linePerMessage?: boolean;
finalReplyOnly?: boolean;
+ renderMarkdown?: boolean;
}): MessagingBindingRow {
const now = new Date().toISOString();
const configJson = JSON.stringify(args.config);
@@ -183,8 +194,9 @@ export class MessagingBindingsRepo {
this.db
.prepare(
`INSERT INTO messaging_bindings
- (session_id, channel, account_id, config_json, line_per_message, final_reply_only, created_at, updated_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ (session_id, channel, account_id, config_json, line_per_message, final_reply_only,
+ render_markdown, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
)
.run(
args.sessionId,
@@ -193,6 +205,9 @@ export class MessagingBindingsRepo {
configJson,
args.linePerMessage === true ? 1 : 0,
args.finalReplyOnly === true ? 1 : 0,
+ // Absent means ON, matching the column default: a binding created without an
+ // opinion renders Markdown, which is the behaviour a new binding should have.
+ args.renderMarkdown === false ? 0 : 1,
now,
now,
);
@@ -204,6 +219,7 @@ export class MessagingBindingsRepo {
SET account_id = ?, config_json = ?,
line_per_message = COALESCE(?, line_per_message),
final_reply_only = COALESCE(?, final_reply_only),
+ render_markdown = COALESCE(?, render_markdown),
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,
@@ -216,6 +232,7 @@ export class MessagingBindingsRepo {
// 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,
+ args.renderMarkdown === undefined ? null : args.renderMarkdown ? 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.ts
index 4fc46446..978dc6e5 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -138,6 +138,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel
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 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 line
+ render_markdown INTEGER NOT NULL DEFAULT 1, -- delivery preference: 1 = a relayed reply's Markdown is rendered in the channel's own markup (Telegram HTML, a Feishu card, QQ markdown), 0 = the reply's characters are sent as written. DEFAULT 1 because the model writes Markdown and showing it raw was the defect; the per-channel subsets and the plain-text fallback live in the connectors
last_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 it
last_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 twice
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index b0490af4..7ffd5c99 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -26,11 +26,12 @@
* 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 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.
+ * A PUT also carries the three saved fields that are not credentials: `linePerMessage`
+ * (whether a relayed reply is delivered one message per non-blank line), `finalReplyOnly`
+ * (whether a run relays only its last completed assistant message, at the run's end, instead
+ * of each one as it completes) and `renderMarkdown` (whether its Markdown is rendered in the
+ * channel's own markup). All three are ordinary form fields applied on Save — omitted keeps
+ * the stored value — and none 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
@@ -118,6 +119,7 @@ function toFeishuInfo(row: MessagingBindingRow): FeishuBindingInfo {
enabled: row.enabled,
linePerMessage: row.linePerMessage,
finalReplyOnly: row.finalReplyOnly,
+ renderMarkdown: row.renderMarkdown,
lastChatKnown: row.lastChatId !== null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -134,6 +136,7 @@ function toTelegramInfo(row: MessagingBindingRow): TelegramBindingInfo {
enabled: row.enabled,
linePerMessage: row.linePerMessage,
finalReplyOnly: row.finalReplyOnly,
+ renderMarkdown: row.renderMarkdown,
lastChatKnown: row.lastChatId !== null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -150,6 +153,7 @@ function toQQInfo(row: MessagingBindingRow): QQBindingInfo {
enabled: row.enabled,
linePerMessage: row.linePerMessage,
finalReplyOnly: row.finalReplyOnly,
+ renderMarkdown: row.renderMarkdown,
lastChatKnown: row.lastChatId !== null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
@@ -324,6 +328,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
const baseDomain = parseBaseDomain(optionalString(body, "baseDomain", { maxLen: 500 }));
const linePerMessage = optionalBoolean(body, "linePerMessage");
const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
+ const renderMarkdown = optionalBoolean(body, "renderMarkdown");
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
@@ -360,6 +365,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
config: { appId, appSecret, baseDomain },
...(linePerMessage !== undefined ? { linePerMessage } : {}),
...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
+ ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
});
// 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
@@ -466,6 +472,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
const clearToken = (body as { clearBotToken?: unknown }).clearBotToken === true;
const linePerMessage = optionalBoolean(body, "linePerMessage");
const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
+ const renderMarkdown = optionalBoolean(body, "renderMarkdown");
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),
@@ -512,6 +519,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
config: { botToken },
...(linePerMessage !== undefined ? { linePerMessage } : {}),
...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
+ ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
});
// Same save/enable split as Feishu: only an enabled binding restarts its connector.
if (saved.enabled) await deps.messaging.sync(row.sessionId);
@@ -613,6 +621,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
const clearSecret = (body as { clearAppSecret?: unknown }).clearAppSecret === true;
const linePerMessage = optionalBoolean(body, "linePerMessage");
const finalReplyOnly = optionalBoolean(body, "finalReplyOnly");
+ const renderMarkdown = optionalBoolean(body, "renderMarkdown");
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
@@ -646,6 +655,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
config: { appId, appSecret },
...(linePerMessage !== undefined ? { linePerMessage } : {}),
...(finalReplyOnly !== undefined ? { finalReplyOnly } : {}),
+ ...(renderMarkdown !== undefined ? { renderMarkdown } : {}),
});
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.ts
index 1f0fa3e1..7fa5e71d 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -43,7 +43,12 @@
* 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
+ * both sends that final reply one message per line). With the binding's `renderMarkdown` set
+ * (the default) each message additionally carries a request to render it: the connector
+ * converts the model's Markdown into its own channel's markup and falls back to sending the
+ * plain source if the channel refuses the result, so formatting is the only thing a rendering
+ * failure can cost, and the chunking follows the request, cutting at boundaries the document
+ * actually has (see markdown.ts). 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
@@ -89,6 +94,7 @@ import type {
MessagingSendNote,
} from "./connector.js";
import { messagingErrorKind } from "./error-kind.js";
+import { chunkMarkdown } from "./markdown.js";
import { MessagingMediaTooLargeError, MessagingPermissionError, isImageFileName } from "./media.js";
import { replyFileMentions } from "./reply-files.js";
@@ -472,12 +478,25 @@ export function chunkMessagingText(text: string, max = MESSAGING_TEXT_CHUNK_CHAR
* 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
+ * `chunk`, 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.
+ * other), so the reply reaches the chat entire either way. `chunk` is the caller's own
+ * chunker so the estimate agrees with what it will actually do — Markdown cuts at different
+ * places (see chunkMarkdown).
+ *
+ * It composes with Markdown rendering by staying literal there too. Each line becomes its own
+ * message and is converted on its own, so a line that is not a whole construct renders as the
+ * text it is: one row of a table arrives as `| a | b |`, one line out of a fenced block
+ * arrives as that line of code. That is the honest reading of a message containing one line —
+ * and the alternative, holding constructs together, is the "smart" grouping this option exists
+ * to avoid.
*/
-export function splitReplyLines(text: string, max = MESSAGING_MAX_LINE_MESSAGES): string[] {
+export function splitReplyLines(
+ text: string,
+ max = MESSAGING_MAX_LINE_MESSAGES,
+ chunk: (body: string) => string[] = chunkMessagingText,
+): string[] {
const lines = text
.split("\n")
.map((line) => line.trimEnd())
@@ -486,9 +505,9 @@ export function splitReplyLines(text: string, max = MESSAGING_MAX_LINE_MESSAGES)
let used = 0;
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i]!;
- const lineCost = chunkMessagingText(line).length;
+ const lineCost = chunk(line).length;
const rest = lines.slice(i + 1);
- const restCost = rest.length === 0 ? 0 : chunkMessagingText(rest.join("\n")).length;
+ const restCost = rest.length === 0 ? 0 : chunk(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
@@ -1571,6 +1590,14 @@ export class MessagingBridge {
* 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.
+ *
+ * A binding with `renderMarkdown` set relays the model's Markdown as formatting rather
+ * than as characters. The bridge only carries the REQUEST: the conversion is the
+ * connector's, because what a channel can show and what it does with a rendering the
+ * channel refuses are both channel-shaped (see MessagingSendOptions). What is not
+ * channel-shaped is where a reply too long for one message may be cut, and that is why the
+ * chunker changes with the flag — a cut through a code fence or an emphasis run costs the
+ * construct everywhere, and on a strict parser costs the whole message's formatting.
*/
private async deliverReply(
entry: BridgeEntry,
@@ -1583,6 +1610,7 @@ export class MessagingBridge {
// 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.
+ if (!this.live(entry)) return;
const liveInboundMessageId = entry.lastInboundMessageId;
const target = await this.sendTarget(entry);
if (target === null) return;
@@ -1594,12 +1622,15 @@ export class MessagingBridge {
isDirect: row.lastChatIsDirect,
inboundMessageId: liveInboundMessageId,
};
+ const markdown = row.renderMarkdown;
+ const chunkBody = (body: string): string[] =>
+ markdown ? chunkMarkdown(body, MESSAGING_TEXT_CHUNK_CHARS) : chunkMessagingText(body);
// 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, entry.connector.replyBudget ?? MESSAGING_MAX_LINE_MESSAGES)
+ ? splitReplyLines(text, entry.connector.replyBudget ?? MESSAGING_MAX_LINE_MESSAGES, chunkBody)
: [text];
- const messages = bodies.flatMap((body) => chunkMessagingText(body));
+ const messages = bodies.flatMap(chunkBody);
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.
@@ -1611,9 +1642,9 @@ export class MessagingBridge {
try {
if (threadOnto !== null) {
entry.threadedThisRun = true;
- this.noteSend(entry, await client.replyText(threadOnto, chunk));
+ this.noteSend(entry, await client.replyText(threadOnto, chunk, { markdown }));
} else {
- this.noteSend(entry, await client.sendText(to.chatId, chunk));
+ this.noteSend(entry, await client.sendText(to.chatId, chunk, { markdown }));
}
} catch (err) {
this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");
@@ -1659,6 +1690,7 @@ export class MessagingBridge {
since: number,
at: ReplyTarget | null = null,
): Promise<void> {
+ if (!this.live(entry)) return;
try {
const row = this.deps.repo.find(entry.sessionId, entry.channel);
if (!row || row.lastChatId === null) return; // no chat known yet: nothing mirrors
@@ -1764,6 +1796,7 @@ export class MessagingBridge {
/** One-line notice (approval waiting) to the last known chat; silent before one exists. */
private async deliverNotice(entry: BridgeEntry, text: string): Promise<void> {
+ if (!this.live(entry)) return;
const target = await this.sendTarget(entry);
if (target === null) return;
try {
@@ -1792,6 +1825,20 @@ export class MessagingBridge {
}
}
+ /**
+ * Whether this entry still holds its Session's connection — asked at the head of every
+ * step of the send chain, the way `observe` asks it of every event.
+ *
+ * The chain outlives what fed it. A run's last messages and the files behind them are
+ * queued on it, and `stop()` — App dispose, a hot swap — drops the entry and takes the
+ * database with it while they are still waiting their turn. A step that ran anyway would
+ * read a closed database, and it would fail again inside its own error recording, leaving
+ * the chain rejected with nothing left to catch it.
+ */
+ private live(entry: BridgeEntry): boolean {
+ return this.entries.get(entry.sessionId) === entry;
+ }
+
/** 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();
diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.ts
index 66c9cf01..ea1dc845 100644
--- a/packages/server/src/runtime/messaging/connector.ts
+++ b/packages/server/src/runtime/messaging/connector.ts
@@ -180,14 +180,40 @@ export interface MessagingOutboundFile {
data: Buffer;
}
+/** How one outbound text should be rendered. Absent throughout means plain text. */
+export interface MessagingSendOptions {
+ /**
+ * Read the text as Markdown and render it in whatever this channel's markup is.
+ *
+ * A REQUEST, not an instruction: the connector owns both what its channel can show and
+ * what to do when the channel refuses the rendered form, and it must fall back to sending
+ * this same text plainly rather than let a formatting failure cost the message. What
+ * survives the conversion differs per channel and is documented at each renderer
+ * (telegram-html.ts, feishu-card.ts, qq-markdown.ts).
+ *
+ * Only a relayed assistant message ever sets it. The fixed notices and the test message
+ * carry no markup and are sent as they are written, so a bug in a renderer can never
+ * reach the one message a user sends to check whether the binding works at all.
+ */
+ markdown?: boolean;
+}
+
/** Outbound half of one bound account. Every method throws on failure with a readable reason. */
export interface MessagingClient {
/** Credential check (used by the test endpoint); resolving means the config signs in. */
checkCredentials(): Promise<MessagingAccountInfo | null>;
/** Sends a text message into a chat by chat id; resolves a MessagingSendNote when it degraded. */
- sendText(chatId: string, text: string): Promise<MessagingSendNote | void>;
+ sendText(
+ chatId: string,
+ text: string,
+ opts?: MessagingSendOptions,
+ ): Promise<MessagingSendNote | void>;
/** Replies a text message to a specific inbound message (threads correctly in group chats). */
- replyText(messageId: string, text: string): Promise<MessagingSendNote | void>;
+ replyText(
+ messageId: string,
+ text: string,
+ opts?: MessagingSendOptions,
+ ): Promise<MessagingSendNote | void>;
/**
* Sends a picture into a chat, so a chart the Agent drew arrives as something the reader
* can see rather than as a download. Channels that need an upload step first do it here —
diff --git a/packages/server/src/runtime/messaging/error-kind.ts b/packages/server/src/runtime/messaging/error-kind.ts
index 9a17f181..470aaa16 100644
--- a/packages/server/src/runtime/messaging/error-kind.ts
+++ b/packages/server/src/runtime/messaging/error-kind.ts
@@ -43,6 +43,14 @@ import {
* noteFileFailure). Every other code fails with the chat hearing nothing at all — a reply that
* never went out, an inbound message whose Task never started, a connection that will not come
* up — so the dashboard is where it has to be noticed.
+ *
+ * A Markdown send the channel refuses adds no code here, and that is deliberate. The
+ * connector retries it as plain text (see the three renderers' fallback), so the ordinary
+ * outcome is a DELIVERED message and nothing is recorded at all — there is no failure to
+ * file and nothing to tell anyone. Only a send that then fails on its own terms records
+ * anything, as `messaging_send_failed`, and that code stays out of this set for the reason
+ * every other send failure does: the message that would have carried the explanation is the
+ * message that did not go out.
*/
const CODES_EXPLAINED_IN_CHAT = new Set([
"messaging_image_fetch_failed",
diff --git a/packages/server/src/runtime/messaging/feishu-card.ts b/packages/server/src/runtime/messaging/feishu-card.ts
new file mode 100644
index 00000000..da11d0a5
--- /dev/null
+++ b/packages/server/src/runtime/messaging/feishu-card.ts
@@ -0,0 +1,331 @@
+/**
+ * Renders a parsed Markdown reply into a Feishu interactive card.
+ *
+ * Feishu's plain `text` message shows exactly what it is given, so a reply reaches it as
+ * `**bold**`. The rich-text component of a JSON 2.0 card is what renders instead
+ * (https://open.feishu.cn/document/feishu-cards/card-json-v2-components/content-components/rich-text):
+ * `{"tag": "markdown", "content": …}` inside `{"schema": "2.0", "body": {"elements": […]}}`,
+ * sent as `msg_type: "interactive"` with the card JSON serialized into `content`.
+ *
+ * This is the widest of the three channels: headings 1–6, bold, italic, strikethrough,
+ * inline code, fenced code with a language, ordered and unordered lists with nesting,
+ * blockquotes, horizontal rules, links and tables all render. So the output is Markdown
+ * again rather than another markup — but Feishu's Markdown, not the model's, and the two
+ * differ in the three places below.
+ *
+ * ## Escaping
+ *
+ * Feishu's rule is HTML entities, not backslashes: "if the character you want to display
+ * matches special markdown characters (such as `*`, `~`, `>`, `<`), you must perform HTML
+ * entity escaping". Its table is `&#60; &#62; &#42; &#91; &#93; &#35; &#92;` plus `&sim;`
+ * for `~`. Two deliberate departures from that table:
+ *
+ * - `~` is written `&#126;`, not the documented `&sim;`. `&sim;` is U+223C TILDE OPERATOR,
+ * a different character from the one the model typed; every other entry in the table is
+ * the numeric entity for its own character, and the decoder that reads those reads this.
+ * - `` ` `` is added, as `&#96;`. It is not in the table, and it is live syntax here since
+ * inline code renders — an unescaped stray backtick swallows the text up to the next one,
+ * which loses content rather than merely showing it oddly.
+ *
+ * `&` is escaped first, and to `&amp;`, or the entities above would be escaped by each
+ * other. `_` is deliberately NOT escaped: the documented emphasis marker is `*`, and this
+ * product's replies are full of snake_case identifiers that five characters of entity would
+ * disfigure on every line.
+ *
+ * ## Tables
+ *
+ * The component renders at most 5 data rows per table and at most 4 tables. Past either
+ * limit the rows are simply not shown — a silent truncation, and the wrong failure for a
+ * reply whose point is usually the numbers. An over-limit table is therefore rendered as a
+ * fenced code block of its own rows instead: monospaced, complete, and aligned, which is
+ * what the table was for.
+ */
+import { isSafeUrl, parseMarkdown } from "./markdown.js";
+import type {
+ BlockContent,
+ DefinitionContent,
+ List,
+ ListItem,
+ PhrasingContent,
+ RootContent,
+ Table,
+} from "mdast";
+
+/** The card envelope Feishu's `msg_type: "interactive"` carries, serialized into `content`. */
+export interface FeishuCard {
+ schema: "2.0";
+ body: { elements: { tag: "markdown"; content: string }[] };
+}
+
+/** How many data rows one rich-text table may carry, and how many tables one component may hold. */
+const TABLE_MAX_ROWS = 5;
+const TABLE_MAX_PER_MESSAGE = 4;
+
+/** One indent level inside a list, as the component's own documentation specifies. */
+const LIST_INDENT = " ";
+
+const ENTITIES: Readonly<Record<string, string>> = {
+ "&": "&amp;",
+ "<": "&#60;",
+ ">": "&#62;",
+ "*": "&#42;",
+ "~": "&#126;",
+ "[": "&#91;",
+ "]": "&#93;",
+ "#": "&#35;",
+ "\\": "&#92;",
+ "`": "&#96;",
+};
+
+const ESCAPABLE = /[&<>*~[\]#\\`]/g;
+
+/**
+ * Entity-escapes literal text so Feishu shows the characters the model typed (see the module
+ * doc).
+ *
+ * ONE pass, not one pass per character. A replacement per entry would feed its own output
+ * back to the entries after it — `<` becomes `&#60;`, whose `#` the `#` rule then rewrites,
+ * and the reader gets `&&#35;60;` where a `<` was meant.
+ */
+function esc(text: string): string {
+ return text.replace(ESCAPABLE, (ch) => ENTITIES[ch] ?? ch);
+}
+
+/**
+ * Neutralizes a block marker that a rendered line happens to START with.
+ *
+ * The characters escaped above are the ones that mean something anywhere; these mean
+ * something only at the head of a line, so escaping them everywhere would put an entity in
+ * the middle of every hyphenated word and every decimal number. A paragraph that opens with
+ * one — "- 40 degrees", "1. first of all" — would otherwise be re-read as the list it
+ * never was.
+ */
+function guardLineStarts(text: string): string {
+ const entity = (ch: string): string => `&#${ch.codePointAt(0)};`;
+ return text
+ .split("\n")
+ .map((line) =>
+ line
+ .replace(/^(\s*)([-+=])/, (_m, lead: string, ch: string) => lead + entity(ch))
+ .replace(/^(\s*\d+)([.)])/, (_m, lead: string, ch: string) => lead + entity(ch)),
+ )
+ .join("\n");
+}
+
+/** The fence that safely closes a code value containing backticks of its own. */
+function fenceFor(value: string): string {
+ let longest = 0;
+ let run = 0;
+ for (const ch of value) {
+ run = ch === "`" ? run + 1 : 0;
+ if (run > longest) longest = run;
+ }
+ return "`".repeat(Math.max(3, longest + 1));
+}
+
+/** A link target, with the two characters that would close the `](…)` early made safe. */
+function href(url: string): string {
+ return url.replaceAll("(", "%28").replaceAll(")", "%29");
+}
+
+function inline(nodes: readonly PhrasingContent[]): string {
+ return nodes.map(phrasing).join("");
+}
+
+function phrasing(node: PhrasingContent): string {
+ switch (node.type) {
+ case "text":
+ return esc(node.value);
+ case "strong":
+ return `**${inline(node.children)}**`;
+ case "emphasis":
+ return `*${inline(node.children)}*`;
+ case "delete":
+ return `~~${inline(node.children)}~~`;
+ case "inlineCode": {
+ // A code span's contents are literal, so they are NOT entity-escaped; the fence grows
+ // instead, and a value that starts or ends with a backtick needs the padding spaces
+ // Markdown strips back off.
+ const fence = "`".repeat(Math.max(1, fenceFor(node.value).length - 2));
+ const pad = node.value.startsWith("`") || node.value.endsWith("`") ? " " : "";
+ return `${fence}${pad}${node.value}${pad}${fence}`;
+ }
+ case "link": {
+ const label = inline(node.children);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "image": {
+ // The rich-text component documents no image syntax; the reply's own pictures travel
+ // as real Feishu images instead (see reply-files.ts), so a remote one is a link.
+ const alt = node.alt ?? "";
+ const label = esc(alt !== "" ? alt : node.url);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "break":
+ return "\n";
+ case "html":
+ // The model's own angle brackets, shown rather than forwarded: the component accepts a
+ // handful of tags of its own, and none of them is anything a reply should be able to emit.
+ return esc(node.value);
+ case "footnoteReference":
+ return esc(`[^${node.identifier}]`);
+ case "linkReference":
+ case "imageReference":
+ return "children" in node ? inline(node.children) : esc(node.label ?? node.identifier);
+ default:
+ return "";
+ }
+}
+
+/** Inline content as unformatted text, for the inside of a fence where no markup applies. */
+function plainText(nodes: readonly PhrasingContent[]): string {
+ return nodes
+ .map((node) => {
+ if (node.type === "text" || node.type === "inlineCode" || node.type === "html") {
+ return node.value;
+ }
+ if (node.type === "break") return " ";
+ if (node.type === "image") return node.alt ?? "";
+ return "children" in node ? plainText(node.children) : "";
+ })
+ .join("");
+}
+
+function tableRows(node: Table): string[] {
+ return node.children.map(
+ (row) => `| ${row.children.map((cell) => plainText(cell.children)).join(" | ")} |`,
+ );
+}
+
+/** A table small enough for the component, as the Markdown table it is. */
+function renderTable(node: Table): string {
+ const [header, ...body] = node.children;
+ if (header === undefined) return "";
+ const width = header.children.length;
+ const cells = (row: (typeof node.children)[number]): string =>
+ `| ${Array.from({ length: width }, (_, i) => inline(row.children[i]?.children ?? [])).join(" | ")} |`;
+ return [cells(header), `| ${Array.from({ length: width }, () => "---").join(" | ")} |`]
+ .concat(body.map(cells))
+ .join("\n");
+}
+
+function itemMarker(list: List, index: number): string {
+ return list.ordered === true ? `${(list.start ?? 1) + index}. ` : "- ";
+}
+
+/** A GFM task item's box. The component has no checkbox, so the glyph is the checkbox. */
+function itemCheckbox(item: ListItem): string {
+ if (item.checked === true) return "☑ ";
+ if (item.checked === false) return "☐ ";
+ return "";
+}
+
+function renderList(list: List, indent: string, ctx: RenderContext): string {
+ return list.children
+ .map((item, i) => {
+ const head = `${indent}${itemMarker(list, i)}${itemCheckbox(item)}`;
+ const parts: string[] = [];
+ for (const [j, child] of item.children.entries()) {
+ if (j === 0 && child.type === "paragraph") {
+ parts.push(head + inline(child.children));
+ continue;
+ }
+ if (child.type === "list") {
+ parts.push(renderList(child, indent + LIST_INDENT, ctx));
+ continue;
+ }
+ const rendered = block(child, indent + LIST_INDENT, ctx);
+ if (rendered !== "") {
+ parts.push(
+ rendered
+ .split("\n")
+ .map((line) => indent + LIST_INDENT + line)
+ .join("\n"),
+ );
+ }
+ }
+ return parts.filter((part) => part !== "").join("\n");
+ })
+ .filter((line) => line !== "")
+ .join("\n");
+}
+
+/** Per-message render state: only the table budget, which is counted across the whole component. */
+interface RenderContext {
+ tables: number;
+}
+
+function block(
+ node: BlockContent | DefinitionContent | RootContent,
+ indent: string,
+ ctx: RenderContext,
+): string {
+ switch (node.type) {
+ case "paragraph":
+ return guardLineStarts(inline(node.children));
+ case "heading":
+ // Six levels, exactly as Markdown writes them.
+ return `${"#".repeat(Math.min(node.depth, 6))} ${inline(node.children)}`;
+ case "code": {
+ const fence = fenceFor(node.value);
+ const lang = typeof node.lang === "string" ? node.lang : "";
+ return `${fence}${lang}\n${node.value}\n${fence}`;
+ }
+ case "blockquote":
+ return node.children
+ .map((child) => block(child, indent, ctx))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ case "list":
+ return renderList(node, indent, ctx);
+ case "table": {
+ ctx.tables += 1;
+ const dataRows = Math.max(node.children.length - 1, 0);
+ if (dataRows > TABLE_MAX_ROWS || ctx.tables > TABLE_MAX_PER_MESSAGE) {
+ // Over one of the component's limits, where a real table would drop rows silently.
+ const rows = tableRows(node).join("\n");
+ return `${fenceFor(rows)}\n${rows}\n${fenceFor(rows)}`;
+ }
+ return renderTable(node);
+ }
+ case "thematicBreak":
+ return "---";
+ case "html":
+ return esc(node.value);
+ case "footnoteDefinition":
+ return `**${esc(`[^${node.identifier}]`)}** ${node.children.map((child) => block(child, indent, ctx)).join("\n\n")}`;
+ case "definition":
+ return "";
+ default:
+ return "";
+ }
+}
+
+/** One relayed message as the rich-text component's `content`. */
+export function feishuMarkdownOf(markdown: string): string {
+ const root = parseMarkdown(markdown);
+ const ctx: RenderContext = { tables: 0 };
+ return root.children
+ .map((node) => block(node, "", ctx))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .trim();
+}
+
+/**
+ * One relayed message as the card the IM API sends.
+ *
+ * A card body is capped at 30KB, which a message chunked under the channel-neutral 4000
+ * characters cannot reach except through pathological escaping (every character an entity).
+ * That case is not guarded here on purpose: Feishu answers an over-size card with a refusal,
+ * and the connector's plain-text fallback already turns a refusal into a delivered message.
+ */
+export function feishuCardOf(markdown: string): FeishuCard {
+ return {
+ schema: "2.0",
+ body: { elements: [{ tag: "markdown", content: feishuMarkdownOf(markdown) }] },
+ };
+}
diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.ts
index 17cb06eb..09f6d3b4 100644
--- a/packages/server/src/runtime/messaging/feishu-connector.ts
+++ b/packages/server/src/runtime/messaging/feishu-connector.ts
@@ -15,8 +15,11 @@ import type {
MessagingConnectorHandlers,
MessagingInboundFile,
MessagingInboundImage,
+ MessagingSendOptions,
} from "./connector.js";
+import { feishuCardOf } from "./feishu-card.js";
import type { FeishuApiClient, FeishuCredentials, FeishuMention, FeishuSdk } from "./feishu-sdk.js";
+import { FeishuApiError } from "./feishu-sdk.js";
/** Default Feishu open-platform domain (Lark tenants override it in the form). */
export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";
@@ -158,6 +161,34 @@ function fileOfContent(content: string): { fileKey: string; fileName: string } |
}
}
+/**
+ * One outbound message: an interactive card when the binding asked for Markdown, a plain
+ * `text` bubble when it did not — and a plain `text` bubble anyway if Feishu refuses the
+ * card.
+ *
+ * The fallback runs on a REFUSAL only: a `{code}` envelope means Feishu answered and
+ * delivered nothing, so the same message may safely go out again. A transport failure — a
+ * timeout, a reset — carries no code and propagates untouched, because it may already have
+ * put the card in the chat and a retry would post the reply twice. A permission denial
+ * propagates too: it is not about the card, and its scope names and console link are the
+ * whole of what the user can act on (see MessagingPermissionError).
+ *
+ * The plain text is the model's own Markdown source, unaltered — the same bytes the switch
+ * would have sent with formatting off.
+ */
+function sendFormatted(
+ opts: MessagingSendOptions | undefined,
+ text: string,
+ asCard: (card: ReturnType<typeof feishuCardOf>) => Promise<void>,
+ asText: (plain: string) => Promise<void>,
+): Promise<void> {
+ if (opts?.markdown !== true) return asText(text);
+ return asCard(feishuCardOf(text)).catch((err: unknown) => {
+ if (!(err instanceof FeishuApiError)) throw err;
+ return asText(text);
+ });
+}
+
export class FeishuConnector implements MessagingChannelConnector {
readonly channel = "feishu" as const;
@@ -167,9 +198,29 @@ export class FeishuConnector implements MessagingChannelConnector {
return feishuConfigOf(config);
}
- createClient(config: Record<string, unknown>): Promise<MessagingClient> {
- // FeishuApiClient already satisfies MessagingClient member for member.
- return this.sdk.createClient(this.credsOf(config));
+ async createClient(config: Record<string, unknown>): Promise<MessagingClient> {
+ const api = await this.sdk.createClient(this.credsOf(config));
+ // FeishuApiClient satisfies the seam's other members verbatim; only the two text sends
+ // are wrapped, and only to choose between a card and a bubble (see sendFormatted).
+ return {
+ checkCredentials: () => api.checkCredentials(),
+ sendText: (chatId, text, opts) =>
+ sendFormatted(
+ opts,
+ text,
+ (card) => api.sendCard(chatId, card),
+ (plain) => api.sendText(chatId, plain),
+ ),
+ replyText: (messageId, text, opts) =>
+ sendFormatted(
+ opts,
+ text,
+ (card) => api.replyCard(messageId, card),
+ (plain) => api.replyText(messageId, plain),
+ ),
+ sendImage: (chatId, file) => api.sendImage(chatId, file),
+ sendFile: (chatId, file) => api.sendFile(chatId, file),
+ };
}
async connect(
diff --git a/packages/server/src/runtime/messaging/feishu-sdk.ts b/packages/server/src/runtime/messaging/feishu-sdk.ts
index 7f1daf39..e1e42851 100644
--- a/packages/server/src/runtime/messaging/feishu-sdk.ts
+++ b/packages/server/src/runtime/messaging/feishu-sdk.ts
@@ -9,6 +9,7 @@
* which would tax every typecheck for the handful of calls made here; the local interfaces
* below are the contract, and the adapter casts the loaded module once.
*/
+import type { FeishuCard } from "./feishu-card.js";
import {
MessagingMediaTooLargeError,
MessagingPermissionError,
@@ -87,6 +88,18 @@ export interface FeishuApiClient {
sendText(chatId: string, text: string): Promise<void>;
/** Replies a text message to a specific inbound message (threads correctly in group chats). */
replyText(messageId: string, text: string): Promise<void>;
+ /**
+ * Sends an interactive card into a chat by chat_id — how a reply's Markdown renders (see
+ * feishu-card.ts). `msg_type: "interactive"` with the card JSON serialized into `content`;
+ * a refusal throws FeishuApiError, so the caller can send the plain text instead.
+ */
+ sendCard(chatId: string, card: FeishuCard): Promise<void>;
+ /**
+ * Replies an interactive card to a specific inbound message. The reply endpoint takes the
+ * same `msg_type` set as the send one, so a card threads in a group exactly as text does —
+ * which is what keeps the group's one reply-to relation working with formatting on.
+ */
+ replyCard(messageId: string, card: FeishuCard): Promise<void>;
/**
* This app's own bot open id, so a group message's mention of THIS bot can be told apart
* from a mention of anyone else (the ids are the only thing that distinguishes them —
@@ -190,8 +203,8 @@ interface LarkResponse {
msg?: string;
}
-/** The `msg_type` values this adapter sends (Feishu has many more; these are the three it uses). */
-type FeishuMessageType = "text" | "image" | "file";
+/** The `msg_type` values this adapter sends (Feishu has many more; these are the four it uses). */
+type FeishuMessageType = "text" | "image" | "file" | "interactive";
/**
* Feishu's upload categories. `stream` is the general one — the rest exist because the
@@ -256,7 +269,7 @@ interface LarkClient {
}): Promise<LarkResponse>;
reply(payload: {
path: { message_id: string };
- data: { content: string; msg_type: "text" };
+ data: { content: string; msg_type: FeishuMessageType };
}): Promise<LarkResponse>;
};
messageResource: {
@@ -373,6 +386,26 @@ function scopeDenialDetail(msg: string): { scopes: string[]; grantUrl: string |
return { scopes, grantUrl: url !== null && url.length <= GRANT_URL_MAX ? url : null };
}
+/**
+ * A call Feishu itself REFUSED, carrying the `{code}` it refused with.
+ *
+ * Its own class for the reason telegram-api's TelegramApiError is one: a refusal and a
+ * request that never completed are the same outcome and opposite facts. Feishu answered, so
+ * nothing was delivered and the same message may safely be sent again in another form —
+ * which is what the card-to-text fallback does. A timeout or a reset carries no code, stays
+ * a plain Error, and must never be retried: it may well have been delivered already, and a
+ * retry would put the reply in the chat twice.
+ */
+export class FeishuApiError extends Error {
+ constructor(
+ message: string,
+ readonly code: number | undefined,
+ ) {
+ super(message);
+ this.name = "FeishuApiError";
+ }
+}
+
/**
* The error a refused call throws: a permission denial when Feishu said so by CODE, a plain
* failure otherwise. Only the scope names and the console link travel with the first — the
@@ -387,6 +420,8 @@ function larkFailure(envelope: LarkErrorEnvelope | null, err: unknown, what?: st
const { scopes, grantUrl } = scopeDenialDetail(envelope.msg);
if (scopes.length > 0) return new MessagingPermissionError(scopes, grantUrl, text);
}
+ // An envelope with a code is Feishu's own refusal; anything else never reached it.
+ if (envelope?.code !== undefined) return new FeishuApiError(text, envelope.code);
return new Error(text);
}
@@ -552,7 +587,7 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
const sendContent = async (
chatId: string,
msgType: FeishuMessageType,
- content: Record<string, string>,
+ content: unknown,
): Promise<void> => {
let res: LarkResponse;
try {
@@ -568,6 +603,26 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
}
ensureOk(res, "Message send");
};
+ /** One `im.v1.message.reply`, the threading twin of sendContent. */
+ const replyContent = async (
+ messageId: string,
+ msgType: FeishuMessageType,
+ content: unknown,
+ ): Promise<void> => {
+ let res: LarkResponse;
+ try {
+ res = await deadline(
+ client.im.v1.message.reply({
+ path: { message_id: messageId },
+ data: { content: JSON.stringify(content), msg_type: msgType },
+ }),
+ "Message reply",
+ );
+ } catch (err) {
+ throw larkFailure(larkErrorEnvelope(err), err);
+ }
+ ensureOk(res, "Message reply");
+ };
return {
async checkCredentials(): Promise<null> {
@@ -588,20 +643,14 @@ export function createLarkSdk(opts: LarkSdkOpts = {}): FeishuSdk {
sendText(chatId: string, text: string): Promise<void> {
return sendContent(chatId, "text", { text });
},
- async replyText(messageId: string, text: string): Promise<void> {
- let res: LarkResponse;
- try {
- res = await deadline(
- client.im.v1.message.reply({
- path: { message_id: messageId },
- data: { content: JSON.stringify({ text }), msg_type: "text" },
- }),
- "Message reply",
- );
- } catch (err) {
- throw larkFailure(larkErrorEnvelope(err), err);
- }
- ensureOk(res, "Message reply");
+ sendCard(chatId: string, card: FeishuCard): Promise<void> {
+ return sendContent(chatId, "interactive", card);
+ },
+ replyText(messageId: string, text: string): Promise<void> {
+ return replyContent(messageId, "text", { text });
+ },
+ replyCard(messageId: string, card: FeishuCard): Promise<void> {
+ return replyContent(messageId, "interactive", card);
},
async botOpenId(): Promise<string | null> {
// Best effort by contract (see FeishuApiClient.botOpenId): every failure shape —
diff --git a/packages/server/src/runtime/messaging/markdown.ts b/packages/server/src/runtime/messaging/markdown.ts
new file mode 100644
index 00000000..9d56eb2e
--- /dev/null
+++ b/packages/server/src/runtime/messaging/markdown.ts
@@ -0,0 +1,285 @@
+/**
+ * The half of Markdown relaying that must not differ per channel: reading the model's
+ * reply as Markdown, and deciding where a reply too long for one message may be cut.
+ *
+ * It sits beside the connectors for the same reason media.ts does. The Agent writes one
+ * reply, and which constructs that reply CONTAINS is a fact about the text, not about the
+ * chat it lands in — so the dialect is fixed here (CommonMark plus GFM, matching what the
+ * web transcript renders) and each connector renders the resulting tree into its own
+ * markup. A channel that parsed for itself would disagree with the others about what the
+ * model wrote, and the same reply would then carry different content in two chats.
+ *
+ * The parser is `remark-parse` + `remark-gfm` over `unified` — the stack packages/web
+ * already renders Markdown with, so the two surfaces read a reply the same way. A parser
+ * is not something to hand-roll here: emphasis, links and fenced code are context-
+ * sensitive, and a substitution pass mangles exactly the replies (code containing
+ * asterisks, nested emphasis, links with parentheses) that make the feature worth having.
+ *
+ * The RENDER is deliberately not shared. Three channels accept three different subsets —
+ * Telegram has code and no headings, lists or tables; Feishu has all of them; QQ has
+ * headings and lists but no code and no tables — over two different markups and three
+ * different escaping rules. A printer parameterised over that would be a table of six
+ * capability flags whose every branch belongs to exactly one channel, which is the
+ * connector's own job under a name that hides it. So each channel renders this tree itself:
+ * telegram-html.ts, feishu-card.ts and qq-markdown.ts, each beside the adapter that sends
+ * its output. Nothing in this module knows any channel's markup.
+ */
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import { unified } from "unified";
+import type { Nodes, Root, RootContent } from "mdast";
+
+/**
+ * The one processor, built once: `unified` compiles the extension lists on first use, and
+ * a fresh processor per relayed message would redo that for every reply. Parsing is
+ * stateless, so one instance serves every binding.
+ */
+const processor = unified().use(remarkParse).use(remarkGfm);
+
+/** Reads a reply as Markdown. Never throws: any text at all is a valid document. */
+export function parseMarkdown(text: string): Root {
+ return processor.parse(text);
+}
+
+/**
+ * The URL schemes a rendered link may point at.
+ *
+ * Shared for the same reason the parse is: the reply is model output steerable by whoever
+ * is in the chat, and which destinations a link may name is a safety answer, not a
+ * presentation one — it cannot come out differently on two channels. Everything else
+ * renders as its own label text, so nothing is hidden from the reader, only made
+ * unclickable.
+ */
+const SAFE_LINK_SCHEMES: ReadonlySet<string> = new Set([
+ "http:",
+ "https:",
+ "mailto:",
+ "tel:",
+ "tg:",
+]);
+
+/** Whether a Markdown link's target may be rendered as a link at all (see SAFE_LINK_SCHEMES). */
+export function isSafeUrl(url: string): boolean {
+ // A scheme-relative or in-document target carries no scheme to object to; a bare relative
+ // path has nowhere to resolve against in a chat, but it cannot execute either.
+ if (url === "" || url.startsWith("#")) return false;
+ try {
+ return SAFE_LINK_SCHEMES.has(new URL(url, "https://example.invalid/").protocol);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A node's source span. Every node a parse produces carries one; the type is optional
+ * because mdast allows synthesised trees, which nothing here builds.
+ */
+function spanOf(node: Nodes): { from: number; to: number } | null {
+ const { position } = node;
+ if (position?.start.offset === undefined || position.end.offset === undefined) return null;
+ return { from: position.start.offset, to: position.end.offset };
+}
+
+/**
+ * Parents whose children are BLOCKS rather than inline content, so a cut between two of
+ * them must be moved back to the start of its source line.
+ *
+ * The prefix is why. A blockquote's second paragraph starts after the `> ` that introduces
+ * it, and a list item's after its `- `; cutting at the child's own offset would open the
+ * next message with a line whose marker was left behind in the previous one, and the
+ * construct would be gone. Inline parents get the opposite treatment — their children all
+ * sit on one line, and snapping would collapse every candidate onto the same offset.
+ */
+const BLOCK_PARENTS: ReadonlySet<string> = new Set([
+ "root",
+ "blockquote",
+ "list",
+ "listItem",
+ "table",
+ "footnoteDefinition",
+]);
+
+/** The offset of the start of the source line `offset` sits on. */
+function lineStart(text: string, offset: number): number {
+ return text.lastIndexOf("\n", offset - 1) + 1;
+}
+
+/** The longest run of backticks in a string — what a fence has to beat to close correctly. */
+function longestBacktickRun(value: string): number {
+ let best = 0;
+ let run = 0;
+ for (const ch of value) {
+ run = ch === "`" ? run + 1 : 0;
+ if (run > best) best = run;
+ }
+ return best;
+}
+
+/**
+ * Splits a string at hard character boundaries, preferring the last whitespace in each
+ * window. The last resort under every other rule below: reached only by a single
+ * unbreakable line longer than one whole message.
+ */
+function splitHard(text: string, max: number): string[] {
+ const out: string[] = [];
+ let rest = text;
+ while (rest.length > max) {
+ const window = rest.slice(0, max);
+ const space = window.search(/\s\S*$/);
+ // Only a break in the window's back half is worth taking — an early one would produce a
+ // tiny fragment and many more messages.
+ const cut = space > max / 2 ? space : max;
+ out.push(rest.slice(0, cut));
+ rest = rest.slice(cut).replace(/^\s+/, "");
+ }
+ if (rest !== "") out.push(rest);
+ return out;
+}
+
+/**
+ * Splits a span at its own line boundaries, keeping every line whole.
+ *
+ * The fallback for a block with no usable interior structure, and line-aligned because the
+ * markers that make a block what it is live at the front of each of its lines: a blockquote
+ * continued into a second message still opens each line with `>`, a list still opens each
+ * item with its bullet.
+ */
+function splitLines(src: string, max: number): string[] {
+ const out: string[] = [];
+ let buf = "";
+ for (const line of src.split("\n")) {
+ if (buf !== "" && buf.length + 1 + line.length > max) {
+ out.push(buf);
+ buf = "";
+ }
+ if (line.length > max) {
+ if (buf !== "") {
+ out.push(buf);
+ buf = "";
+ }
+ for (const piece of splitHard(line, max)) out.push(piece);
+ continue;
+ }
+ buf = buf === "" ? line : `${buf}\n${line}`;
+ }
+ if (buf !== "") out.push(buf);
+ return out;
+}
+
+/**
+ * Splits a fenced code block into several fenced code blocks.
+ *
+ * A code fence is the one construct whose halves cannot simply be handed to two messages:
+ * the opening fence would run to the end of the first and the remainder would arrive as
+ * prose, so the second half loses both its monospacing and the escaping that keeps its
+ * contents from being read as markup. Each piece is therefore re-opened and re-closed with
+ * the same language, and every message reads as the code block it is part of.
+ */
+function splitFencedCode(value: string, lang: string | null | undefined, max: number): string[] {
+ const language = typeof lang === "string" ? lang : "";
+ const fence = "`".repeat(Math.max(3, longestBacktickRun(value) + 1));
+ const open = `${fence}${language}`;
+ const room = max - open.length - fence.length - 2; // the two newlines around the body
+ if (room <= 0) return splitHard(value, max); // a max this small has no room for a fence
+ return splitLines(value, room).map((piece) => `${open}\n${piece}\n${fence}`);
+}
+
+/**
+ * Splits one over-long block, preferring the boundaries between its own children.
+ *
+ * The children of a paragraph are its inline runs, so cutting between two of them is what
+ * keeps a `**bold**` or a `[link](…)` out of two messages — split through one, neither
+ * half renders as anything and the reader gets the asterisks. Where the children give no
+ * usable cut (one enormous child, or none at all) the line splitter takes over.
+ */
+function splitBlock(text: string, node: RootContent, max: number): string[] {
+ const span = spanOf(node);
+ if (span === null) return [];
+ const src = text.slice(span.from, span.to);
+ if (src.length <= max) return [src];
+ if (node.type === "code") return splitFencedCode(node.value, node.lang, max);
+ const children: readonly Nodes[] = "children" in node ? node.children : [];
+ const snap = BLOCK_PARENTS.has(node.type);
+ // Ascending, deduped cut offsets strictly inside the block. The first child's start is
+ // not one: everything before it (a list's bullet, a heading's hashes) belongs with it.
+ const cuts: number[] = [];
+ for (const child of children.slice(1)) {
+ const childSpan = spanOf(child);
+ if (childSpan === null) continue;
+ const at = snap ? lineStart(text, childSpan.from) : childSpan.from;
+ if (at > span.from && at < span.to && at !== cuts.at(-1)) cuts.push(at);
+ }
+ if (cuts.length === 0) return splitLines(src, max);
+ const bounds = [span.from, ...cuts, span.to];
+ const out: string[] = [];
+ let buf = "";
+ for (let i = 0; i + 1 < bounds.length; i += 1) {
+ const piece = text.slice(bounds[i]!, bounds[i + 1]!);
+ if (buf !== "" && buf.length + piece.length > max) {
+ out.push(buf);
+ buf = "";
+ }
+ if (piece.length > max) {
+ if (buf !== "") {
+ out.push(buf);
+ buf = "";
+ }
+ for (const part of splitLines(piece, max)) out.push(part);
+ continue;
+ }
+ buf += piece;
+ }
+ if (buf !== "") out.push(buf);
+ return out;
+}
+
+/**
+ * Splits a Markdown reply into pieces of at most `max` characters, each of which parses on
+ * its own as the Markdown it was part of.
+ *
+ * The plain-text chunker splits wherever a newline happens to fall near the limit, which is
+ * fine for text and wrong for markup: a cut between a construct's halves costs the
+ * construct on every channel, and on a channel with a strict parser it costs the whole
+ * message's formatting — the reply still arrives, stripped, through the connector's
+ * fallback, which is the quiet failure this avoids. So the cut is taken at a boundary the
+ * document actually has: between two top-level blocks first, then inside the one block that
+ * is itself too long (see splitBlock), and only then at characters.
+ *
+ * The pieces are slices of the ORIGINAL source, whitespace between blocks included, so a
+ * reply that fits in one message is returned byte for byte.
+ */
+export function chunkMarkdown(text: string, max: number): string[] {
+ const trimmed = text.trim();
+ if (trimmed === "") return [];
+ if (trimmed.length <= max) return [trimmed];
+ const root = parseMarkdown(text);
+ const out: string[] = [];
+ let buf = "";
+ const flush = (): void => {
+ const piece = buf.trim();
+ if (piece !== "") out.push(piece);
+ buf = "";
+ };
+ const blocks = root.children;
+ for (const [i, block] of blocks.entries()) {
+ const span = spanOf(block);
+ if (span === null) continue;
+ // Up to the NEXT block's start rather than this one's end: the blank line between two
+ // paragraphs is what keeps them two paragraphs, and it belongs to whichever message
+ // keeps both of them.
+ const to = spanOf(blocks[i + 1] ?? block)?.from ?? span.to;
+ const src = text.slice(span.from, Math.max(to, span.to));
+ if (src.trimEnd().length > max) {
+ flush();
+ for (const piece of splitBlock(text, block, max)) {
+ buf = piece;
+ flush();
+ }
+ continue;
+ }
+ if (buf !== "" && (buf + src).trimEnd().length > max) flush();
+ buf += src;
+ }
+ flush();
+ return out;
+}
diff --git a/packages/server/src/runtime/messaging/qq-api.ts b/packages/server/src/runtime/messaging/qq-api.ts
index 40d1e45e..82d25537 100644
--- a/packages/server/src/runtime/messaging/qq-api.ts
+++ b/packages/server/src/runtime/messaging/qq-api.ts
@@ -111,7 +111,18 @@ export interface QQInboundEvent {
export interface QQSendArgs {
kind: QQChatKind;
openid: string;
+ /**
+ * The message body. Sent as `msg_type: 0` plain text, unless `markdown` is set — the
+ * platform requires `content` to be EMPTY once a markdown object rides along, so the two
+ * are alternatives rather than a body plus a rendering hint.
+ */
content: string;
+ /**
+ * QQ Markdown (see qq-markdown.ts), sent as `msg_type: 2` with `markdown.content`.
+ * Free-form markdown is open to every bot in single and group chats; the deprecated
+ * template fields are deliberately not used.
+ */
+ markdown?: string;
/** The inbound message being answered — what makes this a passive reply rather than a push. */
msgId: string;
/**
@@ -268,6 +279,16 @@ interface QQErrorBody {
* "the reply window closed" and "the reply count ran out" into a single code, so the text
* has to name both. qq-connector.ts exists largely to keep it from ever being returned.
*/
+/**
+ * The send refusals that say nothing about the message BODY: the reply window closed, the
+ * budget ran out, the user turned bots off. Re-sending the same message in another form
+ * cannot help, and on this channel the attempt costs a slot out of four — so the
+ * markdown-to-text fallback stops at these rather than spending one to learn nothing.
+ */
+export const QQ_BODY_INDEPENDENT_SEND_CODES: ReadonlySet<number> = new Set([
+ 40034128, 40034005, 304103, 40034024, 40034105, 40054013,
+]);
+
export function qqSendErrorText(errCode: number | undefined, message: string): string {
if (errCode === 40034128) {
return `${message} — QQ allows only a few replies to one message, within minutes of it`;
@@ -281,6 +302,26 @@ export function qqSendErrorText(errCode: number | undefined, message: string): s
return message;
}
+/**
+ * A call the platform itself REFUSED, carrying the `err_code` it refused with.
+ *
+ * Its own class for the reason telegram-api's TelegramApiError is one: a refusal and a
+ * request that never completed are the same outcome and opposite facts. The platform
+ * answered, so nothing was delivered and the same message may safely be sent again in
+ * another form — which is what the markdown-to-text fallback does. A timeout or a reset
+ * carries no code, stays a plain Error, and must never be retried: it may already have been
+ * delivered, and on this channel a retry also spends another slot of a four-reply budget.
+ */
+export class QQApiError extends Error {
+ constructor(
+ message: string,
+ readonly code: number | undefined,
+ ) {
+ super(message);
+ this.name = "QQApiError";
+ }
+}
+
export interface QQTransportOpts {
/** Test hook: gateway reconnect backoff (default: exponential, 1s → 60s). */
gatewayRetryMs?: (failures: number) => number;
@@ -378,8 +419,11 @@ function createProductionClient(creds: QQCredentials): ProductionClient {
}
const errCode = body?.err_code ?? body?.code;
const detail = qqSendErrorText(errCode, body?.message ?? `HTTP ${res.status}`);
- throw new Error(
+ // The platform answered, whatever it said: a refused request delivered nothing, which is
+ // what makes another form of the same message safe to send (see QQApiError).
+ throw new QQApiError(
`Message send failed: ${detail}${errCode !== undefined ? ` (code ${errCode})` : ""}`,
+ errCode,
);
};
@@ -393,10 +437,14 @@ function createProductionClient(creds: QQCredentials): ProductionClient {
args.kind === "group"
? `/v2/groups/${encodeURIComponent(args.openid)}/messages`
: `/v2/users/${encodeURIComponent(args.openid)}/messages`;
+ const markdown = args.markdown;
return post(path, {
- content: args.content,
- // 0 = plain text. Markdown, ark and rich-media types each need separate approval.
- msg_type: 0,
+ // "传了 markdown 后此字段必须为空" — the platform rejects a payload carrying both.
+ content: markdown === undefined ? args.content : "",
+ // 0 = plain text, 2 = markdown. Rich media (7) needs a publicly reachable URL for the
+ // bytes, which is why this channel refuses outbound files (see qq-connector).
+ msg_type: markdown === undefined ? 0 : 2,
+ ...(markdown !== undefined ? { markdown: { content: markdown } } : {}),
msg_id: args.msgId,
msg_seq: args.msgSeq,
});
diff --git a/packages/server/src/runtime/messaging/qq-connector.ts b/packages/server/src/runtime/messaging/qq-connector.ts
index bf707082..9aaba2ce 100644
--- a/packages/server/src/runtime/messaging/qq-connector.ts
+++ b/packages/server/src/runtime/messaging/qq-connector.ts
@@ -72,14 +72,16 @@
* reads as no text, which the bridge answers with its notice) and outbound files are
* refused with a reason — see refuseMedia, which explains what QQ would require.
*/
-import { chunkMessagingText } from "./bridge.js";
+import { MESSAGING_TEXT_CHUNK_CHARS, chunkMessagingText } from "./bridge.js";
import { MessagingUnsupportedError } from "./media.js";
import type {
MessagingChannelConnector,
MessagingClient,
MessagingConnection,
MessagingConnectorHandlers,
+ MessagingSendOptions,
} from "./connector.js";
+import { chunkMarkdown } from "./markdown.js";
import type {
QQBotClient,
QQChatKind,
@@ -87,6 +89,8 @@ import type {
QQInboundEvent,
QQTransport,
} from "./qq-api.js";
+import { QQ_BODY_INDEPENDENT_SEND_CODES, QQApiError } from "./qq-api.js";
+import { qqMarkdownOf } from "./qq-markdown.js";
/** The QQ binding's stored config document (`messaging_bindings.config_json`). */
export interface QQBindingConfig extends Record<string, unknown> {
@@ -256,6 +260,12 @@ interface QQReplyLedger {
spent: number;
/** Text withheld for the reserved final slot. */
tail: string[];
+ /**
+ * Whether the withheld tail goes out as Markdown. The binding's own preference, carried
+ * on the chat rather than on each body: it is one saved setting and it does not change
+ * within a run, while the tail is combined into a single message that needs one answer.
+ */
+ markdown: boolean;
/**
* The client the last send used, which is the one a deferred flush uses too. Held here
* rather than passed in: a flush can be triggered by an INBOUND event, whose path has no
@@ -305,9 +315,13 @@ export class QQConnector implements MessagingChannelConnector {
async createClient(config: Record<string, unknown>): Promise<MessagingClient> {
const creds = qqConfigOf(config);
const bot = this.transport.createClient(creds);
- const deliver = (chatId: string, text: string): Promise<void> => {
+ const deliver = (
+ chatId: string,
+ text: string,
+ opts: MessagingSendOptions | undefined,
+ ): Promise<void> => {
const { kind, openid } = parseQQChatId(chatId);
- return this.enqueue(creds, bot, kind, openid, text);
+ return this.enqueue(creds, bot, kind, openid, text, opts?.markdown === true);
};
// Assembled into a variable rather than returned as a literal: the media methods below
// are refusals rather than implementations, and a channel that grows one later should
@@ -320,12 +334,13 @@ export class QQConnector implements MessagingChannelConnector {
// back would confirm nothing.
return null;
},
- sendText: (chatId: string, text: string) => deliver(chatId, text),
+ sendText: (chatId: string, text: string, opts?: MessagingSendOptions) =>
+ deliver(chatId, text, opts),
// Same operation as sendText: `msg_id` is an authorization anchor on QQ, not a
// visible quote, so there is no threading to honour (see the module doc).
- replyText: (ref: string, text: string) => {
+ replyText: (ref: string, text: string, opts?: MessagingSendOptions) => {
const { kind, openid } = chatOfReplyRef(ref);
- return this.enqueue(creds, bot, kind, openid, text);
+ return this.enqueue(creds, bot, kind, openid, text, opts?.markdown === true);
},
sendImage: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),
sendFile: (_chatId: string, file: QQOutboundFile) => refuseMedia(file),
@@ -396,6 +411,7 @@ export class QQConnector implements MessagingChannelConnector {
receivedAt: 0,
spent: 0,
tail: [],
+ markdown: false,
bot: null,
timer: null,
chain: Promise.resolve(),
@@ -479,9 +495,11 @@ export class QQConnector implements MessagingChannelConnector {
kind: QQChatKind,
openid: string,
text: string,
+ markdown: boolean,
): Promise<void> {
const ledger = this.ledgerFor(creds.appId, kind, openid);
ledger.bot = bot;
+ ledger.markdown = markdown;
if (!this.repliable(ledger)) {
// `async` so this is a rejection rather than a synchronous throw: the seam's methods
// are typed as promises, and a caller that only attaches `.catch` — as any caller
@@ -496,7 +514,7 @@ export class QQConnector implements MessagingChannelConnector {
}
const budget = QQ_REPLY_BUDGET[kind];
if (ledger.spent < budget - 1) {
- await this.chain(ledger, () => this.sendNow(ledger, text));
+ await this.chain(ledger, () => this.sendNow(ledger, text, markdown));
return;
}
this.withhold(ledger, text);
@@ -535,7 +553,12 @@ export class QQConnector implements MessagingChannelConnector {
private async flush(ledger: QQReplyLedger): Promise<void> {
if (ledger.tail.length === 0) return;
if (!this.repliable(ledger) || ledger.spent >= QQ_REPLY_BUDGET[ledger.kind]) return;
- const chunks = chunkMessagingText(ledger.tail.join("\n\n"));
+ const combined = ledger.tail.join("\n\n");
+ // Chunked the same way the bridge chunks a reply, so the cut lands where the document
+ // has a boundary rather than through a construct (see markdown.ts chunkMarkdown).
+ const chunks = ledger.markdown
+ ? chunkMarkdown(combined, MESSAGING_TEXT_CHUNK_CHARS)
+ : chunkMessagingText(combined);
const head = chunks[0];
if (head === undefined) {
ledger.tail = [];
@@ -543,7 +566,7 @@ export class QQConnector implements MessagingChannelConnector {
}
ledger.tail = chunks.slice(1);
try {
- await this.sendNow(ledger, head);
+ await this.sendNow(ledger, head, ledger.markdown);
} catch (err) {
// The slot is spent (sendNow reserves the sequence number before the wire) but the
// TEXT is not lost: `head` goes back to the front of the tail, so the next inbound
@@ -554,21 +577,45 @@ export class QQConnector implements MessagingChannelConnector {
}
}
- /** One real send: the next `msg_seq` against the ledger's anchor message. */
- private async sendNow(ledger: QQReplyLedger, text: string): Promise<void> {
+ /**
+ * One real send: the next `msg_seq` against the ledger's anchor message, as Markdown when
+ * the binding asked for it and as plain text if the platform refuses that.
+ *
+ * The fallback costs a SLOT here, which it does on no other channel: a repeated
+ * `(msg_id, msg_seq)` pair is refused rather than deduplicated, so the retry must carry a
+ * fresh sequence number and that number is one of the four an inbound message funds. It is
+ * still the right trade — a reply the reader never sees is worse than a reply that spent
+ * an extra slot — but it is only taken while a slot remains, and never for a refusal that
+ * was not about the body in the first place (see QQ_BODY_INDEPENDENT_SEND_CODES): those
+ * would fail identically as text and burn the slot reserved for the withheld tail.
+ */
+ private async sendNow(ledger: QQReplyLedger, text: string, markdown: boolean): Promise<void> {
const msgId = ledger.msgId;
const bot = ledger.bot;
if (msgId === null || bot === null) return;
- // Reserved before the await: a rejected send has still consumed its sequence number,
- // and reusing one is refused by the platform (40054005) rather than retried.
- ledger.spent += 1;
- await bot.sendMessage({
- kind: ledger.kind,
- openid: ledger.openid,
- content: text,
- msgId,
- msgSeq: ledger.spent,
- });
+ const send = (body: Partial<{ markdown: string }>): Promise<void> => {
+ // Reserved before the await: a rejected send has still consumed its sequence number,
+ // and reusing one is refused by the platform (40054005) rather than retried.
+ ledger.spent += 1;
+ return bot.sendMessage({
+ kind: ledger.kind,
+ openid: ledger.openid,
+ content: text,
+ ...body,
+ msgId,
+ msgSeq: ledger.spent,
+ });
+ };
+ if (!markdown) return send({});
+ try {
+ await send({ markdown: qqMarkdownOf(text) });
+ return;
+ } catch (err) {
+ if (!(err instanceof QQApiError)) throw err;
+ if (err.code !== undefined && QQ_BODY_INDEPENDENT_SEND_CODES.has(err.code)) throw err;
+ if (ledger.spent >= QQ_REPLY_BUDGET[ledger.kind]) throw err;
+ }
+ await send({});
}
/**
diff --git a/packages/server/src/runtime/messaging/qq-markdown.ts b/packages/server/src/runtime/messaging/qq-markdown.ts
new file mode 100644
index 00000000..2a9c82a4
--- /dev/null
+++ b/packages/server/src/runtime/messaging/qq-markdown.ts
@@ -0,0 +1,247 @@
+/**
+ * Renders a parsed Markdown reply into QQ's free-form Markdown message
+ * (https://bot.q.qq.com/wiki/develop/api-v2/server-inter/message/type/markdown.html),
+ * carried by `msg_type: 2` as `markdown.content`.
+ *
+ * The platform's own subset, and it is a third shape again rather than a smaller Feishu:
+ * headings, bold, italic, strikethrough, links, images, ordered and unordered lists with
+ * nesting, blockquotes, horizontal rules and line breaks all render — while INLINE CODE,
+ * FENCED CODE and TABLES have no syntax at all here. QQ renders headings and lists that
+ * Telegram cannot, and cannot render the code that both other channels can.
+ *
+ * ## Code, which is most of what this product writes
+ *
+ * There is no monospaced anything to fall back to, so the deliberate answer is: a code
+ * block's lines go out as ordinary lines, escaped, with a blank line above and below to set
+ * the block off from the prose around it. The alternatives were considered and rejected —
+ * a fence arrives as six literal backticks, an indent spends the narrow width a phone gives
+ * on nothing, and a per-line marker corrupts the copy-paste that is the whole point of
+ * putting code in a chat. Inline code loses its backticks the same way and becomes its own
+ * text. The language tag has nowhere to go and is dropped.
+ *
+ * ## Escaping
+ *
+ * The platform documents NO escaping rule — not entities like Feishu, not backslashes.
+ * Backslash escaping is what every Markdown implementation this syntax is derived from
+ * supports, so that is what this emits, and the choice is safe in the direction that
+ * matters: if QQ honours it, the text is exact; if it does not, a `\` becomes visible in
+ * front of a character that is already there. Escaping can only ever ADD a character.
+ * Leaving code unescaped cannot — `# comment` would become a heading and `_name_` would
+ * become italics, and both LOSE the characters they ate. For a channel with no documented
+ * escape, never losing a character is the invariant to hold.
+ *
+ * The always-escaped set is what means something anywhere; `#`, `>`, the bullets and the
+ * ordered markers mean something only at the head of a line and are escaped only there, so
+ * ordinary hyphens and decimals stay ordinary.
+ */
+import { isSafeUrl, parseMarkdown } from "./markdown.js";
+import type {
+ BlockContent,
+ DefinitionContent,
+ List,
+ ListItem,
+ PhrasingContent,
+ RootContent,
+ Table,
+} from "mdast";
+
+/** One indent level inside a list, as the platform's own documentation specifies. */
+const LIST_INDENT = " ";
+
+/** The horizontal rule QQ documents. `---` is not it. */
+const RULE = "***";
+
+/** Characters that open a construct wherever they appear. `\` leads, or it would escape the escapes. */
+const INLINE_SPECIALS = /[\\`*_~[\]<]/g;
+
+/** Backslash-escapes literal text (see the module doc for why backslashes and not entities). */
+function esc(text: string): string {
+ return text.replace(INLINE_SPECIALS, (ch) => `\\${ch}`);
+}
+
+/**
+ * Escapes a marker a line happens to START with. These mean nothing mid-line, and escaping
+ * them everywhere would put a backslash in every hyphenated word and every decimal number.
+ */
+function guardLineStarts(text: string): string {
+ return text
+ .split("\n")
+ .map((line) => line.replace(/^(\s*)([#>\-+=])/, "$1\\$2").replace(/^(\s*\d+)([.)])/, "$1\\$2"))
+ .join("\n");
+}
+
+/** Every line of a block escaped as literal text, markers included. */
+function escLines(value: string): string {
+ return guardLineStarts(esc(value));
+}
+
+/** A link target, with the two characters that would close the `](…)` early made safe. */
+function href(url: string): string {
+ return url.replaceAll("(", "%28").replaceAll(")", "%29");
+}
+
+function inline(nodes: readonly PhrasingContent[]): string {
+ return nodes.map(phrasing).join("");
+}
+
+function phrasing(node: PhrasingContent): string {
+ switch (node.type) {
+ case "text":
+ return esc(node.value);
+ case "strong":
+ return `**${inline(node.children)}**`;
+ case "emphasis":
+ // `*text*` rather than `_text_`: both are documented, and the asterisk form cannot be
+ // confused with the underscores in an identifier.
+ return `*${inline(node.children)}*`;
+ case "delete":
+ return `~~${inline(node.children)}~~`;
+ case "inlineCode":
+ // No inline code on this channel — the backticks would arrive as backticks.
+ return esc(node.value);
+ case "link": {
+ const label = inline(node.children);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "image": {
+ // QQ's image syntax needs pixel dimensions and a publicly reachable URL, neither of
+ // which a reply's `![alt](…)` carries — so a remote image is a link, like everywhere
+ // else here. The reply's own pictures cannot travel on this channel at all (see
+ // qq-connector's refuseMedia).
+ const alt = node.alt ?? "";
+ const label = esc(alt !== "" ? alt : node.url);
+ return isSafeUrl(node.url) ? `[${label}](${href(node.url)})` : label;
+ }
+ case "break":
+ // A newline IS a line break here: the platform's own example separates lines with one
+ // and needs no blank line between them.
+ return "\n";
+ case "html":
+ return esc(node.value);
+ case "footnoteReference":
+ return esc(`[^${node.identifier}]`);
+ case "linkReference":
+ case "imageReference":
+ return "children" in node ? inline(node.children) : esc(node.label ?? node.identifier);
+ default:
+ return "";
+ }
+}
+
+/** Inline content as unformatted text, for the rows of a table that cannot be a table. */
+function plainText(nodes: readonly PhrasingContent[]): string {
+ return nodes
+ .map((node) => {
+ if (node.type === "text" || node.type === "inlineCode" || node.type === "html") {
+ return node.value;
+ }
+ if (node.type === "break") return " ";
+ if (node.type === "image") return node.alt ?? "";
+ return "children" in node ? plainText(node.children) : "";
+ })
+ .join("");
+}
+
+/**
+ * A table's rows as lines. There is no table syntax here and no monospace to align one in,
+ * so the pipes stay: they are what still says which value belongs to which column.
+ */
+function renderTable(node: Table): string {
+ return escLines(
+ node.children
+ .map((row) => `| ${row.children.map((cell) => plainText(cell.children)).join(" | ")} |`)
+ .join("\n"),
+ );
+}
+
+function itemMarker(list: List, index: number): string {
+ return list.ordered === true ? `${(list.start ?? 1) + index}. ` : "- ";
+}
+
+/** A GFM task item's box. QQ has no checkbox, so the glyph is the checkbox. */
+function itemCheckbox(item: ListItem): string {
+ if (item.checked === true) return "☑ ";
+ if (item.checked === false) return "☐ ";
+ return "";
+}
+
+function renderList(list: List, indent: string): string {
+ return list.children
+ .map((item, i) => {
+ const head = `${indent}${itemMarker(list, i)}${itemCheckbox(item)}`;
+ const parts: string[] = [];
+ for (const [j, child] of item.children.entries()) {
+ if (j === 0 && child.type === "paragraph") {
+ parts.push(head + inline(child.children));
+ continue;
+ }
+ if (child.type === "list") {
+ parts.push(renderList(child, indent + LIST_INDENT));
+ continue;
+ }
+ const rendered = block(child, indent + LIST_INDENT);
+ if (rendered !== "") {
+ parts.push(
+ rendered
+ .split("\n")
+ .map((line) => indent + LIST_INDENT + line)
+ .join("\n"),
+ );
+ }
+ }
+ return parts.filter((part) => part !== "").join("\n");
+ })
+ .filter((line) => line !== "")
+ .join("\n");
+}
+
+function block(node: BlockContent | DefinitionContent | RootContent, indent: string): string {
+ switch (node.type) {
+ case "paragraph":
+ return guardLineStarts(inline(node.children));
+ case "heading":
+ return `${"#".repeat(Math.min(node.depth, 6))} ${inline(node.children)}`;
+ case "code":
+ // Plain escaped lines — see the module doc. The blank lines around every block put
+ // this one on its own, which is all the setting-apart the channel offers.
+ return escLines(node.value);
+ case "blockquote":
+ return node.children
+ .map((child) => block(child, indent))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ case "list":
+ return renderList(node, indent);
+ case "table":
+ return renderTable(node);
+ case "thematicBreak":
+ return RULE;
+ case "html":
+ return escLines(node.value);
+ case "footnoteDefinition":
+ return `**${esc(`[^${node.identifier}]`)}** ${node.children.map((child) => block(child, indent)).join("\n\n")}`;
+ case "definition":
+ return "";
+ default:
+ return "";
+ }
+}
+
+/**
+ * One relayed message as QQ Markdown.
+ *
+ * Blocks are separated by a blank line throughout, which the platform requires in the one
+ * case it names — "a list preceded by ordinary text needs a blank line before it, or it is
+ * not recognized" — and tolerates everywhere else.
+ */
+export function qqMarkdownOf(markdown: string): string {
+ const root = parseMarkdown(markdown);
+ return root.children
+ .map((node) => block(node, ""))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .trim();
+}
diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.ts
index 8fc44702..5d487b95 100644
--- a/packages/server/src/runtime/messaging/telegram-api.ts
+++ b/packages/server/src/runtime/messaging/telegram-api.ts
@@ -197,6 +197,13 @@ export interface TelegramBotClient {
text: string;
replyToMessageId?: number;
messageThreadId?: number;
+ /**
+ * How `text` is to be parsed. Omitted, it is delivered verbatim — which is what every
+ * fixed notice wants. `"HTML"` reads it as Telegram's closed tag set (see
+ * telegram-html.ts); a construct it dislikes is a 400 for the WHOLE message, so a
+ * caller that sets it must have a plain-text send to fall back to.
+ */
+ parseMode?: "HTML";
}): Promise<void>;
/**
* Long-poll for updates: blocks up to `timeoutSec` (0 = return immediately) and resolves
@@ -425,10 +432,17 @@ export function createTelegramTransport(opts: TelegramTransportOpts = {}): Teleg
return {
getMe: () => call<TelegramBotUser>("getMe", {}),
getWebhookInfo: () => call<TelegramWebhookInfo>("getWebhookInfo", {}),
- async sendMessage({ chatId, text, replyToMessageId, messageThreadId }): Promise<void> {
+ async sendMessage({
+ chatId,
+ text,
+ replyToMessageId,
+ messageThreadId,
+ parseMode,
+ }): Promise<void> {
await call("sendMessage", {
chat_id: wireChatId(chatId),
text,
+ ...(parseMode !== undefined ? { parse_mode: parseMode } : {}),
...(messageThreadId !== undefined ? { message_thread_id: messageThreadId } : {}),
// Degrade to a plain send when the replied-to message is gone, rather than fail.
...(replyToMessageId !== undefined
diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.ts
index 1ca0af48..a457a65b 100644
--- a/packages/server/src/runtime/messaging/telegram-connector.ts
+++ b/packages/server/src/runtime/messaging/telegram-connector.ts
@@ -47,6 +47,7 @@ import type {
MessagingSendNote,
} from "./connector.js";
import { imageMimeOfName } from "./media.js";
+import { telegramHtmlOf } from "./telegram-html.js";
import type {
TelegramBotClient,
TelegramBotUser,
@@ -195,7 +196,7 @@ const THREAD_DROPPED_NOTE = "forum topic gone, the reply went to General instead
*/
async function sendWithThreadFallback(
bot: TelegramBotClient,
- args: { chatId: string; text: string; replyToMessageId?: number },
+ args: { chatId: string; text: string; replyToMessageId?: number; parseMode?: "HTML" },
threadId: number | undefined,
): Promise<MessagingSendNote | void> {
if (threadId === undefined) {
@@ -212,6 +213,45 @@ async function sendWithThreadFallback(
return THREAD_DROPPED_NOTE;
}
+/**
+ * One send, rendered as HTML when the binding asked for it, degrading to the plain text if
+ * Telegram will not parse it.
+ *
+ * The formatted attempt can fail for a reason no amount of care here prevents: the tag set
+ * is closed and the parser is strict, so a construct combination it dislikes answers 400
+ * `Bad Request: can't parse entities`, and the whole message is refused. A reply is never
+ * worth that. The plain text — what the model actually wrote, `**` and all — goes out
+ * instead, and the reader loses the formatting rather than the answer.
+ *
+ * ANY 400 is retried, not a 400 whose description mentions entities. `description` is prose
+ * Telegram rewords without notice (see telegram-api's TelegramApiError), and there is no
+ * distinct code for a parse failure; a 400 from some other cause simply fails again on the
+ * plain attempt and reaches the caller as it always did, one wasted request later. Every
+ * other shape propagates on its first attempt for the reasons sendWithThreadFallback gives:
+ * a 429 must not be answered with a second request, and a transport failure may already
+ * have delivered the message.
+ *
+ * The order matters. The entity fallback wraps the THREAD fallback rather than the other
+ * way round, so a parse failure inside a forum topic — which the inner retry cannot fix,
+ * both of its attempts carrying the same bad HTML — still ends in a plain send that keeps
+ * the topic.
+ */
+async function sendFormatted(
+ bot: TelegramBotClient,
+ args: { chatId: string; text: string; replyToMessageId?: number },
+ threadId: number | undefined,
+ markdown: boolean,
+): Promise<MessagingSendNote | void> {
+ if (!markdown) return sendWithThreadFallback(bot, args, threadId);
+ const html = telegramHtmlOf(args.text);
+ try {
+ return await sendWithThreadFallback(bot, { ...args, text: html, parseMode: "HTML" }, threadId);
+ } catch (err) {
+ if (!(err instanceof TelegramApiError) || err.errorCode !== 400) throw err;
+ }
+ return sendWithThreadFallback(bot, args, threadId);
+}
+
/** Whether this entity is a mention OF the bot itself, by either of the two shapes Telegram uses. */
function mentionsBot(text: string, entity: TelegramMessageEntity, me: TelegramBotUser): boolean {
if (entity.type === "text_mention") return entity.user?.id === me.id;
@@ -421,17 +461,22 @@ export class TelegramConnector implements MessagingChannelConnector {
: {}),
};
},
- sendText(chatRef, text) {
+ sendText(chatRef, text, opts) {
const { chatId, threadId } = parseChatRef(chatRef);
- return sendWithThreadFallback(bot, { chatId, text }, threadId);
+ return sendFormatted(bot, { chatId, text }, threadId, opts?.markdown === true);
},
- replyText(messageRef, text) {
+ replyText(messageRef, text, opts) {
const { chatId, messageId, threadId } = parseReplyRef(messageRef);
// The thread rides along even though a reply normally inherits its target's topic:
// `allow_sending_without_reply` degrades a vanished target to a plain send, and a
// plain send with no thread lands in General — losing the topic exactly when the
// conversation is least able to spare it.
- return sendWithThreadFallback(bot, { chatId, text, replyToMessageId: messageId }, threadId);
+ return sendFormatted(
+ bot,
+ { chatId, text, replyToMessageId: messageId },
+ threadId,
+ opts?.markdown === true,
+ );
},
async sendImage(chatId, file) {
await bot.sendPhoto({ chatId, fileName: file.fileName, data: file.data });
diff --git a/packages/server/src/runtime/messaging/telegram-html.ts b/packages/server/src/runtime/messaging/telegram-html.ts
new file mode 100644
index 00000000..5a1b0d79
--- /dev/null
+++ b/packages/server/src/runtime/messaging/telegram-html.ts
@@ -0,0 +1,239 @@
+/**
+ * Renders a parsed Markdown reply into Telegram's HTML parse mode.
+ *
+ * HTML rather than MarkdownV2, which the Bot API also offers. Two reasons, and both are
+ * about what happens when the model writes something unexpected. MarkdownV2 reserves
+ * eighteen characters that must be backslash-escaped ANYWHERE they appear, including inside
+ * what looks like an entity, so one missed character turns the whole message into a 400;
+ * HTML reserves three (`&`, `<`, `>`). And an unsupported construct in HTML degrades — an
+ * unknown tag is refused, but text that merely looks like markup is text — where in
+ * MarkdownV2 a stray `[` derails the parse of everything after it.
+ *
+ * ## What Telegram can and cannot show
+ *
+ * The tag set is small and CLOSED (https://core.telegram.org/bots/api#html-style): `b i u s
+ * tg-spoiler a code pre blockquote`, plus the aliases and the two custom tags this does not
+ * use. "Only the tags mentioned above are currently supported" — anything else is a 400,
+ * not a fallback. So three constructs the model writes constantly have no tag at all and
+ * need a deliberate answer:
+ *
+ * - **Headings** become a bold line. Telegram has no heading of any level, and depth is not
+ * recoverable from a chat bubble anyway — `<b>` is what a reader reads as "this names the
+ * section".
+ * - **Lists** become their marker as literal text: `• ` for a bullet, `1. ` for a number,
+ * two spaces of indent per nesting level. The marker has to be in the text because
+ * Telegram will not draw one.
+ * - **Tables** become a `<pre>` block of their own rows. A chat has no table, and pipe-
+ * separated rows in a proportional font do not line up — inside `<pre>` they do, which is
+ * the whole of what a table was for.
+ *
+ * ## Escaping
+ *
+ * Every literal `&`, `<` and `>` the model wrote is entity-escaped, `&` first so the
+ * escapes cannot escape each other. That is what makes `5 < 6` arrive as `5 < 6` rather
+ * than as a 400, and what keeps a `<script>` in a code block a `<script>` in a code block:
+ * the bytes reach `<pre>` as `&lt;script&gt;` and Telegram renders them as text. A raw HTML
+ * node in the model's own Markdown gets exactly the same treatment — it is text the model
+ * typed, never markup this server passes through, since passing it through is how a closed
+ * tag set becomes a 400 for the whole message.
+ */
+import { isSafeUrl, parseMarkdown } from "./markdown.js";
+import type {
+ BlockContent,
+ DefinitionContent,
+ List,
+ ListItem,
+ PhrasingContent,
+ RootContent,
+ Table,
+} from "mdast";
+
+/** Telegram's own rule: "All <, > and & symbols that are not a part of a tag … must be replaced". */
+function esc(text: string): string {
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
+}
+
+/** The same, plus the quote that would otherwise close an attribute. `&quot;` is one of the four named entities Telegram accepts. */
+function escAttr(text: string): string {
+ return esc(text).replaceAll('"', "&quot;");
+}
+
+/**
+ * The `language-…` class on a `<pre><code>`. Restricted to what a language tag can be
+ * because the value comes from the model: a fence's info string is free text, and it is
+ * being written into an attribute.
+ */
+function languageClass(lang: string | null | undefined): string {
+ if (typeof lang !== "string" || !/^[A-Za-z0-9+#._-]{1,20}$/.test(lang)) return "";
+ return ` class="language-${lang}"`;
+}
+
+/** The horizontal rule, as text. Telegram has no `<hr>`; three em dashes read as one. */
+const RULE = "———";
+
+function inline(nodes: readonly PhrasingContent[]): string {
+ return nodes.map(phrasing).join("");
+}
+
+function phrasing(node: PhrasingContent): string {
+ switch (node.type) {
+ case "text":
+ return esc(node.value);
+ case "strong":
+ return `<b>${inline(node.children)}</b>`;
+ case "emphasis":
+ return `<i>${inline(node.children)}</i>`;
+ case "delete":
+ return `<s>${inline(node.children)}</s>`;
+ case "inlineCode":
+ // No language on a standalone `code` tag — the Bot API says so explicitly, and the
+ // attribute would be refused rather than ignored.
+ return `<code>${esc(node.value)}</code>`;
+ case "link": {
+ const label = inline(node.children);
+ // An unrenderable scheme keeps its label and loses only its clickability: the reader
+ // still sees everything the model wrote.
+ return isSafeUrl(node.url) ? `<a href="${escAttr(node.url)}">${label}</a>` : label;
+ }
+ case "image": {
+ // Telegram cannot place an image inside a text message, and the reply's OWN pictures
+ // arrive separately (see reply-files.ts). A remote one is therefore a link, labelled
+ // with its alt text where the model wrote one.
+ const alt = node.alt ?? "";
+ const label = esc(alt !== "" ? alt : node.url);
+ return isSafeUrl(node.url) ? `<a href="${escAttr(node.url)}">${label}</a>` : label;
+ }
+ case "break":
+ return "\n";
+ case "html":
+ // Text the model typed, not markup to forward — see the module doc.
+ return esc(node.value);
+ case "footnoteReference":
+ return esc(`[^${node.identifier}]`);
+ case "linkReference":
+ case "imageReference":
+ // A reference whose definition sits elsewhere in the reply, or nowhere. Its label is
+ // the part the reader was meant to read.
+ return "children" in node ? inline(node.children) : esc(node.label ?? node.identifier);
+ default:
+ return "";
+ }
+}
+
+/** One line of a table, as its cells were written. */
+function tableRows(node: Table): string[] {
+ return node.children.map((row) => {
+ const cells = row.children.map((cell) => plainText(cell.children));
+ return `| ${cells.join(" | ")} |`;
+ });
+}
+
+/**
+ * Inline content flattened to unformatted text, for the places a tag cannot go: inside
+ * `<pre>`, where Telegram permits no nested formatting at all.
+ */
+function plainText(nodes: readonly PhrasingContent[]): string {
+ return nodes
+ .map((node) => {
+ if (node.type === "text" || node.type === "inlineCode" || node.type === "html") {
+ return node.value;
+ }
+ if (node.type === "break") return " ";
+ if (node.type === "image") return node.alt ?? "";
+ return "children" in node ? plainText(node.children) : "";
+ })
+ .join("");
+}
+
+/** The bullet or number that opens a list item, plus the indent of its nesting level. */
+function itemMarker(list: List, index: number): string {
+ if (list.ordered !== true) return "• ";
+ return `${(list.start ?? 1) + index}. `;
+}
+
+/** A GFM task item's box, drawn since Telegram has no checkbox of its own. */
+function itemCheckbox(item: ListItem): string {
+ if (item.checked === true) return "☑ ";
+ if (item.checked === false) return "☐ ";
+ return "";
+}
+
+function renderList(list: List, indent: string): string {
+ return list.children
+ .map((item, i) => {
+ const head = `${indent}${itemMarker(list, i)}${itemCheckbox(item)}`;
+ const parts: string[] = [];
+ for (const [j, child] of item.children.entries()) {
+ // The item's first paragraph shares the marker's line; everything after it is a
+ // block of its own, indented under the marker.
+ if (j === 0 && child.type === "paragraph") {
+ parts.push(head + inline(child.children));
+ continue;
+ }
+ if (child.type === "list") {
+ parts.push(renderList(child, `${indent} `));
+ continue;
+ }
+ const rendered = block(child, `${indent} `);
+ parts.push(rendered === "" ? "" : `${indent} ${rendered}`);
+ }
+ return parts.filter((part) => part !== "").join("\n");
+ })
+ .filter((line) => line !== "")
+ .join("\n");
+}
+
+function block(node: BlockContent | DefinitionContent | RootContent, indent: string): string {
+ switch (node.type) {
+ case "paragraph":
+ return inline(node.children);
+ case "heading":
+ // No heading tag exists; a bold line is what a chat reads as one.
+ return `<b>${inline(node.children)}</b>`;
+ case "code": {
+ // The two forms the Bot API documents and no third: a bare `pre` with no language, and
+ // a `pre` wrapping a `code` that carries one. The nested pair exists only to name the
+ // language ("Use nested pre and code tags, to define programming language").
+ const cls = languageClass(node.lang);
+ const body = esc(node.value);
+ return cls === "" ? `<pre>${body}</pre>` : `<pre><code${cls}>${body}</code></pre>`;
+ }
+ case "blockquote":
+ // Telegram's blockquote does not nest: a quote inside a quote renders its contents
+ // once, at the outer level, rather than risking a refused tag pair.
+ return `<blockquote>${node.children.map((child) => (child.type === "blockquote" ? child.children.map((inner) => block(inner, indent)).join("\n\n") : block(child, indent))).join("\n\n")}</blockquote>`;
+ case "list":
+ return renderList(node, indent);
+ case "table":
+ // A monospaced block is the only place pipe-separated rows line up.
+ return `<pre>${esc(tableRows(node).join("\n"))}</pre>`;
+ case "thematicBreak":
+ return RULE;
+ case "html":
+ return esc(node.value);
+ case "footnoteDefinition":
+ return `<b>${esc(`[^${node.identifier}]`)}</b> ${node.children.map((child) => block(child, indent)).join("\n\n")}`;
+ case "definition":
+ // A link definition is invisible in the source and stays invisible here.
+ return "";
+ default:
+ return "";
+ }
+}
+
+/**
+ * One relayed message as Telegram HTML.
+ *
+ * The result is what `sendMessage` carries under `parse_mode: "HTML"`. It can still be
+ * refused — a construct combination Telegram dislikes answers 400 `can't parse entities` —
+ * which is why the connector sends the plain text behind it rather than trusting this
+ * (see telegram-connector's sendFormatted). A reply is never worth a formatting bug.
+ */
+export function telegramHtmlOf(markdown: string): string {
+ const root = parseMarkdown(markdown);
+ return root.children
+ .map((node) => block(node, ""))
+ .filter((rendered) => rendered !== "")
+ .join("\n\n")
+ .trim();
+}
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index 43081f06..f52d4de1 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -433,6 +433,70 @@ describe("openDatabase table and index upgrades", () => {
}
}
+ /**
+ * Seeds a database in the shape it had before messaging_bindings.render_markdown existed:
+ * today's schema with that column dropped. Same derivation rule as the helpers around it.
+ */
+ function seedPreRenderMarkdownDb(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 render_markdown");
+ seed(db);
+ } finally {
+ db.close();
+ }
+ }
+
+ it("adds render_markdown to a messaging_bindings formed before it, existing rows ON", () => {
+ const dbPath = path.join(dir, "web-md.db");
+ const ts = "2026-01-01T00:00:00.000Z";
+ seedPreRenderMarkdownDb(dbPath, (old) => {
+ old
+ .prepare(
+ `INSERT INTO messaging_bindings
+ (session_id, channel, account_id, config_json, enabled, created_at, updated_at)
+ VALUES ('session-old', 'feishu', 'cli_x', '{"appId":"cli_x"}', 1, ?, ?)`,
+ )
+ .run(ts, ts);
+ });
+ const before = new sqlite.DatabaseSync(dbPath);
+ try {
+ const columns = before.prepare("PRAGMA table_info(messaging_bindings)").all() as {
+ name: string;
+ }[];
+ expect(columns.map((c) => c.name)).not.toContain("render_markdown");
+ } finally {
+ before.close();
+ }
+
+ const db = openDatabase(dbPath);
+ try {
+ const repo = new MessagingBindingsRepo(db);
+ const row = repo.find("session-old", "feishu");
+ // ON, unlike every other added flag: this column's default is the CORRECTED behaviour
+ // rather than the previous one, so an existing binding starts rendering Markdown after
+ // the upgrade. That is a visible change to every relayed message and is deliberate —
+ // relaying the model's Markdown as characters was the defect.
+ expect(row?.renderMarkdown).toBe(true);
+ // Nothing else about the row moved.
+ expect(row?.enabled).toBe(true);
+ expect(row?.config.appId).toBe("cli_x");
+ // And it is writable immediately, in the direction a user would actually want.
+ expect(
+ repo.upsert({
+ sessionId: "session-old",
+ channel: "feishu",
+ accountId: "cli_x",
+ config: { appId: "cli_x" },
+ renderMarkdown: false,
+ }).renderMarkdown,
+ ).toBe(false);
+ } 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";
diff --git a/packages/server/test/messaging-markdown.test.ts b/packages/server/test/messaging-markdown.test.ts
new file mode 100644
index 00000000..2f2e6577
--- /dev/null
+++ b/packages/server/test/messaging-markdown.test.ts
@@ -0,0 +1,394 @@
+/**
+ * The Markdown conversion the three messaging channels relay a reply through: the shared
+ * parse and chunking (markdown.ts), and each channel's own renderer.
+ *
+ * Three renderers rather than one because the three platforms accept three different
+ * subsets, and the tests are organized to say so: every construct the model actually writes
+ * is asserted per channel, including the ones a channel CANNOT show, because how a missing
+ * construct degrades is the part a reader of a chat notices. The escaping cases are grouped
+ * on their own — a reply is model output steered by whoever is in the chat, so text that
+ * looks like markup has to arrive as text on every channel.
+ *
+ * Delivery — that a rendered send actually goes out with the right `parse_mode` / `msg_type`,
+ * and that a refused one falls back to plain text — is proven against each channel's own
+ * wire fake in messaging.test.ts, messaging-telegram.test.ts, messaging-qq.test.ts and
+ * messaging-wire.test.ts. Nothing here sends anything.
+ */
+import { describe, expect, it } from "vitest";
+import { attachedFileLine } from "@prismshadow/penguin-core";
+import { MESSAGING_TEXT_CHUNK_CHARS } from "../src/runtime/messaging/bridge.js";
+import { chunkMarkdown, isSafeUrl, parseMarkdown } from "../src/runtime/messaging/markdown.js";
+import { feishuCardOf, feishuMarkdownOf } from "../src/runtime/messaging/feishu-card.js";
+import { qqMarkdownOf } from "../src/runtime/messaging/qq-markdown.js";
+import { telegramHtmlOf } from "../src/runtime/messaging/telegram-html.js";
+
+describe("parseMarkdown", () => {
+ it("reads GFM, so tables and task lists are constructs rather than punctuation", () => {
+ const root = parseMarkdown("| a |\n| - |\n| 1 |\n\n- [x] done\n\n~~gone~~");
+ expect(root.children.map((n) => n.type)).toEqual(["table", "list", "paragraph"]);
+ });
+
+ it("never throws: any text at all is a document", () => {
+ for (const text of ["", " ", "**unclosed", "```\nno end", "| broken |"]) {
+ expect(() => parseMarkdown(text)).not.toThrow();
+ }
+ });
+});
+
+describe("isSafeUrl", () => {
+ it("admits the schemes a chat can open and refuses the rest", () => {
+ for (const url of [
+ "https://x.com/a",
+ "http://x.com",
+ "mailto:[email protected]",
+ "tel:+1",
+ "tg://user?id=1",
+ ]) {
+ expect(isSafeUrl(url)).toBe(true);
+ }
+ for (const url of [
+ "javascript:alert(1)",
+ "data:text/html,<script>",
+ "file:///etc/passwd",
+ "",
+ "#anchor",
+ ]) {
+ expect(isSafeUrl(url)).toBe(false);
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Telegram — HTML, a closed tag set with no headings, lists or tables
+// ---------------------------------------------------------------------------
+
+describe("telegramHtmlOf", () => {
+ it("renders the inline constructs Telegram has tags for", () => {
+ expect(telegramHtmlOf("**b** *i* ~~s~~ `c`")).toBe("<b>b</b> <i>i</i> <s>s</s> <code>c</code>");
+ expect(telegramHtmlOf("[label](https://x.com/p)")).toBe('<a href="https://x.com/p">label</a>');
+ expect(telegramHtmlOf("> quoted\n> more")).toBe("<blockquote>quoted\nmore</blockquote>");
+ });
+
+ it("puts a fenced block in pre/code with its language, as the Bot API requires", () => {
+ expect(telegramHtmlOf("```python\nprint(1)\n```")).toBe(
+ '<pre><code class="language-python">print(1)</code></pre>',
+ );
+ // No language: a bare `pre`. The Bot API refuses a class on a standalone `code` tag, so
+ // a fence with no info string must not grow one.
+ expect(telegramHtmlOf("```\nplain\n```")).toBe("<pre>plain</pre>");
+ // A fence's info string is free text and it would land in an attribute, so anything that
+ // is not a plausible language tag drops back to the bare form rather than being quoted in.
+ expect(telegramHtmlOf('```py"onerror=x\nprint(1)\n```')).toBe("<pre>print(1)</pre>");
+ });
+
+ it("degrades a heading to a bold line, since Telegram has no heading at any depth", () => {
+ expect(telegramHtmlOf("# Top")).toBe("<b>Top</b>");
+ expect(telegramHtmlOf("###### Deep")).toBe("<b>Deep</b>");
+ // The hashes themselves must not survive into the text: that is leaking markup.
+ expect(telegramHtmlOf("## Report")).not.toContain("#");
+ });
+
+ it("draws list markers as text, since Telegram will not draw them", () => {
+ expect(telegramHtmlOf("- one\n- two")).toBe("• one\n• two");
+ expect(telegramHtmlOf("3. three\n4. four")).toBe("3. three\n4. four");
+ expect(telegramHtmlOf("- a\n - b")).toBe("• a\n • b");
+ expect(telegramHtmlOf("- [ ] todo\n- [x] done")).toBe("• ☐ todo\n• ☑ done");
+ });
+
+ it("puts a table in a pre block, the only place its columns line up", () => {
+ expect(telegramHtmlOf("| a | b |\n| - | - |\n| 1 | 2 |")).toBe(
+ "<pre>| a | b |\n| 1 | 2 |</pre>",
+ );
+ });
+
+ it("renders a rule as text and an image as a link, neither having a tag", () => {
+ expect(telegramHtmlOf("---")).toBe("———");
+ expect(telegramHtmlOf("![a chart](https://x.com/c.png)")).toBe(
+ '<a href="https://x.com/c.png">a chart</a>',
+ );
+ });
+
+ it("escapes the model's own HTML characters rather than emitting them as tags", () => {
+ expect(telegramHtmlOf("5 < 6 and a & b and 7 > 2")).toBe("5 &lt; 6 and a &amp; b and 7 &gt; 2");
+ // A `<script>` inside a fence is text about a script, and stays text.
+ expect(telegramHtmlOf('```js\nconst s = "<script>alert(1)</script>";\n```')).toBe(
+ '<pre><code class="language-js">const s = &quot;&lt;script&gt;alert(1)&lt;/script&gt;&quot;;</code></pre>'.replaceAll(
+ "&quot;",
+ '"',
+ ),
+ );
+ // Raw HTML the model typed is shown, never forwarded: the tag set is closed, so a
+ // forwarded tag is a 400 for the whole message.
+ expect(telegramHtmlOf("<b>not mine</b>")).toBe("&lt;b&gt;not mine&lt;/b&gt;");
+ });
+
+ it("keeps an unopenable link's label and drops only its clickability", () => {
+ expect(telegramHtmlOf("[click](javascript:alert(1))")).toBe("click");
+ expect(telegramHtmlOf('[q](https://x.com/?a="b")')).toBe(
+ '<a href="https://x.com/?a=&quot;b&quot;">q</a>',
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Feishu — the widest subset, entity escaping
+// ---------------------------------------------------------------------------
+
+describe("feishuMarkdownOf", () => {
+ it("keeps every construct the rich-text component renders", () => {
+ expect(feishuMarkdownOf("# One\n###### Six")).toBe("# One\n\n###### Six");
+ expect(feishuMarkdownOf("**b** *i* ~~s~~ `c`")).toBe("**b** *i* ~~s~~ `c`");
+ expect(feishuMarkdownOf("```python\nprint(1)\n```")).toBe("```python\nprint(1)\n```");
+ expect(feishuMarkdownOf("- a\n - b")).toBe("- a\n - b");
+ expect(feishuMarkdownOf("1. one\n2. two")).toBe("1. one\n2. two");
+ expect(feishuMarkdownOf("> quoted")).toBe("> quoted");
+ expect(feishuMarkdownOf("---")).toBe("---");
+ expect(feishuMarkdownOf("[l](https://x.com)")).toBe("[l](https://x.com)");
+ expect(feishuMarkdownOf("| a | b |\n| - | - |\n| 1 | 2 |")).toBe(
+ "| a | b |\n| --- | --- |\n| 1 | 2 |",
+ );
+ });
+
+ it("escapes literal text with entities, in ONE pass so entities cannot escape each other", () => {
+ // The `#` of a `&#60;` must not be rewritten by the rule for `#`.
+ expect(feishuMarkdownOf("5 < 6 & a > b")).toBe("5 &#60; 6 &amp; a &#62; b");
+ // The backslashes are Markdown's own escapes and are consumed by the parse; what is
+ // being escaped here is the characters they were protecting.
+ expect(feishuMarkdownOf("literal \\* and \\# and ~ and \\[x]")).toBe(
+ "literal &#42; and &#35; and &#126; and &#91;x&#93;",
+ );
+ // Underscores are deliberately left alone: `*` is the documented emphasis marker, and
+ // snake_case is everywhere in this product's replies.
+ expect(feishuMarkdownOf("call read_file_at once")).toBe("call read_file_at once");
+ });
+
+ it("leaves a code block's contents literal — a fence needs no escaping inside it", () => {
+ expect(feishuMarkdownOf('```js\nconst s = "<script>alert(1)</script>"; // a & b\n```')).toBe(
+ '```js\nconst s = "<script>alert(1)</script>"; // a & b\n```',
+ );
+ // A value containing a fence gets a longer one, or it would close early.
+ expect(feishuMarkdownOf("````\nhas ``` inside\n````")).toContain("````\nhas ``` inside\n````");
+ });
+
+ it("neutralizes a block marker a paragraph happens to open with", () => {
+ // Written escaped by the model, so it is a paragraph and must stay one.
+ expect(feishuMarkdownOf("\\- 40 degrees below")).toBe("&#45; 40 degrees below");
+ expect(feishuMarkdownOf("1\\. not a list")).toBe("1&#46; not a list");
+ });
+
+ it("sends an over-long table as a code block rather than letting rows be dropped", () => {
+ const wide = [
+ "| a | b |",
+ "| - | - |",
+ ...Array.from({ length: 7 }, (_, i) => `| r${i} | ${i} |`),
+ ];
+ const out = feishuMarkdownOf(wide.join("\n"));
+ expect(out.startsWith("```")).toBe(true);
+ // Every row survives, which a five-row table would not have managed.
+ for (let i = 0; i < 7; i += 1) expect(out).toContain(`| r${i} | ${i} |`);
+ });
+
+ it("wraps the content in the schema 2.0 card envelope the IM API carries", () => {
+ expect(feishuCardOf("**hi**")).toEqual({
+ schema: "2.0",
+ body: { elements: [{ tag: "markdown", content: "**hi**" }] },
+ });
+ });
+
+ it("keeps an unopenable link's label and drops only its clickability", () => {
+ expect(feishuMarkdownOf("[click](javascript:alert(1))")).toBe("click");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// QQ — headings and lists but no code and no tables; backslash escaping
+// ---------------------------------------------------------------------------
+
+describe("qqMarkdownOf", () => {
+ it("keeps the constructs QQ documents", () => {
+ expect(qqMarkdownOf("## Two")).toBe("## Two");
+ expect(qqMarkdownOf("**b** *i* ~~s~~")).toBe("**b** *i* ~~s~~");
+ expect(qqMarkdownOf("- a\n - b")).toBe("- a\n - b");
+ expect(qqMarkdownOf("1. one\n2. two")).toBe("1. one\n2. two");
+ expect(qqMarkdownOf("> quoted")).toBe("> quoted");
+ expect(qqMarkdownOf("[l](https://x.com)")).toBe("[l](https://x.com)");
+ });
+
+ it("uses the rule QQ documents, which is not the one Markdown writes", () => {
+ expect(qqMarkdownOf("---")).toBe("***");
+ });
+
+ it("sends a code block as plain escaped lines, never as literal backticks", () => {
+ const out = qqMarkdownOf("```python\n# a comment\nx = a ** b\n```");
+ expect(out).not.toContain("```");
+ // The `#` would have become a heading and the `**` a bold run; both are escaped, and
+ // every character the model wrote is still present.
+ expect(out).toBe("\\# a comment\nx = a \\*\\* b");
+ expect(qqMarkdownOf("use `read_file` first")).toBe("use read\\_file first");
+ });
+
+ it("sends a table as its rows, there being no table syntax at all", () => {
+ expect(qqMarkdownOf("| a | b |\n| - | - |\n| 1 | 2 |")).toBe("| a | b |\n| 1 | 2 |");
+ });
+
+ it("escapes with backslashes, which can only ever add a character", () => {
+ expect(qqMarkdownOf("literal * and _ and ~ and [x] and `t`")).toBe(
+ "literal \\* and \\_ and \\~ and \\[x\\] and t",
+ );
+ // `#` and `>` mean something only at the head of a line, so an ordinary sentence keeps
+ // its punctuation unescaped.
+ expect(qqMarkdownOf("issue \\#12 and a > b")).toBe("issue #12 and a > b");
+ // At the head of one they are escaped, so a paragraph is not re-read as a heading.
+ expect(qqMarkdownOf("\\# not a heading")).toBe("\\# not a heading");
+ });
+
+ it("keeps an unopenable link's label and drops only its clickability", () => {
+ expect(qqMarkdownOf("[click](javascript:alert(1))")).toBe("click");
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Inbound file paths quoted back out
+// ---------------------------------------------------------------------------
+
+/**
+ * An inbound file is handed to the model as an `[attached file: <path>]` line folded into the
+ * message text, and the model quotes that path back constantly ("I read …"). The path is
+ * scratchpad-shaped and full of characters these renderers escape, so it is the one piece of
+ * text guaranteed to travel both directions through the conversion.
+ *
+ * The spelling comes from core's own `attachedFileLine`, not a literal, so the case tracks the
+ * marker rather than a copy of it.
+ */
+describe("a reply quoting an inbound file's attachment line", () => {
+ const PATH = "/home/u/.penguin/data/scratchpad/session-2026-08-27-aa/my_report_v2.pdf";
+ const LINE = attachedFileLine(PATH);
+
+ it("keeps the marker line literal rather than reading it as a link or a reference", () => {
+ // `[…]` with nothing after it is not a link, and the brackets are content: a reader who
+ // sees the line at all has to see the path inside it.
+ expect(telegramHtmlOf(`I read ${LINE}`)).toBe(`I read ${LINE}`);
+ // Feishu entity-escapes the brackets, which is how they survive its Markdown.
+ expect(feishuMarkdownOf(`I read ${LINE}`)).toBe(`I read &#91;attached file: ${PATH}&#93;`);
+ expect(qqMarkdownOf(`I read ${LINE}`)).toBe(
+ `I read \\[attached file: ${PATH.replaceAll("_", "\\_")}\\]`,
+ );
+ });
+
+ it("carries a scratchpad path through a code span byte for byte", () => {
+ // The everyday shape: the model puts the path in backticks. Intraword underscores are not
+ // emphasis, so nothing about `my_report_v2` is at risk — and inside a code span the path is
+ // literal on both channels that have one.
+ expect(telegramHtmlOf(`The file \`${PATH}\` is here.`)).toBe(
+ `The file <code>${PATH}</code> is here.`,
+ );
+ expect(feishuMarkdownOf(`The file \`${PATH}\` is here.`)).toBe(`The file \`${PATH}\` is here.`);
+ });
+
+ it("escapes a path's HTML characters, so Telegram's parser cannot be broken by one", () => {
+ // A parse failure here would cost the whole message's formatting through the connector's
+ // fallback — silently, which is the failure worth pinning.
+ const nasty = "/tmp/a&b<c>d<script>.txt";
+ const html = telegramHtmlOf(`Read ${attachedFileLine(nasty)} and \`${nasty}\`.`);
+ expect(html).not.toMatch(/<(?!\/?(b|i|s|u|code|pre|a|blockquote)[ >])/);
+ expect(html).toContain("a&amp;b&lt;c&gt;d&lt;script&gt;.txt");
+ // Balanced, which is what makes it parseable at all.
+ expect(html.split("<code>").length).toBe(html.split("</code>").length);
+ });
+
+ it("degrades a path that genuinely IS Markdown emphasis without losing its characters", () => {
+ // `/_draft_/` is emphasis in the dialect the whole product reads, so the chat and the web
+ // transcript agree about it — that is the point of parsing once. What must not happen is
+ // characters going missing, and on the channels with a code span the backticked form is
+ // exact.
+ const emphasized = "/home/u/scratch/_draft_/notes.md";
+ expect(telegramHtmlOf(`Read ${emphasized}`)).toBe("Read /home/u/scratch/<i>draft</i>/notes.md");
+ expect(telegramHtmlOf(`Read \`${emphasized}\``)).toBe(`Read <code>${emphasized}</code>`);
+ expect(feishuMarkdownOf(`Read \`${emphasized}\``)).toBe(`Read \`${emphasized}\``);
+ // QQ has no code span, so the path arrives as escaped text — every character present,
+ // with backslashes added rather than anything removed.
+ const qq = qqMarkdownOf(`Read \`${emphasized}\``);
+ expect(qq.replaceAll("\\", "")).toBe(`Read ${emphasized}`);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Chunking
+// ---------------------------------------------------------------------------
+
+describe("chunkMarkdown", () => {
+ it("returns a reply that fits byte for byte, and nothing for an empty one", () => {
+ expect(chunkMarkdown("**hi** there", MESSAGING_TEXT_CHUNK_CHARS)).toEqual(["**hi** there"]);
+ expect(chunkMarkdown(" \n ", MESSAGING_TEXT_CHUNK_CHARS)).toEqual([]);
+ });
+
+ it("cuts between blocks, so no chunk opens mid-construct", () => {
+ const src = ["# Head", "", "para one here.", "", "para two here.", "", "para three."].join(
+ "\n",
+ );
+ const out = chunkMarkdown(src, 20);
+ expect(out).toEqual(["# Head", "para one here.", "para two here.", "para three."]);
+ for (const chunk of out) expect(chunk.length).toBeLessThanOrEqual(20);
+ // Blocks that fit together stay together, the blank lines between them included — those
+ // are what keep two paragraphs two paragraphs.
+ expect(chunkMarkdown(src, 40)).toEqual([
+ "# Head\n\npara one here.\n\npara two here.",
+ "para three.",
+ ]);
+ });
+
+ it("re-fences a code block too long for one message, so every piece is still code", () => {
+ const lines = Array.from({ length: 40 }, (_, i) => `const line${i} = ${i};`);
+ const out = chunkMarkdown("```js\n" + lines.join("\n") + "\n```", 300);
+ expect(out.length).toBeGreaterThan(1);
+ for (const chunk of out) {
+ expect(chunk.startsWith("```js\n")).toBe(true);
+ expect(chunk.endsWith("\n```")).toBe(true);
+ expect(chunk.length).toBeLessThanOrEqual(300);
+ }
+ // Nothing was dropped between the pieces.
+ const rejoined = out.map((c) => c.slice("```js\n".length, -"\n```".length)).join("\n");
+ expect(rejoined).toBe(lines.join("\n"));
+ });
+
+ it("cuts a long paragraph between inline runs, never through one", () => {
+ const bold = "**one-unbroken-bold-run**";
+ const src = `${"x".repeat(120)} ${bold} ${"y".repeat(120)}`;
+ const out = chunkMarkdown(src, 150);
+ expect(out.length).toBeGreaterThan(1);
+ // The run lands whole in exactly one chunk — a cut through it would leave stray
+ // asterisks in two messages and render as bold in neither.
+ expect(out.filter((c) => c.includes(bold))).toHaveLength(1);
+ for (const chunk of out) {
+ expect(chunk.split("**").length % 2).toBe(1); // balanced markers
+ }
+ });
+
+ it("keeps the line prefixes that make a blockquote and a list what they are", () => {
+ const quote = Array.from({ length: 8 }, (_, i) => `> quoted line ${i} with padding text`);
+ for (const chunk of chunkMarkdown(quote.join("\n"), 150)) {
+ for (const line of chunk.split("\n")) expect(line.startsWith("> ")).toBe(true);
+ }
+ const list = Array.from({ length: 10 }, (_, i) => `- item ${i} with some padding text here`);
+ for (const chunk of chunkMarkdown(list.join("\n"), 150)) {
+ for (const line of chunk.split("\n")) expect(line.startsWith("- ")).toBe(true);
+ }
+ });
+
+ it("still bounds a single unbreakable line, the last resort", () => {
+ const out = chunkMarkdown("z".repeat(500), 100);
+ expect(out.every((c) => c.length <= 100)).toBe(true);
+ expect(out.join("")).toBe("z".repeat(500));
+ });
+
+ it("produces chunks each renderer accepts on its own", () => {
+ // The whole point of cutting at document boundaries: a chunk is a document, so every
+ // channel's renderer reads it as the constructs it was part of.
+ const src = `# Head\n\n${"a".repeat(200)}\n\n\`\`\`js\nconst x = 1;\n\`\`\`\n\n- one\n- two`;
+ for (const chunk of chunkMarkdown(src, 220)) {
+ expect(() => telegramHtmlOf(chunk)).not.toThrow();
+ expect(() => feishuMarkdownOf(chunk)).not.toThrow();
+ expect(() => qqMarkdownOf(chunk)).not.toThrow();
+ }
+ });
+});
diff --git a/packages/server/test/messaging-qq-transport.test.ts b/packages/server/test/messaging-qq-transport.test.ts
index ee093260..07442fbd 100644
--- a/packages/server/test/messaging-qq-transport.test.ts
+++ b/packages/server/test/messaging-qq-transport.test.ts
@@ -23,6 +23,7 @@ import type {
import {
QQ_API_BASE,
QQ_INTENT_GROUP_AND_C2C,
+ QQApiError,
createQQTransport,
} from "../src/runtime/messaging/qq-api.js";
import { waitFor } from "./helpers.js";
@@ -329,6 +330,50 @@ describe("the QQ OpenAPI send", () => {
});
});
+ it("posts a markdown reply as msg_type 2, with `content` emptied as the platform requires", async () => {
+ await withFetch(defaults, async (calls) => {
+ const bot = createQQTransport().createClient(CREDS);
+ await bot.sendMessage({ ...args, markdown: "## Head\n\n**bold**" });
+ const sent = calls.filter((c) => c.url.includes("/v2/"))[0]!;
+ // "传了 markdown 后此字段必须为空" — a payload carrying both is rejected, so `content`
+ // goes out empty rather than merely ignored. The deprecated template fields are absent.
+ expect(JSON.parse(sent.body)).toEqual({
+ content: "",
+ msg_type: 2,
+ markdown: { content: "## Head\n\n**bold**" },
+ msg_id: "msg_1",
+ msg_seq: 2,
+ });
+ });
+ });
+
+ it("types a refusal as QQApiError and a transfer failure as a plain Error", async () => {
+ // The distinction the markdown-to-text fallback turns on: the platform answered and
+ // delivered nothing, so another form of the same message is safe to send — where a
+ // request that never completed may already have been delivered.
+ await withFetch(
+ (call) => (call.url.includes("/v2/") ? jsonResponse({ err_code: 40054001 }, 400) : null),
+ async () => {
+ const bot = createQQTransport().createClient(CREDS);
+ const err = await bot.sendMessage(args).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(QQApiError);
+ expect((err as QQApiError).code).toBe(40054001);
+ },
+ );
+ await withFetch(
+ (call) => {
+ if (!call.url.includes("/v2/")) return null;
+ throw new TypeError("fetch failed");
+ },
+ async () => {
+ const bot = createQQTransport().createClient(CREDS);
+ const err = await bot.sendMessage(args).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(Error);
+ expect(err).not.toBeInstanceOf(QQApiError);
+ },
+ );
+ });
+
it("replays a 401 once on a fresh token, and gives up rather than looping", async () => {
// A secret rotated in the console, or a clock further off than the refresh margin
// covers: the cached token died before its stated expiry.
diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.ts
index 7e831c62..1b51a473 100644
--- a/packages/server/test/messaging-qq.test.ts
+++ b/packages/server/test/messaging-qq.test.ts
@@ -42,7 +42,7 @@ import type {
QQSendArgs,
QQTransport,
} from "../src/runtime/messaging/qq-api.js";
-import { normalizeDispatch, qqSendErrorText } from "../src/runtime/messaging/qq-api.js";
+import { QQApiError, normalizeDispatch, qqSendErrorText } from "../src/runtime/messaging/qq-api.js";
import type { QQConnectorOpts } from "../src/runtime/messaging/qq-connector.js";
import {
QQ_PASSIVE_WINDOW_MS,
@@ -90,6 +90,11 @@ class FakeQQClient implements QQBotClient {
}
async sendMessage(args: QQSendArgs): Promise<void> {
+ // The platform refusing a `msg_type: 2` body while accepting the plain one behind it —
+ // the shape the markdown-to-text fallback has to survive.
+ if (args.markdown !== undefined && this.t.failMarkdownSend !== null) {
+ throw this.t.failMarkdownSend;
+ }
if (this.t.failSend !== null) throw new Error(this.t.failSend);
this.sends.push(args);
}
@@ -117,6 +122,8 @@ class FakeQQTransport implements QQTransport {
failAuth: string | null = null;
/** Non-null makes every send throw with this message. */
failSend: string | null = null;
+ /** Non-null makes only the `msg_type: 2` sends throw THIS, leaving the plain ones working. */
+ failMarkdownSend: Error | null = null;
createClient(creds: QQCredentials): FakeQQClient {
const client = new FakeQQClient(creds, this);
@@ -352,8 +359,8 @@ describe("qq binding routes and the passive reply budget", () => {
let runs: TextPayload[][];
/** Save the credentials, then flip the toggle on and wait for the gateway handshake. */
- const bindEnabled = async (sid: string, appId = APP_ID) => {
- expect((await api.put(BASE(sid), { appId, appSecret: APP_SECRET })).status).toBe(200);
+ const bindEnabled = async (sid: string, appId = APP_ID, put: Record<string, unknown> = {}) => {
+ expect((await api.put(BASE(sid), { appId, appSecret: APP_SECRET, ...put })).status).toBe(200);
expect((await api.post(`${BASE(sid)}/state`, { enabled: true })).status).toBe(200);
await waitFor(() => t.deps.messaging.statusOf(sid, "qq").state === "connected");
};
@@ -549,6 +556,81 @@ describe("qq binding routes and the passive reply budget", () => {
expect(runs).toHaveLength(0);
});
+ // —— renderMarkdown: the per-binding formatting option ————————————————————————
+
+ it("renders the constructs QQ has, and degrades the two it does not", async () => {
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(
+ row,
+ multiMessageFakeSession(SID2, [
+ "## Result\n\nRan **2** tests, `all green`.\n\n```py\n# note\nx = a ** b\n```",
+ ]),
+ );
+ await bindEnabled(SID2);
+ await fake.lastGateway().fire(c2cText("go", "msg_md"));
+ await waitFor(() => fake.allSends().length === 1);
+ // The heading and the bold survive; inline code loses its backticks and the fenced block
+ // becomes plain escaped lines, this channel having no code syntax at all. Nothing arrives
+ // as a wall of literal backticks, and no character is lost — only backslashes added.
+ expect(fake.allSends()[0]!.markdown).toBe(
+ "## Result\n\nRan **2** tests, all green.\n\n\\# note\nx = a \\*\\* b",
+ );
+ });
+
+ it("renderMarkdown off reproduces the plain msg_type 0 send, byte for byte", async () => {
+ const raw = "## Result\n\nRan **2** tests.";
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, [raw]));
+ await bindEnabled(SID2, APP_ID, { renderMarkdown: false });
+ await fake.lastGateway().fire(c2cText("go", "msg_md_off"));
+ await waitFor(() => fake.allSends().length === 1);
+ const sent = fake.allSends()[0]!;
+ // No markdown body at all, and the reply's own characters: what this channel sent
+ // before the option existed.
+ expect(sent.markdown).toBeUndefined();
+ expect(sent.content).toBe(raw);
+ });
+
+ it("a markdown send the platform REFUSES falls back to plain text, at the cost of one slot", async () => {
+ const raw = "**bold** and more";
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, [raw]));
+ await bindEnabled(SID2);
+ fake.failMarkdownSend = new QQApiError(
+ "Message send failed: bad markdown (code 40054001)",
+ 40054001,
+ );
+ await fake.lastGateway().fire(c2cText("go", "msg_md_reject"));
+ await waitFor(() => fake.allSends().length === 1);
+ const sent = fake.allSends()[0]!;
+ expect(sent.markdown).toBeUndefined();
+ expect(sent.content).toBe(raw);
+ // The retry needs a FRESH msg_seq — a repeated (msg_id, msg_seq) pair is refused rather
+ // than deduplicated — so the fallback costs a second slot of the four this message funds.
+ expect(sent.msgSeq).toBe(2);
+ });
+
+ it("a refusal that was not about the body is not retried, so the reserved slot is kept", async () => {
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["**bold**"]));
+ await bindEnabled(SID2);
+ // 40034128 is "the window closed, or the replies ran out". Plain text fails identically,
+ // and the attempt would spend a slot to learn nothing.
+ fake.failMarkdownSend = new QQApiError(
+ "Message send failed: reply limit (code 40034128)",
+ 40034128,
+ );
+ await fake.lastGateway().fire(c2cText("go", "msg_md_nobody"));
+ await waitFor(() =>
+ t.deps.errorsRepo.recent(projectId).some((r) => r.code === "messaging_send_failed"),
+ );
+ expect(fake.allSends()).toEqual([]);
+ });
+
// —— The budget ——————————————————————————————————————————————————————————
it("a run of six messages reaches QQ as four, the last carrying the remainder", async () => {
diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.ts
index 94bc1efd..2dd47c82 100644
--- a/packages/server/test/messaging-telegram.test.ts
+++ b/packages/server/test/messaging-telegram.test.ts
@@ -22,6 +22,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
approvalDecision,
assistantText,
+ attachedFileLine,
matchAttachedFileLine,
modelVisiblePath,
scratchpadDir,
@@ -85,6 +86,8 @@ interface SentMessage {
text: string;
replyTo?: number;
threadId?: number;
+ /** Present only when the send asked Telegram to parse the text — the formatted path. */
+ parseMode?: "HTML";
}
/**
@@ -157,8 +160,15 @@ class FakeBotClient implements TelegramBotClient {
text: string;
replyToMessageId?: number;
messageThreadId?: number;
+ parseMode?: "HTML";
}): Promise<void> {
this.sendCalls++;
+ // The 400 Telegram answers for HTML it will not parse: only the formatted attempt fails,
+ // and the same message without `parse_mode` goes through — which is the shape the
+ // entity fallback has to survive.
+ if (args.parseMode !== undefined && this.t.failParsedSend !== null) {
+ throw new TelegramApiError(this.t.failParsedSend, this.t.failParsedSendCode);
+ }
if (this.t.failSend !== null) {
// A plain Error is a transport failure (no envelope, so no code); a TelegramApiError is
// Telegram answering `ok: false`, and only its code may be branched on.
@@ -176,6 +186,7 @@ class FakeBotClient implements TelegramBotClient {
text: args.text,
...(args.replyToMessageId !== undefined ? { replyTo: args.replyToMessageId } : {}),
...(args.messageThreadId !== undefined ? { threadId: args.messageThreadId } : {}),
+ ...(args.parseMode !== undefined ? { parseMode: args.parseMode } : {}),
});
}
@@ -276,6 +287,9 @@ class FakeTelegramTransport {
failSend: string | null = null;
/** `failSend`'s Bot API `error_code`; null makes it a transport failure, which carries none. */
failSendCode: number | null = null;
+ /** Non-null makes only the sends that carry a `parse_mode` throw (HTML Telegram will not parse). */
+ failParsedSend: string | null = null;
+ failParsedSendCode: number | undefined = 400;
/** Non-null makes only the sends that carry a forum topic throw (a deleted/closed topic). */
failThreadedSend: string | null = null;
/** `failThreadedSend`'s `error_code`: 400 is the deleted-topic shape, 429 a flood wait. */
@@ -361,6 +375,8 @@ class FakeFeishuSdk implements FeishuSdk {
},
async sendText() {},
async replyText() {},
+ async sendCard() {},
+ async replyCard() {},
async botOpenId() {
return null;
},
@@ -872,7 +888,12 @@ describe("telegram binding routes and connector loop", () => {
expect(row.lastChatIsDirect).toBe(true);
// Task end mirrors the assistant text to that chat as a plain send (direct chat).
await waitFor(() => fake.allSends().length > 0);
- expect(fake.allSends()).toContainEqual({ chatId: "42424242", text: "Reply text" });
+ // `parse_mode` rides every relayed reply: rendering the model's Markdown is the default.
+ expect(fake.allSends()).toContainEqual({
+ chatId: "42424242",
+ text: "Reply text",
+ parseMode: "HTML",
+ });
// A second message is processed exactly once: the loop confirmed the first update
// via its offset, so nothing re-delivers.
@@ -947,6 +968,7 @@ describe("telegram binding routes and connector loop", () => {
expect(fake.allSends()).toContainEqual({
chatId: "-1002233445566",
text: "Reply text",
+ parseMode: "HTML",
replyTo: 77,
});
});
@@ -1083,6 +1105,7 @@ describe("telegram binding routes and connector loop", () => {
expect(fake.allSends()).toContainEqual({
chatId: String(chatId),
text: "Reply text",
+ parseMode: "HTML",
replyTo: 4,
});
});
@@ -1270,16 +1293,20 @@ describe("telegram binding routes and connector loop", () => {
);
});
- it("a threaded send that fails both times surfaces the failure after exactly two attempts", async () => {
+ it("a send that fails every way surfaces the failure after a bounded number of attempts", async () => {
await bindEnabled(SID);
- // `Bad Request: chat not found` is a 400 too, so the fallback fires — and then fails as
+ // `Bad Request: chat not found` is a 400 too, so both fallbacks fire — and then fail as
// well. The reply is lost either way; what must not be lost is the report.
fake.failSend = "sendMessage failed: Bad Request: chat not found (code 400)";
fake.failSendCode = 400;
fake.push(forumText("into a chat that is gone", 207));
await waitFor(() => runs.length === 1);
await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").lastDeliveryError !== undefined);
- expect(fake.allSendCalls()).toBe(2);
+ // Four, and each one is a named step: the two fallbacks compose, the entity one wrapping
+ // the thread one, so a 400 no fallback can fix walks HTML-with-topic,
+ // HTML-without-topic, plain-with-topic, plain-without-topic and then stops. What matters
+ // is that it STOPS — nothing here retries a 429 or a transport failure.
+ expect(fake.allSendCalls()).toBe(4);
expect(t.deps.messaging.statusOf(SID, "telegram").lastDeliveryError?.detail).toContain(
"chat not found",
);
@@ -1590,7 +1617,13 @@ describe("telegram binding routes and connector loop", () => {
fake.push(privateText("go"));
await waitFor(() => fake.allSends().length === 3);
expect(fake.allSends()).toEqual([
- { chatId: "42424242", text: "Rendered `chart.png`, notes in `notes.md`." },
+ // The backticks the mention scanner reads are also inline code, so the same text is
+ // both a file mention and a rendered construct.
+ {
+ chatId: "42424242",
+ text: "Rendered <code>chart.png</code>, notes in <code>notes.md</code>.",
+ parseMode: "HTML",
+ },
{ kind: "photo", chatId: "42424242", fileName: "chart.png", bytes: PHOTO_BYTES.length },
{ kind: "document", chatId: "42424242", fileName: "notes.md", bytes: 5 },
]);
@@ -1609,12 +1642,12 @@ describe("telegram binding routes and connector loop", () => {
// The first message is already in the chat while the run is still running.
await waitFor(() => fake.allSends().length === 1);
expect(t.deps.manager.statusOf(SID2)).toBe("running");
- expect(fake.allSends()).toEqual([{ chatId: "42424242", text: "step one" }]);
+ expect(fake.allSends()).toEqual([{ chatId: "42424242", text: "step one", parseMode: "HTML" }]);
release();
await waitFor(() => fake.allSends().length === 2);
expect(fake.allSends()).toEqual([
- { chatId: "42424242", text: "step one" },
- { chatId: "42424242", text: "step two" },
+ { chatId: "42424242", text: "step one", parseMode: "HTML" },
+ { chatId: "42424242", text: "step two", parseMode: "HTML" },
]);
});
@@ -1632,8 +1665,8 @@ describe("telegram binding routes and connector loop", () => {
await waitFor(() => fake.allSends().length === 2);
// One reply-to anchors the exchange; the follow-up is a plain send into the same chat.
expect(fake.allSends()).toEqual([
- { chatId: "-1002233445566", text: "first", replyTo: 91 },
- { chatId: "-1002233445566", text: "second" },
+ { chatId: "-1002233445566", text: "first", parseMode: "HTML", replyTo: 91 },
+ { chatId: "-1002233445566", text: "second", parseMode: "HTML" },
]);
});
@@ -1650,6 +1683,152 @@ describe("telegram binding routes and connector loop", () => {
expect(sends.map((s) => s.text).join("")).toBe("x".repeat(9000));
});
+ // —— renderMarkdown: the per-binding formatting option ————————————————————————
+
+ /** SID2 replying with one fixed text, bound and connected, ready to be messaged. */
+ const bindReplying = async (text: string, token: string, put: Record<string, unknown> = {}) => {
+ const row2 = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row2);
+ t.deps.manager.adopt(row2, echoFakeSession(SID2, runs, text));
+ expect((await api.put(BASE(SID2), { botToken: token, ...put })).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");
+ };
+
+ it("renders the constructs Telegram has, and degrades the three it does not", async () => {
+ await bindReplying(
+ "## Result\n\nRan **2** tests, `all green`.\n\n- one\n- two\n\n| a | b |\n| - | - |\n| 1 | 2 |",
+ "7000000010:test-secret-MD01-0001",
+ );
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length === 1);
+ const sent = fake.allTexts()[0]!;
+ expect(sent.parseMode).toBe("HTML");
+ // The heading is a bold line, the bullets are text, the table is a pre block — and the
+ // markup the model wrote is nowhere in the output as characters.
+ expect(sent.text).toBe(
+ [
+ "<b>Result</b>",
+ "",
+ "Ran <b>2</b> tests, <code>all green</code>.",
+ "",
+ "• one\n• two",
+ "",
+ "<pre>| a | b |\n| 1 | 2 |</pre>",
+ ].join("\n"),
+ );
+ });
+
+ it("escapes the model's own HTML characters instead of letting Telegram parse them", async () => {
+ await bindReplying(
+ '5 < 6 & a > b\n\n```js\nconst s = "<script>alert(1)</script>";\n```',
+ "7000000011:test-secret-MD02-0002",
+ );
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allTexts()[0]!.text).toBe(
+ '5 &lt; 6 &amp; a &gt; b\n\n<pre><code class="language-js">const s = "&lt;script&gt;alert(1)&lt;/script&gt;";</code></pre>',
+ );
+ });
+
+ it("renderMarkdown off reproduces the plain send, byte for byte and with no parse_mode", async () => {
+ const raw = "## Result\n\nRan **2** tests.";
+ await bindReplying(raw, "7000000012:test-secret-MD03-0003", { renderMarkdown: false });
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length === 1);
+ // What this channel sent before the option existed: the characters the model wrote, and
+ // no `parse_mode` field at all.
+ expect(fake.allSends()).toEqual([{ chatId: "42424242", text: raw }]);
+ });
+
+ it("a formatted send Telegram REFUSES falls back to plain text, so the reply still arrives", async () => {
+ const raw = "**bold** and more";
+ await bindReplying(raw, "7000000013:test-secret-MD04-0004");
+ // The 400 Telegram answers for entities it cannot parse. Only the formatted attempt
+ // fails; the same message without `parse_mode` goes through.
+ fake.failParsedSend = "sendMessage failed: Bad Request: can't parse entities (code 400)";
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length === 1);
+ // Two requests, one delivery: the refusal cost a retry, not the message.
+ expect(fake.allSendCalls()).toBe(2);
+ expect(fake.allSends()).toEqual([{ chatId: "42424242", text: raw }]);
+ expect(t.deps.errorsRepo.recent(projectId).map((r) => r.code)).not.toContain(
+ "messaging_send_failed",
+ );
+ });
+
+ it("a formatted send that never completed is NOT retried, since it may have been delivered", async () => {
+ await bindReplying("**bold**", "7000000014:test-secret-MD05-0005");
+ // A transport failure carries no `error_code`, so it is not Telegram refusing anything.
+ fake.failParsedSend = "sendMessage failed: request timed out";
+ fake.failParsedSendCode = undefined;
+ fake.push(privateText("go"));
+ await waitFor(
+ () => t.deps.messaging.statusOf(SID2, "telegram").lastDeliveryError !== undefined,
+ );
+ expect(fake.allSendCalls()).toBe(1);
+ expect(fake.allSends()).toEqual([]);
+ });
+
+ it("relays a reply quoting an inbound file's path without downgrading the formatting", async () => {
+ // Inbound files and outbound Markdown now share a conversation: an inbound file is folded
+ // into the message text as an `[attached file: <path>]` line, and the model quotes that
+ // path back. The path is scratchpad-shaped and full of characters the converter escapes,
+ // so this is where a formatting bug would show up as a 400 and be SILENTLY downgraded to
+ // plain text by the fallback — the reply would still arrive and nobody would know the
+ // formatting had been lost.
+ const filePath = "/home/u/.penguin/data/scratchpad/session-2026-08-27-aa/my_report_v2.pdf";
+ await bindReplying(
+ `I read ${attachedFileLine(filePath)}\n\nThe file \`${filePath}\` has **3** rows.`,
+ "7000000016:test-secret-MD07-0007",
+ );
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length === 1);
+ const sent = fake.allTexts()[0]!;
+ // ONE request: the formatted send was accepted, so no fallback ran.
+ expect(fake.allSendCalls()).toBe(1);
+ expect(sent.parseMode).toBe("HTML");
+ // The marker line stays literal and the backticked path is byte-exact inside `<code>`.
+ expect(sent.text).toBe(
+ `I read ${attachedFileLine(filePath)}\n\nThe file <code>${filePath}</code> has <b>3</b> rows.`,
+ );
+ });
+
+ it("chunks a long formatted reply without splitting a code fence or an entity", async () => {
+ // A reply that straddles the size boundary with a fence open across it — the case that
+ // would otherwise reach Telegram as one unterminated block and one wall of prose, and
+ // whose 400 the fallback would then downgrade to plain text.
+ const lines = Array.from({ length: 400 }, (_, i) => `const someValue${i} = ${i};`);
+ await bindReplying(
+ `Here is the file:\n\n\`\`\`ts\n${lines.join("\n")}\n\`\`\`\n\nThat is **all** of it.`,
+ "7000000015:test-secret-MD06-0006",
+ );
+ fake.push(privateText("go"));
+ await waitFor(() => fake.allSends().length >= 3);
+ const sends = fake.allTexts();
+ for (const sent of sends) {
+ expect(sent.parseMode).toBe("HTML");
+ expect(sent.text.length).toBeLessThanOrEqual(4096);
+ // Balanced tags: no message opens a `pre` or a `b` it does not close.
+ expect(sent.text.split("<pre>").length).toBe(sent.text.split("</pre>").length);
+ expect(sent.text.split("<b>").length).toBe(sent.text.split("</b>").length);
+ }
+ // The proof the fence was re-opened rather than merely closed: the block spans several
+ // messages and EVERY one of them is a code block with the language still on it. A cut
+ // that did not re-fence would leave the second message's lines as bare prose.
+ const codeMessages = sends.filter((x) => x.text.includes("const someValue"));
+ expect(codeMessages.length).toBeGreaterThan(1);
+ for (const sent of codeMessages) {
+ expect(sent.text).toContain('<pre><code class="language-ts">');
+ expect(sent.text.endsWith("</code></pre>")).toBe(true);
+ }
+ // Nothing was lost between the messages: every line of the file arrived, and the prose
+ // after the block still renders.
+ const all = sends.map((x) => x.text).join("\n");
+ for (const line of lines) expect(all).toContain(line);
+ expect(all).toContain("That is <b>all</b> of it.");
+ });
+
it("connect drains the dark-period backlog: only messages after enabling reach the Session", async () => {
await api.put(BASE(SID), { botToken: TOKEN });
// Messages sent while the binding was saved-but-disabled pile up server-side …
diff --git a/packages/server/test/messaging-wire.test.ts b/packages/server/test/messaging-wire.test.ts
index f2610c57..5cb98d7a 100644
--- a/packages/server/test/messaging-wire.test.ts
+++ b/packages/server/test/messaging-wire.test.ts
@@ -31,7 +31,8 @@ import { Readable } from "node:stream";
import { Agent, getGlobalDispatcher, setGlobalDispatcher } from "undici";
import type { Dispatcher } from "undici";
import { afterEach, describe, expect, it } from "vitest";
-import { createLarkSdk } from "../src/runtime/messaging/feishu-sdk.js";
+import { FeishuApiError, createLarkSdk } from "../src/runtime/messaging/feishu-sdk.js";
+import { feishuCardOf } from "../src/runtime/messaging/feishu-card.js";
import { createTelegramTransport } from "../src/runtime/messaging/telegram-api.js";
import type {
TelegramTransport,
@@ -333,6 +334,60 @@ describe("feishu adapter against the SDK's HTTP boundary", () => {
await expect(client.sendText("oc_wire", "still working")).resolves.toBeUndefined();
});
+ it("sends a card as msg_type interactive, with the schema 2.0 envelope serialized in", async () => {
+ const { http, calls } = larkHttp((url) =>
+ url.includes("tenant_access_token")
+ ? TOKEN_ANSWER
+ : { body: { code: 0, msg: "success", data: {} } },
+ );
+ const client = await createLarkSdk({ httpInstance: http }).createClient(CREDS);
+ await client.sendCard("oc_wire", feishuCardOf("## Head\n\n**bold**"));
+ const sent = calls.find((c) => String(c.url).endsWith("/im/v1/messages"))!;
+ expect(sent.data).toEqual({
+ receive_id: "oc_wire",
+ msg_type: "interactive",
+ // The card JSON goes in `content` as a STRING, which is the whole of what the IM API
+ // accepts for a card — the deprecated template fields are not used.
+ content: JSON.stringify({
+ schema: "2.0",
+ body: { elements: [{ tag: "markdown", content: "## Head\n\n**bold**" }] },
+ }),
+ });
+ expect((sent.params as { receive_id_type: string }).receive_id_type).toBe("chat_id");
+ });
+
+ it("threads a card through the reply endpoint, which takes the same msg_type set", async () => {
+ const { http, calls } = larkHttp((url) =>
+ url.includes("tenant_access_token")
+ ? TOKEN_ANSWER
+ : { body: { code: 0, msg: "success", data: {} } },
+ );
+ const client = await createLarkSdk({ httpInstance: http }).createClient(CREDS);
+ await client.replyCard("om_wire_9", feishuCardOf("**hi**"));
+ // The `:message_id` path parameter is filled by the SDK; a card replies exactly as text
+ // does, which is what keeps a group's one reply-to relation working with formatting on.
+ const sent = calls.find((c) => String(c.url).includes("/im/v1/messages/om_wire_9/reply"))!;
+ expect((sent.data as { msg_type: string }).msg_type).toBe("interactive");
+ expect(JSON.parse((sent.data as { content: string }).content)).toEqual({
+ schema: "2.0",
+ body: { elements: [{ tag: "markdown", content: "**hi**" }] },
+ });
+ });
+
+ it("types a refused call as FeishuApiError and a stalled one as a plain Error", async () => {
+ // The distinction the card-to-text fallback turns on: Feishu answered and delivered
+ // nothing, so the same message is safe to send again as text.
+ const { http } = larkHttp((url) =>
+ url.includes("tenant_access_token")
+ ? TOKEN_ANSWER
+ : { body: { code: 230001, msg: "invalid card" } },
+ );
+ const client = await createLarkSdk({ httpInstance: http }).createClient(CREDS);
+ const err = await client.sendCard("oc_wire", feishuCardOf("x")).catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(FeishuApiError);
+ expect((err as FeishuApiError).code).toBe(230001);
+ });
+
it("uploads a picture, then sends the returned key as an image message", async () => {
// The upload endpoints resolve to their INNER `data` object rather than the `{code,msg}`
// envelope the JSON endpoints return — a difference invisible to a seam-level fake, and
@@ -471,6 +526,18 @@ describe("telegram adapter against the fetch boundary", () => {
expect(err?.message).not.toContain("SECRET");
});
+ it("puts parse_mode on the wire only when the send asked for it", async () => {
+ const stub = stubFetch(() => okJson({ message_id: 1 }));
+ const bot = stub.transport.createClient({ botToken: TOKEN });
+ await bot.sendMessage({ chatId: "42", text: "<b>hi</b>", parseMode: "HTML" });
+ // A fixed notice carries no markup and must go out verbatim, which means no field at all
+ // rather than a field naming plain text.
+ await bot.sendMessage({ chatId: "42", text: "plain notice" });
+ const bodies = stub.bodies.map((b) => JSON.parse(String(b)) as Record<string, unknown>);
+ expect(bodies[0]).toEqual({ chat_id: 42, text: "<b>hi</b>", parse_mode: "HTML" });
+ expect(bodies[1]).toEqual({ chat_id: 42, text: "plain notice" });
+ });
+
it("refuses a file the API already says is over the cap, as a size error", async () => {
const stub = stubFetch(() =>
okJson({ file_path: "photos/f.jpg", file_size: 30 * 1024 * 1024 }),
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index 3208e9ae..0cfcba0c 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -76,6 +76,8 @@ import type {
MessagingInboundMessage,
} from "../src/runtime/messaging/connector.js";
import { FeishuConnector } from "../src/runtime/messaging/feishu-connector.js";
+import type { FeishuCard } from "../src/runtime/messaging/feishu-card.js";
+import { FeishuApiError } from "../src/runtime/messaging/feishu-sdk.js";
import {
MessagingPermissionError,
collectUnderCap,
@@ -131,6 +133,15 @@ interface ImageFetch {
maxBytes: number;
}
+/** The rich-text content out of a card, which is the whole of what a card carries here. */
+function cardContent(card: FeishuCard): string {
+ const element = card.body.elements[0];
+ if (card.schema !== "2.0" || element?.tag !== "markdown") {
+ throw new Error(`unexpected card envelope: ${JSON.stringify(card)}`);
+ }
+ return element.content;
+}
+
/** The bytes as a stream, so the fakes read them through the real capped reader. */
async function* oneChunk(bytes: Buffer): AsyncGenerator<Uint8Array> {
yield bytes;
@@ -144,6 +155,15 @@ const FILE_BYTES = Buffer.from("quarterly revenue: 42\n", "utf8");
class FakeClient implements FeishuApiClient {
readonly sends: Sent[] = [];
+ /**
+ * The card sends specifically, as the rich-text content they carried.
+ *
+ * A card is ALSO recorded in `sends` as an ordinary text send, so the routing, ordering
+ * and threading assertions read the same whichever transport carried the message — those
+ * are what they are about. This list is what separates the two, and it is what a test
+ * asserting the plain path checks is empty.
+ */
+ readonly cards: SentText[] = [];
/** When each send was recorded, parallel to `sends`: what the pacing test measures. */
readonly sentAt: number[] = [];
readonly imageFetches: ImageFetch[] = [];
@@ -170,6 +190,28 @@ class FakeClient implements FeishuApiClient {
this.record({ kind: "reply", target: messageId, text });
await this.sdk.hold();
}
+ async sendCard(chatId: string, card: FeishuCard): Promise<void> {
+ // The typed failures fire on a card exactly as they do on a text bubble: Feishu refuses a
+ // missing scope on EVERY send, whatever the msg_type, so a fake that let a card through
+ // would make the card path quietly immune to the failure the text path is asserted on.
+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;
+ if (this.sdk.failCard !== null) throw this.sdk.failCard;
+ if (this.sdk.failSend !== null) throw new Error(this.sdk.failSend);
+ this.sdk.noteSend();
+ this.recordCard({ kind: "send", target: chatId, text: cardContent(card) });
+ await this.sdk.hold();
+ }
+ async replyCard(messageId: string, card: FeishuCard): Promise<void> {
+ if (this.sdk.failSendWith !== null) throw this.sdk.failSendWith;
+ if (this.sdk.failCard !== null) throw this.sdk.failCard;
+ this.sdk.noteSend();
+ this.recordCard({ kind: "reply", target: messageId, text: cardContent(card) });
+ await this.sdk.hold();
+ }
+ private recordCard(sent: SentText): void {
+ this.cards.push(sent);
+ this.record(sent);
+ }
private record(sent: SentText): void {
this.sends.push(sent);
this.sentAt.push(Date.now());
@@ -260,6 +302,11 @@ class FakeSdk implements FeishuSdk {
failSend: string | null = null;
/** Non-null makes every outbound sendText throw THIS — for the failure shapes that carry data. */
failSendWith: Error | null = null;
+ /**
+ * Non-null makes every CARD send throw this, leaving the plain text sends working — the
+ * shape of a channel that refuses a rendering and accepts the message behind it.
+ */
+ failCard: Error | null = null;
/**
* Non-null holds every createClient until it resolves, which is what makes the bridge's
* one await between reading the binding row and its first send observable to a test.
@@ -318,6 +365,10 @@ class FakeSdk implements FeishuSdk {
allTexts(): SentText[] {
return this.allSends().filter((s): s is SentText => s.kind === "send" || s.kind === "reply");
}
+ /** Only the messages that went out as an interactive card, across every client. */
+ allCards(): SentText[] {
+ return this.clients.flatMap((c) => c.cards);
+ }
/** Every image download asked of any client, in order. */
allImageFetches(): ImageFetch[] {
return this.clients.flatMap((c) => c.imageFetches);
@@ -1145,12 +1196,19 @@ describe("messaging binding routes and bridge", () => {
*/
const SPOKEN = "Line one.\n\n Line two. \nLine three.";
- /** SID2 replying with one fixed text, bound and connected, ready to be messaged. */
+ /**
+ * SID2 replying with one fixed text, bound and connected, ready to be messaged.
+ *
+ * Markdown rendering is OFF unless a case turns it on: these cases are about which lines
+ * become which messages, and SPOKEN's indent and trailing padding are the point of the
+ * fixture — a rendering pass normalizes exactly that whitespace away. The interaction
+ * between the two options has its own case below.
+ */
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 });
+ await bindEnabled(SID2, { ...PUT_BODY, renderMarkdown: false, ...put });
};
/** One inbound text into a direct chat, which becomes the reply target. */
@@ -1249,7 +1307,12 @@ describe("messaging binding routes and bridge", () => {
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 });
+ await bindEnabled(SID2, {
+ ...PUT_BODY,
+ appId: "cli_lines_approve",
+ linePerMessage: true,
+ renderMarkdown: false,
+ });
// Hold every send open: the whole reply is then still in flight when the approval fires.
let release = () => {};
fake.heldSends = new Promise<void>((resolve) => {
@@ -1416,6 +1479,10 @@ describe("messaging binding routes and bridge", () => {
appId: "cli_final_lines",
finalReplyOnly: true,
linePerMessage: true,
+ // Markdown rendering off: this case is about WHICH text is split and how, and SPOKEN's
+ // indent and trailing padding are the point of the fixture — a rendering pass
+ // normalizes exactly that whitespace away.
+ renderMarkdown: false,
});
await messageBot("oc_final_lines");
await waitFor(() => fake.allSends().length === 3);
@@ -1466,6 +1533,96 @@ describe("messaging binding routes and bridge", () => {
expect(both?.linePerMessage).toBe(true);
});
+ // —— renderMarkdown: the per-binding formatting option ————————————————————————
+
+ /** A reply with the constructs Feishu's rich-text component renders. */
+ const RICH = "## Result\n\nRan **2** tests, `all green`.\n\n- one\n- two";
+
+ it("renderMarkdown on (the default) sends an interactive card carrying the rich text", async () => {
+ await bindReplying(RICH, { appId: "cli_md_on", renderMarkdown: undefined });
+ // The default, on a binding whose PUT never mentioned the field.
+ expect(t.deps.messagingRepo.find(SID2, "feishu")?.renderMarkdown).toBe(true);
+ await messageBot("oc_md_on");
+ await waitFor(() => fake.allSends().length > 0);
+ // A card, not a text bubble — which is the whole difference the switch makes here.
+ expect(fake.allCards()).toEqual([{ kind: "send", target: "oc_md_on", text: RICH }]);
+ });
+
+ it("renderMarkdown off reproduces the plain text bubble, byte for byte", async () => {
+ await bindReplying(RICH, { appId: "cli_md_off", renderMarkdown: false });
+ await messageBot("oc_md_off");
+ await waitFor(() => fake.allSends().length > 0);
+ // No card at all, and the reply's own characters: what this channel sent before the
+ // option existed.
+ expect(fake.allCards()).toEqual([]);
+ expect(fake.allSends()).toEqual([{ kind: "send", target: "oc_md_off", text: RICH }]);
+ });
+
+ it("a card Feishu REFUSES falls back to a plain text bubble, so the reply still arrives", async () => {
+ await bindReplying(RICH, { appId: "cli_md_reject", renderMarkdown: true });
+ // The platform answering `{code}`: it received the request and delivered nothing.
+ fake.failCard = new FeishuApiError("Message send failed: invalid card (code 230001)", 230001);
+ await messageBot("oc_md_reject");
+ await waitFor(() => fake.allSends().length === 1);
+ // Two attempts, one delivery: the card was refused and the same message went out as
+ // text. The formatting is what the refusal cost, never the answer.
+ expect(fake.allCards()).toHaveLength(0);
+ expect(fake.allSends()).toEqual([{ kind: "send", target: "oc_md_reject", text: RICH }]);
+ // And it is a delivery, not a failure: nothing is recorded against the binding.
+ expect(
+ t.deps.db.prepare("SELECT code FROM error_records WHERE source = 'messaging'").all(),
+ ).toEqual([]);
+ });
+
+ it("a card that never completed is NOT retried, since it may already have been delivered", async () => {
+ await bindReplying(RICH, { appId: "cli_md_timeout", renderMarkdown: true });
+ // No `{code}`: a timeout or a reset, which says nothing about whether the card landed.
+ fake.failCard = new Error("Message send failed: Message send timed out after 60000ms");
+ await messageBot("oc_md_timeout");
+ // The failure is recorded and nothing goes out a second time — a retry here would post
+ // the reply twice.
+ await waitFor(
+ () =>
+ (
+ t.deps.db.prepare("SELECT code FROM error_records WHERE source = 'messaging'").all() as {
+ code: string;
+ }[]
+ ).length > 0,
+ );
+ expect(fake.allSends()).toEqual([]);
+ });
+
+ it("with linePerMessage, each line is converted on its own", async () => {
+ // A table row alone is not a table, and that is the honest reading of a message
+ // containing one line: it arrives as the text it is rather than as a broken construct.
+ await bindReplying("**bold line**\n| a | b |", {
+ appId: "cli_md_lines",
+ linePerMessage: true,
+ renderMarkdown: true,
+ });
+ await messageBot("oc_md_lines");
+ await waitFor(() => fake.allSends().length === 2);
+ expect(fake.allCards().map((c) => c.text)).toEqual(["**bold line**", "| a | b |"]);
+ });
+
+ it("PUT saves renderMarkdown, defaults it ON, and an omitted one keeps the stored value", async () => {
+ // A binding created without an opinion renders Markdown: the corrected behaviour is the
+ // default, because sending the model's Markdown as characters was the defect.
+ await api.put(BASE(SID), { appId: PUT_BODY.appId, appSecret: PUT_BODY.appSecret });
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.renderMarkdown).toBe(true);
+ // Round trip: PUT -> row -> the masked read the editor renders its switch from.
+ await api.put(BASE(SID), { ...PUT_BODY, renderMarkdown: false });
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.renderMarkdown).toBe(false);
+ const read = (await (await api.get(BASE(SID))).json()) as FeishuBindingResponse;
+ expect(read.binding?.renderMarkdown).toBe(false);
+ // A credentials-only save says nothing about it, so an OFF binding stays off — the
+ // default must not creep back in on every later save.
+ await api.put(BASE(SID), { appId: PUT_BODY.appId });
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.renderMarkdown).toBe(false);
+ await api.put(BASE(SID), { ...PUT_BODY, renderMarkdown: true });
+ expect(t.deps.messagingRepo.find(SID, "feishu")?.renderMarkdown).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);
diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsx
index b3c49bb0..5bdc65bf 100644
--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx
+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx
@@ -935,9 +935,11 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
</>
)}
{/* 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
+ sitting among them. Every row is 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.
+ effect in: which messages are sent, then how each one is split, then how each of
+ those is rendered. The Markdown row's sentence is the one that differs per channel,
+ because what a channel can show is the whole of what the reader needs to decide.
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
@@ -969,6 +971,18 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })
checked={delivery.linePerMessage}
onChange={(v) => patchDelivery({ linePerMessage: v })}
/>
+ <DeliveryOptionRow
+ label={S.messaging.renderMarkdown}
+ help={
+ channel === "telegram"
+ ? S.messaging.renderMarkdownHelpTelegram
+ : channel === "qq"
+ ? S.messaging.renderMarkdownHelpQQ
+ : S.messaging.renderMarkdownHelpFeishu
+ }
+ checked={delivery.renderMarkdown}
+ onChange={(v) => patchDelivery({ renderMarkdown: v })}
+ />
</div>
);
}
diff --git a/packages/web/src/features/messaging/messaging-binding-form.ts b/packages/web/src/features/messaging/messaging-binding-form.ts
index 7746dcac..93f005e3 100644
--- a/packages/web/src/features/messaging/messaging-binding-form.ts
+++ b/packages/web/src/features/messaging/messaging-binding-form.ts
@@ -9,7 +9,8 @@
* there is nothing for a domain to switch between.
*
* 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
+ * line), `finalReplyOnly` (send only a run's last reply, when the run ends) and
+ * `renderMarkdown` (render its Markdown in the channel's own markup) 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.
*
@@ -36,15 +37,17 @@ export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";
const TELEGRAM_TOKEN_RE = /^\d+:[A-Za-z0-9_-]{5,}$/;
/**
- * 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.
+ * The delivery preferences every channel carries — the 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;
+ /** Render a reply's Markdown in this channel's own markup instead of sending its characters. */
+ renderMarkdown: boolean;
}
export interface FeishuFormFields extends MessagingDeliveryFields {
@@ -100,6 +103,8 @@ export type MessagingTestRequestByChannel =
export function emptyMessagingForm(channel: MessagingChannel = "feishu"): MessagingFormState {
return {
channel,
+ // `renderMarkdown` starts ON, matching what the server gives a binding created without
+ // an opinion: a reply's Markdown is meant to render, and raw `**bold**` was the defect.
feishu: {
appId: "",
appSecret: "",
@@ -107,14 +112,22 @@ export function emptyMessagingForm(channel: MessagingChannel = "feishu"): Messag
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
+ },
+ telegram: {
+ botToken: "",
+ clearToken: false,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
},
- telegram: { botToken: "", clearToken: false, linePerMessage: false, finalReplyOnly: false },
qq: {
appId: "",
appSecret: "",
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
};
}
@@ -137,6 +150,7 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormS
clearSecret: false,
linePerMessage: info.linePerMessage,
finalReplyOnly: info.finalReplyOnly,
+ renderMarkdown: info.renderMarkdown,
};
} else if (info.channel === "qq") {
form.qq = {
@@ -145,6 +159,7 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormS
clearSecret: false,
linePerMessage: info.linePerMessage,
finalReplyOnly: info.finalReplyOnly,
+ renderMarkdown: info.renderMarkdown,
};
} else {
// Telegram's only credential field is the secret itself, so its sub-state loads empty
@@ -154,6 +169,7 @@ export function bindingsToForm(bindings: MessagingBindingInfo[]): MessagingFormS
clearToken: false,
linePerMessage: info.linePerMessage,
finalReplyOnly: info.finalReplyOnly,
+ renderMarkdown: info.renderMarkdown,
};
}
}
@@ -198,6 +214,7 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M
// would make turning either option back off impossible.
linePerMessage: form.telegram.linePerMessage,
finalReplyOnly: form.telegram.finalReplyOnly,
+ renderMarkdown: form.telegram.renderMarkdown,
},
};
}
@@ -218,6 +235,7 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M
// Always sent, for the same reason as the other channels': an omitted flag means "keep".
linePerMessage: form.qq.linePerMessage,
finalReplyOnly: form.qq.finalReplyOnly,
+ renderMarkdown: form.qq.renderMarkdown,
},
};
}
@@ -240,6 +258,7 @@ export function formToPut(form: MessagingFormState, hasStoredSecret: boolean): M
// Always sent, for the same reason as Telegram's: an omitted flag means "keep".
linePerMessage: form.feishu.linePerMessage,
finalReplyOnly: form.feishu.finalReplyOnly,
+ renderMarkdown: form.feishu.renderMarkdown,
},
};
}
@@ -290,7 +309,8 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormState
form.telegram.botToken.trim() !== "" ||
form.telegram.clearToken ||
form.telegram.linePerMessage !== baseline.telegram.linePerMessage ||
- form.telegram.finalReplyOnly !== baseline.telegram.finalReplyOnly
+ form.telegram.finalReplyOnly !== baseline.telegram.finalReplyOnly ||
+ form.telegram.renderMarkdown !== baseline.telegram.renderMarkdown
);
}
if (form.channel === "qq") {
@@ -299,7 +319,8 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormState
form.qq.appSecret.trim() !== "" ||
form.qq.clearSecret ||
form.qq.linePerMessage !== baseline.qq.linePerMessage ||
- form.qq.finalReplyOnly !== baseline.qq.finalReplyOnly
+ form.qq.finalReplyOnly !== baseline.qq.finalReplyOnly ||
+ form.qq.renderMarkdown !== baseline.qq.renderMarkdown
);
}
return (
@@ -308,7 +329,8 @@ export function formDirty(form: MessagingFormState, baseline: MessagingFormState
form.feishu.appSecret.trim() !== "" ||
form.feishu.clearSecret ||
form.feishu.linePerMessage !== baseline.feishu.linePerMessage ||
- form.feishu.finalReplyOnly !== baseline.feishu.finalReplyOnly
+ form.feishu.finalReplyOnly !== baseline.feishu.finalReplyOnly ||
+ form.feishu.renderMarkdown !== baseline.feishu.renderMarkdown
);
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 61e313a2..784ff525 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1981,6 +1981,19 @@ 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: render a reply's Markdown in the channel's own markup. */
+ renderMarkdown: "Render Markdown",
+ /**
+ * Its disclosure, beside the label. One per channel, because what a channel can show is
+ * the whole of what the reader needs to know here — a shared sentence would have to say
+ * "depending on the channel", which answers nothing.
+ */
+ renderMarkdownHelpFeishu:
+ "A reply's Markdown arrives as formatting instead of as `**characters**`. Feishu renders it as a card: headings, bold, italic, strikethrough, code and fenced code blocks, lists, quotes, rules, links and tables. A table longer than five rows arrives as a code block so no row is hidden. If Feishu refuses the card, the reply is sent as plain text rather than lost.",
+ renderMarkdownHelpTelegram:
+ "A reply's Markdown arrives as formatting instead of as `**characters**`. Telegram shows bold, italic, strikethrough, links, inline code and code blocks; it has no headings, lists or tables, so a heading becomes a bold line, list markers become part of the text, and a table arrives as a code block. If Telegram refuses the formatting, the reply is sent as plain text rather than lost.",
+ renderMarkdownHelpQQ:
+ "A reply's Markdown arrives as formatting instead of as `**characters**`. QQ shows headings, bold, italic, strikethrough, lists, quotes, rules and links; it has no code formatting and no tables, so a code block arrives as plain lines and a table as its rows. If QQ refuses the formatting, the reply is sent as plain text — which costs one more of the few replies QQ allows per message.",
/** 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. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 42e2b2f8..9a673f3c 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1935,6 +1935,19 @@ Benchmark:
credentialMissingHint: "先填写并保存凭证,再启用连接",
/** Why the clear checkbox is gated while the channel's connection is enabled. */
disableBeforeClearHint: "先停用连接,才能清除凭证",
+ /** The saved delivery option: render a reply's Markdown in the channel's own markup. */
+ renderMarkdown: "渲染 Markdown",
+ /**
+ * Its disclosure, beside the label. One per channel, because what a channel can show is
+ * the whole of what the reader needs to know here — a shared sentence would have to say
+ * "depending on the channel", which answers nothing.
+ */
+ renderMarkdownHelpFeishu:
+ "开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。飞书以卡片渲染:标题、粗体、斜体、删除线、行内代码与代码块、列表、引用、分割线、链接和表格都支持。超过五行的表格改以代码块发送,任何一行都不会被隐藏。若飞书拒绝该卡片,回复会改以纯文本发出,不会丢失。",
+ renderMarkdownHelpTelegram:
+ "开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。Telegram 支持粗体、斜体、删除线、链接、行内代码与代码块;它没有标题、列表和表格,因此标题渲染为一行粗体,列表符号作为文本的一部分保留,表格改以代码块发送。若 Telegram 拒绝该排版,回复会改以纯文本发出,不会丢失。",
+ renderMarkdownHelpQQ:
+ "开启后,回复中的 Markdown 以排版形式到达,而不是显示为 `**字符**`。QQ 支持标题、粗体、斜体、删除线、列表、引用、分割线和链接;它没有代码格式,也没有表格,因此代码块按普通文本行到达,表格按其行到达。若 QQ 拒绝该排版,回复会改以纯文本发出——这会多占用 QQ 对每条消息只允许的少数几条回复中的一条。",
/** 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. */
diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.ts
index 939d4d79..a33ca1dc 100644
--- a/packages/web/test/messaging-binding-editor.test.ts
+++ b/packages/web/test/messaging-binding-editor.test.ts
@@ -206,19 +206,53 @@ describe("MessagingBindingBody", () => {
});
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
+ // One row per option, each 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;
+ // Markdown rendering defaults ON, so the fresh form already has two of the three rows in
+ // opposite states — which is what makes each row's slice worth reading separately.
const html = render(stateOf("telegram", {}, { form }));
const finalAt = html.indexOf(S.messaging.finalReplyOnly);
const lineAt = html.indexOf(S.messaging.linePerMessage);
+ const markdownAt = html.indexOf(S.messaging.renderMarkdown);
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(markdownAt).toBeGreaterThan(lineAt);
+ // Each switch reads its own field: flipped, unflipped, and on by default.
expect(html.slice(finalAt, lineAt)).toContain('aria-checked="true"');
- expect(html.slice(lineAt)).toContain('aria-checked="false"');
+ expect(html.slice(lineAt, markdownAt)).toContain('aria-checked="false"');
+ expect(html.slice(markdownAt)).toContain('aria-checked="true"');
+ });
+
+ it('closes the form with the Markdown option too, its per-channel explanation behind the "?"', () => {
+ const help = {
+ feishu: S.messaging.renderMarkdownHelpFeishu,
+ telegram: S.messaging.renderMarkdownHelpTelegram,
+ qq: S.messaging.renderMarkdownHelpQQ,
+ } as const;
+ for (const channel of ["feishu", "telegram", "qq"] as MessagingChannel[]) {
+ const html = render(stateOf(channel));
+ expect(html).toContain(S.messaging.renderMarkdown);
+ // Semantics disclose — the sentence is in the popover panel, which renders collapsed.
+ expect(html).toContain(S.common.moreInfoAbout(S.messaging.renderMarkdown));
+ expect(html).not.toContain(help[channel]);
+ // One sentence per channel: what a channel can show is the whole of what the reader
+ // needs here, and a shared line would have to say "depending on the channel".
+ for (const other of ["feishu", "telegram", "qq"] as MessagingChannel[]) {
+ if (other !== channel) expect(html).not.toContain(help[other]);
+ }
+ // After the credential fields, like the other delivery preference.
+ const fieldAt = html.indexOf(
+ channel === "telegram"
+ ? S.telegram.botToken
+ : channel === "qq"
+ ? S.qq.appId
+ : S.feishu.appId,
+ );
+ expect(html.indexOf(S.messaging.renderMarkdown)).toBeGreaterThan(fieldAt);
+ }
});
it("states QQ's replies-only rule on screen, not in a collapsed fold", () => {
diff --git a/packages/web/test/messaging-binding-form.test.ts b/packages/web/test/messaging-binding-form.test.ts
index 4d3fcda8..70c8e687 100644
--- a/packages/web/test/messaging-binding-form.test.ts
+++ b/packages/web/test/messaging-binding-form.test.ts
@@ -34,6 +34,7 @@ const STORED_FEISHU: FeishuBindingInfo = {
enabled: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
lastChatKnown: true,
createdAt: "2026-08-25T00:00:00.000Z",
updatedAt: "2026-08-25T00:00:00.000Z",
@@ -48,6 +49,9 @@ const STORED_TELEGRAM: TelegramBindingInfo = {
// Set on one fixture only, so a per-channel load cannot pass by copying the other channel.
linePerMessage: true,
finalReplyOnly: false,
+ // Off on one fixture only, for the same reason — and because ON is the default, so a load
+ // that ignored the stored value would still look right on the other two.
+ renderMarkdown: false,
lastChatKnown: false,
createdAt: "2026-08-26T00:00:00.000Z",
updatedAt: "2026-08-26T00:00:00.000Z",
@@ -62,6 +66,7 @@ const STORED_QQ: QQBindingInfo = {
linePerMessage: false,
// The other flag, set on a different fixture: neither can pass by riding the other.
finalReplyOnly: true,
+ renderMarkdown: true,
lastChatKnown: true,
createdAt: "2026-08-27T00:00:00.000Z",
updatedAt: "2026-08-27T00:00:00.000Z",
@@ -71,6 +76,7 @@ describe("emptyMessagingForm / bindingsToForm", () => {
it("starts empty forms on Feishu with the default domain, both channels blank", () => {
expect(emptyMessagingForm()).toEqual({
channel: "feishu",
+ // Markdown rendering starts ON, matching the server's default for a fresh binding.
feishu: {
appId: "",
appSecret: "",
@@ -78,14 +84,22 @@ describe("emptyMessagingForm / bindingsToForm", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
+ },
+ telegram: {
+ botToken: "",
+ clearToken: false,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
},
- telegram: { botToken: "", clearToken: false, linePerMessage: false, finalReplyOnly: false },
qq: {
appId: "",
appSecret: "",
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
});
});
@@ -103,9 +117,17 @@ describe("emptyMessagingForm / bindingsToForm", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
+ },
+ // Each channel's delivery preferences come from its own stored config — including the
+ // one whose default is ON, which only a stored `false` can prove was actually read.
+ telegram: {
+ botToken: "",
+ clearToken: false,
+ linePerMessage: true,
+ finalReplyOnly: false,
+ renderMarkdown: false,
},
- // 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: "",
@@ -113,6 +135,7 @@ describe("emptyMessagingForm / bindingsToForm", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
});
// All three coexist: every saved channel loads its own non-secret fields.
@@ -142,6 +165,7 @@ describe("formToPut (feishu)", () => {
baseDomain: "https://open.larksuite.com",
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
});
});
@@ -174,6 +198,7 @@ describe("formToPut (feishu)", () => {
baseDomain: "https://open.larksuite.com",
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
});
// The models idiom: a typed replacement wins over a stale checked box.
@@ -185,6 +210,7 @@ describe("formToPut (feishu)", () => {
baseDomain: "https://open.larksuite.com",
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
});
// Without a stored secret there is nothing to clear: the flag never reaches the body.
const nothingStored = emptyMessagingForm();
@@ -205,6 +231,7 @@ describe("formToPut (feishu)", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
};
const blankDomain = formToPut(form, false);
expect(blankDomain.ok && blankDomain.channel === "feishu" && blankDomain.body.baseDomain).toBe(
@@ -228,6 +255,7 @@ describe("formToPut (telegram)", () => {
botToken: "7000000001:secret-token-AAAA",
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
},
});
// With a stored token an empty field means "keep it": the body omits the token — but not
@@ -236,7 +264,7 @@ describe("formToPut (telegram)", () => {
expect(formToPut(form, true)).toEqual({
ok: true,
channel: "telegram",
- body: { linePerMessage: false, finalReplyOnly: false },
+ body: { linePerMessage: false, finalReplyOnly: false, renderMarkdown: true },
});
// A first bind must carry one.
expect(formToPut(form, false)).toEqual({ ok: false, errors: { botToken: "required" } });
@@ -248,7 +276,12 @@ describe("formToPut (telegram)", () => {
expect(formToPut(form, true)).toEqual({
ok: true,
channel: "telegram",
- body: { clearBotToken: true, linePerMessage: false, finalReplyOnly: false },
+ body: {
+ clearBotToken: true,
+ linePerMessage: false,
+ finalReplyOnly: false,
+ renderMarkdown: true,
+ },
});
form.telegram.botToken = "7000000001:replacement-token";
const typed = formToPut(form, true);
@@ -256,6 +289,7 @@ describe("formToPut (telegram)", () => {
botToken: "7000000001:replacement-token",
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
});
});
@@ -280,6 +314,7 @@ describe("formToPut (telegram)", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
};
feishuSide.telegram.botToken = "garbage";
expect(formToPut(feishuSide, false).ok).toBe(true);
@@ -332,6 +367,7 @@ describe("formToTest", () => {
clearSecret: false,
linePerMessage: false,
finalReplyOnly: false,
+ renderMarkdown: true,
};
expect(formToTest(feishu)).toEqual({
channel: "feishu",
@@ -435,7 +471,12 @@ 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, finalReplyOnly: true },
+ body: {
+ appId: "102000001",
+ linePerMessage: false,
+ finalReplyOnly: true,
+ renderMarkdown: true,
+ },
});
form.qq.appSecret = " fresh-secret ";
@@ -447,6 +488,7 @@ describe("the QQ channel", () => {
appSecret: "fresh-secret",
linePerMessage: false,
finalReplyOnly: true,
+ renderMarkdown: true,
},
});
});
@@ -468,6 +510,7 @@ describe("the QQ channel", () => {
clearAppSecret: true,
linePerMessage: false,
finalReplyOnly: true,
+ renderMarkdown: true,
},
});
// A typed secret wins over a stale clear checkbox (the models idiom).
@@ -480,6 +523,7 @@ describe("the QQ channel", () => {
appSecret: "typed",
linePerMessage: false,
finalReplyOnly: true,
+ renderMarkdown: true,
},
});
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ff01b249..523493b1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -298,6 +298,12 @@ importers:
node-pty:
specifier: ^1.1.0
version: 1.1.0
+ remark-gfm:
+ specifier: ^4.0.0
+ version: 4.0.1([email protected])
+ remark-parse:
+ specifier: ^11.0.0
+ version: 11.0.0([email protected])
smol-toml:
specifier: ^1.3.0
version: 1.6.1
@@ -307,6 +313,9 @@ importers:
undici:
specifier: ^7.29.0
version: 7.29.0
+ unified:
+ specifier: ^11.0.5
+ version: 11.0.5
ws:
specifier: ^8.18.3
version: 8.21.0
@@ -314,6 +323,9 @@ importers:
specifier: ^2.5.0
version: 2.9.0
devDependencies:
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/node':
specifier: ^24.0.0
version: 24.13.3
@@ -4711,9 +4723,12 @@ snapshots:
fflate: 0.8.3
hono: 4.12.34
node-pty: 1.1.0
+ remark-gfm: 4.0.1([email protected])
+ remark-parse: 11.0.0([email protected])
smol-toml: 1.6.1
tar: 7.5.22
undici: 7.29.0
+ unified: 11.0.5
ws: 8.21.0
yaml: 2.9.0
transitivePeerDependencies:
@@ -4735,9 +4750,12 @@ snapshots:
fflate: 0.8.3
hono: 4.12.34
node-pty: 1.1.0
+ remark-gfm: 4.0.1([email protected])
+ remark-parse: 11.0.0([email protected])
smol-toml: 1.6.1
tar: 7.5.22
undici: 7.29.0
+ unified: 11.0.5
ws: 8.21.0
yaml: 2.9.0
transitivePeerDependencies: