Skip to content

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

fix(server): Telegram replies stay in the forum topic they were asked in (#507)

Yaowei Zheng7af12f475ebf
diff --git a/changelog/unreleased/2026-08-26-telegram-forum-topics.md b/changelog/unreleased/2026-08-26-telegram-forum-topics.md
new file mode 100644
index 00000000..7e5620db
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-telegram-forum-topics.md
@@ -0,0 +1,60 @@
+# Replies stay in the Telegram forum topic they were asked in
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507)
+
+[中文版](2026-08-26-telegram-forum-topics.zh.md)
+
+A forum supergroup splits one chat into topics, and every message carries the topic it was
+written in. Only the first reply of a run stayed there — Telegram infers a reply's topic from the
+message it quotes — while everything after it walked out of the conversation into **General**:
+the run's later completed messages, every chunk after the first of a long one, the
+tool-approval notice, and the test message. Half an answer arrived where it was asked for and the
+rest turned up somewhere else.
+
+## The topic rides the chat id
+
+The topic was packed into `messaging_bindings.last_chat_id` as `<chat id>:<topic id>`, leaving the
+bare chat id for every message written outside one. `MessagingInboundMessage.chatId` was already
+opaque to the bridge in the way `messageId` is — the connector mints it and the connector consumes
+it in `sendText` — so the topic reached every outbound path without the channel-neutral seam, the
+repo or the schema learning what a forum topic is, and it crossed a restart in the column that
+already stored the chat.
+
+The binding was given the **most recent** topic, matching what it already did with the chat
+itself: a user who moves to a new topic gets the replies there.
+
+Reply refs gained the same optional component, because `allow_sending_without_reply` degrades a
+vanished reply target to a plain send, which would have dropped the topic along with it.
+
+Rows written before this change need nothing done to them — see
+[backward compatibility](2026-08-27-backward-compatibility.md).
+
+## Only a real forum topic is remembered
+
+Telegram sets a message's `message_thread_id` on an ordinary reply chain too — in a private chat,
+and in a supergroup that is no forum — while `sendMessage` takes the parameter for forum
+supergroups only, and refuses anything else with `Bad Request: message thread not found`. A topic
+was therefore minted only from a message whose chat reports `is_forum` and which itself reports
+`is_topic_message`. Everywhere else the refs stayed bare chat and message ids, and an outbound
+message stayed the single request it always was.
+
+## A deleted topic degrades instead of losing the reply
+
+The Bot API has no `allow_sending_without_thread` to match the reply flag, so a send into a topic
+that has since been deleted or closed fails with a `400`. Such a send was retried once without the
+topic, which puts the message in General. Only a `400` is retried, and only when a topic was
+attached: a flood wait would be lengthened by an immediate second request, and a transport failure
+carries no answer from Telegram at all, so the message it was sent for may already have arrived. A
+send that carried no topic is never retried, and a genuine failure still surfaces as
+`messaging_send_failed`. A reply that reached General this way is logged, once per episode rather
+than once per message.
+
+## One reply, one place
+
+A reply's two halves — the chat it goes to, and the inbound message its first chunk quotes — were
+snapshotted together before the first send, instead of one of them being re-read for every chunk.
+A message arriving in a second topic mid-delivery had been able to move them apart, splitting one
+reply between two topics.
diff --git a/changelog/unreleased/2026-08-26-telegram-forum-topics.zh.md b/changelog/unreleased/2026-08-26-telegram-forum-topics.zh.md
new file mode 100644
index 00000000..e0ed4c2f
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-telegram-forum-topics.zh.md
@@ -0,0 +1,49 @@
+# 回复留在被提问的那个 Telegram 话题里
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`
+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507)
+
+[English](2026-08-26-telegram-forum-topics.md)
+
+论坛型超级群把一个会话拆成若干话题,每条消息都带着它被写在哪个话题里。此前只有一轮运行的第一条回
+复留在原处——Telegram 会从被引用的消息推断回复所属话题——其余的都走出了对话、落进 **General**:本轮
+后续完成的消息、长回复第一段之后的每一段、工具审批提示,以及测试消息。答案的一半到了该到的地方,
+另一半出现在别处。
+
+## 话题搭在 chat id 上
+
+话题被打包进 `messaging_bindings.last_chat_id`,形如 `<chat id>:<话题 id>`;写在话题之外的消息仍
+留裸 chat id。`MessagingInboundMessage.chatId` 本就对消息桥不透明,与 `messageId` 同理——由连接器
+铸造、也由连接器在 `sendText` 中消费——因此话题抵达了每一条出站路径,而渠道中立的接口、仓储与
+schema 都不必知道「论坛话题」是什么;它也随着本就存储会话的那一列一起跨过了重启。
+
+绑定拿到的是**最近一个**话题,与它此前对会话本身的处理一致:用户换到新话题,回复就跟到新话题。
+
+回复引用(reply ref)也获得了同样的可选分量,因为 `allow_sending_without_reply` 会在被引用消息消
+失时退化为普通发送,那会把话题一并丢掉。
+
+此前写入的行无需任何处理——见[向后兼容](2026-08-27-backward-compatibility.zh.md)。
+
+## 只记住真正的论坛话题
+
+Telegram 也会在普通的回复链上设置消息的 `message_thread_id`——私聊里如此,非论坛的超级群里也如此
+——而 `sendMessage` 的同名参数只接受论坛型超级群,其余一律以
+`Bad Request: message thread not found` 拒绝。因此只有当消息所在会话报告 `is_forum`、且该消息自身
+报告 `is_topic_message` 时,才会铸造出话题。其他任何地方,引用都仍是裸 chat id 与消息 id,出站消息
+也仍是它一贯的那一次请求。
+
+## 话题被删除时退化,而不是丢失回复
+
+Bot API 没有与回复标志对应的 `allow_sending_without_thread`,因此向一个已被删除或关闭的话题发送会
+以 `400` 失败。这类发送会不带话题重试一次,于是消息落在 General。只有 `400` 会重试,且只在本次发送
+带了话题时重试:限流等待会被一次毫无间隔的重发拉得更长,而传输层失败根本没有拿到 Telegram 的任何答
+复,它要发的那条消息可能已经送达。不带话题的发送绝不重试,真正的失败仍会以 `messaging_send_failed`
+呈现。以这种方式落进 General 的回复会被记入日志,每次退化记一条,而不是每条消息记一条。
+
+## 一条回复,一个地方
+
+一条回复的两半——它要去的会话,以及第一段所引用的入站消息——在第一次发送之前被一起快照下来,而不再
+由其中一半在每一段时重新读取。此前,投递途中到来的、写在另一个话题里的消息,能够把这两半分开,从而
+把一条回复劈到两个话题里。
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.md b/changelog/unreleased/2026-08-27-backward-compatibility.md
index a05c5e12..9a2c4478 100644
--- a/changelog/unreleased/2026-08-27-backward-compatibility.md
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.md
@@ -1,21 +1,23 @@
-# Backward compatibility: install-scoped browser state
+# Backward compatibility
- **Date:** 2026-08-27
- **Type:** process
- **Scope:** `server`, `web`
-- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+- **Breaking:** yes — on downgrade only: a Telegram binding whose last message was written in a forum topic sends nothing on a build from before this change until its next inbound message
[中文版](2026-08-27-backward-compatibility.zh.md)
+This batch touched three things that outlive a release.
[Scoping browser-persisted UI state to its data root](2026-08-26-install-scoped-local-state.md)
-touched two things that outlive a release: a new file in the data root, `<root>/install-id`,
-and a new `localStorage` entry, `penguin.installId`. Only the browser side needed a decision;
-the file and the key are recorded here too, so a reader looking for "does my install need
-anything?" finds every answer in one place.
+added a file in the data root, `<root>/install-id`, and a `localStorage` entry,
+`penguin.installId`; and
+[a Telegram reply carrying the forum topic it was asked in](2026-08-26-telegram-forum-topics.md)
+changed what `messaging_bindings.last_chat_id` means on an existing `web.db`, without adding or
+dropping a column or rewriting a row. Only the browser side and the column needed a decision; the
+file and the key are recorded here too, so a reader looking for "does my install need anything?"
+finds every answer in one place.
-(The batch dated 2026-08-26 has its own
-[backward compatibility](2026-08-26-backward-compatibility.md) entry, about `web.db` and the
-messaging bindings. The two are unrelated.)
## The browser that has keys but no recorded id
@@ -69,7 +71,41 @@ no identity at all, and an unknown identity sweeps nothing.
key the sweep never removes: it is what the comparison reads. Builds from before this change
do not know the key and leave it alone, so a downgrade is invisible in both directions.
+## The `last_chat_id` column
+
+The column held a bare chat id, which every channel handed to its own API as-is. It now holds a
+string only the channel's connector may read: the Telegram connector writes `<chat id>:<topic id>`
+for a message written in a forum topic, and the bare chat id for every other message.
+
+Chosen: **permanent dual-format tolerance.** A row written before this change parses as itself —
+no separator means no topic — so nothing has to be migrated, converted or reset, and a binding
+that has never seen a forum topic is byte-identical to what it was.
+
+Calling that tolerance and asking how long it stays would be the wrong question. The bare form is
+not a legacy encoding: it is the only encoding a chat with no topic has, and every direct chat,
+every ordinary group and every forum's General topic writes one on every message. The two-form
+parse is the format, so nothing ever stops writing the bare form and nothing ever removes the code
+that reads it. `chatRefOf` in `telegram-connector.ts` carries the same note.
+
## 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.
+
+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.
+
+Downgrading is the leg that shows. A user who upgrades, chats in a forum topic and then rolls back
+has `last_chat_id` holding something like `-1004475424385:91`; a build from before this change
+passes that to Telegram as the chat id, `Number("-1004475424385:91")` is `NaN`, and the string
+goes on the wire, so every reply and every test message fails with `Bad Request: chat not found`.
+It repairs itself: the next inbound message on that binding overwrites the column with a bare id.
+Sending the bot one message is the whole fix, and clearing the column by hand does the same:
+
+```sql
+UPDATE messaging_bindings SET last_chat_id = NULL
+WHERE channel = 'telegram' AND last_chat_id LIKE '%:%';
+```
+
+No other channel is affected: Feishu chat ids are opaque strings the connector has always passed
+through untouched.
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
index 21bc816a..c70318ff 100644
--- a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
@@ -1,19 +1,20 @@
-# 向后兼容:按数据根划定作用域的浏览器状态
+# 向后兼容
- **Date:** 2026-08-27
- **Type:** process
- **Scope:** `server`, `web`
-- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+- **PR:** [#507](https://github.com/Prism-Shadow/penguin-harness/pull/507), [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+- **Breaking:** yes — 仅在降级时:最后一条消息写在论坛话题里的 Telegram 绑定,在此改动之前的构建上会一直发不出消息,直到下一条入站消息到来
[English](2026-08-27-backward-compatibility.md)
-[把浏览器持久化的 UI 状态按数据根划定作用域](2026-08-26-install-scoped-local-state.zh.md)动到了两样
-会跨越版本存活的东西:数据根里新增的文件 `<root>/install-id`,以及新增的 `localStorage` 条目
-`penguin.installId`。需要做决定的只有浏览器一侧;这个文件和这个键也一并记在这里,方便有人来查
-「我这套安装需要做什么吗?」时,在同一处找到全部答案。
+本批改动动到了三样会跨越版本存活的东西。[把浏览器持久化的 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-26 那一批有它自己的[向后兼容](2026-08-26-backward-compatibility.zh.md)条目,讲的是
-`web.db` 与消息绑定。两者互不相干。)
## 有键、但从未记录过 id 的浏览器
@@ -56,6 +57,34 @@
`penguin.installId` 是在 Web App 原有那些键之外新增的一条,也是清扫唯一从不删除的键:它正是比较时
读取的那一个。本次改动之前的构建不认识这个键,会原样放着,因此降级在两个方向上都不可察觉。
+## `last_chat_id` 列
+
+该列此前存的是裸 chat id,各渠道原样交给自己的 API。现在它存的是只有该渠道的连接器才可以解读的字符
+串:Telegram 连接器为写在论坛话题里的消息写入 `<chat id>:<话题 id>`,其余消息仍写裸 chat id。
+
+选择:**永久容忍两种形式。**此前写入的行按其本身解析——没有分隔符即没有话题——因此无需迁移、转换或
+重置;从未遇到过论坛话题的绑定与从前逐字节相同。
+
+把这称作「兼容代码」并追问它保留多久,问的就不是对的问题。裸形式不是遗留编码:它是「没有话题的会
+话」唯一的编码,每个私聊、每个普通群、每个论坛的 General 话题,每条消息写的都是它。两种形式的解析
+本身就是这个格式,所以裸形式永远会继续被写入,读取它的代码也永远不会被删除。
+`telegram-connector.ts` 里的 `chatRefOf` 写有同样的说明。
+
## 兼容性
升级与降级都不需要做任何操作。对在本版本之前清空过数据根的用户而言,唯一需要手动执行的一步在上文。
+
+升级对用户没有任何要求。升级后的第一条消息会照常重写该列,在那之前存着的裸 id 与从前一样可用。
+
+会显现出来的是降级这条腿。用户升级后在论坛话题里聊过,再回滚,此时 `last_chat_id` 里存的是
+`-1004475424385:91` 这样的值;此改动之前的构建会把它当作 chat id 交给 Telegram,
+`Number("-1004475424385:91")` 是 `NaN`,于是该字符串直接上了线,所有回复与测试消息都会以
+`Bad Request: chat not found` 失败。它会自愈:该绑定的下一条入站消息就会把这一列改回裸 id。给机器
+人发一条消息就是全部修法,手工清空该列也一样:
+
+```sql
+UPDATE messaging_bindings SET last_chat_id = NULL
+WHERE channel = 'telegram' AND last_chat_id LIKE '%:%';
+```
+
+其他渠道不受影响:飞书的 chat id 一直是连接器原样透传的不透明字符串。
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index 5a2ce3f8..96fa37ba 100644
--- a/packages/server/src/db/repos/messaging-bindings.ts
+++ b/packages/server/src/db/repos/messaging-bindings.ts
@@ -51,7 +51,12 @@ export interface MessagingBindingRow {
* original behaviour exactly. Ordinary saved state — the PUT owns it, like the config.
*/
linePerMessage: boolean;
- /** Most recent inbound chat (null until the bot is messaged once). */
+ /**
+ * 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
+ * topic into it, so it is not always a bare chat id. Pass it to `MessagingClient.sendText`,
+ * never to a channel API directly.
+ */
lastChatId: string | null;
/** Whether that chat is a direct chat; group chats prefer reply-to-message. */
lastChatIsDirect: boolean;
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index a3be8bc1..58f700ec 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -129,7 +129,7 @@ CREATE TABLE IF NOT EXISTS messaging_bindings ( -- Session ↔ messaging-channel
config_json TEXT NOT NULL, -- channel-specific credentials/config JSON (feishu: appId/appSecret/baseDomain; telegram: botToken; qq: appId/appSecret); secrets plaintext at rest (same trade-off as the proxy address in server_settings), masked at every API surface; a cleared secret is stored as "" (the row and its account identity stay)
enabled INTEGER NOT NULL DEFAULT 0, -- INTENT state (the connection's runtime status stays in memory): new bindings start disabled — saving credentials never opens a connection, the explicit state toggle 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
- last_chat_id TEXT, -- most recent inbound chat (NULL until the bot is messaged once; replies and test messages target it)
+ 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
created_at TEXT NOT NULL,
diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.ts
index 7f245196..bb6eda43 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -56,6 +56,7 @@ import type {
MessagingChannelConnector,
MessagingClient,
MessagingInboundMessage,
+ MessagingSendNote,
} from "./connector.js";
/**
@@ -287,6 +288,13 @@ interface BridgeEntry {
*/
lastInboundAt: string | null;
lastDeliveryError: MessagingDeliveryError | null;
+ /**
+ * The degradation the last outbound send reported (see MessagingSendNote), so a standing
+ * one is logged once per episode: a deleted forum topic degrades every chunk of every
+ * message, and a line per send would bury the fact that it started. Cleared by the first
+ * send that lands as addressed, so a later episode says so again.
+ */
+ lastSendNote: MessagingSendNote | null;
/**
* The last connection failure, kept across recovery. `status.lastError` is wiped by the
* next successful connect, which is exactly the case worth reporting: a connector that
@@ -492,6 +500,7 @@ export class MessagingBridge {
lastInboundMessageId: null,
lastInboundAt: null,
lastDeliveryError: null,
+ lastSendNote: null,
lastConnectionError: null,
active: runState,
armed: runState === "idle",
@@ -615,6 +624,18 @@ export class MessagingBridge {
this.recordError(entry.sessionId, err, code);
}
+ /**
+ * A send that landed somewhere less right than it was addressed to. Not a failure — the
+ * message arrived — so it stays out of `lastDeliveryError` and off the panel, and goes to
+ * the log, which is where "the replies moved to General a while ago" is answerable at all.
+ */
+ private noteSend(entry: BridgeEntry, note: MessagingSendNote | void): void {
+ const seen = typeof note === "string" ? note : null;
+ if (seen === entry.lastSendNote) return;
+ entry.lastSendNote = seen;
+ if (seen !== null) this.log(`[messaging] ${entry.channel} delivered degraded: ${seen}`);
+ }
+
private async clientFor(sessionId: string, row: MessagingBindingRow): Promise<MessagingClient> {
// The cached client belongs to the CONNECTED channel; another channel's caller (a
// test message on a saved-but-dark binding) gets a fresh client instead.
@@ -709,8 +730,12 @@ export class MessagingBridge {
const row = this.deps.repo.find(entry.sessionId, entry.channel);
if (!row) return;
const client = await this.clientFor(entry.sessionId, row);
- if (msg.chatKind === "direct") await client.sendText(msg.chatId, text);
- else await client.replyText(msg.messageId, text);
+ this.noteSend(
+ entry,
+ msg.chatKind === "direct"
+ ? await client.sendText(msg.chatId, text)
+ : await client.replyText(msg.messageId, text),
+ );
}
// —— Outbound ——————————————————————————————————————————————————————————————
@@ -797,6 +822,13 @@ export class MessagingBridge {
* headers over the whole conversation.
*/
private async deliverReply(entry: BridgeEntry, text: string): Promise<void> {
+ // Both halves of the target are snapshotted together, ahead of every await: this line runs
+ // before sendTarget, which reads the chat ref off the row synchronously before its own.
+ // An inbound message arriving mid-delivery moves them independently, and a reply whose
+ // first chunk threaded onto the new message while the rest went to the chat the row
+ // still named would be split across two places — two forum topics, on a channel that
+ // packs one into the chat ref.
+ const inboundMessageId = entry.lastInboundMessageId;
const target = await this.sendTarget(entry);
if (target === null) return;
const { row, chatId, client } = target;
@@ -811,15 +843,15 @@ export class MessagingBridge {
// about one a second, so they go out at that pace rather than back to back.
if (i > 0 && row.linePerMessage) await this.pace();
const threadOnto =
- !row.lastChatIsDirect && entry.lastInboundMessageId !== null && !entry.threadedThisRun
- ? entry.lastInboundMessageId
+ !row.lastChatIsDirect && inboundMessageId !== null && !entry.threadedThisRun
+ ? inboundMessageId
: null;
try {
if (threadOnto !== null) {
entry.threadedThisRun = true;
- await client.replyText(threadOnto, chunk);
+ this.noteSend(entry, await client.replyText(threadOnto, chunk));
} else {
- await client.sendText(chatId, chunk);
+ this.noteSend(entry, await client.sendText(chatId, chunk));
}
} catch (err) {
this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");
@@ -832,7 +864,7 @@ export class MessagingBridge {
const target = await this.sendTarget(entry);
if (target === null) return;
try {
- await target.client.sendText(target.chatId, text);
+ this.noteSend(entry, await target.client.sendText(target.chatId, text));
} catch (err) {
this.recordDeliveryFailure(entry, err, "send", "messaging_send_failed");
}
diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.ts
index fdfa1594..bd88651c 100644
--- a/packages/server/src/runtime/messaging/connector.ts
+++ b/packages/server/src/runtime/messaging/connector.ts
@@ -16,7 +16,13 @@ export type MessagingChannel = "feishu" | "telegram" | "qq";
/** One inbound chat message, normalized across channels. */
export interface MessagingInboundMessage {
- /** Channel-scoped chat id (the reply target for direct chats). */
+ /**
+ * Channel-scoped chat id, and the reply target for direct chats. Opaque to the bridge, for
+ * the same reason `messageId` is: the connector both mints it here and consumes it in
+ * `sendText`, so a channel whose replies need more routing context than a chat identity
+ * encodes it (Telegram appends the forum topic). It is stored verbatim as the binding's
+ * last known chat, so whatever is encoded here is what survives a restart.
+ */
chatId: string;
/** Direct chat with the bot, or a group chat (groups prefer reply-to-message). */
chatKind: "direct" | "group";
@@ -79,14 +85,24 @@ export interface MessagingAccountInfo {
readsGroupMessages?: boolean;
}
+/**
+ * What a send had to give up in order to land, as a short readable phrase. The message DID
+ * arrive — a send that did not throws — so this is not a failure: it says the message is
+ * somewhere less right than it was addressed to, which is otherwise invisible from the
+ * outside. A channel that always delivers as addressed returns nothing at all; Telegram is
+ * the one that reports, a forum topic deleted under a live conversation sending the reply to
+ * General instead.
+ */
+export type MessagingSendNote = string;
+
/** 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. */
- sendText(chatId: string, text: string): Promise<void>;
+ /** Sends a text message into a chat by chat id; resolves a MessagingSendNote when it degraded. */
+ sendText(chatId: string, text: string): Promise<MessagingSendNote | void>;
/** Replies a text message to a specific inbound message (threads correctly in group chats). */
- replyText(messageId: string, text: string): Promise<void>;
+ replyText(messageId: string, text: string): Promise<MessagingSendNote | void>;
}
export interface MessagingChannelConnector {
diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.ts
index d3c8f45f..33ea26de 100644
--- a/packages/server/src/runtime/messaging/telegram-api.ts
+++ b/packages/server/src/runtime/messaging/telegram-api.ts
@@ -59,6 +59,8 @@ export interface TelegramMessage {
id: number;
/** `private` for a direct chat with the bot; `group` / `supergroup` / `channel` otherwise. */
type: string;
+ /** "True, if the supergroup chat is a forum" — i.e. it is split into topics at all. */
+ is_forum?: boolean;
};
/** Present only for text messages; anything else (photo, sticker, voice, …) omits it. */
text?: string;
@@ -68,6 +70,26 @@ export interface TelegramMessage {
* `caption_entities` instead — the day this connector reads captions, it reads that.
*/
entities?: TelegramMessageEntity[];
+ /**
+ * "Unique identifier of a message thread or forum topic to which the message belongs; for
+ * supergroups and private chats only."
+ *
+ * Inbound and outbound are NOT symmetric, and the difference is the whole reason
+ * `is_topic_message` is read below. This field is also set on an ordinary reply chain — in
+ * a private chat, and in a supergroup that is no forum — while `sendMessage`'s
+ * `message_thread_id` is "for forum supergroups only" and answers anything else with
+ * `Bad Request: message thread not found`. So a value seen here may only be sent back once
+ * `chat.is_forum` and `is_topic_message` both say it names a forum topic.
+ *
+ * Absent in a forum supergroup's General topic — which is why absence has to mean "send
+ * without a thread" rather than "send to General by id".
+ */
+ message_thread_id?: number;
+ /**
+ * "True, if the message is sent to a forum topic." Absent for a forum's General topic and
+ * for the reply-chain `message_thread_id` above, which is exactly what tells the two apart.
+ */
+ is_topic_message?: boolean;
from?: {
first_name?: string;
username?: string;
@@ -101,8 +123,18 @@ export interface TelegramBotClient {
* reports the URL and leaves the bot alone.
*/
getWebhookInfo(): Promise<TelegramWebhookInfo>;
- /** Sends a text message into a chat; `replyToMessageId` threads it under an inbound message. */
- sendMessage(args: { chatId: string; text: string; replyToMessageId?: number }): Promise<void>;
+ /**
+ * Sends a text message into a chat; `replyToMessageId` threads it under an inbound message,
+ * and `messageThreadId` puts it in a forum topic. Without the latter a send lands in a forum
+ * supergroup's General topic, wherever the conversation actually is — and with it anywhere
+ * that is not a forum topic the call fails, the parameter being "for forum supergroups only".
+ */
+ sendMessage(args: {
+ chatId: string;
+ text: string;
+ replyToMessageId?: number;
+ messageThreadId?: number;
+ }): Promise<void>;
/**
* Long-poll for updates: blocks up to `timeoutSec` (0 = return immediately) and resolves
* the pending updates at or after `offset` (confirming everything before it; -1 means
@@ -136,6 +168,26 @@ interface TelegramEnvelope<T> {
error_code?: number;
}
+/**
+ * A Bot API call the server answered with `ok: false`, carrying Telegram's own `error_code`.
+ *
+ * The code is the only part of the envelope a caller may branch on: `description` is prose
+ * Telegram rewords without notice, so a retry keyed on its wording breaks silently. A
+ * transport failure — a timeout, a reset, an unparseable body — has no code and stays a
+ * plain Error, which keeps "the request never completed" distinguishable from "Telegram
+ * refused it"; nothing may retry the former, because the message may well have been
+ * delivered.
+ */
+export class TelegramApiError extends Error {
+ constructor(
+ message: string,
+ readonly errorCode: number | undefined,
+ ) {
+ super(message);
+ this.name = "TelegramApiError";
+ }
+}
+
/**
* The two 409s a Bot API caller can actually act on, rewritten to lead with the action.
* Telegram's own wording buries it — "Conflict: terminated by other getUpdates request;
@@ -198,7 +250,7 @@ export function createTelegramTransport(): TelegramTransport {
described ??
`HTTP ${res.status}`;
const code = body?.error_code !== undefined ? ` (code ${body.error_code})` : "";
- throw new Error(`${method} failed: ${detail}${code}`);
+ throw new TelegramApiError(`${method} failed: ${detail}${code}`, body?.error_code);
}
return body.result as T;
};
@@ -213,10 +265,11 @@ export function createTelegramTransport(): TelegramTransport {
return {
getMe: () => call<TelegramBotUser>("getMe", {}),
getWebhookInfo: () => call<TelegramWebhookInfo>("getWebhookInfo", {}),
- async sendMessage({ chatId, text, replyToMessageId }): Promise<void> {
+ async sendMessage({ chatId, text, replyToMessageId, messageThreadId }): Promise<void> {
await call("sendMessage", {
chat_id: wireChatId(chatId),
text,
+ ...(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 c89153ae..07490a03 100644
--- a/packages/server/src/runtime/messaging/telegram-connector.ts
+++ b/packages/server/src/runtime/messaging/telegram-connector.ts
@@ -2,7 +2,8 @@
* Telegram messaging connector — the second implementation of the
* MessagingChannelConnector seam, and the proof the seam is channel-neutral. It owns
* everything Telegram-specific: the config document's shape (a single bot token), the
- * Bot API transport behind it (injectable for tests — see telegram-api.ts), and the
+ * Bot API transport behind it (injectable for tests — see telegram-api.ts), the forum-topic
+ * routing it packs into the bridge's opaque chat and reply refs (see chatRefOf), and the
* inbound side as a `getUpdates` long-poll loop — Telegram pushes nothing without a
* public webhook URL, so the connector pulls, which keeps local deployments working
* exactly like the Feishu long connection does.
@@ -41,15 +42,18 @@ import type {
MessagingConnection,
MessagingConnectorHandlers,
MessagingInboundMessage,
+ MessagingSendNote,
} from "./connector.js";
import type {
TelegramBotClient,
TelegramBotUser,
TelegramCredentials,
+ TelegramMessage,
TelegramMessageEntity,
TelegramTransport,
TelegramUpdate,
} from "./telegram-api.js";
+import { TelegramApiError } from "./telegram-api.js";
/** The Telegram binding's stored config document (`messaging_bindings.config_json`). */
export interface TelegramBindingConfig extends Record<string, unknown> {
@@ -91,18 +95,63 @@ export interface TelegramConnectorOpts {
retryDelayMs?: (failures: number) => number;
}
-/** Reply refs pack the chat id in with the message id: Telegram message ids are only unique per chat. */
-function replyRefOf(chatId: number, messageId: number): string {
- return `${chatId}:${messageId}`;
+/**
+ * Chat and reply refs pack this channel's routing context into the two opaque strings the
+ * bridge already carries for it (MessagingInboundMessage's `chatId` and `messageId`): the
+ * connector mints them and the connector consumes them, so nothing between the two has to
+ * learn what a forum topic is — and the chat ref reaches `sendText` through the stored
+ * `messaging_bindings.last_chat_id`, which is what makes the remembered topic survive a
+ * restart with no column of its own.
+ *
+ * `:` is the separator because a Telegram chat id is a bare integer and a message id and a
+ * thread id both are too, so no component can ever contain one.
+ *
+ * A missing trailing component means "no forum topic", which covers every chat a topic
+ * cannot be sent to (see topicIdOf) as well as a forum's General topic — and it is also what
+ * every chat id stored before this existed looks like, so old rows parse as themselves. That
+ * is not compatibility code with a removal date: the bare form is the only encoding a chat
+ * with no topic has, so nothing ever stops writing it and nothing ever stops reading it.
+ */
+function chatRefOf(chatId: number, threadId: number | undefined): string {
+ return threadId === undefined ? `${chatId}` : `${chatId}:${threadId}`;
}
-function parseReplyRef(ref: string): { chatId: string; messageId: number } {
+function parseChatRef(ref: string): { chatId: string; threadId?: number } {
const i = ref.indexOf(":");
- const messageId = i >= 0 ? Number(ref.slice(i + 1)) : NaN;
- if (i <= 0 || !Number.isSafeInteger(messageId)) {
+ if (i < 0) return { chatId: ref };
+ const threadId = Number(ref.slice(i + 1));
+ if (i === 0 || !Number.isSafeInteger(threadId)) {
+ throw new Error(`malformed telegram chat ref "${ref}"`);
+ }
+ return { chatId: ref.slice(0, i), threadId };
+}
+
+/** Reply refs pack the chat id in with the message id: Telegram message ids are only unique per chat. */
+function replyRefOf(chatId: number, messageId: number, threadId: number | undefined): string {
+ const base = `${chatId}:${messageId}`;
+ return threadId === undefined ? base : `${base}:${threadId}`;
+}
+
+function parseReplyRef(ref: string): { chatId: string; messageId: number; threadId?: number } {
+ const [chatId, rawMessageId, rawThreadId, ...rest] = ref.split(":");
+ const messageId = Number(rawMessageId);
+ if (
+ chatId === undefined ||
+ chatId === "" ||
+ rawMessageId === undefined ||
+ !Number.isSafeInteger(messageId) ||
+ rest.length > 0
+ ) {
+ throw new Error(`malformed telegram reply ref "${ref}"`);
+ }
+ // The thread half is optional: refs minted before it existed have two components, and so
+ // does every message written outside a forum topic (see topicIdOf).
+ if (rawThreadId === undefined) return { chatId, messageId };
+ const threadId = Number(rawThreadId);
+ if (!Number.isSafeInteger(threadId)) {
throw new Error(`malformed telegram reply ref "${ref}"`);
}
- return { chatId: ref.slice(0, i), messageId };
+ return { chatId, messageId, threadId };
}
/** Abortable sleep (the backoff must not outlive a closed connection). */
@@ -122,6 +171,43 @@ function sleep(ms: number, signal: AbortSignal): Promise<void> {
});
}
+/** The note `sendWithThreadFallback` resolves when the topic had to be dropped to deliver. */
+const THREAD_DROPPED_NOTE = "forum topic gone, the reply went to General instead";
+
+/**
+ * One send, with the forum topic when there is one, degrading to a send without it if
+ * Telegram rejects the topic.
+ *
+ * A topic can be deleted or closed under a conversation that was happily using it, and the
+ * Bot API offers no `allow_sending_without_thread` to match the reply flag — the call simply
+ * fails with `Bad Request: message thread not found`. Retrying without the topic puts the
+ * message in General rather than losing a reply the model has already produced.
+ *
+ * Only a 400 is retried, and only when a thread was attached. Every other shape must reach
+ * the caller on its first attempt: a 429 flood-wait would be made worse by an immediate
+ * second request, and a transport failure — a timeout, a reset — may well have delivered the
+ * message already, so re-sending it would duplicate it in the chat. Those failures surface
+ * as `messaging_send_failed` instead, like any other.
+ */
+async function sendWithThreadFallback(
+ bot: TelegramBotClient,
+ args: { chatId: string; text: string; replyToMessageId?: number },
+ threadId: number | undefined,
+): Promise<MessagingSendNote | void> {
+ if (threadId === undefined) {
+ await bot.sendMessage(args);
+ return;
+ }
+ try {
+ await bot.sendMessage({ ...args, messageThreadId: threadId });
+ return;
+ } catch (err) {
+ if (!(err instanceof TelegramApiError) || err.errorCode !== 400) throw err;
+ }
+ await bot.sendMessage(args);
+ return THREAD_DROPPED_NOTE;
+}
+
/** 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;
@@ -160,6 +246,23 @@ function stripBotMention(
return (text.slice(0, lead.offset) + text.slice(lead.offset + lead.length)).trim();
}
+/**
+ * The forum topic this message was written in, or undefined when it was written anywhere a
+ * topic cannot be sent back to.
+ *
+ * `message_thread_id` alone does not mean "forum topic": Telegram also sets it on an
+ * ordinary reply chain, in a private chat and in a supergroup that is no forum, while
+ * `sendMessage`'s `message_thread_id` is accepted for forum topics only. Echoing one back
+ * anywhere else fails every outbound message of that binding with `Bad Request: message
+ * thread not found` — permanently, since the value is what gets persisted. Both flags are
+ * therefore required before a value is minted into a ref.
+ */
+function topicIdOf(msg: TelegramMessage): number | undefined {
+ return msg.chat.is_forum === true && msg.is_topic_message === true
+ ? msg.message_thread_id
+ : undefined;
+}
+
/**
* One update reduced to the bridge's normalized shape; null for updates that are not chat
* messages. `me` is this bot's own account (null before the first `getMe` of a connection
@@ -172,10 +275,14 @@ function normalizeUpdate(
const msg = update.message;
if (msg === undefined) return null;
const senderName = msg.from?.first_name ?? msg.from?.username;
+ const topicId = topicIdOf(msg);
return {
- chatId: String(msg.chat.id),
+ // The topic rides the chat id so the binding remembers the LAST one written in, the same
+ // way it already remembers the last chat: a user who moves to a new topic gets the
+ // replies there.
+ chatId: chatRefOf(msg.chat.id, topicId),
chatKind: msg.chat.type === "private" ? "direct" : "group",
- messageId: replyRefOf(msg.chat.id, msg.message_id),
+ messageId: replyRefOf(msg.chat.id, msg.message_id, topicId),
// Only text messages carry `text`; every other message type normalizes to null (the
// bridge answers those with the text-only notice).
text: typeof msg.text === "string" ? stripBotMention(msg.text, msg.entities, me) : null,
@@ -213,12 +320,17 @@ export class TelegramConnector implements MessagingChannelConnector {
: {}),
};
},
- async sendText(chatId, text) {
- await bot.sendMessage({ chatId, text });
+ sendText(chatRef, text) {
+ const { chatId, threadId } = parseChatRef(chatRef);
+ return sendWithThreadFallback(bot, { chatId, text }, threadId);
},
- async replyText(messageRef, text) {
- const { chatId, messageId } = parseReplyRef(messageRef);
- await bot.sendMessage({ chatId, text, replyToMessageId: messageId });
+ replyText(messageRef, text) {
+ 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);
},
};
}
diff --git a/packages/server/test/messaging-qq.test.ts b/packages/server/test/messaging-qq.test.ts
index 54bdd394..09865a8f 100644
--- a/packages/server/test/messaging-qq.test.ts
+++ b/packages/server/test/messaging-qq.test.ts
@@ -31,6 +31,7 @@ import {
MESSAGING_TEST_MESSAGE,
MESSAGING_TEXT_ONLY_NOTICE,
} from "../src/runtime/messaging/bridge.js";
+import type { MessagingClient } from "../src/runtime/messaging/connector.js";
import type {
QQBotClient,
QQCredentials,
@@ -742,7 +743,7 @@ describe("the passive-reply ledger's lifetime", () => {
}
/** Spends every immediate slot of a single chat's budget, leaving only the reserved one. */
- async function spendImmediate(client: { sendText(chatId: string, text: string): Promise<void> }) {
+ async function spendImmediate(client: Pick<MessagingClient, "sendText">) {
for (const text of ["a", "b", "c"]) await client.sendText(CHAT, text);
}
diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.ts
index 43be8349..0a084faa 100644
--- a/packages/server/test/messaging-telegram.test.ts
+++ b/packages/server/test/messaging-telegram.test.ts
@@ -12,8 +12,8 @@
* transport maps a 409 to). No test opens real network.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { assistantText } from "@prismshadow/penguin-core";
-import type { OmniMessage, TextPayload } from "@prismshadow/penguin-core";
+import { approvalDecision, assistantText, toolCall } from "@prismshadow/penguin-core";
+import type { ApproveFn, OmniMessage, TextPayload } from "@prismshadow/penguin-core";
import type {
FeishuBindingResponse,
MessagingBindingsResponse,
@@ -23,6 +23,7 @@ import type {
import type { SessionRow } from "../src/db/repos/sessions.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import {
+ MESSAGING_APPROVAL_NOTICE,
MESSAGING_TEXT_ONLY_NOTICE,
MESSAGING_TEST_MESSAGE,
} from "../src/runtime/messaging/bridge.js";
@@ -34,7 +35,10 @@ import type {
TelegramUpdate,
TelegramWebhookInfo,
} from "../src/runtime/messaging/telegram-api.js";
-import { createTelegramTransport } from "../src/runtime/messaging/telegram-api.js";
+import {
+ TelegramApiError,
+ createTelegramTransport,
+} from "../src/runtime/messaging/telegram-api.js";
import { TelegramConnector, telegramBotIdOf } from "../src/runtime/messaging/telegram-connector.js";
import type {
FeishuApiClient,
@@ -59,10 +63,13 @@ interface SentMessage {
chatId: string;
text: string;
replyTo?: number;
+ threadId?: number;
}
class FakeBotClient implements TelegramBotClient {
readonly sends: SentMessage[] = [];
+ /** Every sendMessage ATTEMPT, failures included — `sends` records only what got through. */
+ sendCalls = 0;
getMeCalls = 0;
/** A long poll is currently parked waiting for an update. */
parked = false;
@@ -97,12 +104,26 @@ class FakeBotClient implements TelegramBotClient {
chatId: string;
text: string;
replyToMessageId?: number;
+ messageThreadId?: number;
}): Promise<void> {
- if (this.t.failSend !== null) throw new Error(this.t.failSend);
+ this.sendCalls++;
+ 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.
+ throw this.t.failSendCode === null
+ ? new Error(this.t.failSend)
+ : new TelegramApiError(this.t.failSend, this.t.failSendCode);
+ }
+ // A topic deleted or closed under a live conversation: the threaded call fails and the
+ // same call without a thread succeeds, which is the shape the fallback has to survive.
+ if (args.messageThreadId !== undefined && this.t.failThreadedSend !== null) {
+ throw new TelegramApiError(this.t.failThreadedSend, this.t.failThreadedSendCode);
+ }
this.sends.push({
chatId: args.chatId,
text: args.text,
...(args.replyToMessageId !== undefined ? { replyTo: args.replyToMessageId } : {}),
+ ...(args.messageThreadId !== undefined ? { threadId: args.messageThreadId } : {}),
});
}
@@ -161,6 +182,12 @@ class FakeTelegramTransport {
failGetMe: string | null = null;
/** Non-null makes sendMessage throw with this message. */
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 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. */
+ failThreadedSendCode = 400;
/** Fails this many upcoming getUpdates calls. */
failPolls = 0;
/** The webhook registered on the bot; the empty string means none, as the Bot API encodes it. */
@@ -202,6 +229,11 @@ class FakeTelegramTransport {
allSends(): SentMessage[] {
return this.clients.flatMap((c) => c.sends);
}
+
+ /** Every sendMessage attempt across every client: what tells one round trip from two. */
+ allSendCalls(): number {
+ return this.clients.reduce((n, c) => n + c.sendCalls, 0);
+ }
}
/**
@@ -285,6 +317,26 @@ function multiMessageFakeSession(
};
}
+/** Fake Session that parks on one approval per run (drives an approval_request event). */
+function parkingFakeSession(sessionId: string): RuntimeSession {
+ return {
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run(_input: OmniMessage[], opts: { approve: ApproveFn; signal: AbortSignal }) {
+ const tc = toolCall({ name: "exec_command", arguments: "{}", toolCallId: "tc-forum" });
+ yield tc;
+ const decision = await opts.approve(tc);
+ yield approvalDecision(decision, "tc-forum");
+ yield assistantText("after approval");
+ },
+ async *compact() {},
+ };
+}
+
function sessionRowOf(sessionId: string, projectId: string): SessionRow {
return {
sessionId,
@@ -315,6 +367,8 @@ describe("telegram binding routes and connector loop", () => {
let fake: FakeTelegramTransport;
let projectId: string;
let runs: TextPayload[][];
+ /** The server log, so a delivery that succeeded only in a degraded form is observable. */
+ let logLines: string[];
/** Save the token, then flip the toggle on and wait for the poll loop's handshake. */
const bindEnabled = async (sid: string, botToken = TOKEN) => {
@@ -325,10 +379,12 @@ describe("telegram binding routes and connector loop", () => {
beforeEach(async () => {
fake = new FakeTelegramTransport();
+ logLines = [];
t = await createTestApp({
telegramTransport: fake,
telegramRetryDelayMs: () => 1,
feishuSdk: new FakeFeishuSdk(),
+ log: (line) => logLines.push(line),
});
const { cookie } = await provisionUser(t.app, "birder");
api = apiClient(t.app, cookie);
@@ -841,6 +897,248 @@ describe("telegram binding routes and connector loop", () => {
});
});
+ // —— Forum supergroup topics ————————————————————————————————————————————————
+ // A forum supergroup splits one chat into topics, and a message carries the topic it was
+ // written in. A send that omits it lands in General — so the run's first reply threaded
+ // correctly (Telegram infers a reply's topic from its target) while every message after
+ // it, and the approval notice, walked out of the conversation.
+
+ const FORUM_CHAT = -1004475424385;
+ const TOPIC = 91;
+
+ /**
+ * A message in a forum topic, as Telegram sends it: the chat says it is a forum and the
+ * message says it is in a topic. `null` is the same forum's General topic, which carries
+ * neither the thread nor the flag.
+ */
+ const forumText = (text: string, messageId = 200, threadId: number | null = TOPIC) => ({
+ message_id: messageId,
+ chat: { id: FORUM_CHAT, type: "supergroup", is_forum: true },
+ ...(threadId !== null ? { message_thread_id: threadId, is_topic_message: true } : {}),
+ text,
+ from: { first_name: "Ada" },
+ });
+
+ it("remembers the topic, and every later message of the run reaches it", async () => {
+ // Three completed messages in ONE run: the first threads onto the inbound message, the
+ // two after it are plain sends — which is precisely where the topic used to be lost.
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["first", "second", "third"]));
+ await bindEnabled(SID2);
+
+ fake.push(forumText("status?"));
+ await waitFor(() => fake.allSends().length === 3, 5000);
+ const sends = fake.allSends();
+ // Every one of them, not just the threaded first.
+ expect(sends.map((x) => x.threadId)).toEqual([TOPIC, TOPIC, TOPIC]);
+ expect(sends.map((x) => x.text)).toEqual(["first", "second", "third"]);
+ // The first still quotes the inbound message; the rest are plain sends, as before.
+ expect(sends[0]!.replyTo).toBe(200);
+ expect(sends[1]!.replyTo).toBeUndefined();
+ // The topic is on the stored chat, which is what carries it across a restart.
+ expect(t.deps.messagingRepo.find(SID2, "telegram")?.lastChatId).toBe(`${FORUM_CHAT}:${TOPIC}`);
+ });
+
+ it("moves to the newest topic the user writes in, like the chat it already remembers", async () => {
+ await bindEnabled(SID);
+ fake.push(forumText("in the first topic", 201, TOPIC));
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allSends()[0]!.threadId).toBe(TOPIC);
+
+ fake.push(forumText("now over here", 202, 77));
+ await waitFor(() => runs.length === 2);
+ await waitFor(() => fake.allSends().length === 2);
+ expect(fake.allSends()[1]!.threadId).toBe(77);
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe(`${FORUM_CHAT}:77`);
+ });
+
+ it("sends the approval notice and the test message into the remembered topic", async () => {
+ const row = sessionRowOf(SID2, projectId);
+ // The approval only becomes an event when something is actually asked.
+ row.approvalMode = "always-ask";
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, parkingFakeSession(SID2));
+ await bindEnabled(SID2);
+
+ fake.push(forumText("do the thing", 203));
+ // The notice is a bare send with no inbound message to thread onto — the shape that had
+ // nothing at all to put it back in the topic.
+ await waitFor(() => fake.allSends().some((x) => x.text === MESSAGING_APPROVAL_NOTICE), 5000);
+ const notice = fake.allSends().find((x) => x.text === MESSAGING_APPROVAL_NOTICE)!;
+ expect(notice.threadId).toBe(TOPIC);
+ expect(notice.replyTo).toBeUndefined();
+
+ // The test message reads the stored chat straight off the row, so it is the path that
+ // would hand an encoded string to the API if the connector were not the one parsing it.
+ expect((await api.post(`${BASE(SID2)}/test-message`, {})).status).toBe(200);
+ const test = fake.allSends().find((x) => x.text === MESSAGING_TEST_MESSAGE)!;
+ expect(test.chatId).toBe(String(FORUM_CHAT));
+ expect(test.threadId).toBe(TOPIC);
+
+ t.deps.manager.decideApproval(SID2, "tc-forum", "allow");
+ await waitFor(() => t.deps.manager.statusOf(SID2) === "idle");
+ });
+
+ it("a topic that has been deleted degrades to a plain send instead of losing the reply", async () => {
+ // Three completed messages in one run: the topic is gone for every one of them, which is
+ // what the trace has to survive without turning into a line per send.
+ const row = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row);
+ t.deps.manager.adopt(row, multiMessageFakeSession(SID2, ["first", "second", "third"]));
+ await bindEnabled(SID2);
+ // No `allow_sending_without_thread` exists to match the reply flag, so the call simply
+ // fails with a 400. Landing in General is worse than the right topic and far better than
+ // dropping a reply the model has already produced.
+ fake.failThreadedSend = "sendMessage failed: Bad Request: message thread not found (code 400)";
+ fake.push(forumText("still there?", 204));
+ await waitFor(() => fake.allSends().length === 3, 5000);
+ const sends = fake.allSends();
+ expect(sends.map((x) => x.text)).toEqual(["first", "second", "third"]);
+ expect(sends.map((x) => x.threadId)).toEqual([undefined, undefined, undefined]);
+ expect(sends.every((x) => x.chatId === String(FORUM_CHAT))).toBe(true);
+ // Two attempts per message and no more: the threaded one Telegram refused, then the
+ // fallback that carried no topic.
+ expect(fake.allSendCalls()).toBe(6);
+ // The messages DID arrive, so this is not a delivery failure and must not read as one on
+ // the panel; the log is where "the replies moved to General" is answerable, once for the
+ // episode rather than once per send.
+ expect(t.deps.messaging.statusOf(SID2, "telegram").lastDeliveryError).toBeUndefined();
+ expect(logLines.filter((l) => l.includes("delivered degraded"))).toEqual([
+ "[messaging] telegram delivered degraded: forum topic gone, the reply went to General instead",
+ ]);
+ });
+
+ it("a flood wait is not retried: one refusal must not cost two requests", async () => {
+ await bindEnabled(SID);
+ // `Too Many Requests: retry after 5` against a per-chat allowance of about one message a
+ // second. An immediate second request lengthens the flood wait and fails again, so only
+ // the 400 that means "no such thread" may be retried.
+ fake.failThreadedSend = "sendMessage failed: Too Many Requests: retry after 5 (code 429)";
+ fake.failThreadedSendCode = 429;
+ fake.push(forumText("under a flood wait", 206));
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").lastDeliveryError !== undefined);
+ expect(fake.allSendCalls()).toBe(1);
+ expect(fake.allSends()).toHaveLength(0);
+ expect(t.deps.messaging.statusOf(SID, "telegram").lastDeliveryError?.detail).toContain(
+ "retry after 5",
+ );
+ });
+
+ it("a threaded send that fails both times surfaces the failure after exactly two attempts", async () => {
+ await bindEnabled(SID);
+ // `Bad Request: chat not found` is a 400 too, so the fallback fires — and then fails 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);
+ expect(t.deps.messaging.statusOf(SID, "telegram").lastDeliveryError?.detail).toContain(
+ "chat not found",
+ );
+ expect(t.deps.errorsRepo.recent(projectId).map((r) => r.code)).toContain(
+ "messaging_send_failed",
+ );
+ });
+
+ it("a forum's General topic is byte-identical: no topic minted, none sent, no retry", async () => {
+ await bindEnabled(SID);
+ // No `message_thread_id` on the way in means none on the way out — General and an
+ // ordinary group are the same thing here, and both predate this encoding.
+ fake.push(forumText("written in General", 205, null));
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allSends()[0]!.threadId).toBeUndefined();
+ // A send that carried no topic is never retried — one round trip, as before this existed.
+ expect(fake.allSendCalls()).toBe(1);
+ // The stored chat is the bare id every row written before this feature already holds, so
+ // an existing row and a new one are the same string.
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe(String(FORUM_CHAT));
+ });
+
+ // —— Threads that are not forum topics ——————————————————————————————————————
+ // `Message.message_thread_id` is populated "for supergroups and private chats only", which
+ // includes an ordinary reply chain; `sendMessage`'s parameter is "for forum supergroups
+ // only". Minting one from the former and sending it back fails with `message thread not
+ // found` on EVERY outbound message of that binding, permanently — the value is what gets
+ // persisted — and the fallback then re-sends, doubling the request rate against Telegram's
+ // roughly one-message-a-second per-chat allowance.
+
+ it("mints no topic in a private chat, where a reply to the bot carries a thread id", async () => {
+ await bindEnabled(SID);
+ // Using Telegram's reply on one of the bot's own messages is the ordinary way to answer
+ // it in a DM, and that update carries `message_thread_id`.
+ fake.push({
+ message_id: 1,
+ chat: { id: 123456789, type: "private" },
+ message_thread_id: 1,
+ text: "reply in a DM",
+ from: { first_name: "Ada" },
+ });
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allSends()[0]!.threadId).toBeUndefined();
+ expect(fake.allSendCalls()).toBe(1);
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe("123456789");
+ });
+
+ it("mints no topic in a supergroup that is not a forum", async () => {
+ await bindEnabled(SID);
+ // The common case under Group Privacy: with it on, the bot mostly sees replies to its own
+ // messages — exactly the ones that carry a reply-chain `message_thread_id`.
+ fake.push({
+ message_id: 500,
+ chat: { id: -1002233445566, type: "supergroup" },
+ message_thread_id: 500,
+ text: "reply in a plain supergroup",
+ from: { first_name: "Ada" },
+ });
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allSends()[0]!.threadId).toBeUndefined();
+ expect(fake.allSendCalls()).toBe(1);
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe("-1002233445566");
+ });
+
+ it("mints no topic for a reply chain in a forum's General topic", async () => {
+ await bindEnabled(SID);
+ // A forum, so `is_forum` is set, but General is not a topic: `is_topic_message` is absent
+ // and the thread id names the reply chain. Only both flags together mean "forum topic".
+ fake.push({
+ message_id: 208,
+ chat: { id: FORUM_CHAT, type: "supergroup", is_forum: true },
+ message_thread_id: 208,
+ text: "reply in General",
+ from: { first_name: "Ada" },
+ });
+ await waitFor(() => runs.length === 1);
+ await waitFor(() => fake.allSends().length === 1);
+ expect(fake.allSends()[0]!.threadId).toBeUndefined();
+ expect(fake.allSendCalls()).toBe(1);
+ expect(t.deps.messagingRepo.find(SID, "telegram")?.lastChatId).toBe(String(FORUM_CHAT));
+ });
+
+ it("keeps sending to a chat id stored before topics existed", async () => {
+ await bindEnabled(SID);
+ // Every row on disk holds a bare chat id. The parse has to read it as "no topic" rather
+ // than reject it, or a working binding breaks on upgrade. Written straight to the column
+ // an older build would have written, rather than through the repo, so the fixture states
+ // the stored shape and does not track the repo's current signature.
+ t.deps.db
+ .prepare(
+ "UPDATE messaging_bindings SET last_chat_id = ? WHERE session_id = ? AND channel = ?",
+ )
+ .run(String(FORUM_CHAT), SID, "telegram");
+ expect((await api.post(`${BASE(SID)}/test-message`, {})).status).toBe(200);
+ const sent = fake.allSends().find((x) => x.text === MESSAGING_TEST_MESSAGE)!;
+ expect(sent.chatId).toBe(String(FORUM_CHAT));
+ expect(sent.threadId).toBeUndefined();
+ });
+
it("a group message that is nothing but the bot's mention starts no task", async () => {
await bindEnabled(SID);
fake.push({
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index 4b60c5fd..280a4908 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -140,7 +140,18 @@ class FakeSdk implements FeishuSdk {
botIdentityLookups = 0;
/** Non-null makes every outbound sendText throw with this message. */
failSend: string | 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.
+ */
+ createClientGate: Promise<void> | null = null;
+ /** How many createClient calls the gate has held. */
+ gated = 0;
async createClient(creds: FeishuCredentials): Promise<FeishuApiClient> {
+ if (this.createClientGate !== null) {
+ this.gated++;
+ await this.createClientGate;
+ }
const client = new FakeClient(creds, this);
this.clients.push(client);
return client;
@@ -804,6 +815,49 @@ describe("messaging binding routes and bridge", () => {
]);
});
+ it("delivers every chunk of one reply to the chat the row named when the delivery began", async () => {
+ // A reply long enough to chunk, so the first chunk (which threads onto the inbound
+ // message) and the rest (plain sends to the stored chat) can disagree at all.
+ const long = `${"a".repeat(3000)}\n${"b".repeat(3000)}`;
+ const row2 = sessionRowOf(SID2, projectId);
+ t.deps.sessionsRepo.insert(row2);
+ t.deps.manager.adopt(row2, echoFakeSession(SID2, [], long));
+ await bindEnabled(SID2, { ...PUT_BODY, appId: "cli_snapshot" });
+
+ let release!: () => void;
+ fake.createClientGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await fake.lastConnection().fire({
+ chatId: "oc_group_a",
+ chatType: "group",
+ messageId: "om_a",
+ messageType: "text",
+ content: JSON.stringify({ text: "ask in one place" }),
+ });
+ // The delivery is now parked inside the bridge's client lookup, holding a row that names
+ // chat A — the one window in which the two halves of the reply target can move apart.
+ await waitFor(() => fake.gated === 1);
+
+ // A second message lands in another chat mid-delivery. Between messages this is the
+ // documented "answer wherever the user last wrote"; inside one delivery it would split a
+ // single reply across two places (on Telegram, two forum topics).
+ await fake.lastConnection().fire({
+ chatId: "oc_group_b",
+ chatType: "group",
+ messageId: "om_b",
+ messageType: "text",
+ content: JSON.stringify({ text: "and now over here" }),
+ });
+ release();
+
+ await waitFor(() => fake.allSends().length >= 2);
+ expect(fake.allSends().slice(0, 2)).toEqual([
+ { kind: "reply", target: "om_a", text: "a".repeat(3000) },
+ { kind: "send", target: "oc_group_a", text: "b".repeat(3000) },
+ ]);
+ });
+
// —— linePerMessage: the per-binding delivery option ————————————————————————
/**