Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(telegram): shared message lifecycle + fresh final delivery (#2383)

Chris Zhang7a92869a6624
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index 1b765a077d..1097fc5795 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -59,6 +59,7 @@ import {
type TurnDeliveryPayload,
type TurnEndPayload,
} from '@cindy/slack-hook-protocol';
+import { createTelegramMessageLifecycle, type TelegramMessageLifecycle } from '@cindy/im';
import { HOOK_CHAT_WORKSPACE_ALIAS } from '../../shared/hookControlIpc.js';
import type { GroupHistoryAccessScope } from '../im/shared/groupHistoryAccess.js';
@@ -607,6 +608,22 @@ interface PendingReopen {
expiresAt: number;
}
+/**
+ * 官方 legacy adapter 的消息生命周期。
+ *
+ * Slack / X 继续沿用原路径;只有 Telegram 任务接入共享内核。当前服务端仍由
+ * `turn.progress` / `turn.end` 实际发布,所以这里的 sent 表示终态已进入客户端
+ * 可靠发布边界,不冒充 Telegram Bot API 的最终回执。
+ */
+function telegramLegacyLifecycle(
+ connectionId: string,
+ requestId: string,
+ source: TaskSource | undefined,
+): TelegramMessageLifecycle | null {
+ if (source?.im !== 'telegram') return null;
+ return createTelegramMessageLifecycle(`telegram-official:${connectionId}:${requestId}`);
+}
+
export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
const {
getConnection,
@@ -1233,6 +1250,11 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
}
const requestId = randomUUID();
const requestKey = ackKey(entry.connectionId, requestId);
+ const messageLifecycle = telegramLegacyLifecycle(
+ entry.connectionId,
+ requestId,
+ entry.source,
+ );
let claimed = false;
// runner 可能在 watch() 里**同步**收口(会话已不在进程里就直接 onAbandon),
// 那时 cancelWatch 还没赋值 —— 用这个标记决定要不要登记, 不去碰它。
@@ -1317,6 +1339,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
},
onProgress: (text) => {
if (revoked || !claimed || !isCurrentGeneration(entry.accountGeneration)) return;
+ if (messageLifecycle && !messageLifecycle.acceptProgress()) return;
const send = sendFns.get(entry.connectionId);
if (send) send(makeTurnProgress({ requestId, text }));
},
@@ -1329,6 +1352,9 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
if (revoked || !claimed || !isCurrentGeneration(entry.accountGeneration)) return;
const status: 'ok' | 'error' | 'cancelled' = wasCancelled ? 'cancelled' : outcome.status;
const isError = status === 'error';
+ // Fence progress before the legacy terminal frame. Continuation
+ // callbacks can race the async attachment-collection tail.
+ const finalIntent = messageLifecycle?.beginFinal() ?? null;
// 续跑轮的 turn.end **直发不缓存**, 与普通任务(sendOrBuffer 断线补发)刻意
// 相反: 普通任务的消息由 server 建、断线期间没人动它, 补发就能定稿; 而续跑
// 轮的消息在断连那一刻已被 server 的孤儿收口改写并解绑 requestId, 迟到的
@@ -1351,11 +1377,16 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
}),
) === true;
if (!delivered) {
+ if (messageLifecycle && finalIntent) messageLifecycle.markFinalFailed(finalIntent);
// 没发出去 => server 已把这条消息收口并解绑本轮 requestId, 再拿它当
// reopenOf 只会被静默忽略。这条消息线到此为止, 不再登记可续跑。
log.warn(`hook continuation turn.end dropped (connection offline): ${requestId}`);
return;
}
+ if (messageLifecycle && finalIntent) {
+ messageLifecycle.markFinalSent(finalIntent);
+ if (messageLifecycle.beginCleanup()) messageLifecycle.finishCleanup();
+ }
// 续跑又失败了 -> 允许再续一次(用户还得再点一次重试, 天然限流)。
// reopenOf 换成这一轮的 requestId: server 侧那条消息现在挂在它上面。
if (isError && !denyRemember) {
@@ -1423,11 +1454,17 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
// 发收口帧把那条旧消息定稿; 但不再记待续跑(它已经不是"最新一轮"了)。
dropContinuation(sessionId, { silent: false, remember: false });
runningByRequest.set(requestKey, { sessionId, connectionId: task.connectionId });
+ const messageLifecycle = telegramLegacyLifecycle(
+ task.connectionId,
+ task.requestId,
+ task.run.source,
+ );
// 进度快照直发不缓存: 断线期间的中间帧没有补发价值(turn.end 会带最终
// 结果), 发送失败静默丢弃即可
const onProgress = (text: string): void => {
if (!isCurrentGeneration(task.accountGeneration)) return;
+ if (messageLifecycle && !messageLifecycle.acceptProgress()) return;
const send = sendFns.get(task.connectionId);
if (send) send(makeTurnProgress({ requestId: task.requestId, text }));
};
@@ -1537,6 +1574,10 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
? { attachments: outcome.attachments }
: {}),
};
+ // Open the final fence before the legacy terminal frame enters any async
+ // outbox path. A late progress callback from the observer must never write
+ // over the answer after this point.
+ const finalIntent = messageLifecycle?.beginFinal() ?? null;
// Protocol idempotency replays only the original ACK. The terminal record
// is written as a pending outbox entry before sending; an offline frame
// stays buffered in memory until onConnected flushes the full payload.
@@ -1546,6 +1587,10 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
ack: task.ack,
turnEnd: durableTurnEnd(turnEnd),
});
+ if (messageLifecycle && finalIntent) {
+ messageLifecycle.markFinalSent(finalIntent);
+ if (messageLifecycle.beginCleanup()) messageLifecycle.finishCleanup();
+ }
// 表情换终态。连接断了也要**调**一次 —— 传一个必然失败的发送器, 让
// ackReactions 把它记进待补发队列; 直接跳过的话那条消息会永远挂着 👀,
// 而重连补发拿不到任何东西可补。
diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.md
index d52b4922d9..0f33930957 100644
--- a/docs/product-rules/telegram-bot-parity.md
+++ b/docs/product-rules/telegram-bot-parity.md
@@ -74,7 +74,7 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
| 过程中 | **第一帧真实内容用 `sendMessage` 建消息(这一条会推送),之后持续 `editMessageText` 覆盖(编辑不推送)**,用户看着它长大:过程区在上、正文在下,正文是整轮累计内容 | **私聊**:进 Telegram **草稿**(`sendDraft`)——在输入框那个位置,**不在消息流里**;**群**:一条进度消息,`editMessageText` 覆盖。桌面端对 Telegram 专门用 `progressBodyMode: 'whole'`,在 3800 字单帧上限内同样累计展示整轮正文;超过后退回当前 assistant 消息,避免头部截断把最新答案藏掉。Slack / X 仍只展示当前 assistant 消息 |
| `done` 交接 | 最后一帧由个人 driver 自己定稿 | 桌面端在 `turn.end` 之前先 `flushProgress()`,跳过尚余的 1.5 秒尾沿节流,把最新安全快照放进既有进度载体;这是防止 observer teardown 吞掉最后一帧的客户端兜底,**不等于**服务端终稿已发布成功 |
| 终稿内容(**成功收口**) | **只有正文**(`composeStreamingView` 在 `turn.done` 时直接 `return body`,不再合成过程区) | **只有正文**(`presenter.finalText()` 取 body 引擎的缓冲,不经过 `composeProgressView`) |
-| 终稿落在哪 | **单段且原位编辑成功时**留在那条消息里。**会新发消息的只有两种**:终稿超长被切成多段(第 1 段仍原位,第 2 段起逐段 `send`);原位编辑失败后整条 repost 承载终稿,再尽力删掉停在过程态的旧消息——**删不掉就两条并存**。**受管图片不算**:它只让终稿跳过 rich 一次性定稿(`editFinal`),后面照样算 `inPlaceText` 走 `finalizeInPlaceOrRepost` 编辑原消息,图片随后由 `uploadImages` 另发 | **私聊**:新发一条正文消息,草稿随之消失;**群**:编辑那条进度消息 |
+| 终稿落在哪 | **永远新发一条独立消息**,落地后才尽力删掉停在过程态的旧载体——**删不掉就两条并存**。优先 `sendRichMessage`(表格/公式原生渲染、32768 上限免分段);**Telegram 完整应答的任一 4xx** 都判为「这条 Rich 没落地」并回落新发 HTML——判据是**有没有拿到应答**而非错误码大小:404(方法缺失,另触发实例级熔断,后续不再试 Rich)、400(本条解析不过)、**429(`callSend` 按 `retry_after` 退避重试后仍限流;不熔断,下一轮照常试 Rich)**。抛错只留给拿不到应答的情况(网络中断、超时、5xx)——那时无法判断 Telegram 是否已接收,补发 HTML 可能造成两份答案。超长时第 2 段起逐段 `send`。**受管图片**让终稿跳过 Rich 直接走 HTML 新发,图片随后由 `uploadImages` 挂到新终稿上。过程载体从不承担答案,因此最后一次编辑撞 flood 不再丢终稿 | **私聊**:新发一条正文消息,草稿随之消失;**群**:编辑那条进度消息 |
| **失败收口**(普通轮次) | **过程区保留**:错误路径不置 `turn.done`,`composeStreamingView` 仍走运行中合成——卡片定稿成「过程区 + 正文 + ❌ 错误:…」,用户能看到失败前干到了哪一步 | 终稿正文为**空**,错误信息走独立的 `errorMessage` 字段,由服务端按语言渲染成「任务失败:…」——**不带过程区** |
| **失败收口**(群开了 `always` 的 **ambient 轮次**) | **和普通轮次一样**照吐 `❌ 错误:…`——`turnRunner` 不认识 ambient。惰性占位这时会被真建出来,群里凭空多一条错误消息,而这一轮本来连话都不打算说。**这是缺口 2f,不是裁决** | **静默**:不发失败通知(`finalFailureNoticeSent !== true && !entry.ambient`),删掉过程消息、记一句「completed silently」。删不掉时标 `retainAmbientCleanup` 留给下一拍重试 |
@@ -87,10 +87,10 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:
- **失败收口本身还要分普通轮次与 ambient 轮次**,两侧的差别正好反过来:普通轮次是
「个人留现场 / 官方一句错误」,ambient 轮次是「个人照样吐错误 / 官方全静默」。所以
上表把失败拆成两行——一个无条件的「失败怎么收口」结论会同时说错其中一半(缺口 2f)。
-- **「过程区消失」也不是无条件的**。原位编辑成功时,终稿覆盖掉同一条消息,过程区确实
- 没了;走 repost 那条路时,旧的过程消息是**尽力删**——`deleteMessage` 失败被吞掉
- (权限、已被删、API 报错),于是聊天里会同时留着一条停在「⚙️ 工作中 · …」的旧消息和
- 一条新终稿。答案不会丢,但「只剩正文」这句话在这种情况下不成立。
+- **「过程区消失」也不是无条件的**。个人 bot 的终稿永远是新消息,旧的过程消息是**尽力
+ 删**——`deleteMessage` 失败被吞掉(权限、已被删、API 报错),于是聊天里会同时留着一条
+ 停在「⚙️ 工作中 · …」的旧消息和一条新终稿。答案不会丢,但「只剩正文」这句话在这种情况
+ 下不成立。清理排在终稿确认之后,清理失败不回退终稿状态、更不删除已送达的答案。
过程阶段的载体差异(个人在聊天记录里、官方私聊在输入框草稿里)已经裁决过,见下节。
diff --git a/docs/product-rules/telegram-bridge-design.md b/docs/product-rules/telegram-bridge-design.md
new file mode 100644
index 0000000000..e307207a8e
--- /dev/null
+++ b/docs/product-rules/telegram-bridge-design.md
@@ -0,0 +1,580 @@
+# Telegram 统一消息桥接设计
+
+> 状态:设计稿,供客户端实现与跨仓协议评审使用。本文不是已上线能力清单。
+>
+> 目标:让官方 bot 与个人 bot 在用户能感知的消息过程、终稿收口和能力降级上遵守同一套
+> 消息语义,同时保留两条入口在身份、绑定、权限、群触发和可靠性上的必要差异。
+>
+> 本文只设计客户端边界,不修改服务端、`cindy-protocol`、数据库 schema 或线上行为。
+> 文中标为“目标”的内容不应被读成当前已经接线。
+
+## 1. 先给结论
+
+最终形态不是两份互相复制的 Telegram 消息系统,也不是把两个 bot 强行塞进一个带条件分支
+的 adapter。应采用一份共享的消息内核,加上两个很薄的传输出口:
+
+```text
+ ┌──────────────────────────┐
+ │ Telegram 消息内核 │
+ │ 事件 → 呈现 → 生命周期 │
+ │ 终稿栅栏 → 回执/重试 │
+ └────────────┬─────────────┘
+ │ provider-neutral intents
+ ┌────────────┴─────────────┐
+ │ │
+ 个人 bot adapter 官方 bot adapter
+ Telegram Bot API msg.op / legacy frames
+ owner + local token binding + principal + server auth
+```
+
+共享内核拥有“这一轮消息应该经历什么状态”;adapter 只拥有“怎样把一个意图投递到对应
+的 Telegram 连接”。官方 adapter 在新服务端支持时使用细粒度 `msg.op`,在旧服务端或能力
+未协商时继续使用 `turn.progress` / `turn.end` 回退。个人 adapter 直接调用 Bot API。
+
+这会解决“最后一个答案一直等、迟到的进度又把终稿改回去、两条代码越维护越不一样”这类
+客户端问题,但不会假装客户端可以替服务端完成官方 bot 的授权和消息操作。官方真正的
+`send` / `edit` / `delete` / `typing` / `media` 仍须等服务端提供并声明对应能力。
+
+### 1.1 当前实现与目标设计的边界
+
+| 范围 | 当前已经存在 | 本设计要达到的目标 |
+| ----------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| 文本与过程合成 | `apps/desktop/src/main/im/shared/turnPresenter.ts`、`turnActivity.ts` 已共享 | 由内核继续作为唯一过程视图来源;不把两种正文累积模式误合成一种 |
+| 个人 bot 过程消息 | `sendMessage` 建首条真实消息,之后 `editMessageText` 节流更新;终稿有原位编辑失败后的 repost 兜底 | 统一为“过程载体”和“新鲜终稿”两个明确阶段;删除旧载体不阻塞答案 |
+| 官方 bot 过程消息 | 主要由 `turn.progress` / `turn.end` 驱动;桌面端目前只真正消费 `msg.op` 的 `react` | 用官方 adapter 兑现同一内核意图;未协商时保留旧帧回退 |
+| 终稿 | 官方桌面已有本地 `requestLedger` 持久终稿账本;服务端不保存正文/outbox;个人主要是进程内尽力投递 | 终稿发送独立于过程更新,建立终稿栅栏、幂等键和不确定回执处理 |
+| 草稿 | 个人曾试用原生草稿,因只能承载一行纯文本而撤回;当前个人 DM 也走消息流 | 只有声明支持完整过程内容的 DM draft 能力时才启用;草稿永远不承载终稿 |
+| 消息效果 | 官方服务端已有 DM 终稿 `messageEffectId`;个人能力契约为不支持 | 以可选装饰意图下发;失败只降级装饰,不影响正文送达 |
+| 数据库 | 群消息库与保留核心已共享,但 provider namespace 分开 | 保留 namespace 隔离和消息所有权;本设计不改 schema |
+
+### 1.2 与已合并的 #2305 的关系
+
+PR #2305(官方 Telegram 进度呈现与完成收口)已经合并。它补的是官方 `turn.end` 之前
+的最后一次进度 flush,防止 observer 的尾沿节流在 teardown 时吞掉最后快照;它不是
+`msg.op` 消息桥,也没有让官方 bot 具备个人 bot 的完整终稿生命周期。
+
+本设计把 #2305 的 flush 保留为**旧帧 adapter 的兼容回退**,不回退、不重复实现。未来
+官方 adapter 切到 `msg.op` 后,终稿栅栏仍要先阻止迟到的 `turn.progress`,而不是依赖
+“再 flush 一次”来保证答案。
+
+## 2. 术语与不可变身份
+
+### 2.1 用户可见术语
+
+面向用户仍使用“任务、对话、消息”的既有边界;`turn` 是内部“一轮”,不要在 UI 文案里
+把一轮称为新的产品对象。过程载体、终稿和交互卡都是消息呈现阶段,不是额外的任务。
+
+### 2.2 一轮的身份键
+
+内核不直接接受裸 `chatId` 或裸消息 ID。每个事件和出站意图都带有以下逻辑身份(具体
+wire 字段由未来协议另行裁定):
+
+```ts
+type TelegramRoundIdentity = {
+ provider: "telegram-personal" | "telegram-official";
+ accountId: string; // personal botId;official connection/account
+ scope: {
+ kind: "dm" | "group";
+ chatId: string;
+ deliveryThreadId: string | null; // Telegram 投递位置,可是 reply root
+ topicId: string | null; // 仅 is_topic_message 才是归属 topic
+ replyToMessageId: string | null; // 本轮受理时冻结的回挂锚点
+ };
+ principalId: string | null; // official 必须来自触发者;personal 可为空
+ bindingId: string | null; // official 绑定代际
+ bindingGeneration: number;
+ connectionGeneration: number;
+ roundId: string;
+};
+```
+
+`deliveryThreadId` 与 `topicId` 不能互换。Telegram 普通群的 reply 链也可能带
+`message_thread_id`;它决定消息投到哪里,但只有 `is_topic_message === true` 才能决定
+它属于哪个 topic lane。
+
+`replyToMessageId` 在本轮被受理时冻结。过程消息、交互卡和终稿都从这份 round identity
+取回挂目标,不能在发送终稿时重新从“最近群消息”或可变队列领取;这是防止群友新发言把
+最后答案挂错位置、看起来像被替换的关键不变量。
+
+内核生成的每个意图还带 `sequence`(同一 `roundId` 单调递增)和 `phase`。adapter 必须
+拒绝不匹配的 `bindingGeneration` / `connectionGeneration`,以及终稿栅栏之后的过程更新。
+
+## 3. 身份、主人、群友和陌生人路由矩阵
+
+下表描述**现有行为必须保留**的身份差异;统一的是消息内核,不是权限模型。
+
+| 入口与来信 | lane / 身份 | 是否创建任务 | 允许的执行范围 | 用户可见响应 |
+| ---------------------------------------------- | ---------------------------------------------------------------------------------- | ----------------------------------: | -------------------------------------------------------------------------- | ------------------------------------------------- |
+| 个人 bot 私聊,bot owner | `telegram-personal:<botId>` + user chat | 是 | 按个人 bot 的 owner 权限与本地设置 | 正常过程消息、终稿、交互卡 |
+| 个人 bot 私聊,非 owner 或未通过 auth | 仍按该 bot 的 chat 隔离 | 由个人 auth/policy 决定;不通过则否 | 不得越过 owner / channel policy | 现有陌生人或权限提示;不把拒绝伪装成已执行 |
+| 个人 bot 群内正确 `@`、回复 bot 或有效命令 | 一群(及 topic)共享 per-chat lane | 是 | 群轮次沿用个人 bot 的低权限/强制确认策略;不因统一内核改成 owner bypass | 过程消息与终稿发回原群/原 reply 位置 |
+| 个人 bot 群友/陌生人普通发言(`mention` 模式) | 写入共享群窗口,不取得 owner 身份 | 否 | 仅作同群上下文;不能借 owner 轮次访问其它群或私聊 | 无主动回复 |
+| 个人 bot 群 `always` 的 ambient 消息 | 同一群 lane,`ambient=true` | 是(若正文有效) | 同上 | 不 typing、不打过程表情;模型可用 `NO_REPLY` 静默 |
+| 官方 bot 私聊,已绑定 principal | `telegram:<principalId>` | 是 | 路由到该 principal 当前 `bindingId` 的 Cindy 桌面;使用官方既有权限口径 | 由绑定桌面驱动过程、交互和终稿 |
+| 官方 bot 私聊,未绑定 principal | 无有效 binding | 否 | 不创建任务、不猜测其他人的桌面 | 限频关联/绑定提示 |
+| 官方 bot 群内,已绑定 principal 正确 `@` | 主群 `telegram:group:…:<principal>`;topic `telegram:topic:…:<thread>:<principal>` | 是 | 只进入发言者自己的 binding;不把被 @ 的其他群友当主人 | 回到该群;relay 的其他副本不等于该轮的回答 |
+| 官方 bot 群内,未绑定发言者 `@` | 无有效 binding | 否 | 不创建任务,不替未绑定用户执行 | 限频关联提示;不得把提示当作任务结果 |
+| 官方群友/陌生人普通发言(未触发) | 可能成为 `group.message` relay 上下文 | 否 | 只能投给该群已登记且 recipient 代际匹配的桌面;不取得任何 binding 的执行权 | 无主动回复 |
+| 官方群 relay 给同群其他已登记桌面 | `group.message` + 精确 `recipient{bindingId,principalId}` | 否(除非该桌面随后收到自己的触发) | 只作为本地群窗口/上下文;接收方代际必须精确匹配 | 通常无 Telegram 出站;不会覆盖别人的终稿 |
+| 任一 bot 的 topic/reply | `topicId` 由归属判据决定,裸 thread 只用于投递 | 按上行触发规则 | topic lane 与主群 lane 隔离;普通 reply 不得凭空新建 topic lane | 终稿沿用原 reply/topic 目标 |
+| 连接重连、换绑、解绑后迟到帧 | 原 round 的旧 generation | 否 | fail-closed;不向新主人或新 binding 写消息 | 旧过程载体可留在原聊天,但新终稿不能被旧帧覆盖 |
+
+### 3.1 “官方 bot 关联任何被 @ 的人”具体含义
+
+官方 bot 的 `principalId` 是**发言人的 Telegram user ID**。`@Cindy` 不是把消息发送给
+被 @ 的任意群友,而是把这条触发路由到发言人自己绑定的 Cindy 桌面。群中其他已登记桌面
+可能收到 relay 上下文,但它们不是这条任务的 owner,也不能借 relay 结果回写回答。
+
+个人 bot 则是用户自持 token 的低权限入口;群里多人共用一条 per-chat lane 的既有行为
+不能被官方 principal lane 的规则覆盖。
+
+## 4. 共享消息内核与两个 adapter 的边界
+
+### 4.1 内核负责什么
+
+共享内核是纯客户端业务层,至少包含以下职责:
+
+1. 把 thinking、工具调用、正文增量、交互请求和终态转换为统一的活动模型;
+2. 使用 `turnPresenter` / `turnActivity` 的同一过程视图规格,保留
+ `finalized-segments` 与 `buffer-replace` 两种明确正文模式;
+3. 管理过程载体(draft 或过程消息)、终稿消息、交互卡和 typing 的生命周期;
+4. 只生成 provider-neutral 的 `send`、`edit`、`delete`、`react`、`typing`、`media`、
+ `effect`、`flush`、`reconcile` 意图;
+5. 执行长度限制、分段、Markdown/HTML/Rich Message 分层和降级顺序;
+6. 在终稿栅栏后丢弃迟到的过程帧,处理 `NO_REPLY`、取消、失败、断线和不确定回执;
+7. 给每个意图分配稳定的 `roundId + phase + sequence`,保证幂等和所有权可追踪;
+8. 把可测试的结果状态交给 adapter,不把“API 调用返回了”误当成“用户已经看到”。
+
+内核不负责 Telegram token、服务端 binding、principal 授权、群成员证据、服务端 relay
+扇出或消息数据库 schema。
+
+### 4.2 过程区与工具调用的用户可见规则
+
+两个 bot 的过程内容必须来自同一套 presenter 输出,不允许 adapter 自己拼另一份“更像
+Telegram”的时间线:
+
+- thinking、工具调用和正文按实际发生顺序进入同一轮;同一个 thinking block 原位更新,
+ 同一个 `toolUseId` 在 replay/重连后去重;
+- 工具调用显示共享的人类可读摘要,不直接倾倒整段 JSON、命令参数或可能含凭证的原始输入;
+- 默认展示最近五个可读步骤和总步骤数,正文继续显示在过程区下方;等待授权、等待回答、
+ 自动重试与“正在写”是明确状态,不伪装成一个新的工具步骤;
+- 稠密事件按同一 trailing-edge 规格合帧;完全相同的快照不重复编辑,前缀相似不能被误判
+ 为相同,否则正文增量会看起来卡死;
+- DM draft 若不能完整承载这些步骤,就必须降级为真实过程消息,不能只显示一行“思考中”;
+- 成功终稿只包含正文;失败是否保留过程现场、ambient 是否静默继续按 parity 台账裁决,
+ 不在 presenter 里偷做统一。
+
+adapter 只决定这些内容放进 draft、真实过程消息还是 legacy progress 帧,不得改变顺序、
+文案摘要、去重和终态语义。
+
+### 4.3 个人 bot adapter 负责什么
+
+- 持有 Bot API client、token、owner 和本地 `configVersion`;
+- 解析 Telegram 入站的 `is_topic_message`、reply、media 和群 activation;
+- 把内核意图投到 `sendMessage` / `editMessageText` / `deleteMessage` /
+ `sendChatAction` / media API;
+- 维护本地 reply target、typing loop 和个人 bot 的 outbox/重试边界;
+- 以 `telegram-personal:<botId>` 隔离群消息窗口和消息所有权;
+- 在每个真实出站 await 前验证本轮 owner 与 connection generation 仍有效。
+
+个人 adapter 不能因为共享内核而获得官方 bot 的 principal 绑定语义,也不能把群成员的
+消息自动提升为 owner 权限。
+
+### 4.4 官方 bot adapter 负责什么
+
+- 把入站 `task.dispatch` / `group.message` 解释成官方 principal/binding 上下文;
+- 在 `recipient{bindingId,principalId}`、当前 binding 和 generation 不一致时丢弃;
+- 新能力可用时经 `msg.op` 请求服务端执行 Telegram 出站;
+- 未协商或旧服务端时回退到现有 `turn.progress` / `turn.end`;
+- 处理官方桌面本地 `requestLedger` 终稿账本、ACK、客户端重投和 24 小时终稿时效;服务端
+ 不取得正文 outbox 所有权;
+- 保留官方 `/status`、`/unlink`、群 onboarding 和 per-principal lane;
+- 不把客户端自带的 `chatId` 当授权依据,所有发送目标必须来自服务端授权上下文。
+
+官方 adapter 不能把个人 bot 的本地 token、群低权限模型或 per-chat lane 带入官方出口。
+
+### 4.5 内核意图的最小形状(设计,不是当前协议)
+
+```ts
+type BridgeIntent = {
+ round: TelegramRoundIdentity;
+ phase: "process" | "final" | "cleanup" | "interaction" | "decoration";
+ sequence: number;
+ deliveryKey: string; // roundId + phase + logical part;重试不变
+ op:
+ | { kind: "send-process"; content: RenderedContent }
+ | { kind: "update-process"; carrier: CarrierRef; content: RenderedContent }
+ | { kind: "send-final"; content: RenderedContent; effect?: string }
+ | { kind: "clear-process"; carrier: CarrierRef }
+ | { kind: "delete-process"; carrier: CarrierRef }
+ | { kind: "typing"; active: boolean }
+ | { kind: "react"; target: InboundMessageRef; emoji: string }
+ | { kind: "media"; content: MediaContent }
+ | { kind: "reconcile"; deliveryKey: string };
+};
+```
+
+`BridgeIntent` 不是本 PR 要加入的 wire 类型;它是未来客户端内核和 adapter 之间的内部
+边界。协议字段、版本和服务端授权要在后续跨仓 PR 中单独定义。
+
+## 5. 消息状态机
+
+```text
+ ┌──────────────┐
+ │ CREATED │
+ └──────┬───────┘
+ │ activity / first content
+ ┌──────▼───────┐
+ │ RUNNING │
+ └──────┬───────┘
+ │ send/update process carrier
+ ┌──────▼───────┐
+ │ CARRIER_LIVE │──────┐
+ └──────┬───────┘ │ cancel / fail / NO_REPLY
+ │ terminal │
+ ┌──────▼───────┐ │
+ │ FINAL_INTENT │ │
+ └──────┬───────┘ │
+ │ fresh send │
+ ┌──────▼───────┐ │
+ │ FINAL_PENDING │ │
+ └──────┬───────┘ │
+ │ accepted │
+ ┌──────▼───────┐ │
+ │ FINAL_SENT │ │
+ └──────┬───────┘ │
+ │ cleanup │
+ ┌──────▼───────┐ │
+ │ SETTLED │ │
+ └──────────────┘ │
+ ▼
+ NO_REPLY / CANCELLED / FAILED
+```
+
+### 5.1 状态不变量
+
+- `FINAL_INTENT` 一旦创建,任何 `update-process`、typing 续命和过程表情都失效;它们
+ 可以被记录为 stale,但不能再触达 Telegram。
+- 一个 `roundId` 只能有一个逻辑终稿。长文本的多个 Telegram 分段属于同一个终稿,使用
+ 固定的 part index 和稳定 `deliveryKey`。
+- 终稿默认是**新鲜普通消息**,不把 draft 转存成终稿,也不依赖旧过程消息编辑成功。
+ 这样群 relay、迟到帧和消息替换都不会把最终答案重新变成过程态。
+- `FINAL_SENT` 以 adapter 的成功回执为准;清理过程载体失败不能把状态倒退成失败,也不能
+ 删除已经确认的终稿。
+- `UNKNOWN` 回执不能直接当失败重发。adapter 必须先 reconcile;无法核实时保留终稿出箱
+ 记录,使用同一 `deliveryKey` 做有界重试或人工可见的待投递状态。
+- 长终稿只送达部分分段时进入 `FINAL_PARTIAL`:已经确认的 part 不重发,只重试未确认
+ part;所有 part 都确认后才进入 `FINAL_SENT`。不能因为末段失败而复制前面已经看到的内容。
+- 删除失败允许“旧过程消息 + 新终稿”并存,答案优先;不能为了视觉整洁而再次删除终稿。
+- 所有状态变更都检查 round identity。换绑、解绑、owner 变化和连接切换不能让旧回调写入
+ 新聊天。
+
+## 6. Cindy 的“过程载体 → 新鲜终稿 → 清理”算法
+
+Hermes 的可借鉴点是同轮 draft 身份、草稿与持久消息的区分、终稿编辑失败后的立即补送、
+FloodWait/分段测试和 Rich 能力降级,不是逐字照搬它当前的终稿算法。对 2026-08-10 最新
+`upstream/main` 的复核显示:Hermes 对流式 Rich 消息优先用 `editMessageText + rich_message`
+原地定稿,只有最终编辑失败时才新发终稿,目的是避免清理竞态期间短暂出现两份答案。
+
+Cindy 这里仍选择“新鲜普通终稿先送达,旧过程载体后清理”,因为产品目标明确要求终稿不再
+被群 relay、迟到过程帧或旧载体更新替换。这是 Cindy 的一致性取舍,不应在实现说明里写成
+“Hermes 当前就是这样”。共享的原则仍是:同一轮只复用自己的过程载体;草稿不等于持久
+送达;终稿失败不长时间卡在等待;清理永远排在答案之后。
+
+### 6.1 过程载体选择
+
+1. DM 且 adapter 声明 `draft.rich-process-v1`:为本轮生成唯一 `draftId`,过程更新始终
+ 使用它;同一轮内不换 `draftId`,下一轮绝不复用。
+2. DM 不支持完整 draft,或是群/topic:使用真实过程消息。第一次有可显示内容时
+ `send-process`,之后 `update-process`;空过程不创建消息。
+3. 不能把旧的“单行纯文本 draft”重新打开。工具步骤、thinking 和正文无法在那条通道
+ 完整呈现时,必须退回过程消息;宁可多一条可编辑消息,也不能给用户一个看似在思考、
+ 实际没有内容的输入框动画。
+
+### 6.2 正常终稿
+
+1. 收到终态后先停止新的过程事件进入发送队列,设置 `FINAL_INTENT` 栅栏。
+2. 立即从 presenter 取得完整正文,按 adapter 能力选择 Rich → HTML/Markdown → plain,
+ 分段并为每段生成稳定 `deliveryKey`。
+3. **发送新的普通终稿消息**,并沿用 round identity 中冻结的 `replyToMessageId`。不要先编辑
+ 旧过程消息,不要把 draft 当成已送达消息,也不要从此刻最新的群消息重新选回挂目标。
+4. 所有终稿分段都获得成功/可确认回执后,标记 `FINAL_SENT`。
+5. 如果使用 draft,发送一个空内容清理请求;如果使用过程消息,尽力删除旧载体。两者
+ 都是 cleanup,不得阻塞第 3 步,也不得覆盖第 4 步的结果。
+6. 清理失败记录为 `CLEANUP_PENDING`,在同一 round 的安全重试窗口中处理;重试时只操作
+ 本轮拥有的 carrier。
+
+### 6.3 失败、超时和不确定回执
+
+- 已知永久失败:保留过程载体,发送可见错误(若该轮不是 ambient);不声称终稿已送达。
+- 临时失败:终稿 intent 进入 outbox,重试使用相同 `deliveryKey`;终稿栅栏仍然生效,
+ 不能让新的过程帧插入。
+- 请求超时但服务端可能已受理:状态为 `UNKNOWN`,先调用 `reconcile` 或等待服务端
+ `msg.op.result`;没有确认前不盲目再发一条,避免重复答案。
+- 断线:过程更新可以丢弃或降级,终稿必须进入相应 adapter 的持久/内存出箱;恢复后先
+ 清理过期项,再按 delivery key 重放。官方沿用桌面本地 `requestLedger` 约 24 小时的发布
+ 边界;服务端不新增正文 outbox。个人是否引入等价落盘属于后续产品决策,不在本设计中
+ 偷偷改变。
+- 取消在终稿受理前生效:停止过程与终稿发送,清理 carrier,回写“已取消”;取消在终稿
+ 已受理后到达:不删除终稿,只记录“取消晚于完成”,避免用户看不到答案。
+- `NO_REPLY`:不发送终稿;清理 draft/过程消息尽力而为。若删不掉,允许留下过程痕迹,
+ 但不能发一条“空答案”或错误消息。
+
+## 7. 能力协商与降级
+
+当前 `HOOK_FEATURE_MESSAGE_OPS` 是一个较粗的总开关。服务端 PR #366 把它落实为一个
+**reaction 专用**的安全网关:桌面侧实际也只用它发送带 `requestId` 的 ack / 结果 reaction。
+它不是“服务端已经可以替客户端发送消息”的信号。目标是保持这个总开关兼容,同时增加
+逐操作声明;本 PR 不修改协议,只规定客户端应如何消费。
+
+建议的能力粒度(名称仅为设计候选):
+
+| 能力 | 用途 | 未声明时的降级 |
+| -------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| `msg-op-v1` | 当前仅为 request-scoped reaction 与其回执;未来操作 envelope 的共同底座 | reaction 不发;正文、过程与终稿仍走 `turn.progress` / `turn.end` |
+| `msg-op.send` | 发送新消息 | 旧终稿帧路径;不能假设服务端可代发 |
+| `msg-op.edit` | 编辑指定 bot 消息 | 过程快照走旧 progress;终稿仍新发 |
+| `msg-op.delete` | 删除 bot 自己的过程消息 | 留两条并存,答案不丢 |
+| `msg-op.typing` | typing 生命周期 | 不显示 typing,不影响任务 |
+| `msg-op.media` | 图片/文件出站 | 文字终稿先送,媒体单独降级/重试 |
+| `msg-op.result-v1` | 每个操作的成功、失败或未知回执 | 只允许可确认的旧帧路径 |
+| `msg-op.recipient-v1` | binding/principal 精确接收者 | 未协商时沿用旧 relay 安全路径;新客户端不接受无 recipient 的新 relay |
+| `telegram.rich-message-v1` | Rich Message 内容 | HTML/Markdown,再退 plain |
+| `telegram.draft.rich-process-v1` | 完整 DM 过程 draft | 真实过程消息 + edit |
+| `telegram.message-effect-v1` | 终稿 `messageEffectId` | 不带效果重发/继续正文,不重复发送正文 |
+| `telegram.custom-emoji-v1` | 自定义 emoji 内容或 reaction | 标准 emoji 或纯文本语义 |
+
+能力必须按当前连接和 binding 快照使用。连接重建后重新协商;旧快照不能跨 generation
+继续发操作。未知能力一律按未声明处理,不通过“尝试一下再看报错”探测。
+
+特别地,客户端在只看见 `msg-op-v1` 时,**只能**发 `react`;不得把服务端会返回
+“not supported”的 `send`、`edit`、`delete`、`typing` 或 `media` 当作可用的降级路径。
+启用任一非 reaction 操作前,必须先有该操作的显式能力声明,并在同一连接上同时确认
+`msg.op.result` 回执。这样 PR #366 可以单独上线,客户端共享内核和官方 legacy adapter
+也可以同时开发,而不会把正文投递押在尚未发布的服务端功能上。
+
+## 8. 新旧客户端与新旧服务端兼容矩阵
+
+| | 旧服务端 | 新服务端 |
+| ------------ | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **旧客户端** | 当前行为:官方 `turn.progress` / `turn.end`,个人 Bot API;无新操作 | 新服务端继续发送旧帧;旧客户端忽略未知可选字段/操作,不接收 `msg.op`,行为与左格相同 |
+| **新客户端** | 连接能力为空;官方使用 legacy adapter(含 #2305 的末帧 flush),个人仍可使用共享内核;不发送未协商 `msg.op` | 仅有 PR #366 的 `msg-op-v1` 时只通过网关发送 reaction,正文仍走 legacy;以后协商到逐操作能力才启用对应 adapter 意图,缺能力的单项按上一列降级,不能整轮卡住 |
+
+兼容要求是“可独立发布”:任何一端单独升级都不能出现石沉大海、最后终稿永久等待或把
+迟到过程帧写回终稿。新客户端不能要求新服务端先上线;新服务端也不能假定所有客户端都
+会消费 `msg.op`。
+
+## 9. 绑定、换绑、代际和 fail-closed
+
+### 9.1 官方
+
+- `recipient.bindingId` 与 `recipient.principalId` 必须同时精确匹配当前 confirmed binding;
+ 缺一、错一或成员证据过期都丢弃。
+- 官方 task dispatch 的 `principalId` 来自入站发言者,不从客户端传来的 `chatId` 推主人。
+- 解绑、换绑、退群、账号退出和 binding 状态不确定时,停止新出站;保留旧 binding 的状态
+ 只用于完成幂等 ACK/清理,不得把答案写给新主人。
+- relay 只做上下文投影,不取得任务执行权;旧 relay 帧不能覆盖新 principal 的终稿。
+- 服务端授权失效代际必须按 binding/principal 隔离;无关 Telegram 用户的绑定、解绑或换绑
+ 不能让当前操作误报失效。
+- 同一目标消息的 mutation(至少 `react` / `edit` / `delete`)必须按
+ `(botId, chatId, messageId)` 串行;只按 `opId` 合并不能阻止较老操作延迟完成后覆盖新状态。
+- 撤销与外部 Bot API 副作用必须有明确线性化边界。建议以 per-binding 队列/租约覆盖授权复核
+ 到 Bot API 请求受理:先在线性化点取得执行权的操作可以完成,先完成撤销的操作必须拒绝。
+ 仅在 API 返回后再比较全局 epoch,既撤不回已经发生的副作用,也会误伤无关 binding。
+
+### 9.2 个人
+
+- 每轮拍下 `ownerUserId`、Bot API client 和 `configVersion`;每次真实出站(包括 repost、
+ edit、delete、图片分组中的每一张)前重新验证。
+- 换 token、换 owner、dispose、轮询重启或 API client 替换都使旧 round 的出站失效。
+- 失效后不把暂时读不到配置当成新授权;保守地停止该轮并保留可恢复的终稿记录。
+
+### 9.3 统一规则
+
+generation 是安全边界,不是 UI 状态。任何“旧消息刚好能编辑成功”都不能证明它仍属于
+当前 round;所有 adapter 都必须先验证身份,再调用 API。
+
+## 10. 数据库命名空间与消息所有权
+
+消息数据库已经共享实现,但命名空间不能合并:
+
+- 官方:`telegram:<principalId>`;
+- 个人:`telegram-personal:<botId>`。
+
+群窗口的字节上限、回收低水位和 SQL lane 条件继续来自共享 `groupWindowCore` /
+`groupHistorySearch`。保留策略按字节,不改成按条数,也不在本设计里增加 migration。
+
+每个出站记录的逻辑 owner 至少是:
+
+```text
+provider + accountId + bindingId/principalId + chatId + topicId + roundId + carrier/final role
+```
+
+过程载体只能由创建它的 adapter、同一 round 和同一 generation 编辑/删除;终稿消息与过程
+消息是两种不同 role,不能以“同一 chat”互相替代。入站消息上的 reaction 是另一种 owner
+关系,必须通过当前 bot/provider 的授权判据。
+
+## 11. Rich Message、reaction、message effect 与 custom emoji
+
+这四类能力不能混为一谈:
+
+| 能力 | 语义 | 当前状态 | 目标降级顺序 |
+| -------------- | ------------------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------- |
+| Rich Message | 正文的结构化排版(标题、列表、表格、代码、公式、details、媒体引用) | 个人已有 `rich_message` 定稿尝试;官方桌面尚未通过 msg.op 接线 | Rich → HTML/Markdown → plain |
+| reaction | 给入站触发消息打 ack/结果表情,是装饰/反馈 | 个人已有;官方目前通过 `msg.op` 接入 | 变体 emoji → 基础 emoji → 不打表情 |
+| message effect | Telegram 终稿的动画/夸张效果 | 官方 DM 服务端已有 `messageEffectId`;个人能力为 false | 带 effect 发送 → 不带 effect 的同一终稿 |
+| custom emoji | 消息正文或 reaction 中的自定义 emoji | 依赖具体 Bot API / 服务端能力协商 | 自定义 emoji → 标准 emoji → 文本语义 |
+
+当前协议的 `send` 已能承载正文、reply、tier、silent 和按钮,`media` 能承载附件,`react.big`
+能承载夸张 reaction;但它没有显式 `messageEffectId`,也没有完整过程 draft 动词。阶段 5 若仍以
+“客户端决定消息形态、服务端只执行”为目标,就必须补协议字段/动作,不能让服务端从 `tier`
+或正文内容猜效果,也不能继续把 legacy 服务端渲染误称为共享内核已经接管。
+
+装饰失败不能让正文重发一遍。若正文发送回执不确定,先 reconcile;只有确认正文尚未送达
+且 adapter 能保证相同 `deliveryKey` 幂等时才允许重试。
+
+## 12. 取消、失败、重连和清理矩阵
+
+| 情况 | 过程载体 | 终稿 | 清理与可见结果 |
+| ---------------------- | ---------------------------------------------- | ----------------------------------------- | -------------------------------------------------------------------------- |
+| 正常成功 | 停止更新 | 新鲜普通消息,全部分段确认后 `FINAL_SENT` | 清 draft/删旧过程;失败可两条并存 |
+| 模型失败(普通轮次) | 保留现场 | 不伪造成功终稿;按 adapter 发错误 | 记录错误,必要时保留过程区 |
+| ambient 失败 | 官方按既有静默策略;个人当前行为需另立 PR 判定 | 不发错误终稿 | 至少保留日志/任务记录,不能因静默而丢诊断 |
+| 用户取消,终稿尚未受理 | 尽力清理 | 不发送 | 卡片/typing 一并结束,状态 `CANCELLED` |
+| 取消晚于终稿受理 | 不再更新 | 保留已确认终稿 | 只记录竞态,不删除答案 |
+| 连接断开 | 可以丢过程帧 | 进入 adapter outbox | 官方沿用桌面本地 `requestLedger` TTL,服务端不存正文;个人落盘策略后续裁决 |
+| 终稿发送超时,回执未知 | 冻结,不再更新 | `UNKNOWN`,先 reconcile | 不盲目重复,恢复后用同一 key 处理 |
+| 删除旧过程失败 | 不再更新旧载体 | 已送达终稿不受影响 | 允许旧过程 + 新终稿并存,记录 cleanup pending |
+| `NO_REPLY` | 停止过程更新 | 不发送 | 清 draft/删过程尽力而为,不能发空消息 |
+| 交互卡在终稿边界 | 卡片决策先入内核 | 决策完成后才可发终稿 | 卡片回调必须带 round/generation,迟到点击 fail-closed |
+| 迟到 progress / relay | 丢弃 | 不得覆盖 | 以终稿栅栏和 recipient/generation 作为双重门 |
+
+## 13. 分阶段迁移计划
+
+每一阶段都必须能单独发布和回滚;后续阶段永远不能成为前一阶段的运行前置。
+
+### 阶段 0:本设计(当前 PR)
+
+- 写入本设计、补 parity 台账引用;
+- 只读核对当前客户端、Hermes 参考和官方身份边界;
+- 不改服务端、协议、schema、线上行为;
+- 产出双出口 golden test 规格,作为实现验收清单。
+
+### 阶段 1:客户端共享内核(客户端可独立发布)
+
+- 把过程视图、终稿栅栏、delivery key、取消/失败/清理状态机抽成共享纯逻辑;
+- 先让个人 adapter 和官方 legacy adapter 使用它,但输出保持当前形态;
+- 增加状态机、generation、迟到帧和双出口 golden tests;
+- 回滚只移除内核接线,不改变数据库和协议。
+
+### 阶段 2:个人 bot 先切换
+
+- 个人 adapter 采用“过程载体 → 新鲜终稿 → 清理”语义;
+- 继续在不支持完整 draft 时使用真实过程消息;不重新启用旧单行 draft;
+- 终稿发送成功后再清理,补齐未知回执与本地可恢复边界;
+- 官方行为不受影响,便于先在用户自持 bot 上验证。
+
+### 阶段 3:官方 legacy adapter 加固(无需等待 msg.op)
+
+- 在 `turn.progress` / `turn.end` 回退路径中启用终稿栅栏,收到终态后拒绝迟到 progress;
+- 保留 #2305 的末帧 flush,但不让 flush 参与终稿正确性;
+- 让官方桌面本地 `requestLedger`、ACK 重放和客户端清理都经过同一生命周期模型;服务端
+ 继续只做授权执行,不新增正文 outbox;
+- 这阶段仍不能让服务端执行任意 client-driven `send/edit/delete`,因此消息载体能力有限。
+
+### 阶段 4:从 reaction 网关扩展细粒度 msg.op(跨仓独立 PR)
+
+- 以 PR #366 的 reaction 网关为起点,逐项增加 `send/edit/delete/typing/media` 的显式能力,
+ 不能仅复用 `msg-op-v1` 这个粗开关来暗示它们可用;
+- 每个新操作先实现授权、recipient、message owner、op result 与幂等/未知回执,再向客户端宣告;
+- 新客户端仅在对应 capability 出现时启用 `send/edit/delete/typing/media`;
+- 新旧四格矩阵逐格验收,旧客户端继续收到 legacy frames;
+- 不把服务端未合并的操作预先假定为可用。
+
+### 阶段 5:Rich、draft、effect 和 custom emoji
+
+- 逐项启用,不以一个总开关捆绑所有 Telegram 新 API;
+- 先在 DM 验证 draft 和 message effect,再扩展可安全的群/ topic 能力;
+- 每项能力都要有失败只降级装饰/排版、不丢正文的测试。
+
+### 阶段 6:清理 legacy(最后做)
+
+- 只有新客户端和新服务端覆盖率、回执可观测性和回滚路径稳定后,才删除旧 progress/end
+ adapter;
+- 删除前至少保留一个版本周期的能力缺失回退,避免旧桌面或降级 relay 被黑洞吞掉。
+
+## 14. 双出口 golden tests
+
+### 14.1 共享内核测试
+
+每个 fixture 输入同一组 thinking、tool、正文增量、交互卡、终态和故障注入,断言:
+
+- 过程视图顺序和文本完全一致;
+- 同一 round 的过程更新在终稿栅栏后全部被丢弃;
+- 正常终稿一定先 `send-final`,后 `clear/delete-process`;
+- `NO_REPLY`、取消、失败、未知回执和删除失败符合第 12 节;
+- 重试使用相同 delivery key,迟到/重复回执不会生成第二个逻辑终稿;
+- binding 或 generation 改变后不再产生有效出站意图。
+
+### 14.2 个人 adapter fixtures
+
+至少覆盖:
+
+1. DM 首次真实内容、多个工具步骤、长终稿分段;
+2. 无 draft 能力时过程消息编辑;有完整 draft 能力时同轮 draft id 复用、跨轮 id 隔离;
+3. 原位编辑失败 → 新发终稿 → 删除失败,断言答案仍在;
+4. `NO_REPLY` 在“尚未建消息”和“已经流出正文”两种时序;
+5. 换 token/owner、重连、图片多组上传中的 generation 失效;
+6. message effect/custom emoji 不支持时正文只发送一次。
+
+### 14.3 官方 adapter fixtures
+
+至少覆盖:
+
+1. 新旧服务端四格能力协商;
+2. `msg.op` send/edit/delete/result 的成功、永久失败、临时失败和未知回执;
+3. legacy `turn.progress` / `turn.end` 末帧 flush 与终稿栅栏竞态;
+4. binding/principal/recipient 不匹配、换绑和 relay 迟到帧;
+5. 群友正确 `@`、未绑定陌生人 `@`、ambient、topic/reply;
+6. 官方桌面本地 `requestLedger` 重连、24 小时过期和服务端重复 dispatch;
+7. 官方 DM effect、Rich、media 能力单项缺失时的降级。
+
+同一 fixture 的“用户可见事件序列”应能被两个 adapter 各自解释;不要求 Telegram API
+调用字面相同,只要求阶段、所有权、终态和失败语义一致。
+
+## 15. 当前可做与当前不能做
+
+### 客户端现在可以直接做
+
+- 抽取并接入共享消息内核与 golden tests;
+- 先统一个人 bot 和官方 legacy 路径的终稿栅栏、迟到帧丢弃、清理非阻塞和状态可观测性;
+- 在个人 bot 上验证 Cindy 的“新终稿再清旧载体”,并复用 Hermes 已验证的失败补送、
+ 回执与能力降级经验;
+- 把 reaction、Rich、effect、custom emoji 作为可选能力,不支持时安全降级;
+- 保持官方/个人身份和群权限差异,不需要等待服务端 PR。
+
+### 必须与服务端/协议配合后才能做
+
+- 官方 bot 真正的 client-driven `send/edit/delete/typing/media`;
+- 官方端的完整 DM draft、Rich Message、message effect 和 custom emoji 出站;
+- 服务端授权、recipient 和逐操作回执的 wire 契约;
+- 删除旧 `turn.progress` / `turn.end` 的兼容路径。
+
+因此本设计不会承诺“现在就把两边完全变成同一份 Telegram 代码”。正确的收敛目标是:
+内核一份、adapter 两份、身份与权限差异显式保留、旧新能力可协商回退。
+
+## 16. 参考实现与审计依据
+
+- 现有共享呈现:`apps/desktop/src/main/im/shared/turnPresenter.ts`、`turnActivity.ts`。
+- 个人 Telegram:`packages/lizi-im/src/telegram/streamingText.ts`、`index.ts`、
+ `presentationCapabilities.ts` 及其测试。
+- 官方 Telegram:`apps/desktop/src/main/hook-control/dispatcher.ts`、`manager.ts`、
+ `session-runner.ts`、`requestLedger.ts`、`ackReactions.ts`。
+- 官方身份与群中继:`hook-control/groupHistoryScope.ts`、`groupWindow.ts`、
+ `manager.ts` 的 recipient/generation 校验。
+- Hermes 本地审计的 `telegram-rich-bot-api`、`messaging-response-design` skill、
+ native draft patch,以及 2026-08-10 的最新 `upstream/main` Telegram adapter/tests:
+ 借鉴 draft 生命周期、最终编辑失败补送、分段、FloodWait、回执测试和 Rich Message
+ 降级;Cindy 的“新终稿再清旧载体”是本项目自己的产品选择,没有把 Hermes 的当前实现
+ 误写成 Cindy 已有能力或一模一样的算法。
+- 能力差异台账:[`telegram-bot-parity.md`](telegram-bot-parity.md)。
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index 59d7e72442..fce4e91df4 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -54,6 +54,13 @@ export { TELEGRAM_DEFAULT_BEHAVIOR } from './telegram/index.js';
export type { TelegramBehaviorConfig } from './telegram/index.js';
export { TELEGRAM_PERSONAL_CAPABILITIES } from './telegram/presentationCapabilities.js';
export type { TelegramDriverCapabilities } from './telegram/presentationCapabilities.js';
+export { createTelegramMessageLifecycle } from './telegram/messageLifecycle.js';
+export { TelegramFinalUnconfirmedError } from './telegram/streamingText.js';
+export type {
+ TelegramFinalIntent,
+ TelegramMessageLifecycle,
+ TelegramMessageLifecyclePhase,
+} from './telegram/messageLifecycle.js';
export { WecomIM, createWecomIM } from './wecom/index.js';
export type { WecomIMOptions } from './wecom/index.js';
export {
diff --git a/packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts b/packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts
new file mode 100644
index 0000000000..9171ee8ea5
--- /dev/null
+++ b/packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { createTelegramMessageLifecycle } from '../messageLifecycle.js';
+
+describe('telegram message lifecycle', () => {
+ it('终稿栅栏后拒绝迟到 progress,且发送后才能进入清理', () => {
+ const lifecycle = createTelegramMessageLifecycle('round-1');
+ expect(lifecycle.acceptProgress()).toBe(true);
+ const final = lifecycle.beginFinal();
+
+ expect(final).toMatchObject({ deliveryKey: 'round-1:final', sequence: 1, attempt: 1 });
+ expect(lifecycle.acceptProgress()).toBe(false);
+ expect(lifecycle.beginCleanup()).toBe(false);
+ expect(lifecycle.markFinalSent(final!)).toBe(true);
+ expect(lifecycle.beginCleanup()).toBe(true);
+ expect(lifecycle.finishCleanup()).toBe(true);
+ expect(lifecycle.phase).toBe('complete');
+ });
+
+ it('重复终态共享同一在途 intent,失败重试保持 delivery key', () => {
+ const lifecycle = createTelegramMessageLifecycle('round-2');
+ const first = lifecycle.beginFinal()!;
+ const duplicate = lifecycle.beginFinal()!;
+
+ expect(duplicate).toEqual(first);
+ expect(lifecycle.markFinalFailed(first)).toBe(true);
+ const retry = lifecycle.beginFinal()!;
+ expect(retry.deliveryKey).toBe(first.deliveryKey);
+ expect(retry.attempt).toBe(2);
+ // 旧尝试的迟到回执不能收口新尝试。
+ expect(lifecycle.markFinalSent(first)).toBe(false);
+ expect(lifecycle.markFinalSent(retry)).toBe(true);
+ });
+
+ it('取消冻结过程与终稿,但不删除已经确认的答案', () => {
+ const pending = createTelegramMessageLifecycle('pending');
+ expect(pending.cancel()).toBe(true);
+ expect(pending.acceptProgress()).toBe(false);
+ expect(pending.beginFinal()).toBeNull();
+
+ const sent = createTelegramMessageLifecycle('sent');
+ const final = sent.beginFinal()!;
+ expect(sent.markFinalSent(final)).toBe(true);
+ expect(sent.cancel()).toBe(false);
+ expect(sent.phase).toBe('final-sent');
+ });
+});
+
diff --git a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
index 362e0c2144..013f46cc82 100644
--- a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
@@ -1,12 +1,15 @@
import { describe, expect, it, vi } from 'vitest';
-import { startTelegramStreaming, type TelegramStreamingDeps } from '../streamingText.js';
+import {
+ startTelegramStreaming,
+ TelegramFinalUnconfirmedError,
+ type TelegramStreamingDeps,
+} from '../streamingText.js';
/**
- * 终稿原位编辑撞 Telegram 编辑 flood 时的兜底(2026-08-04 线上实测: 一个 11 分钟
- * 群轮次的 finalize 吃到 `429 retry after 26`, 整条答案永久丢失, 聊天里只剩一条
- * 停在"⚙️ 工作中"的僵尸消息)。这些用例钉住三件事: 答案必达、顺序是先发新后删旧、
- * 补送后的图片锚点跟到新消息。
+ * 终稿永远使用新消息(2026-08): 过程载体不再承担答案,避免最后一次编辑撞 flood
+ * 或被群 relay 覆盖。用例钉住三件事: 先发新后删旧、Rich 新发保留结构化内容、
+ * Rich 不可用时安全回落 HTML。
*/
interface Harness {
@@ -26,6 +29,7 @@ function makeHarness(
deleteImpl?: (messageId: string) => Promise<void>;
chunk?: (text: string) => string[];
extractImageUrls?: (markdown: string) => string[];
+ sendFinalImpl?: (markdown: string, reuseReplyTarget: boolean) => Promise<string | null>;
/** 不提供 repost 时用于验证回落 send 的行为。 */
withoutRepost?: boolean;
} = {},
@@ -69,24 +73,33 @@ function makeHarness(
return `msg-${nextId++}`;
};
}
+ if (overrides.sendFinalImpl) {
+ deps.sendFinal = async (markdown, reuseReplyTarget) => {
+ calls.push(`final:${markdown}:${reuseReplyTarget}`);
+ return overrides.sendFinalImpl!(markdown, reuseReplyTarget);
+ };
+ }
return { deps, calls, sent, reposted, deleted, uploadAnchors };
}
-describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
- it('原位编辑成功时不新发、不删旧消息', async () => {
+describe('telegram streaming finalize — 新鲜终稿与 Rich 降级', () => {
+ it('过程消息存在时终稿始终新发,随后才删除旧消息', async () => {
const h = makeHarness();
const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 3s');
await handle.finalize('最终答案');
- expect(h.calls).toEqual(['send:⚙️ 工作中 · 3s', 'edit:msg-1']);
- expect(h.deleted).toEqual([]);
+ expect(h.calls).toEqual([
+ 'send:⚙️ 工作中 · 3s',
+ 'repost:最终答案',
+ 'delete:msg-1',
+ ]);
+ expect(h.deleted).toEqual(['msg-1']);
});
- it('原位编辑失败 → 答案改由新消息承载, 且顺序是先发新后删旧', async () => {
- const editErr = new Error('telegram editMessageText failed: 429 Too Many Requests: retry after 26');
+ it('不再依赖终稿 edit,即使 edit 会失败仍先发答案后删过程消息', async () => {
const h = makeHarness({
editImpl: async () => {
- throw editErr;
+ throw new Error('must not edit final');
},
});
const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 10m44s');
@@ -99,7 +112,6 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
// 顺序不可对调: 新消息落地在删除之前。
expect(h.calls).toEqual([
'send:⚙️ 工作中 · 10m44s',
- 'edit:msg-1',
'repost:完整的最终答案',
'delete:msg-1',
]);
@@ -108,9 +120,6 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
it('未提供 repost 时回落 send(兼容不关心回挂语义的调用方)', async () => {
const h = makeHarness({
- editImpl: async () => {
- throw new Error('429');
- },
withoutRepost: true,
});
const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 6s');
@@ -120,32 +129,25 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
expect(h.deleted).toEqual(['msg-1']);
});
- it('新发也失败时抛回原始编辑错误, 并且不删旧消息', async () => {
- const editErr = new Error('editMessageText failed: 429');
+ it('新发失败时保留过程消息并抛出发送错误', async () => {
+ const sendErr = new Error('sendMessage failed: 429');
let sendCount = 0;
const h = makeHarness({
- editImpl: async () => {
- throw editErr;
- },
sendImpl: async () => {
sendCount += 1;
// 第一次是建流式占位, 第二次才是补送。
- if (sendCount > 1) throw new Error('sendMessage failed: 429');
+ if (sendCount > 1) throw sendErr;
return 'msg-1';
},
});
const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 9m');
- // 掩盖真实原因会让线上排障失去线索 —— 必须抛原始编辑错误。
- await expect(handle.finalize('答案')).rejects.toBe(editErr);
+ await expect(handle.finalize('答案')).rejects.toBe(sendErr);
expect(h.deleted).toEqual([]);
});
it('旧消息删不掉不影响已送达的答案', async () => {
const h = makeHarness({
- editImpl: async () => {
- throw new Error('429');
- },
deleteImpl: async () => {
throw new Error("message can't be deleted");
},
@@ -158,9 +160,6 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
it('补送后受管图片锚定到新消息, 不挂在已删的过程消息上', async () => {
const h = makeHarness({
- editImpl: async () => {
- throw new Error('429');
- },
extractImageUrls: () => ['cindy-media://blobs/a.png'],
});
const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 1m');
@@ -187,20 +186,372 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
expect(h.sent).toEqual(['⚙️ 工作中 · 5m', '第二段', '第三段']);
});
- it('rich 原位定稿成功时既不走 HTML 编辑也不补送', async () => {
+ it('分段中途失败后重试不重发任何已出站的段落', async () => {
+ let failTail = true;
const h = makeHarness({
- editImpl: async () => {
- throw new Error('不该走到这里');
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ // 第二段第一次抛错 —— 无法区分 Telegram 到底收到没有。
+ if (markdown === '第二段' && failTail) throw new Error('sendMessage failed: 429');
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 8m');
+
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toThrow(/429/);
+ expect(h.reposted).toEqual(['第一段']);
+
+ failTail = false;
+ // 第二段回执不确定 → 不重发(可能已落地), 只补第三段; 但这一轮没完整确认,
+ // 所以 finalize 以 TelegramFinalUnconfirmedError 收尾而非静默成功。
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toBeInstanceOf(
+ TelegramFinalUnconfirmedError,
+ );
+
+ // 首段与第二段都不再重发, 第三段照常补上。
+ expect(h.reposted).toEqual(['第一段']);
+ expect(h.sent).toEqual(['⚙️ 工作中 · 8m', '第二段', '第三段']);
+ });
+
+ it('分段被 Telegram 明确拒绝(4xx)时保留该段, 重试补齐不缺段', async () => {
+ // 4xx = 报文完整往返、Telegram 拒绝了这一段, 聊天里不可能出现它。
+ // 若按"可能已送达"跳过, 重试后照样 markFinalSent 并清掉过程载体 —— 答案缺段。
+ let rejectTail = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第二段' && rejectTail) {
+ throw Object.assign(new Error('telegram sendMessage failed: 400 Bad Request'), {
+ errorCode: 400,
+ });
+ }
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 5m');
+
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toThrow(/400/);
+
+ rejectTail = false;
+ await handle.finalize('第一段|第二段|第三段');
+
+ // 第二段确定未送达 → 必须重发; 首段已可见 → 绝不重发。
+ expect(h.reposted).toEqual(['第一段']);
+ expect(h.sent).toEqual(['⚙️ 工作中 · 5m', '第二段', '第二段', '第三段']);
+ });
+
+ it('429 是明确拒绝: 该段保留待重试, 不缺段', async () => {
+ // 2026-08-11 review 更正: api.ts 的 parseResponse 只在读回完整响应体后才
+ // 构造带 errorCode 的错误 —— 带 errorCode 的 429 是 Telegram 应答的限流
+ // 拒绝("这条我没收"), 不是回执丢失。真正的未知回执在 fetch 层就抛原生
+ // 错误, 没有 errorCode。
+ let flood = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第二段' && flood) {
+ throw Object.assign(new Error('telegram sendMessage failed: 429'), { errorCode: 429 });
+ }
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 7m');
+
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toThrow(/429/);
+ flood = false;
+ await handle.finalize('第一段|第二段|第三段');
+
+ // 第二段确定未送达 → 必须重发。
+ expect(h.sent).toEqual(['⚙️ 工作中 · 7m', '第二段', '第二段', '第三段']);
+ });
+
+ it('无 errorCode 的网络错误按回执未知处理(不重发, 避免整篇重复)', async () => {
+ // fetch 层的连接中断走不到 parseResponse, 没有 errorCode —— 无法证明
+ // Telegram 没收到, 重试跳过它, 宁可缺一段也不整篇重复。
+ let broken = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第二段' && broken) throw new Error('fetch failed: ECONNRESET');
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 7m');
+
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toThrow(/ECONNRESET/);
+ broken = false;
+ await expect(handle.finalize('第一段|第二段|第三段')).rejects.toBeInstanceOf(
+ TelegramFinalUnconfirmedError,
+ );
+
+ expect(h.sent).toEqual(['⚙️ 工作中 · 7m', '第二段', '第三段']);
+ });
+
+ it('首段未知回执时不重铸整条终稿, 重试只补后续分段', async () => {
+ // 首条终稿已被 Telegram 接受但响应中断: deliveredChunks 若停在 0,
+ // 重试会给用户再发一份完整答案。
+ let broken = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第一段' && broken) throw new Error('socket hang up');
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 6m');
+
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/socket hang up/);
+ broken = false;
+ // 首段按已送达记账(不重铸整篇), 但它从未确认 —— 这一轮以未确认收尾。
+ const err = await handle.finalize('第一段|第二段').catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(TelegramFinalUnconfirmedError);
+ expect((err as TelegramFinalUnconfirmedError).firstChunkConfirmed).toBe(false);
+
+ // 首段不重发; 只补第二段。
+ expect(h.reposted).toEqual(['第一段']);
+ expect(h.sent).toEqual(['⚙️ 工作中 · 6m', '第二段']);
+ });
+
+ it('首段被明确拒绝时保持未投递, 重试重发整条终稿', async () => {
+ let rejected = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第一段' && rejected) {
+ throw Object.assign(new Error('telegram failed: 400'), { errorCode: 400 });
+ }
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 6m');
+
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/400/);
+ rejected = false;
+ await handle.finalize('第一段|第二段');
+
+ // 确定未送达 → 首段必须重发。
+ expect(h.reposted).toEqual(['第一段', '第一段']);
+ });
+
+ it('从未确认送达时不清理过程载体(既没答案也没现场是最坏结果)', async () => {
+ // fetch 在请求写出前就失败(DNS/连接建立失败): deliveredChunks 被推满防重复,
+ // 但内容其实从未出现在聊天里。此时删掉载体会让用户什么都看不到。
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown.startsWith('⚙️')) return 'carrier-msg';
+ throw new Error('getaddrinfo ENOTFOUND api.telegram.org');
},
});
- const editFinal = vi.fn(async () => true);
- const handle = await startTelegramStreaming({ ...h.deps, editFinal }, '⚙️ 工作中 · 4s');
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 4m');
+
+ await expect(handle.finalize('唯一的答案')).rejects.toThrow(/ENOTFOUND/);
+
+ // 重试: deliveredChunks 已被推满(防重复), 于是全部分段被跳过、不再有 I/O。
+ // 但从未确认过任何一次送达 —— 不能删载体(否则既没答案也没现场), 也不能静默
+ // 成功(上游会当成收口)。
+ const err = await handle.finalize('唯一的答案').catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(TelegramFinalUnconfirmedError);
+ expect((err as TelegramFinalUnconfirmedError).firstChunkConfirmed).toBe(false);
+ expect(h.deleted).toEqual([]);
+ // 载体还在, 上游仍可凭它判断这一轮没收口。
+ expect(h.sent).toEqual(['⚙️ 工作中 · 4m']);
+ });
+
+ it('首段未确认时, 尾段成功也不清理载体(尾段证明不了首段送达)', async () => {
+ // 首段 DNS 失败(未知回执) → 计数推进防重复; 重试跳过首段、尾段成功。
+ // 一个全局"确认过"布尔会被尾段置真并误删现场, 用户只剩尾段。
+ let firstBroken = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown.startsWith('⚙️')) return 'carrier-msg';
+ if (markdown === '第一段' && firstBroken) {
+ throw new Error('getaddrinfo ENOTFOUND api.telegram.org');
+ }
+ return 'msg-x';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 9m');
+
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/ENOTFOUND/);
+ firstBroken = false;
+ // 重试: 首段被跳过(计数已推进), 第二段发出并成功 —— 但尾段的成功回执证明
+ // 不了首段被接受, 所以这一轮仍以未确认收尾。
+ const err = await handle.finalize('第一段|第二段').catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(TelegramFinalUnconfirmedError);
+ expect((err as TelegramFinalUnconfirmedError).firstChunkConfirmed).toBe(false);
+
+ expect(h.sent).toContain('第二段');
+ // 首段从未确认 → 载体必须留着。
+ expect(h.deleted).toEqual([]);
+ });
+
+ it('首段未确认时暂停图片上传, 不把载体 id 当锚点', async () => {
+ // messageIdValue 这时还是过程载体 ID: 把图挂上去, 载体一旦被删图就没了。
+ let broken = true;
+ const h = makeHarness({
+ extractImageUrls: () => ['cindy-media://blobs/a.png'],
+ sendImpl: async (markdown) => {
+ if (markdown.startsWith('⚙️')) return 'carrier-msg';
+ if (broken) throw new Error('socket hang up');
+ return 'final-msg';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 3m');
+
+ await expect(handle.finalize('带图的答案')).rejects.toThrow(/socket hang up/);
+ // 重试时首段被跳过(未知回执已计数), 但没有真实终稿 id —— 必须拒绝上传。
+ await expect(handle.finalize('带图的答案')).rejects.toThrow(/unconfirmed/);
+ expect(h.uploadAnchors).toEqual([]);
+ expect(h.deleted).toEqual([]);
+ });
+
+ it('有未确认分段时不进 final-sent, 后续 finalize 仍能进来对账', async () => {
+ // 关键: finalize() 开头会让 final-sent / complete 直接 return。若未确认分段
+ // 存在却提前收口, 这一轮再也无法补投, 而调用方还以为成功了。
+ let tailBroken = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第二段' && tailBroken) throw new Error('socket hang up');
+ return markdown.startsWith('⚙️') ? 'carrier-msg' : 'final-msg';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 5m');
+
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/socket hang up/);
+ tailBroken = false;
+
+ // 第二段回执未知 → 不重投(可能已落地), 也不宣布收口, 且必须让调用方看见:
+ // 静默 resolve 会被上游当成收口成功。
+ const err = await handle.finalize('第一段|第二段').catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(TelegramFinalUnconfirmedError);
+ expect((err as TelegramFinalUnconfirmedError).firstChunkConfirmed).toBe(true);
+ expect((err as TelegramFinalUnconfirmedError).unconfirmedChunks).toEqual([1]);
+ expect(h.deleted).toEqual([]);
+
+ // 未收口 ⇒ 状态没被锁死, 后续 finalize 仍会真正执行(而非被 final-sent 挡在
+ // 第一行直接 return)。用一次会抛错的图片上传把"确实走进了主体"钉住。
+ h.deps.extractImageUrls = () => ['cindy-media://blobs/x.png'];
+ h.deps.uploadImages = async () => {
+ throw new Error('probe: finalize body executed');
+ };
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/probe/);
+ expect(h.sent.filter((t) => t === '第二段')).toHaveLength(1); // 始终不重投
+ });
+
+ it('全部分段确认后正常进入 final-sent 并清理载体', async () => {
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) =>
+ markdown.startsWith('⚙️') ? 'carrier-msg' : 'final-msg',
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 2m');
+
+ await handle.finalize('第一段|第二段');
+ expect(h.deleted).toEqual(['carrier-msg']);
+
+ // 已收口: 再次 finalize 直接返回, 不产生任何出站。
+ const sentBefore = h.sent.length;
+ await handle.finalize('第一段|第二段');
+ expect(h.sent).toHaveLength(sentBefore);
+ });
+
+ it('多批图片: 后批失败后重试从断点续传, 不重复已发附件', async () => {
+ const uploaded: Array<{ start: number; count: number }> = [];
+ let failSecondBatch = true;
+ const h = makeHarness({ extractImageUrls: () => Array.from({ length: 15 }, (_, i) => `img-${i}`) });
+ h.deps.uploadImages = async (_messageId, refs, opts) => {
+ const start = opts?.startIndex ?? 0;
+ uploaded.push({ start, count: refs.length - start });
+ // 第一批 10 张成功, 第二批失败。
+ opts?.onProgress?.(Math.max(start, 10));
+ if (failSecondBatch) {
+ failSecondBatch = false;
+ throw new Error('sendMediaGroup failed');
+ }
+ };
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 2m');
+
+ await expect(handle.finalize('带图答案')).rejects.toThrow(/sendMediaGroup/);
+ await handle.finalize('带图答案');
+
+ // 第二次从第 10 张开始, 不重传前 10 张。
+ expect(uploaded).toEqual([
+ { start: 0, count: 15 },
+ { start: 10, count: 5 },
+ ]);
+ });
+
+ it('清理的是原始过程载体, 不是已经送达的终稿', async () => {
+ // 首段成功后 messageIdValue 已指向终稿; 若从它重算清理目标, 会把答案删掉
+ // 而留下过程载体。全程确认(无未知回执)时才走到清理。
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) =>
+ // 过程载体与终稿必须是不同的 messageId, 否则这条断言没有意义。
+ markdown.startsWith('⚙️') ? 'carrier-msg' : 'final-msg',
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 12m');
+ const carrierId = handle.messageId;
+ expect(carrierId).toBe('carrier-msg');
+
+ await handle.finalize('第一段|第二段');
+
+ // 首段落地后 handle 指向终稿; 删的必须是最初那条过程消息。
+ expect(handle.messageId).not.toBe(carrierId);
+ expect(h.deleted).toEqual([carrierId]);
+ expect(h.deleted).not.toContain(handle.messageId);
+ });
+
+ it('尾段回执未知时保留载体: 重试跳过它, 但正文未完整确认', async () => {
+ // 尾段 500 属于回执未知 —— 不重投(避免重复), 但也不能据此宣称收口。
+ let failTail = true;
+ const h = makeHarness({
+ chunk: (text) => text.split('|'),
+ sendImpl: async (markdown) => {
+ if (markdown === '第二段' && failTail) throw new Error('sendMessage failed: 500');
+ return markdown.startsWith('⚙️') ? 'carrier-msg' : 'final-msg';
+ },
+ });
+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 12m');
+
+ await expect(handle.finalize('第一段|第二段')).rejects.toThrow(/500/);
+ failTail = false;
+ // 重试: 第二段已计数(防重复)故被跳过, 但它始终没拿到回执 —— 以未确认收尾。
+ const err = await handle.finalize('第一段|第二段').catch((e: unknown) => e);
+ expect(err).toBeInstanceOf(TelegramFinalUnconfirmedError);
+ expect((err as TelegramFinalUnconfirmedError).unconfirmedChunks).toEqual([1]);
+
+ // 第二段只发过一次(没有重投), 且因未确认而保留现场。
+ expect(h.sent.filter((t) => t === '第二段')).toHaveLength(1);
+ expect(h.deleted).toEqual([]);
+ });
+
+ it('Rich 终稿新发成功时既不走 HTML 补送也不编辑过程消息', async () => {
+ const sendFinal = vi.fn(async () => 'rich-2');
+ const h = makeHarness();
+ const handle = await startTelegramStreaming({ ...h.deps, sendFinal }, '⚙️ 工作中 · 4s');
await handle.finalize('rich 定稿的答案');
- expect(editFinal).toHaveBeenCalledOnce();
+ expect(sendFinal).toHaveBeenCalledWith('rich 定稿的答案', true);
expect(h.sent).toEqual(['⚙️ 工作中 · 4s']);
- expect(h.deleted).toEqual([]);
+ expect(h.reposted).toEqual([]);
+ expect(h.deleted).toEqual(['msg-1']);
+ });
+
+ it('Rich 明确不可用时回落 HTML 补送,仍保持先发新后删旧', async () => {
+ const sendFinal = vi.fn(async () => null);
+ const h = makeHarness();
+ const handle = await startTelegramStreaming({ ...h.deps, sendFinal }, '⚙️ 工作中 · 4s');
+
+ await handle.finalize('降级后的答案');
+
+ expect(sendFinal).toHaveBeenCalledWith('降级后的答案', true);
+ expect(h.reposted).toEqual(['降级后的答案']);
+ expect(h.deleted).toEqual(['msg-1']);
});
it('NO_REPLY 沉默仍然是撤掉占位, 不会误走补送', async () => {
diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
index 564cb5c6f2..eb06a2f60d 100644
--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts
@@ -1288,13 +1288,10 @@ describe('TelegramIM', () => {
// 私聊不再依赖 sendMessageDraft(草稿只能一行纯文本, 装不下过程时间线)
expect(api.calls.some((c) => c.method === 'sendMessageDraft')).toBe(false);
await handle.finalize('最终回答');
- // 定稿与群一样是原地 rich 升级(同一条消息), 不另发一条
- const richEdits = api.calls.filter(
- (c) => c.method === 'editMessageText' && c.params.rich_message !== undefined,
- );
- expect(richEdits.length).toBe(1);
- expect((richEdits[0].params.rich_message as { markdown?: string }).markdown).toBe('最终回答');
- expect(api.calls.some((c) => c.method === 'sendRichMessage')).toBe(false);
+ // 定稿是独立的 Rich 消息:过程载体不会再被最终答案覆盖。
+ const richSends = api.calls.filter((c) => c.method === 'sendRichMessage');
+ expect(richSends).toHaveLength(1);
+ expect((richSends[0].params.rich_message as { markdown?: string }).markdown).toBe('最终回答');
});
it('DM 中间态能承载多行过程时间线(工具调用在私聊也可见)', async () => {
@@ -1314,50 +1311,89 @@ describe('TelegramIM', () => {
);
// 收口后只留干净正文(过程区由编排层移除), 与群同口径
await handle.finalize('看完了');
- const richEdits = api.calls.filter(
- (c) => c.method === 'editMessageText' && c.params.rich_message !== undefined,
+ const richSends = api.calls.filter((c) => c.method === 'sendRichMessage');
+ expect((richSends.at(-1)?.params.rich_message as { markdown?: string }).markdown).toBe('看完了');
+ });
+
+ it('Rich 新发 429(退避后仍限流)降级 HTML, 答案不停在过程消息', async () => {
+ // turnRunner 的终态路径只把 finalize() 异常记成 non-fatal 警告、不会重试,
+ // 所以 Rich 的 429 抛出去 = 用户永远停在"工作中"。callSend 已按 retry_after
+ // 退避过, 仍 429 就是明确拒绝 —— 这条 Rich 没落地, HTML 补发不会重复。
+ await connect();
+ const originalCall = api.call.bind(api);
+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
+ if (method === 'sendRichMessage') {
+ api.calls.push({ method, params: params ?? {} });
+ throw new TelegramApiError('sendRichMessage', 429, 'Too Many Requests', 0);
+ }
+ return originalCall(method, params, signal);
+ }) as FakeApi['call'];
+
+ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 8m');
+ vi.useFakeTimers();
+ try {
+ // callSend 对 429 会按 retry_after 退避重试一次, 之后才交回这里降级。
+ const finalized = handle.finalize('flood 下也必须送到的答案');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await finalized;
+ } finally {
+ vi.useRealTimers();
+ }
+
+ // HTML 新发承载了答案。
+ const answer = api.calls.find(
+ (c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('必须送到的答案'),
+ );
+ expect(answer).toBeDefined();
+ // 429 不是方法缺失, 不该熔断: 下一轮仍会尝试 Rich。
+ const richBefore = api.calls.filter((c) => c.method === 'sendRichMessage').length;
+ const handle2 = await im.startStreamingText(OWNER_ID);
+ vi.useFakeTimers();
+ try {
+ const second = handle2.finalize('第二轮');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await second;
+ } finally {
+ vi.useRealTimers();
+ }
+ expect(api.calls.filter((c) => c.method === 'sendRichMessage').length).toBeGreaterThan(
+ richBefore,
);
- expect((richEdits.at(-1)?.params.rich_message as { markdown?: string }).markdown).toBe('看完了');
});
- it('rich 原地定稿 404(方法不可用)实例级 latch, 后续不再尝试', async () => {
+ it('Rich 新发 404(方法不可用)实例级 latch, 后续不再尝试', async () => {
await connect();
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText' && params?.rich_message !== undefined) {
+ if (method === 'sendRichMessage') {
api.calls.push({ method, params: params ?? {} });
- throw new TelegramApiError('editMessageText', 404, 'Not Found');
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
const handle = await im.startStreamingText(OWNER_ID);
await handle.finalize('回答一');
- const richEditCount = () =>
- api.calls.filter(
- (c) => c.method === 'editMessageText' && c.params.rich_message !== undefined,
- ).length;
- // rich 升级试了一次 → 404 latch; 正文仍由 sendMessage 落地不丢
- expect(richEditCount()).toBe(1);
+ const richSendCount = () => api.calls.filter((c) => c.method === 'sendRichMessage').length;
+ // Rich 试了一次 → 404 latch; 正文仍由新发 sendMessage 落地不丢。
+ expect(richSendCount()).toBe(1);
expect(api.calls.some((c) => c.method === 'sendMessage')).toBe(true);
const handle2 = await im.startStreamingText(OWNER_ID);
await handle2.finalize('回答二');
- expect(richEditCount()).toBe(1);
+ expect(richSendCount()).toBe(1);
});
it('429 退避等满 Telegram 给的 retry_after(不再封顶 10s), 终稿不丢', async () => {
await connect();
const originalCall = api.call.bind(api);
- let htmlEditAttempts = 0;
+ let richSendAttempts = 0;
const flood = (): TelegramApiError =>
new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- // rich 定稿在 flood 下同样撞 429, 让流程落到 HTML 编辑这条真正带退避的路径。
- if (method === 'editMessageText' && params?.rich_message !== undefined) throw flood();
- if (method === 'editMessageText') {
- htmlEditAttempts += 1;
- if (htmlEditAttempts === 1) throw flood();
+ if (method === 'sendRichMessage') {
+ richSendAttempts += 1;
+ if (richSendAttempts === 1) throw flood();
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
@@ -1372,26 +1408,27 @@ describe('TelegramIM', () => {
// 旧实现把退避封在 10s: 此刻已经重试, 而 flood 窗口还剩 16s → 必然二次
// 失败, 整条终稿就是这样丢的(2026-08-04 线上实测)。
await vi.advanceTimersByTimeAsync(10_000);
- expect(htmlEditAttempts).toBe(1);
+ expect(richSendAttempts).toBe(1);
await vi.advanceTimersByTimeAsync(16_000);
await finalized;
- expect(htmlEditAttempts).toBe(2);
+ expect(richSendAttempts).toBe(2);
} finally {
vi.useRealTimers();
}
- // 原位编辑最终成功 → 不需要动用补送, 也不该留下多余消息。
+ // 新鲜 Rich 终稿最终送达,过程消息随后清理。
expect(sendCount()).toBe(sendsBeforeFinalize);
- const lastEdit = api.calls.filter((c) => c.method === 'editMessageText').at(-1);
- expect(String(lastEdit?.params.text ?? '')).toContain('完整的最终答案');
+ const richFinal = api.calls.filter((c) => c.method === 'sendRichMessage').at(-1);
+ expect((richFinal?.params.rich_message as { markdown?: string }).markdown).toContain('完整的最终答案');
});
- it('原位编辑始终失败时, 终稿改由新消息承载并撤掉过程消息', async () => {
+ it('Rich 不可用时, HTML 新消息承载终稿并撤掉过程消息', async () => {
await connect();
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ api.calls.push({ method, params: params ?? {} });
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
@@ -1399,15 +1436,7 @@ describe('TelegramIM', () => {
const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 11m');
const progressMessageId = handle.messageId;
- vi.useFakeTimers();
- try {
- const finalized = handle.finalize('flood 下也必须送到的答案');
- // 两次编辑尝试(rich 直连不退避 + HTML 经 callSend 退避一次)后转补送。
- await vi.advanceTimersByTimeAsync(60_000);
- await finalized;
- } finally {
- vi.useRealTimers();
- }
+ await handle.finalize('降级后也必须送到的答案');
const answer = api.calls.find(
(c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('必须送到的答案'),
@@ -1422,19 +1451,17 @@ describe('TelegramIM', () => {
);
});
- it('群 lane 流式: send+edit 经典路径 + 定稿 rich 原地升级(本次统一的基准)', async () => {
+ it('群 lane 流式: send+edit 过程路径 + 新发 Rich 终稿(本次统一的基准)', async () => {
await connect();
const handle = await im.startStreamingText('g/-100200/r7');
handle.replace('进行中');
await handle.finalize('群里的最终回答');
expect(api.calls.some((c) => c.method === 'sendMessageDraft')).toBe(false);
expect(api.calls.some((c) => c.method === 'sendMessage')).toBe(true);
- // 定稿是 editMessageText + rich_message(表格/LaTeX 原生渲染), 非 HTML edit
- const richEdits = api.calls.filter(
- (c) => c.method === 'editMessageText' && c.params.rich_message !== undefined,
- );
- expect(richEdits.length).toBe(1);
- expect((richEdits[0].params.rich_message as { markdown?: string }).markdown).toBe(
+ // 定稿是新的 Rich 消息(表格/LaTeX 原生渲染), 非 HTML edit。
+ const richSends = api.calls.filter((c) => c.method === 'sendRichMessage');
+ expect(richSends).toHaveLength(1);
+ expect((richSends[0].params.rich_message as { markdown?: string }).markdown).toBe(
'群里的最终回答',
);
});
@@ -1644,7 +1671,7 @@ describe('TelegramIM', () => {
const originalCall = api.call.bind(api);
let releaseFirstSend: (() => void) | null = null;
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'sendMessage' && params?.chat_id === OWNER_ID && !releaseFirstSend) {
+ if (method === 'sendRichMessage' && !releaseFirstSend) {
api.calls.push({ method, params: params ?? {} });
await new Promise<void>((resolve) => {
releaseFirstSend = resolve;
@@ -1719,7 +1746,7 @@ describe('TelegramIM', () => {
.toBe(401);
});
- it("群默认 'first' 档: 终稿编辑失败后, 补送仍引用原触发消息", async () => {
+ it("群默认 'first' 档: Rich 不可用时 HTML 终稿仍引用原触发消息", async () => {
await im.dispose();
im = new TelegramIM(ctx.host, {
apiFactory: () => api,
@@ -1735,8 +1762,8 @@ describe('TelegramIM', () => {
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
@@ -1748,14 +1775,7 @@ describe('TelegramIM', () => {
);
expect((progressSend[0].params.reply_parameters as { message_id: number }).message_id).toBe(80);
- vi.useFakeTimers();
- try {
- const finalized = handle.finalize('flood 下补送出来的答案');
- await vi.advanceTimersByTimeAsync(60_000);
- await finalized;
- } finally {
- vi.useRealTimers();
- }
+ await handle.finalize('Rich 不可用后补送出来的答案');
// 补送的答案不能脱离提问脉络 —— 重新 lease 会拿到空目标, 必须沿用本轮的 80。
const answer = api.calls.find(
@@ -1767,7 +1787,7 @@ describe('TelegramIM', () => {
.toBe(80);
});
- it("回挂档位 off 时, 补送不带 reply_parameters", async () => {
+ it("回挂档位 off 时, HTML 终稿不带 reply_parameters", async () => {
await im.dispose();
im = new TelegramIM(ctx.host, {
apiFactory: () => api,
@@ -1783,21 +1803,14 @@ describe('TelegramIM', () => {
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
const handle = await im.startStreamingText(lane, '⚙️ 工作中 · 3m');
- vi.useFakeTimers();
- try {
- const finalized = handle.finalize('off 档的答案');
- await vi.advanceTimersByTimeAsync(60_000);
- await finalized;
- } finally {
- vi.useRealTimers();
- }
+ await handle.finalize('off 档的答案');
const answer = api.calls.find(
(c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('off 档的答案'),
@@ -1806,7 +1819,7 @@ describe('TelegramIM', () => {
expect(answer!.params.reply_parameters).toBeUndefined();
});
- it("群 'all' 档: 补送同样挂回, 档位语义不被补送破坏", async () => {
+ it("群 'all' 档: HTML 终稿同样挂回, 档位语义不被回落破坏", async () => {
await im.dispose();
im = new TelegramIM(ctx.host, {
apiFactory: () => api,
@@ -1822,21 +1835,14 @@ describe('TelegramIM', () => {
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
const handle = await im.startStreamingText(lane, '⚙️ 工作中 · 2m');
- vi.useFakeTimers();
- try {
- const finalized = handle.finalize('all 档补送的答案');
- await vi.advanceTimersByTimeAsync(60_000);
- await finalized;
- } finally {
- vi.useRealTimers();
- }
+ await handle.finalize('all 档补送的答案');
const groupSends = api.calls.filter(
(c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200',
@@ -1878,7 +1884,7 @@ describe('TelegramIM', () => {
await vi.waitFor(() => expect(sendAttempts).toBe(1));
});
- it('换 owner 后原位编辑与清理都不再触碰旧回合(edit / editFinal / deleteMessage)', async () => {
+ it('换 owner 后终稿发送与清理都不再触碰旧回合', async () => {
await connect();
const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 5m');
const callsBefore = api.calls.length;
@@ -1886,13 +1892,14 @@ describe('TelegramIM', () => {
// 只换主人: 不 stopPolling, api 对象不变 —— 唯一能识别授权易主的是世代/主人。
await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '777888' });
- // editFinal 是 finalize 的第一步, 核验失败即抛 —— 整个收口放弃。
+ // sendFinal 是 finalize 的第一步,核验失败即抛——整个收口放弃。
await expect(handle.finalize('旧回合的终稿')).rejects.toThrow(/round abandoned/);
const after = api.calls.slice(callsBefore);
expect(after.filter((c) => c.method === 'editMessageText')).toEqual([]);
expect(after.filter((c) => c.method === 'deleteMessage')).toEqual([]);
expect(after.filter((c) => c.method === 'sendMessage')).toEqual([]);
+ expect(after.filter((c) => c.method === 'sendRichMessage')).toEqual([]);
});
it('换 owner 后的 NO_REPLY 沉默不再删旧回合的占位消息', async () => {
@@ -1989,13 +1996,13 @@ describe('TelegramIM', () => {
}
});
- it('补送成功后才换 owner: 剩余分段与图片同样不再发给旧 userId', async () => {
+ it('HTML 终稿首段成功后才换 owner: 剩余分段与图片同样不再发给旧 userId', async () => {
await connect();
const originalCall = api.call.bind(api);
let ownerSwitched = false;
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ throw new TelegramApiError('sendRichMessage', 404, 'Not Found');
}
const result = await originalCall(method, params, signal);
// 首段补送刚落地就换主人 —— 此刻 assertRoundStillLive 已经放行过一次,
@@ -2012,16 +2019,9 @@ describe('TelegramIM', () => {
}) as FakeApi['call'];
const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 7m');
- vi.useFakeTimers();
- try {
- // chunkTelegramSource 不会按 | 分段, 用一段超长正文迫使终稿分片。
- const long = `第一段${'甲'.repeat(4200)}\n\n第二段尾巴`;
- const finalized = handle.finalize(long).catch((err: unknown) => err);
- await vi.advanceTimersByTimeAsync(120_000);
- await finalized;
- } finally {
- vi.useRealTimers();
- }
+ // chunkTelegramSource 不会按 | 分段, 用一段超长正文迫使终稿分片。
+ const long = `第一段${'甲'.repeat(4200)}\n\n第二段尾巴`;
+ await handle.finalize(long).catch(() => {});
expect(ownerSwitched).toBe(true);
// 首段已经发出(那时回合还有效), 但换主人之后的剩余分段一律不许再出站。
@@ -2076,8 +2076,8 @@ describe('TelegramIM', () => {
await connect();
const originalCall = api.call.bind(api);
api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {
- if (method === 'editMessageText') {
- throw new TelegramApiError('editMessageText', 429, 'Too Many Requests: retry after 26', 26);
+ if (method === 'sendRichMessage') {
+ throw new TelegramApiError('sendRichMessage', 429, 'Too Many Requests: retry after 26', 26);
}
return originalCall(method, params, signal);
}) as FakeApi['call'];
@@ -2091,21 +2091,23 @@ describe('TelegramIM', () => {
const finalized = handle.finalize(answer).catch((err: unknown) => err);
await vi.advanceTimersByTimeAsync(1_000);
// 只换 ownerUserId、不带 token: 这条分支不 stopPolling, this.api 完全不变,
- // 只有 configVersion / ownerUserId 变了 —— 补送若按当前世代重新取 api 就会
- // 把这轮答案照发给已经失去授权的旧主人。
+ // 只有 configVersion / ownerUserId 变了 —— Rich 终稿若按当前世代重新取 api
+ // 就会把这轮答案照发给已经失去授权的旧主人。
await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '222333' });
await vi.advanceTimersByTimeAsync(120_000);
const outcome = await finalized;
- // 先断言泄露本身: 一个字都不许发出去(未修时补送会成功, 这条先红)。
+ // 先断言泄露本身: 一个字都不许发出去。
expect(
api.calls
.filter((c) => c.method === 'sendMessage')
.map((c) => String(c.params.text ?? ''))
.filter((text) => text.includes('完整答案')),
).toEqual([]);
- // 生命周期失效不能被当成普通编辑失败: 放弃补送并抛回原始编辑错误。
- expect(outcome).toBeInstanceOf(TelegramApiError);
- expect((outcome as TelegramApiError).errorCode).toBe(429);
+ // Rich 的 429 是明确拒绝 → 降级 HTML; 而 HTML 补送前的身份核验发现 owner
+ // 已换, 于是整轮收口作废。关键不变量是"一个字都没发给旧主人"(上面已断言),
+ // 错误类型只需证明它是被生命周期拦下的, 不是普通发送失败。
+ expect(outcome).toBeInstanceOf(Error);
+ expect(String(outcome)).toMatch(/round abandoned/);
} finally {
vi.useRealTimers();
}
@@ -2268,21 +2270,20 @@ describe('TelegramIM', () => {
// A 继续输出并定稿 —— 仍须挂回 70, 不得变 71
await handle.finalize('A 的最终答案');
+ const isGroupSend = (c: { method: string; params: Record<string, unknown> }) =>
+ (c.method === 'sendMessage' || c.method === 'sendRichMessage') &&
+ String(c.params.chat_id) === '-100200';
const quoted = api.calls
- .filter((c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200')
+ .filter(isGroupSend)
.map((c) => (c.params.reply_parameters as { message_id: number } | undefined)?.message_id);
expect(quoted.length).toBeGreaterThanOrEqual(2);
expect(quoted.every((id) => id === 70)).toBe(true);
// B 的目标没被那条提示偷走: B 自己的回合能领到 71
- const beforeB = api.calls.filter(
- (c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200',
- ).length;
+ const beforeB = api.calls.filter(isGroupSend).length;
const bHandle = await im.startStreamingText(lane);
await bHandle.finalize('B 的答案');
- const bSends = api.calls
- .filter((c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200')
- .slice(beforeB);
+ const bSends = api.calls.filter(isGroupSend).slice(beforeB);
expect((bSends[0].params.reply_parameters as { message_id: number } | undefined)?.message_id)
.toBe(71);
});
diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.ts
index 22ba9cf47f..3bb66b32f2 100644
--- a/packages/lizi-im/src/telegram/index.ts
+++ b/packages/lizi-im/src/telegram/index.ts
@@ -808,7 +808,8 @@ export class TelegramIM extends BaseIM implements ChannelIM {
async startStreamingText(userId: string, initial?: string): Promise<StreamingTextHandle> {
// DM 与群/topic 共用同一条流式呈现: send + editMessageText 覆盖同一条
- // 消息, 过程区(工具时间线)与正文一起原地刷新, 定稿原地升级为 rich。
+ // 消息, 过程区(工具时间线)与正文一起原地刷新;定稿始终新发,避免最终答案
+ // 被过程载体的迟到更新或群 relay 替换。
// 私聊曾走 sendMessageDraft 草稿通道 —— 草稿只能承载一行纯文本, 工具调用
// 在私聊里因此整体不可见, 与群聊形成两套体验(Chris 2026-08 点名);
// 呈现规则不再按 DM / 群分叉。
@@ -852,8 +853,8 @@ export class TelegramIM extends BaseIM implements ChannelIM {
// 本轮**每一个**触达 Telegram 的出站入口都先核验回合身份 —— 一个不漏。
// 逐个核验不可省成"补送时查一次": 换 owner 可能发生在任意一次 await 之后,
// 而 owner-only 变更**不换 api 客户端**, 剩下的出站照样能成功。
- // 覆盖面: send / repost(新消息)、edit / editFinal(原位编辑——终稿的主投递
- // 路径, 换主人后编辑成功就等于把答案写进已失权主人的聊天)、deleteMessage
+ // 覆盖面: send / repost(HTML 新消息) / sendFinal(Rich 新消息)、edit(过程
+ // 载体)、deleteMessage
// (失权后连清理都不该再碰对方的聊天)、uploadImages(内部逐次再核验)。
// 正常轮次里这些核验恒为空操作。
send: async (markdown) => {
@@ -879,20 +880,27 @@ export class TelegramIM extends BaseIM implements ChannelIM {
const { html } = markdownToTelegramHtml(markdown);
await this.editHtml(chatId, nativeId, html, undefined);
},
- uploadImages: async (messageId, imageUrls) => {
+ uploadImages: async (messageId, imageUrls, imageOpts) => {
// 图片是多次真实出站(分组 sendMediaGroup、整组失败回落逐张 sendPhoto),
// 每次之间都有 await —— 所以核验要下沉到每次调用前, 只在批次开头查一次
// 挡不住"第一组传完才换主人"这个窗口。
this.assertRoundStillLive(round);
- await this.uploadImages(messageId, imageUrls, () =>
- this.assertRoundStillLive(round),
+ await this.uploadImages(
+ messageId,
+ imageUrls,
+ () => this.assertRoundStillLive(round),
+ imageOpts,
);
},
chunk: chunkTelegramSource,
extractImageUrls: (markdown) => markdownToTelegramHtml(markdown).imageUrls,
- editFinal: (messageId, markdown) => {
+ sendFinal: async (markdown, reuseReplyTarget) => {
this.assertRoundStillLive(round);
- return this.richEditFinal(messageId, markdown);
+ return this.sendRichFinal(
+ userId,
+ markdown,
+ reuseReplyTarget ? round.replyTargetId : undefined,
+ );
},
deleteMessage: async (messageId) => {
this.assertRoundStillLive(round);
@@ -1790,27 +1798,52 @@ export class TelegramIM extends BaseIM implements ChannelIM {
}
/**
- * Rich 原地定稿(editMessageText + rich_message, Bot API 10.1): 把流式占位
- * 消息一步升级成 rich 渲染(表格/标题/代码块/LaTeX 原生, 32768 上限免分段)。
- * DM 与群共用。404 → 实例级 latch; 400(本条解析不过)只回落本条。
+ * 新发 Rich 终稿(sendRichMessage + rich_message): 过程载体从不承担最终答案,
+ * 让最终消息拥有独立 message id,避免群 relay 与迟到过程更新覆盖它。
+ *
+ * Rich 不能用时返回 null,由调用方安全回落 HTML/Markdown 新发;404 代表方法
+ * 不可用,实例级熔断。
+ *
+ * 降级判据是「**Telegram 有没有应答**」,不是错误码大小:4xx 都意味着报文完整
+ * 往返、这条 Rich 没有落地,HTML 补发不会造成重复。**429 也在此列**
+ * (2026-08-11 review):`callSend` 已按 `retry_after` 退避重试过,仍拿到 429 就是
+ * 明确拒绝;而 `turnRunner` 的终态路径只把 `finalize()` 的异常记成 non-fatal
+ * 警告、**不会再调一次**,抛出去等于让用户永远停在过程消息上。HTML 那条路自身
+ * 也走 `callSend`,会再遵守一次 `retry_after`。
+ *
+ * 只有拿不到应答的情况(网络中断、超时、5xx)才抛出:那时无法判断 Telegram
+ * 是否已经接收,补发 HTML 可能造成两份答案。
*/
- private async richEditFinal(messageId: string, markdown: string): Promise<boolean> {
- if (this.richSendDisabled || !markdown.trim()) return false;
- const api = this.api;
- if (!api) return false;
+ private async sendRichFinal(
+ userId: string,
+ markdown: string,
+ reuseReplyTargetId?: string | null,
+ ): Promise<string | null> {
+ if (this.richSendDisabled || !markdown.trim()) return null;
+ const reusing = reuseReplyTargetId !== undefined;
+ const { params: replyParams, lease } = reusing
+ ? { params: replyParamsFor(reuseReplyTargetId), lease: null }
+ : this.leaseReplyTarget(userId);
try {
- const { chatId, messageId: nativeId } = decodeMessageId(messageId);
- await api.call('editMessageText', {
- chat_id: chatId,
- message_id: Number(nativeId),
+ const sent = await this.callSend<TgMessage>('sendRichMessage', {
+ ...this.targetOf(userId),
+ ...replyParams,
rich_message: { markdown },
});
- return true;
+ this.commitReplyTarget(lease);
+ this.recordOwnEcho(userId, markdown, sent);
+ return encodeMessageId(String(sent.chat.id), String(sent.message_id));
} catch (err) {
- if (err instanceof TelegramApiError && err.errorCode === 404) {
- this.richSendDisabled = true;
+ if (err instanceof TelegramApiError && err.errorCode >= 400 && err.errorCode < 500) {
+ // 4xx = Telegram 完整应答后拒绝了这条 Rich, 它没有落地, HTML 补发不会
+ // 造成重复。404 另外表示方法本身不可用 —— 实例级熔断, 后续不再尝试。
+ // 429(退避重试后仍限流)同样在此: 抛出去只会让答案永久停在过程消息。
+ if (err.errorCode === 404) {
+ this.richSendDisabled = true;
+ }
+ return null;
}
- return false;
+ throw err;
}
}
@@ -1933,10 +1966,16 @@ export class TelegramIM extends BaseIM implements ChannelIM {
* 的逐张回落都是。只在进入本方法时查一次挡不住"第一组传完才换主人"的窗口,
* 剩下的图片会照发到已失权的旧聊天。
*/
+ /**
+ * `startIndex` / `onProgress` 支撑终稿重试的断点续传(见 streamingText 的
+ * `uploadImages` 契约): 去重后从 `startIndex` 起传, 每完成一批就回报**累计
+ * 已收口张数**。抛错时调用方据此续传, 用户不会收到重复附件。
+ */
private async uploadImages(
messageId: string,
imageRefs: string[],
assertLive?: () => void,
+ opts?: { startIndex?: number; onProgress?: (deliveredCount: number) => void },
): Promise<void> {
const api = this.api;
if (!api || imageRefs.length === 0) return;
@@ -1966,24 +2005,44 @@ export class TelegramIM extends BaseIM implements ChannelIM {
seen.add(absPath);
absPaths.push(absPath);
}
- if (absPaths.length === 1) {
+ // 续传起点按**去重后**的序号切: 与 onProgress 回报的口径一致。
+ const startIndex = Math.max(0, Math.min(opts?.startIndex ?? 0, absPaths.length));
+ const pending = absPaths.slice(startIndex);
+ if (pending.length === 0) return;
+ // 累计计数含已跳过的部分, 这样调用方存的始终是"总共已收口多少张"。
+ let delivered = startIndex;
+ const report = (): void => opts?.onProgress?.(delivered);
+
+ if (pending.length === 1) {
assertLive?.();
- await this.sendSinglePhoto(chatId, absPaths[0], anchorReply);
+ await this.sendSinglePhoto(chatId, pending[0], anchorReply);
+ delivered += 1;
+ report();
return;
}
- for (let i = 0; i < absPaths.length; i += 10) {
- const group = absPaths.slice(i, i + 10);
+ for (let i = 0; i < pending.length; i += 10) {
+ const group = pending.slice(i, i + 10);
assertLive?.();
// 单张不成相册, 直接走单发 —— 这条是正常路径, 不是相册失败。
const outcome =
group.length > 1 ? await this.sendPhotoAlbum(chatId, group, anchorReply) : 'rejected';
- if (outcome === 'uncertain') continue; // 可能已经发出去了, 不补发
+ if (outcome === 'uncertain') {
+ // 可能已经发出去了, 不补发 —— 同理也要记进已收口, 重试不得重来。
+ delivered += group.length;
+ report();
+ continue;
+ }
if (outcome === 'rejected') {
for (const absPath of group) {
assertLive?.();
await this.sendSinglePhoto(chatId, absPath, anchorReply);
+ delivered += 1;
+ report();
}
+ continue;
}
+ delivered += group.length;
+ report();
}
}
diff --git a/packages/lizi-im/src/telegram/messageLifecycle.ts b/packages/lizi-im/src/telegram/messageLifecycle.ts
new file mode 100644
index 0000000000..2ee6b98513
--- /dev/null
+++ b/packages/lizi-im/src/telegram/messageLifecycle.ts
@@ -0,0 +1,162 @@
+/**
+ * telegram/messageLifecycle.ts
+ * ---------------------------------------------------------------------------
+ * 纯 Telegram 消息生命周期内核。
+ *
+ * 这里不做 Telegram API I/O,也不持有 bot 身份。个人 Bot API 和官方
+ * legacy/msg.op adapter 只消费这份状态边界:过程帧在终稿栅栏后失效,终稿
+ * 使用稳定 delivery key,重复终态不会再铸造第二条答案。
+ *
+ * `final` 的“已送达”语义由 adapter 定义:个人 adapter 在 Bot API send 成功
+ * 后标记;官方 legacy adapter 在终态帧交给其可靠发布边界后标记。它不是对
+ * Telegram 用户已经看到消息的虚假保证。
+ */
+
+export type TelegramMessageLifecyclePhase =
+ | 'created'
+ | 'running'
+ | 'final-pending'
+ | 'final-failed'
+ | 'final-sent'
+ | 'cleanup-pending'
+ | 'complete'
+ | 'cancelled';
+
+export interface TelegramFinalIntent {
+ /** 同一轮同一终稿的重试必须保持不变。 */
+ readonly deliveryKey: string;
+ /** 生命周期内单调递增的终稿序号。 */
+ readonly sequence: number;
+ /** 当前是第几次尝试;不参与 delivery key。 */
+ readonly attempt: number;
+}
+
+export interface TelegramMessageLifecycle {
+ readonly roundId: string;
+ readonly phase: TelegramMessageLifecyclePhase;
+ /** 过程载体仍可接受更新吗?终稿栅栏一打开就永久为 false。 */
+ readonly progressOpen: boolean;
+ /** 接受一帧过程事件;迟到帧返回 false。 */
+ acceptProgress(): boolean;
+ /** 打开终稿栅栏并取得稳定终稿意图;同一在途终稿重复调用返回同一尝试。 */
+ beginFinal(): TelegramFinalIntent | null;
+ /** 终稿已交给 adapter 的可靠边界。 */
+ markFinalSent(intent: TelegramFinalIntent): boolean;
+ /** 终稿尝试失败;允许同一 key 后续重试,但不重新打开过程帧。 */
+ markFinalFailed(intent: TelegramFinalIntent): boolean;
+ /** 终稿确认后开始清理过程载体。 */
+ beginCleanup(): boolean;
+ /** 清理完成;删除失败也可由 adapter 选择直接完成。 */
+ finishCleanup(): boolean;
+ /** 取消尚未送达的终稿;已送达答案不会被取消抹掉。 */
+ cancel(): boolean;
+}
+
+let nextRoundNumber = 0;
+
+function defaultRoundId(): string {
+ nextRoundNumber += 1;
+ return `telegram-round-${nextRoundNumber}`;
+}
+
+/** 创建一个不做 I/O 的 Telegram 消息生命周期。 */
+export function createTelegramMessageLifecycle(roundId = defaultRoundId()): TelegramMessageLifecycle {
+ let currentPhase: TelegramMessageLifecyclePhase = 'created';
+ let progressOpen = true;
+ let sequence = 0;
+ let finalIntent: TelegramFinalIntent | null = null;
+
+ const sameIntent = (intent: TelegramFinalIntent): boolean =>
+ finalIntent !== null && intent.deliveryKey === finalIntent.deliveryKey;
+
+ return {
+ roundId,
+ get phase() {
+ return currentPhase;
+ },
+ get progressOpen() {
+ return progressOpen;
+ },
+ acceptProgress(): boolean {
+ if (!progressOpen || currentPhase === 'cancelled' || currentPhase === 'complete') {
+ return false;
+ }
+ if (currentPhase === 'created') currentPhase = 'running';
+ return true;
+ },
+ beginFinal(): TelegramFinalIntent | null {
+ if (
+ currentPhase === 'cancelled' ||
+ currentPhase === 'complete' ||
+ currentPhase === 'cleanup-pending' ||
+ currentPhase === 'final-sent'
+ ) {
+ return null;
+ }
+ progressOpen = false;
+ if (finalIntent === null) {
+ sequence += 1;
+ finalIntent = {
+ deliveryKey: `${roundId}:final`,
+ sequence,
+ attempt: 1,
+ };
+ currentPhase = 'final-pending';
+ return finalIntent;
+ }
+ // A duplicate terminal event while the adapter is still sending must not
+ // mint a second attempt. The adapter can use the same intent as its
+ // idempotency anchor.
+ if (currentPhase === 'final-pending') return finalIntent;
+ // A failed final attempt may be retried with the same delivery key. Keep
+ // the token immutable and only advance the diagnostic attempt counter.
+ if (currentPhase === 'final-failed') {
+ finalIntent = { ...finalIntent, attempt: finalIntent.attempt + 1 };
+ currentPhase = 'final-pending';
+ return finalIntent;
+ }
+ return null;
+ },
+ markFinalSent(intent: TelegramFinalIntent): boolean {
+ if (
+ !sameIntent(intent) ||
+ finalIntent?.attempt !== intent.attempt ||
+ currentPhase !== 'final-pending'
+ ) {
+ return false;
+ }
+ currentPhase = 'final-sent';
+ return true;
+ },
+ markFinalFailed(intent: TelegramFinalIntent): boolean {
+ if (
+ !sameIntent(intent) ||
+ finalIntent?.attempt !== intent.attempt ||
+ currentPhase !== 'final-pending'
+ ) {
+ return false;
+ }
+ currentPhase = 'final-failed';
+ return true;
+ },
+ beginCleanup(): boolean {
+ if (currentPhase !== 'final-sent') return false;
+ currentPhase = 'cleanup-pending';
+ return true;
+ },
+ finishCleanup(): boolean {
+ // Cleanup is deliberately idempotent. A delete failure can still call
+ // this method so the answer remains the authoritative visible result.
+ if (currentPhase === 'complete') return true;
+ if (currentPhase !== 'cleanup-pending') return false;
+ currentPhase = 'complete';
+ return true;
+ },
+ cancel(): boolean {
+ if (currentPhase === 'final-sent' || currentPhase === 'complete') return false;
+ progressOpen = false;
+ currentPhase = 'cancelled';
+ return true;
+ },
+ };
+}
diff --git a/packages/lizi-im/src/telegram/streamingText.ts b/packages/lizi-im/src/telegram/streamingText.ts
index 2c90c4c719..6453e92159 100644
--- a/packages/lizi-im/src/telegram/streamingText.ts
+++ b/packages/lizi-im/src/telegram/streamingText.ts
@@ -16,12 +16,17 @@
* - "message is not modified" 错误静默吞掉(内容未变的重复编辑);
* - 中间态超过单条上限后停止编辑(终稿由 finalize 分段补发), 与 Discord
* 的 INTERMEDIATE_EDIT_LIMIT 行为一致;
- * - **终稿的原位编辑必须有兜底**: 长轮次会对同一条消息累计上百次编辑, 撞
- * flood 时最后那次(携带答案)最容易失败。finalize 因此在编辑失败后把答案
- * 新发一条消息承载, 见 finalizeInPlaceOrRepost。
+ * - **终稿永远新发**: 过程消息是可替换的载体, 不能承担最终答案。终稿先尝试
+ * 新发 Rich Message, 不可用时回落新发 HTML/Markdown;答案落地后才尽力清理
+ * 过程载体。
*/
import type { StreamingTextHandle } from '../types.js';
+import {
+ createTelegramMessageLifecycle,
+ type TelegramFinalIntent,
+ type TelegramMessageLifecycle,
+} from './messageLifecycle.js';
export const TELEGRAM_UPDATE_THROTTLE_MS = 1500;
/** 中间态渲染后 HTML 超过该长度就不再编辑(接近 4096 上限时停手)。 */
@@ -37,34 +42,97 @@ function isNoReply(text: string): boolean {
return text.trim() === NO_REPLY_SENTINEL;
}
+/**
+ * 这次出站是**确定没送达**, 还是回执未知?
+ *
+ * 判据是「有没有拿到 Telegram 的应答」, 不是错误码大小。`api.ts` 的
+ * `parseResponse` 只在 HTTP 响应体完整读回、且 `ok !== true` 之后才构造带
+ * `errorCode` 的 `TelegramApiError` —— 所以**凡是带 errorCode 的 4xx 都是
+ * Telegram 明确说"这条我没收"**, 聊天里不可能出现它, 把该段留给重试是安全的,
+ * 跳过反而造成答案缺段。
+ *
+ * 429 同属这一类(2026-08-11 review 更正): 它是 Telegram 应答的限流拒绝, 不是
+ * 回执丢失。真正的"可能已送达"是**拿不到应答**的情况 —— 网络中断、超时、连接
+ * 被切, 那些在 fetch 层就抛原生错误, 走不到 parseResponse, 因此没有 errorCode,
+ * 会落到本函数的 false 分支按未知处理。
+ *
+ * 5xx 也按未知处理: Telegram 侧已受理但内部出错时, 消息可能已经落地。
+ *
+ * 用结构判定而非 `instanceof`: 本模块是不做 I/O 的纯生命周期层, 不应反向依赖
+ * api.ts 的具体错误类; deps 的实现方(index.ts)抛的正是带 errorCode 的那一种。
+ */
+/**
+ * 终稿**没有完整确认**就收口时抛出。
+ *
+ * 与普通发送失败的区别: 内容**可能已经落地**, 只是拿不到回执证明。所以调用方
+ * 既不该重投(会重复), 也不该把这一轮当成功 —— 该轮的过程载体保留, 生命周期停在
+ * 可恢复态, 后续同 delivery key 的 finalize 仍能进来对账。
+ *
+ * 单独立类是因为 `finalize()` 静默 resolve 会让上游把未完整确认的终稿当成功
+ * (2026-08-12 review): `TelegramStreamingTextHandle` 不暴露内部 phase, 生产包装器
+ * 只看 resolve/reject。
+ */
+export class TelegramFinalUnconfirmedError extends Error {
+ readonly name = 'TelegramFinalUnconfirmedError';
+ constructor(
+ /** 首段(答案主体、图片锚点)是否已确认。 */
+ readonly firstChunkConfirmed: boolean,
+ /** 回执未知的分段序号(0-based, 升序)。 */
+ readonly unconfirmedChunks: readonly number[],
+ ) {
+ super(
+ `telegram final delivery unconfirmed: firstChunk=${firstChunkConfirmed ? 'confirmed' : 'unconfirmed'}` +
+ `${unconfirmedChunks.length > 0 ? `, chunks=[${unconfirmedChunks.join(',')}]` : ''}` +
+ ' (content may already be delivered; do not resend)',
+ );
+ }
+}
+
+function isDefiniteRejection(err: unknown): boolean {
+ if (typeof err !== 'object' || err === null) return false;
+ const code = (err as { errorCode?: unknown }).errorCode;
+ if (typeof code !== 'number') return false;
+ return code >= 400 && code < 500;
+}
+
export interface TelegramStreamingDeps {
/** 发送一条 markdown 渲染消息, 返回编码 messageId。 */
send: (markdown: string) => Promise<string>;
/**
- * 终稿补送专用的发送(见 finalizeInPlaceOrRepost)。与 send 有两点不同, 都由实现方
- * (index.ts)负责, 本模块只负责在编辑失败时调用它:
+ * HTML/Markdown 终稿的补送专用发送。与 send 有两点不同, 都由实现方
+ * (index.ts)负责:
* 1. 沿用**本轮原始的回挂目标** —— 补送替换的是那条已经消耗掉目标的过程消息,
* 重新领取只会拿到空目标, 群里的答案就此脱离提问脉络;
* 2. 先核验**本轮身份仍然有效**(配置世代/api 客户端/主人未变、未被取消)。补送是
* 一次全新的出站, 会按"当前"状态取连接 —— 换主人之后旧回合的答案绝不能照发。
- * 身份失效时本函数应当抛错: finalize 会据此抛回原始编辑错误并放弃整个收口, 后续
- * 分段与图片一并不发。未提供时回落 send。
+ * 身份失效时本函数应当抛错,终稿与后续分段、图片一并不发。未提供时回落 send。
*/
repost?: (markdown: string) => Promise<string>;
/** 用 markdown 渲染结果覆盖既有消息。 */
edit: (messageId: string, markdown: string) => Promise<void>;
- /** 终稿里的受管图片旁路上传(sendPhoto)。 */
- uploadImages: (messageId: string, imageUrls: string[]) => Promise<void>;
+ /**
+ * 终稿里的受管图片旁路上传(sendPhoto)。
+ *
+ * `startIndex` 是本次要从第几张开始传 —— 上一次尝试已经发出去的不再重传。
+ * 实现方按去重后的顺序切片, 并通过 `onProgress(count)` 回报**累计已收口**的
+ * 张数(相册按批, 单发按张); 抛错时调用方据此从断点续传, 不会让用户收到重复
+ * 附件。不报进度也不算错, 只是重试会从 startIndex 重来。
+ */
+ uploadImages: (
+ messageId: string,
+ imageUrls: string[],
+ opts?: { startIndex?: number; onProgress?: (deliveredCount: number) => void },
+ ) => Promise<void>;
/** markdown 分段(fence 感知)。 */
chunk: (text: string) => string[];
/** 提取 markdown 里的受管图片 URL(渲染由 send/edit 内部完成)。 */
extractImageUrls: (markdown: string) => string[];
/**
- * rich 原地定稿(editMessageText + rich_message): 把流式占位消息一步升级成
- * rich 渲染(DM 与群共用)。返回 false = 本条不可用, 调用方回落 HTML edit
- * 分段定稿。
+ * 新发 Rich Message 终稿。`reuseReplyTarget` 表示过程载体已经消耗本轮回挂
+ * 目标,Rich 终稿必须沿用冻结目标;返回 null 表示本条 Rich 不可用,调用方
+ * 回落 HTML/Markdown 新发。网络/权限失败必须抛出,不能伪装成可安全降级。
*/
- editFinal?: (messageId: string, markdown: string) => Promise<boolean>;
+ sendFinal?: (markdown: string, reuseReplyTarget: boolean) => Promise<string | null>;
/** NO_REPLY 静默时删除流式占位消息。 */
deleteMessage?: (messageId: string) => Promise<void>;
}
@@ -82,6 +150,54 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
private pending: ReturnType<typeof setTimeout> | null = null;
private inFlight: Promise<void> | null = null;
private done = false;
+ /** terminal I/O is serialized so duplicate done events cannot mint two finals. */
+ private finalizing: Promise<void> | null = null;
+ /**
+ * 本轮终稿已经落地的分段数。跨 finalize 重试保留 —— 已经出现在聊天里的段落
+ * 不再重发, 重试只补未送达的部分(设计稿 §5.1 的 FINAL_PARTIAL)。
+ */
+ private deliveredChunks = 0;
+ /**
+ * 已收口的受管图片张数, 跨 finalize 重试保留。
+ *
+ * 不能用「全有或全无」的布尔: 超过 10 张会被切成多批, 前几批已经发出、后一批
+ * 抛错时, 布尔仍是 false, 重试会从第一张重传 —— 用户收到重复附件。
+ */
+ private deliveredImages = 0;
+ /**
+ * **首段**(承载答案主体、且是图片锚点的那条)是否已确认送达。
+ *
+ * 必须与后续分段分开记: `deliveredChunks` 在未知回执下也会推进(防重复), 于是
+ * 首段 DNS 失败、尾段重试成功的轮次里, 一个全局"确认过"的布尔会被尾段置真 ——
+ * 但那证明不了首段曾被 Telegram 接受, 用户可能只剩尾段, 而过程载体还被删了
+ * (2026-08-11 review)。
+ *
+ * 它同时是两件事的前置:
+ * 1. **清理过程载体** —— 正文主体没确认就不动现场;
+ * 2. **图片上传锚点** —— `messageIdValue` 只在首段确认时才指向真实终稿,
+ * 否则它还是过程载体 ID(会把图挂到随后可能被删的消息上)或空串
+ * (`decodeMessageId` 直接抛错)。
+ */
+ private firstChunkConfirmed = false;
+ /**
+ * 回执未知的分段序号(0-based)。
+ *
+ * 这些段**不会重投**(重投会让已落地的那份变成重复), 但它们的存在证明这一轮
+ * 正文没有完整确认 —— 清理过程载体因此要等这个集合为空。它是"宁可留现场,
+ * 不敢删"的判据, 不是待办队列。
+ */
+ private readonly unconfirmedChunks = new Set<number>();
+ /**
+ * 本轮**过程载体**的 messageId, 在首次 finalize 进入终稿路径时冻结。
+ *
+ * 不能在每次尝试里从 `messageIdValue` 重算: 首段一旦新发成功, 那个字段就指向
+ * 终稿了。首段成功、尾段失败后重试时再读它, 清理会把**终稿**删掉而留下过程
+ * 载体 —— 用户看到的就是答案消失、只剩一条停在过程态的消息。
+ *
+ * `null` = 尚未冻结; `''` = 已冻结且本轮从未建过过程载体(惰性占位)。
+ */
+ private carrierMessageId: string | null = null;
+ private readonly lifecycle: TelegramMessageLifecycle;
private extraImageAbsPaths: string[] = [];
/**
* 惰性占位(2026-07-30 review): 有真实正文才发首条消息 — ambient turn 的
@@ -90,7 +206,12 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
*/
private messageIdValue = '';
- private constructor(private readonly deps: TelegramStreamingDeps) {}
+ private constructor(
+ private readonly deps: TelegramStreamingDeps,
+ lifecycle: TelegramMessageLifecycle,
+ ) {
+ this.lifecycle = lifecycle;
+ }
get messageId(): string {
return this.messageIdValue;
@@ -100,9 +221,10 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
deps: TelegramStreamingDeps,
initial?: string,
): Promise<TelegramStreamingTextHandle> {
- const handle = new TelegramStreamingTextHandle(deps);
+ const handle = new TelegramStreamingTextHandle(deps, createTelegramMessageLifecycle());
// 调用方给了真实初始正文才立即建消息(保持旧契约); '…' 一律惰性。
if (initial !== undefined && initial.trim() !== '' && initial !== '…') {
+ handle.lifecycle.acceptProgress();
handle.messageIdValue = await deps.send(initial);
handle.flushed = initial;
handle.buffer = initial;
@@ -111,13 +233,13 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
}
append(delta: string): void {
- if (this.done) return;
+ if (this.done || !this.lifecycle.acceptProgress()) return;
this.buffer += delta;
this.scheduleFlush();
}
replace(fullText: string): void {
- if (this.done) return;
+ if (this.done || !this.lifecycle.acceptProgress()) return;
this.buffer = fullText;
this.scheduleFlush();
}
@@ -128,124 +250,243 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
}
close(): void {
+ if (this.done) return;
this.done = true;
+ this.lifecycle.cancel();
this.clearPending();
}
async finalize(finalText: string): Promise<void> {
- if (this.done) return;
+ if (this.finalizing) return this.finalizing;
+ if (this.lifecycle.phase === 'final-sent' || this.lifecycle.phase === 'complete') return;
+ const intent = this.lifecycle.beginFinal();
+ if (!intent) return;
this.done = true;
this.clearPending();
+ this.finalizing = this.finalizeOnce(finalText, intent).finally(() => {
+ this.finalizing = null;
+ });
+ return this.finalizing;
+ }
+
+ /**
+ * Rich 终稿新发, 并在**未知回执**下把整条正文记成已投递。
+ *
+ * `sendFinal` 返回 null 表示 Telegram 明确说"本条 Rich 我不支持"(404/400),
+ * 那是安全降级信号, 不改记账; 但它**抛错**时同样可能已经落地(网络在响应前
+ * 中断), 这时若让 deliveredChunks 停在 0, 重试会新发第二份完整答案。
+ */
+ private async sendFinalTracked(
+ finalText: string,
+ reuseReplyTarget: boolean,
+ chunkCount: number,
+ ): Promise<string | null> {
+ try {
+ return await this.deps.sendFinal!(finalText, reuseReplyTarget);
+ } catch (err) {
+ if (!isDefiniteRejection(err)) {
+ this.deliveredChunks = chunkCount;
+ this.unconfirmedChunks.add(0);
+ }
+ throw err;
+ }
+ }
+
+ /** One terminal attempt. Retries reuse the lifecycle delivery key. */
+ private async finalizeOnce(finalText: string, intent: TelegramFinalIntent): Promise<void> {
if (this.inFlight) {
try {
await this.inFlight;
} catch {
- /* swallow */
+ /* an intermediate edit is decorative; the final send remains authoritative */
}
}
+ // 过程载体只在**首次**进入终稿路径时冻结; 之后 messageIdValue 会被终稿覆盖,
+ // 重试再读它就会把终稿当成待清理的旧消息(见 carrierMessageId 的说明)。
+ this.carrierMessageId ??= this.messageIdValue;
+ const staleMessageId = this.carrierMessageId;
if (isNoReply(finalText)) {
- // 自主判断选择沉默: 惰性占位下通常从未发过消息(真零痕迹);
- // 若中间态已建消息(哨兵前有过正文流出)则撤掉。
- if (this.messageIdValue) {
+ // 惰性占位下通常从未发过消息(真零痕迹); 已建过程消息则尽力清掉。
+ this.lifecycle.cancel();
+ if (staleMessageId) {
try {
- await this.deps.deleteMessage?.(this.messageIdValue);
+ await this.deps.deleteMessage?.(staleMessageId);
} catch {
/* 删除失败(权限等)保留占位, 不抛错 */
}
}
return;
}
+
const imageUrls = this.deps.extractImageUrls(finalText);
const chunks = this.deps.chunk(finalText);
const firstChunk = chunks[0] ?? '';
- // 惰性占位: 至此必有真实内容 — 没建过消息就用首段正文建。
- if (!this.messageIdValue) {
- const seed =
- firstChunk.trim().length > 0
- ? firstChunk
- : imageUrls.length > 0 || this.extraImageAbsPaths.length > 0
- ? IMAGE_ONLY_PLACEHOLDER
- : '';
- if (seed === '') return; // 空终稿且无图: 无事可做
- this.messageIdValue = await this.deps.send(seed);
- this.flushed = seed;
- }
- // 无受管图片时优先 rich 原地定稿(表格/标题/LaTeX 原生渲染, 32768 上限
- // 免分段); 失败回落 HTML edit 分段。
- if (
- this.deps.editFinal &&
- imageUrls.length === 0 &&
- this.extraImageAbsPaths.length === 0 &&
- finalText.trim().length > 0
- ) {
- const upgraded = await this.deps.editFinal(this.messageIdValue, finalText);
- if (upgraded) return;
- }
- // 原位定稿的目标文本(有正文用首段; 纯图轮次用占位符); null = 消息已是终态。
- const inPlaceText =
- firstChunk.trim().length > 0 && this.flushed !== firstChunk
+ const seed =
+ firstChunk.trim().length > 0
? firstChunk
- : firstChunk.trim().length === 0 &&
- (imageUrls.length > 0 || this.extraImageAbsPaths.length > 0) &&
- this.flushed !== IMAGE_ONLY_PLACEHOLDER
+ : imageUrls.length > 0 || this.extraImageAbsPaths.length > 0
? IMAGE_ONLY_PLACEHOLDER
- : null;
- if (inPlaceText !== null) {
- await this.finalizeInPlaceOrRepost(inPlaceText);
- }
- for (const chunk of chunks.slice(1)) {
- await this.deps.send(chunk);
+ : '';
+ if (seed === '') {
+ this.lifecycle.cancel();
+ return;
}
- // extraImageAbsPaths(tool_result 账本图)与正文图都交 uploadImages 收口;
- // 去重职责在 index.ts 的 uploadImages 实现里(absPath / url 双口径)。
- await this.deps.uploadImages(this.messageIdValue, [
- ...imageUrls,
- ...this.extraImageAbsPaths.map((absPath) => `abs:${absPath}`),
- ]);
- }
- /**
- * 原位定稿(editMessageText 覆盖流式那条消息); 编辑失败则把终稿**新发**一条
- * 消息承载, 落地后再撤掉停在过程态的旧消息。
- *
- * 为什么需要这条兜底: 过程区每 5s 重渲染一次(时长在变), 长轮次会对同一条
- * 消息累计上百次 editMessageText, 迟早撞 Telegram 的编辑 flood。而携带答案
- * 的这一次编辑排在整轮最后, 最容易被撞 —— 实测 2026-08-04 一个 11 分钟的
- * 群轮次就是这样丢掉了整条终稿(`429 retry after 26`), 上游只会记一条
- * non-fatal 警告, 聊天里只剩一条停在"⚙️ 工作中 · 10m44s"的僵尸消息。
- *
- * 顺序固定"先发新、后删旧", 不可对调:
- * - 先删旧: 一旦新发也失败, 答案与过程记录一起消失, 比现状更糟;
- * - 先删再发还会让客户端滚动跳位(与 openclaw 同一条纪律)。
- * 删除是 best-effort —— 删不掉只是多留一条过程消息, 答案已经到了。
- *
- * 补送走 deps.repost(而非 send): 它替换的是那条已经消耗掉本轮回挂目标的过程
- * 消息, 必须沿用同一个 reply 目标, 否则群里的答案会脱离提问脉络。
- *
- * repost 抛错(含"本轮身份已失效"——被取消/换主人/换代)一律按**放弃收口**处理:
- * 抛回原始编辑错误, 且因为本函数抛出, finalize 后面的分段补发与图片上传都不会
- * 执行 —— 它们同属这个已经作废的回合。生命周期取消不能被当成普通编辑失败。
- */
- private async finalizeInPlaceOrRepost(text: string): Promise<void> {
- const staleMessageId = this.messageIdValue;
try {
- await this.deps.edit(staleMessageId, text);
- return;
- } catch (editErr) {
- // 新发失败就把原始编辑错误抛回上游(与改动前同语义), 不掩盖真实原因。
- const repost = this.deps.repost ?? this.deps.send;
- try {
- this.messageIdValue = await repost(text);
- } catch {
- throw editErr;
+ // 分段投递进度跨重试保留: 已经出现在聊天里的段落绝不重发。一次 finalize
+ // 里首段成功、尾段失败时, 上游重试必须从 deliveredChunks 之后继续 ——
+ // 否则用户会看到重复的首段(长答案里就是重复整篇正文)。
+ if (this.deliveredChunks === 0) {
+ // 首段与后续分段同一套回执判据, 但记账方向相反 —— 首段抛错时
+ // deliveredChunks 还是 0, 默认就会重发整条终稿。所以这里要在
+ // **未知回执**下主动把它记成已投递(firstChunkUnknown), 否则网络在
+ // 响应返回前中断时, 重试会给用户再铸一份完整答案。
+ //
+ // 明确拒绝(4xx)则相反: Telegram 说没收, 保持 0 让重试重发是对的。
+ const markFirstChunk = (messageId: string, text: string, chunkCount: number): void => {
+ this.messageIdValue = messageId;
+ this.flushed = text;
+ this.deliveredChunks = chunkCount;
+ // 拿到真实 messageId = 首段确认送达: 清理载体与图片锚点从此都安全。
+ this.firstChunkConfirmed = true;
+ this.unconfirmedChunks.delete(0);
+ };
+ const sendFirstChunk = async (
+ attempt: () => Promise<string>,
+ text: string,
+ chunkCount: number,
+ ): Promise<void> => {
+ try {
+ markFirstChunk(await attempt(), text, chunkCount);
+ } catch (err) {
+ // 拿不到应答 = 可能已落地: 记成已投递(防重复), 但**不算确认** ——
+ // 没有真实 messageId, 既不能删载体也不能拿它当图片锚点。
+ if (!isDefiniteRejection(err)) {
+ this.deliveredChunks = chunkCount;
+ this.unconfirmedChunks.add(0);
+ }
+ throw err;
+ }
+ };
+
+ // Rich 是终稿的新消息,不是对过程载体的原位升级。它可保留表格、公式等
+ // 结构化排版;仅当没有需要旁路上传的受管图片时尝试,失败为「本条不支持」
+ // 才安全降级到 HTML/Markdown。
+ const richEligible =
+ imageUrls.length === 0 && this.extraImageAbsPaths.length === 0 && this.deps.sendFinal;
+ // Rich 一条消息就承载了完整正文, 没有后续分段。
+ const richMessageId = richEligible
+ ? await this.sendFinalTracked(finalText, staleMessageId !== '', chunks.length)
+ : null;
+ if (richMessageId) {
+ markFirstChunk(richMessageId, finalText, chunks.length);
+ } else {
+ // Hermes-style close: always mint a fresh final message. If a process
+ // carrier already exists, repost keeps its frozen reply target; if the
+ // turn was lazy and has no carrier, send consumes the normal target lease.
+ const post = staleMessageId ? (this.deps.repost ?? this.deps.send) : this.deps.send;
+ await sendFirstChunk(() => post(seed), seed, 1);
+ }
+ }
+ // 逐段推进计数: 中途抛错时前面几段的进度已经记下, 重试从这里接着走。
+ //
+ // 计数在 send **发起前**推进 —— 抛错的 send 通常无法区分「Telegram 没收到」
+ // 和「收到了但回执丢在路上」。默认按"可能已送达"记账: 最坏是这一段没出现
+ // (上游仍持有完整正文可再收口); 反过来默认未送达则会在重试时把用户已经看见
+ // 的一段再发一遍, 长答案里就是整篇重复。
+ //
+ // 例外是 Telegram **明确拒绝**(4xx, 429 除外): 报文完整往返、它拒绝了这一段,
+ // 聊天里不可能出现它。这时必须把计数退回去, 否则重试会跳过一段确定未送达的
+ // 正文, 随后照样 markFinalSent 并清掉过程载体 —— 答案就此缺段。
+ while (this.deliveredChunks < chunks.length) {
+ const index = this.deliveredChunks;
+ const chunk = chunks[index]!;
+ this.deliveredChunks += 1;
+ try {
+ await this.deps.send(chunk);
+ this.unconfirmedChunks.delete(index);
+ } catch (err) {
+ if (isDefiniteRejection(err)) {
+ this.deliveredChunks -= 1;
+ } else {
+ // 计入未确认: 尾段的成功回执不能证明它送达, 更不能证明首段送达。
+ this.unconfirmedChunks.add(index);
+ }
+ throw err;
+ }
}
- this.flushed = text;
+ // extraImageAbsPaths(tool_result 账本图)与正文图都交 uploadImages 收口;
+ // 去重职责在 index.ts 的 uploadImages 实现里(absPath / url 双口径)。
+ //
+ // 断点续传: 多批图片里前几批已发、后一批失败时, onProgress 已经记下累计
+ // 张数, 重试从 deliveredImages 继续, 不会重复发已经出现的附件。
+ const allImageRefs = [
+ ...imageUrls,
+ ...this.extraImageAbsPaths.map((absPath) => `abs:${absPath}`),
+ ];
+ // 首段未确认就没有可用的锚点: `messageIdValue` 这时要么还是**过程载体
+ // ID**(图会挂到随后可能被删的"工作中"消息上), 要么是空串
+ // (`decodeMessageId` 直接抛错, 附件永远收不了口)。宁可推迟上传 ——
+ // 正文本身也还没确认, 这一轮整体就没收口(2026-08-11 review)。
+ if (!this.firstChunkConfirmed && allImageRefs.length > 0) {
+ throw new Error(
+ 'telegram final image upload deferred: first chunk delivery unconfirmed (no final message id)',
+ );
+ }
+ if (this.deliveredImages < allImageRefs.length) {
+ await this.deps.uploadImages(this.messageIdValue, allImageRefs, {
+ startIndex: this.deliveredImages,
+ onProgress: (deliveredCount) => {
+ // 单调推进: 实现方回报的是累计张数, 不接受回退。
+ if (deliveredCount > this.deliveredImages) this.deliveredImages = deliveredCount;
+ },
+ });
+ this.deliveredImages = allImageRefs.length;
+ }
+ // 正文**完整确认**才收口成 final-sent。
+ //
+ // 有未确认分段时不能标已送达: `finalize()` 开头会让 final-sent / complete
+ // 状态直接 return, 于是这一轮再也无法对账或补投(2026-08-11 review)。
+ //
+ // 而且**必须抛出**, 不能只改内部 phase 就静默 resolve —— handle 不暴露
+ // phase, 生产包装器只看 resolve/reject, 静默返回等于告诉上游"收口成功"
+ // (2026-08-12 review)。抛 TelegramFinalUnconfirmedError 让上游能区分它与
+ // 普通发送失败: 内容可能已落地, 不该重投, 但这一轮也没收全。
+ //
+ // 抛出后 catch 分支会 markFinalFailed —— 生命周期停在可恢复态, 同一
+ // delivery key 的后续 finalize 仍能进来对账; 过程载体也一并保留。
+ if (!this.firstChunkConfirmed || this.unconfirmedChunks.size > 0) {
+ throw new TelegramFinalUnconfirmedError(
+ this.firstChunkConfirmed,
+ [...this.unconfirmedChunks].sort((a, b) => a - b),
+ );
+ }
+ this.lifecycle.markFinalSent(intent);
+ } catch (err) {
+ // The process carrier remains visible and no cleanup runs. A later
+ // explicit finalize may retry the same delivery key, resuming from
+ // deliveredChunks so already-visible content is never duplicated.
+ this.lifecycle.markFinalFailed(intent);
+ throw err;
}
+
+ if (!staleMessageId) return;
+ // 走到这里意味着正文**完整确认**(未确认已在上面抛出), 才允许动过程载体。
+ //
+ // 判据是两条: 首段确认(拿到过真实 messageId —— 它承载答案主体, 尾段回执证明
+ // 不了它被接受)、且没有未确认的后续分段。deliveredChunks 在未知回执下也会
+ // 推进(防重复), 所以它到达 chunks.length 并不等于内容真的出现在聊天里。
+ // 留着载体最坏是多一条"工作中"; 删错了则既没答案也没现场(2026-08-11 review)。
+ // Answer is already accepted; cleanup is best-effort and cannot make the
+ // final delivery fail. If delete fails, both messages may remain.
+ if (!this.lifecycle.beginCleanup()) return;
try {
await this.deps.deleteMessage?.(staleMessageId);
} catch {
- /* 删不掉(权限/已删)就留着, 不影响已送达的答案 */
+ /* keep the old process message; the fresh answer is authoritative */
+ } finally {
+ this.lifecycle.finishCleanup();
}
}
@@ -265,7 +506,7 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
/* swallow */
}
}
- if (this.done || this.buffer === this.flushed) return;
+ if (this.done || !this.lifecycle.progressOpen || this.buffer === this.flushed) return;
if (this.buffer.length > INTERMEDIATE_EDIT_LIMIT) return;
// 哨兵(或其前缀, 流式可能分片送达)不落地 — 惰性占位下连消息都不建。
const trimmed = this.buffer.trim();
@@ -274,6 +515,7 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {
const next = this.buffer;
this.inFlight = (async () => {
try {
+ if (!this.lifecycle.progressOpen || this.done) return;
if (!this.messageIdValue) {
this.messageIdValue = await this.deps.send(next);
} else {