Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): Telegram 终稿撞编辑 flood 不再静默丢失 (#1636)
Chris Zhang34c435e76544
diff --git a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts b/packages/lizi-im/src/telegram/__tests__/streamingText.test.tsnew file mode 100644index 0000000000..f2307ec57b--- /dev/null+++ b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts@@ -0,0 +1,215 @@+import { describe, expect, it, vi } from 'vitest';++import { startTelegramStreaming, type TelegramStreamingDeps } from '../streamingText.js';++/**+ * 终稿原位编辑撞 Telegram 编辑 flood 时的兜底(2026-08-04 线上实测: 一个 11 分钟+ * 群轮次的 finalize 吃到 `429 retry after 26`, 整条答案永久丢失, 聊天里只剩一条+ * 停在"⚙️ 工作中"的僵尸消息)。这些用例钉住三件事: 答案必达、顺序是先发新后删旧、+ * 补送后的图片锚点跟到新消息。+ */++interface Harness {+ deps: TelegramStreamingDeps;+ /** 按发生顺序记录的出站动作, 用于断言"先发新、后删旧"。 */+ calls: string[];+ sent: string[];+ reposted: string[];+ deleted: string[];+ uploadAnchors: string[];+}++function makeHarness(+ overrides: {+ editImpl?: (messageId: string, markdown: string) => Promise<void>;+ sendImpl?: (markdown: string) => Promise<string>;+ deleteImpl?: (messageId: string) => Promise<void>;+ chunk?: (text: string) => string[];+ extractImageUrls?: (markdown: string) => string[];+ /** 不提供 repost 时用于验证回落 send 的行为。 */+ withoutRepost?: boolean;+ } = {},+): Harness {+ const calls: string[] = [];+ const sent: string[] = [];+ const reposted: string[] = [];+ const deleted: string[] = [];+ const uploadAnchors: string[] = [];+ let nextId = 1;+ const deps: TelegramStreamingDeps = {+ send: async (markdown) => {+ calls.push(`send:${markdown}`);+ sent.push(markdown);+ if (overrides.sendImpl) return overrides.sendImpl(markdown);+ return `msg-${nextId++}`;+ },+ edit: async (messageId, markdown) => {+ calls.push(`edit:${messageId}`);+ if (overrides.editImpl) return overrides.editImpl(messageId, markdown);+ },+ uploadImages: async (messageId, imageUrls) => {+ if (imageUrls.length > 0) {+ calls.push(`upload:${messageId}`);+ uploadAnchors.push(messageId);+ }+ },+ chunk: overrides.chunk ?? ((text) => [text]),+ extractImageUrls: overrides.extractImageUrls ?? (() => []),+ deleteMessage: async (messageId) => {+ calls.push(`delete:${messageId}`);+ deleted.push(messageId);+ if (overrides.deleteImpl) return overrides.deleteImpl(messageId);+ },+ };+ if (overrides.withoutRepost !== true) {+ deps.repost = async (markdown) => {+ calls.push(`repost:${markdown}`);+ reposted.push(markdown);+ if (overrides.sendImpl) return overrides.sendImpl(markdown);+ return `msg-${nextId++}`;+ };+ }+ return { deps, calls, sent, reposted, deleted, uploadAnchors };+}++describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {+ 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([]);+ });++ it('原位编辑失败 → 答案改由新消息承载, 且顺序是先发新后删旧', async () => {+ const editErr = new Error('telegram editMessageText failed: 429 Too Many Requests: retry after 26');+ const h = makeHarness({+ editImpl: async () => {+ throw editErr;+ },+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 10m44s');++ await expect(handle.finalize('完整的最终答案')).resolves.toBeUndefined();++ // 答案确实发出去了(不是只剩一条僵尸过程消息), 且走的是保留回挂目标的 repost。+ expect(h.reposted).toEqual(['完整的最终答案']);+ expect(h.sent).not.toContain('完整的最终答案');+ // 顺序不可对调: 新消息落地在删除之前。+ expect(h.calls).toEqual([+ 'send:⚙️ 工作中 · 10m44s',+ 'edit:msg-1',+ 'repost:完整的最终答案',+ 'delete:msg-1',+ ]);+ expect(h.deleted).toEqual(['msg-1']);+ });++ it('未提供 repost 时回落 send(兼容不关心回挂语义的调用方)', async () => {+ const h = makeHarness({+ editImpl: async () => {+ throw new Error('429');+ },+ withoutRepost: true,+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 6s');++ await expect(handle.finalize('答案')).resolves.toBeUndefined();+ expect(h.sent).toContain('答案');+ expect(h.deleted).toEqual(['msg-1']);+ });++ it('新发也失败时抛回原始编辑错误, 并且不删旧消息', async () => {+ const editErr = new Error('editMessageText 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');+ return 'msg-1';+ },+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 9m');++ // 掩盖真实原因会让线上排障失去线索 —— 必须抛原始编辑错误。+ await expect(handle.finalize('答案')).rejects.toBe(editErr);+ 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");+ },+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 2m');++ await expect(handle.finalize('答案')).resolves.toBeUndefined();+ expect(h.reposted).toContain('答案');+ });++ it('补送后受管图片锚定到新消息, 不挂在已删的过程消息上', async () => {+ const h = makeHarness({+ editImpl: async () => {+ throw new Error('429');+ },+ extractImageUrls: () => ['cindy-media://blobs/a.png'],+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 1m');++ await handle.finalize('带图的答案');++ // 锚点是补送出来的那条(msg-2), 不是被删掉的 msg-1。+ expect(h.uploadAnchors).toEqual(['msg-2']);+ });++ it('补送后剩余分段照常发出', async () => {+ const h = makeHarness({+ editImpl: async () => {+ throw new Error('429');+ },+ chunk: (text) => text.split('|'),+ });+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 5m');++ await handle.finalize('第一段|第二段|第三段');++ // 首段走 repost(承载答案、保留回挂), 其余分段照常 send 追加。+ expect(h.reposted).toEqual(['第一段']);+ expect(h.sent).toEqual(['⚙️ 工作中 · 5m', '第二段', '第三段']);+ });++ it('rich 原位定稿成功时既不走 HTML 编辑也不补送', async () => {+ const h = makeHarness({+ editImpl: async () => {+ throw new Error('不该走到这里');+ },+ });+ const editFinal = vi.fn(async () => true);+ const handle = await startTelegramStreaming({ ...h.deps, editFinal }, '⚙️ 工作中 · 4s');++ await handle.finalize('rich 定稿的答案');++ expect(editFinal).toHaveBeenCalledOnce();+ expect(h.sent).toEqual(['⚙️ 工作中 · 4s']);+ expect(h.deleted).toEqual([]);+ });++ it('NO_REPLY 沉默仍然是撤掉占位, 不会误走补送', async () => {+ const h = makeHarness();+ const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 8s');++ await handle.finalize('NO_REPLY');++ expect(h.deleted).toEqual(['msg-1']);+ expect(h.sent).toEqual(['⚙️ 工作中 · 8s']);+ });+});diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex 85c9df708a..93fecddf03 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -1293,6 +1293,82 @@ describe('TelegramIM', () => {expect(richEditCount()).toBe(1);});+ it('429 退避等满 Telegram 给的 retry_after(不再封顶 10s), 终稿不丢', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let htmlEditAttempts = 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();+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 10m44s');+ const sendCount = (): number => api.calls.filter((c) => c.method === 'sendMessage').length;+ const sendsBeforeFinalize = sendCount();++ vi.useFakeTimers();+ try {+ const finalized = handle.finalize('完整的最终答案');+ // 旧实现把退避封在 10s: 此刻已经重试, 而 flood 窗口还剩 16s → 必然二次+ // 失败, 整条终稿就是这样丢的(2026-08-04 线上实测)。+ await vi.advanceTimersByTimeAsync(10_000);+ expect(htmlEditAttempts).toBe(1);+ await vi.advanceTimersByTimeAsync(16_000);+ await finalized;+ expect(htmlEditAttempts).toBe(2);+ } finally {+ vi.useRealTimers();+ }++ // 原位编辑最终成功 → 不需要动用补送, 也不该留下多余消息。+ expect(sendCount()).toBe(sendsBeforeFinalize);+ const lastEdit = api.calls.filter((c) => c.method === 'editMessageText').at(-1);+ expect(String(lastEdit?.params.text ?? '')).toContain('完整的最终答案');+ });++ it('原位编辑始终失败时, 终稿改由新消息承载并撤掉过程消息', 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);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ 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();+ }++ const answer = api.calls.find(+ (c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('必须送到的答案'),+ );+ expect(answer).toBeDefined();+ // 先发新、后删旧: 补送落地后才撤掉那条停在"工作中"的过程消息。+ const deleted = api.calls.filter((c) => c.method === 'deleteMessage');+ expect(deleted).toHaveLength(1);+ expect(api.calls.indexOf(answer!)).toBeLessThan(api.calls.indexOf(deleted[0]!));+ expect(String(deleted[0]!.params.message_id ?? '')).toBe(+ progressMessageId.split('|')[1] ?? progressMessageId,+ );+ });+it('群 lane 流式: send+edit 经典路径 + 定稿 rich 原地升级(本次统一的基准)', async () => {await connect();const handle = await im.startStreamingText('g/-100200/r7');@@ -1512,6 +1588,494 @@ describe('TelegramIM', () => {.toBe(401);});+ it("群默认 'first' 档: 终稿编辑失败后, 补送仍引用原触发消息", async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'first', replyQuoteDm: 'off' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([groupMessage({ text: '干活', fromId: 222, messageId: 80, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const lane = events[0].senderId;++ 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);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ // 过程消息先落地 —— 'first' 档下它已经把回挂目标 80 消耗掉了。+ const handle = await im.startStreamingText(lane, '⚙️ 工作中 · 11m');+ const progressSend = api.calls.filter(+ (c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200',+ );+ 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();+ }++ // 补送的答案不能脱离提问脉络 —— 重新 lease 会拿到空目标, 必须沿用本轮的 80。+ const answer = api.calls.find(+ (c) =>+ c.method === 'sendMessage' && String(c.params.text ?? '').includes('补送出来的答案'),+ );+ expect(answer).toBeDefined();+ expect((answer!.params.reply_parameters as { message_id: number } | undefined)?.message_id)+ .toBe(80);+ });++ it("回挂档位 off 时, 补送不带 reply_parameters", async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'off', replyQuoteDm: 'off' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([groupMessage({ text: '干活', fromId: 222, messageId: 81, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const lane = events[0].senderId;++ 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);+ }+ 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();+ }++ const answer = api.calls.find(+ (c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('off 档的答案'),+ );+ expect(answer).toBeDefined();+ expect(answer!.params.reply_parameters).toBeUndefined();+ });++ it("群 'all' 档: 补送同样挂回, 档位语义不被补送破坏", async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'all', replyQuoteDm: 'off' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([groupMessage({ text: '干活', fromId: 222, messageId: 82, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const lane = events[0].senderId;++ 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);+ }+ 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();+ }++ const groupSends = api.calls.filter(+ (c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200',+ );+ expect(groupSends.length).toBeGreaterThanOrEqual(2);+ for (const call of groupSends) {+ expect((call.params.reply_parameters as { message_id: number } | undefined)?.message_id)+ .toBe(82);+ }+ });++ it('429 退避期间被 dispose: 不再发第二次请求, 也不留后台重试', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let sendAttempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ sendAttempts += 1;+ throw new TelegramApiError('sendMessage', 429, 'Too Many Requests: retry after 26', 26);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ const sending = im.sendText(OWNER_ID, '停止边界').catch((err: unknown) => err);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sendAttempts).toBe(1);+ // 退避还没走完就销毁 —— 等待必须被取消, 且醒来后不得用旧 api 补发。+ await im.dispose();+ await vi.advanceTimersByTimeAsync(120_000);+ const outcome = await sending;+ expect(outcome).toBeInstanceOf(TelegramApiError);+ expect(sendAttempts).toBe(1);+ } finally {+ vi.useRealTimers();+ }+ // 后台没有遗留任务: 再放一段时间也不会冒出新的请求。+ await vi.waitFor(() => expect(sendAttempts).toBe(1));+ });++ it('换 owner 后原位编辑与清理都不再触碰旧回合(edit / editFinal / deleteMessage)', async () => {+ await connect();+ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 5m');+ const callsBefore = api.calls.length;++ // 只换主人: 不 stopPolling, api 对象不变 —— 唯一能识别授权易主的是世代/主人。+ await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '777888' });++ // editFinal 是 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([]);+ });++ it('换 owner 后的 NO_REPLY 沉默不再删旧回合的占位消息', async () => {+ await connect();+ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 30s');+ const callsBefore = api.calls.length;+ await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '777889' });++ // NO_REPLY 的删除被 finalize 内部 catch 吞掉, 所以不抛 —— 但一定不能真删。+ await handle.finalize('NO_REPLY');+ expect(api.calls.slice(callsBefore).filter((c) => c.method === 'deleteMessage')).toEqual([]);+ });++ it('多组图片中途换 owner: 第一组之后不再向旧 chat 出站', async () => {+ await connect();+ // 11 张 → 分两组(每组 ≤10), 第一组落地后换主人。+ const paths = Array.from({ length: 11 }, (_, i) => {+ const p = path.join(tmpDir, `g${i}.png`);+ fs.writeFileSync(p, 'fake-png');+ return p;+ });+ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 6m');+ for (const p of paths) handle.addExtraImageAbsPath?.(p);++ const originalForm = api.callForm.bind(api);+ let groups = 0;+ api.callForm = (async (method: string, form: FormData, signal?: AbortSignal) => {+ const result = await originalForm(method, form, signal);+ if (method === 'sendMediaGroup') {+ groups += 1;+ if (groups === 1) {+ await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '777890' });+ }+ }+ return result;+ }) as FakeApi['callForm'];++ // uploadImages 的核验在第二组之前失败 → finalize 抛出。+ await expect(handle.finalize('十一张图的回答')).rejects.toThrow(/round abandoned/);+ // 只发出了第一组, 第二组被挡住。+ expect(groups).toBe(1);+ expect(api.calls.filter((c) => c.method === 'sendMediaGroup')).toHaveLength(1);+ });++ it('合法 retry_after 超过 60s 时不提前重试(不再有固定上限)', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let attempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ attempts += 1;+ if (attempts === 1) {+ throw new TelegramApiError('sendMessage', 429, 'Too Many Requests: retry after 180', 180);+ }+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ const sending = im.sendText(OWNER_ID, 'bot-wide flood');+ // 旧实现封在 60s: 此刻已经重试, 而 flood 窗口还剩两分钟 → 必然再失败。+ await vi.advanceTimersByTimeAsync(60_000);+ expect(attempts).toBe(1);+ await vi.advanceTimersByTimeAsync(120_000);+ await sending;+ expect(attempts).toBe(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('retry_after 缺失或非法时走兜底退避(3s)', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let attempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ attempts += 1;+ // 缺失 retry_after+ if (attempts === 1) throw new TelegramApiError('sendMessage', 429, 'Too Many Requests');+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ const sending = im.sendText(OWNER_ID, '无 retry_after');+ await vi.advanceTimersByTimeAsync(3_000);+ await sending;+ expect(attempts).toBe(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('补送成功后才换 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);+ }+ const result = await originalCall(method, params, signal);+ // 首段补送刚落地就换主人 —— 此刻 assertRoundStillLive 已经放行过一次,+ // 剩余分段与图片若不各自核验就会继续发给已失权的旧 userId。+ if (+ method === 'sendMessage' &&+ String(params?.text ?? '').includes('第一段') &&+ !ownerSwitched+ ) {+ ownerSwitched = true;+ await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '444555' });+ }+ return result;+ }) 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();+ }++ expect(ownerSwitched).toBe(true);+ // 首段已经发出(那时回合还有效), 但换主人之后的剩余分段一律不许再出站。+ const tailSends = api.calls.filter(+ (c) => c.method === 'sendMessage' && String(c.params.text ?? '').includes('第二段尾巴'),+ );+ expect(tailSends).toEqual([]);+ // 也不许对新主人产生任何出站。+ expect(+ api.calls.filter((c) => c.method === 'sendMessage' && c.params.chat_id === '444555'),+ ).toEqual([]);+ });++ it('补送成功后换 owner: 受管图片不再上传(sendPhoto / sendMediaGroup 都不发)', async () => {+ await connect();+ const imgPath = path.join(tmpDir, 'shot.png');+ fs.writeFileSync(imgPath, 'fake-png');+ 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);+ }+ const result = await originalCall(method, params, signal);+ // 补送刚落地就换主人 —— 图片上传排在它后面, 若不各自核验就会照传。+ if (method === 'sendMessage' && String(params?.text ?? '').includes('带图答案')) {+ ownerSwitched = true;+ await ctx.handlers.get('telegramBot:set-config')!({ ownerUserId: '444556' });+ }+ return result;+ }) as FakeApi['call'];++ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 4m');+ // 走 abs: 旁路(与既有相册用例同一搭法), 不依赖 resolveImageUrl 注入。+ handle.addExtraImageAbsPath?.(imgPath);+ vi.useFakeTimers();+ try {+ const finalized = handle.finalize('带图答案').catch((err: unknown) => err);+ await vi.advanceTimersByTimeAsync(120_000);+ await finalized;+ } finally {+ vi.useRealTimers();+ }++ expect(ownerSwitched).toBe(true);+ expect(+ api.calls.filter((c) => c.method === 'sendPhoto' || c.method === 'sendMediaGroup'),+ ).toEqual([]);+ });++ it('退避期间只换 owner(api 对象不变): 旧回合的答案不发给已失权的旧 userId', 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);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ const handle = await im.startStreamingText(OWNER_ID, '⚙️ 工作中 · 9m');+ const progressMessageId = handle.messageId;+ const answer = '旧 owner 那一轮的完整答案';++ vi.useFakeTimers();+ try {+ const finalized = handle.finalize(answer).catch((err: unknown) => err);+ await vi.advanceTimersByTimeAsync(1_000);+ // 只换 ownerUserId、不带 token: 这条分支不 stopPolling, this.api 完全不变,+ // 只有 configVersion / ownerUserId 变了 —— 补送若按当前世代重新取 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);+ } finally {+ vi.useRealTimers();+ }++ // 过程消息保留(没有补送成功就不该删), 也没有对新主人产生任何出站。+ expect(api.calls.filter((c) => c.method === 'deleteMessage')).toEqual([]);+ expect(progressMessageId).not.toBe('');+ expect(+ api.calls.filter((c) => c.method === 'sendMessage' && c.params.chat_id === '222333'),+ ).toEqual([]);+ });++ it('dispose() 后重新 init(): 退避重试在新世代恢复可用', async () => {+ await connect();+ // 退出登录 → 再登录(同一实例复用; init 里就有 this.disposing = false)。+ await im.dispose();+ await im.init();+ expect(im.getStatus()).toEqual({ kind: 'connected', appId: String(BOT.id) });++ const originalCall = api.call.bind(api);+ let sendAttempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ sendAttempts += 1;+ if (sendAttempts === 1) {+ throw new TelegramApiError('sendMessage', 429, 'Too Many Requests: retry after 26', 26);+ }+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ const sending = im.sendText(OWNER_ID, '新世代的出站');+ await vi.advanceTimersByTimeAsync(26_000);+ await sending;+ } finally {+ vi.useRealTimers();+ }+ // 一次性的生命周期控制器若不重建, 新世代每次退避都当场判"已停止"→ 永久+ // 关掉 429 重试, 这里就只会有 1 次尝试。+ expect(sendAttempts).toBe(2);+ });++ it('dispose 收尾窗口里的出站: 已取消信号不再干等满整个退避', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let sendAttempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ sendAttempts += 1;+ throw new TelegramApiError('sendMessage', 429, 'Too Many Requests: retry after 26', 26);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ // dispose 的同步段已经 abort 了生命周期取消源, 但它随后要 await stopPolling+ // (那里等 pollLoop 才把 this.api 置空) —— 这个窗口里的出站拿到的是一个+ // **进来就已 aborted** 的信号。+ const disposing = im.dispose();+ const sending = im.sendText(OWNER_ID, '收尾窗口的出站').catch((err: unknown) => err);+ await disposing;+ // 一个定时器都不推进: 已取消的等待必须当场结束, 否则这里会挂到用例超时+ // (旧实现 addEventListener 对已发生的 abort 不触发, 会干等满 26s)。+ expect(await sending).toBeInstanceOf(TelegramApiError);+ expect(sendAttempts).toBe(1);+ } finally {+ vi.useRealTimers();+ }+ });++ it('429 退避期间下线(stopPolling): 不再发第二次请求', async () => {+ await connect();+ const originalCall = api.call.bind(api);+ let sendAttempts = 0;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage') {+ sendAttempts += 1;+ throw new TelegramApiError('sendMessage', 429, 'Too Many Requests: retry after 26', 26);+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ vi.useFakeTimers();+ try {+ const sending = im.sendText(OWNER_ID, '下线边界').catch((err: unknown) => err);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(sendAttempts).toBe(1);+ // 主动下线: stopPolling 会 abort 当前世代并把 this.api 置空 —— 退避必须+ // 就此放弃, 不能用那个已经作废的客户端补发。+ await ctx.handlers.get('telegramBot:set-online')!({ online: false });+ await vi.advanceTimersByTimeAsync(120_000);+ expect(await sending).toBeInstanceOf(TelegramApiError);+ expect(sendAttempts).toBe(1);+ } finally {+ vi.useRealTimers();+ }+ });+it("群 'all' 档: 目标保留整轮, 每条出站都挂回", async () => {await im.dispose();im = new TelegramIM(ctx.host, {diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.tsindex 9d0c27e1b6..204fb0c2d8 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -83,6 +83,21 @@ const POLL_RETRY_BASE_MS = 1_000;const POLL_RETRY_MAX_MS = 30_000;/** 409 = 另一个进程在对同一 token 轮询 — 低频探测等它退出。 */const POLL_CONFLICT_RETRY_MS = 30_000;+/**+ * 429 没给 `retry_after`(或给了非法值)时的兜底退避。**只用于兜底** —— 合法值+ * 一律按服务端给的全长等, 不设上限: 任何上限都等于在 flood 窗口结束前提前重试,+ * 那次重试必然再 429, 终稿于是又丢一次(bot-wide flood 的 retry_after 可以远超+ * 一分钟)。不设上限是安全的, 因为这个等待绑定了连接生命周期取消源(见+ * outboundAbortSignal), dispose / 下线 / 重连会立刻把它收口。+ */+const RETRY_AFTER_FALLBACK_MS = 3_000;++/** 429 退避时长: 合法 `retry_after` 原样采用, 缺失或非法(NaN / ≤0 / 非有限)走兜底。 */+function retryAfterWaitMs(retryAfterSec: number | undefined): number {+ if (typeof retryAfterSec !== 'number') return RETRY_AFTER_FALLBACK_MS;+ if (!Number.isFinite(retryAfterSec) || retryAfterSec <= 0) return RETRY_AFTER_FALLBACK_MS;+ return retryAfterSec * 1000;+}const MAX_OUTBOUND_FILE_BYTES = 50 * 1024 * 1024;const OWNER_NOTICE_TIMEOUT_MS = 4_500;/** typing 状态原生只持续 ~5s — 按 4.5s 续命直到首条真实消息发出。 */@@ -117,6 +132,35 @@ type GroupWindowHandler = (entry: TelegramGroupWindowEntry) => void;*/type ReplyTargetLease = { userId: string; messageId: string } | null;+/**+ * 流式回合的身份快照(建 handle 时拍下)。终稿补送必须绑定它 —— 补送是一次**全新**+ * 的 callSend, 会按"当前"世代重新取 api, 所以旧回合的 429 退避即使正确放弃了,+ * 补送仍可能把旧回合的完整答案发出去。+ */+interface StreamRoundIdentity {+ /** 配置世代(换 token / 换 owner / disconnect / dispose 都会 +1)。 */+ generation: number;+ /** 建 handle 时的 api 客户端身份 —— 重连换了客户端就不是同一回合。 */+ api: TelegramApiClient | null;+ /**+ * 建 handle 时的主人。只换 owner 不换 token 的那条分支不会 stopPolling,+ * **api 对象完全不变**, 只有这个字段(与 generation)能识别出授权已经易主。+ */+ ownerUserId: string;+ /** 本轮回挂目标(此刻还没被任何出站消耗)。 */+ replyTargetId: string | null;+}++type TelegramReplyParams =+ | { reply_parameters: { message_id: number; allow_sending_without_reply: true } }+ | Record<string, never>;++/** 回挂目标 id → 出站请求参数; null/空 = 不挂回。 */+function replyParamsFor(targetId: string | null | undefined): TelegramReplyParams {+ if (!targetId) return {};+ return { reply_parameters: { message_id: Number(targetId), allow_sending_without_reply: true } };+}+/*** 队列里是否存在比 current 更新的触发消息 —— Telegram 同一 chat 内 message_id* 单调递增, 因此更大的 id 就意味着槽位里那个已经过时。@@ -234,6 +278,16 @@ export class TelegramIM extends BaseIM implements ChannelIM {private ownerUserId = '';private configVersion = 0;private pollAbort: AbortController | null = null;+ /**+ * 实例级取消源(dispose 时 abort)。pollAbort 只覆盖"正在轮询"的时段, 而出站也+ * 会发生在连接建立中与下线收尾这类没有轮询的窗口 —— 那时退避等待要靠这个收口。+ *+ * **不可 readonly**: 同一实例支持 dispose → init 复用(退出登录再登录, init 里+ * 就有 `this.disposing = false`)。一次性的控制器 abort 之后永远是 aborted 态,+ * 新世代的每次退避都会当场判定"已停止"而跳过重试 —— 等于把 429 重试永久关掉。+ * 由 resetLifetimeAbort() 在新 init 世代重建。+ */+ private lifetimeAbort = new AbortController();private pollLoop: Promise<void> | null = null;private disposing = false;/** sendRichMessage 方法不可用(404)后的永久 latch(本实例生命周期内)。 */@@ -306,6 +360,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {async init(): Promise<void> {this.disposing = false;+ this.resetLifetimeAbort();const tokenResult = this.secretReadResult(TOKEN_SECRET_KEY);if (tokenResult.kind === 'error') {this.setStatus({ kind: 'error', reason: SECRET_WRITE_FAILED_REASON, code: 'secret-unavailable' });@@ -422,6 +477,8 @@ export class TelegramIM extends BaseIM implements ChannelIM {// 生命周期静默: dispose / 重连不向 owner 发任何播报(桌面端频繁重启会刷屏)。async dispose(): Promise<void> {this.disposing = true;+ // 在途的 429 退避等待就此收口 —— 否则一个最长一分钟的定时器会活过 dispose。+ this.lifetimeAbort.abort();this.configVersion += 1;this.clearAllTypingLoops();// 回挂配对是连接期内存态 — 换代/断开后旧目标一律作废, 不跨代错配。@@ -763,22 +820,64 @@ export class TelegramIM extends BaseIM implements ChannelIM {userId: string,initial?: string,): Promise<StreamingTextHandle> {+ // 建 handle 时拍下本轮身份。回挂目标此刻还没被任何出站消耗+ // (claimTurnReplyTarget 刚领完) —— 'first' 档下过程消息一发就把槽位耗掉了,+ // 补送若重新 lease 会拿到空目标, 那条答案在群里就脱离了提问脉络。+ const round: StreamRoundIdentity = {+ generation: this.configVersion,+ api: this.api,+ ownerUserId: this.ownerUserId,+ replyTargetId: this.turnReplyTargets.get(userId) ?? null,+ };return startTelegramStreaming({+ // 本轮**每一个**触达 Telegram 的出站入口都先核验回合身份 —— 一个不漏。+ // 逐个核验不可省成"补送时查一次": 换 owner 可能发生在任意一次 await 之后,+ // 而 owner-only 变更**不换 api 客户端**, 剩下的出站照样能成功。+ // 覆盖面: send / repost(新消息)、edit / editFinal(原位编辑——终稿的主投递+ // 路径, 换主人后编辑成功就等于把答案写进已失权主人的聊天)、deleteMessage+ // (失权后连清理都不该再碰对方的聊天)、uploadImages(内部逐次再核验)。+ // 正常轮次里这些核验恒为空操作。send: async (markdown) => {+ this.assertRoundStillLive(round);const { messageId } = await this.sendRenderedChunk(userId, markdown);return messageId;},+ repost: async (markdown) => {+ // 核验必须在发之前: 补送是全新的 callSend, 按当前世代重新取 api —— 换+ // owner 那条分支不 stopPolling、api 对象不变, 于是旧回合的答案会照发给+ // **已失去授权的旧 userId**。核验失败就抛, 由 finalize 抛回原始编辑错误。+ this.assertRoundStillLive(round);+ const { messageId } = await this.sendRenderedChunk(+ userId,+ markdown,+ round.replyTargetId,+ );+ return messageId;+ },edit: async (messageId, markdown) => {+ this.assertRoundStillLive(round);const { chatId, messageId: nativeId } = decodeMessageId(messageId);const { html } = markdownToTelegramHtml(markdown);await this.editHtml(chatId, nativeId, html, undefined);},- uploadImages: (messageId, imageUrls) => this.uploadImages(messageId, imageUrls),+ uploadImages: async (messageId, imageUrls) => {+ // 图片是多次真实出站(分组 sendMediaGroup、整组失败回落逐张 sendPhoto),+ // 每次之间都有 await —— 所以核验要下沉到每次调用前, 只在批次开头查一次+ // 挡不住"第一组传完才换主人"这个窗口。+ this.assertRoundStillLive(round);+ await this.uploadImages(messageId, imageUrls, () =>+ this.assertRoundStillLive(round),+ );+ },chunk: chunkTelegramSource,extractImageUrls: (markdown) => markdownToTelegramHtml(markdown).imageUrls,- editFinal: (messageId, markdown) => this.richEditFinal(messageId, markdown),+ editFinal: (messageId, markdown) => {+ this.assertRoundStillLive(round);+ return this.richEditFinal(messageId, markdown);+ },deleteMessage: async (messageId) => {+ this.assertRoundStillLive(round);const { chatId, messageId: nativeId } = decodeMessageId(messageId);await this.requireApi().call('deleteMessage', {chat_id: chatId,@@ -1481,19 +1580,12 @@ export class TelegramIM extends BaseIM implements ChannelIM {* 做的, DM 改走经典路径后该语义必须留在共用发送入口上。*/private leaseReplyTarget(userId: string): {- params:- | { reply_parameters: { message_id: number; allow_sending_without_reply: true } }- | Record<string, never>;+ params: TelegramReplyParams;lease: ReplyTargetLease;} {const target = this.turnReplyTargets.get(userId);if (!target) return { params: {}, lease: null };- return {- params: {- reply_parameters: { message_id: Number(target), allow_sending_without_reply: true },- },- lease: { userId, messageId: target },- };+ return { params: replyParamsFor(target), lease: { userId, messageId: target } };}/**@@ -1519,9 +1611,26 @@ export class TelegramIM extends BaseIM implements ChannelIM {return this.api;}- /** 429 退避一次重试; 'message is not modified' 静默。 */+ /**+ * 429 退避一次重试; 'message is not modified' 静默。+ *+ * 退避时长必须尊重 Telegram 给的 `retry_after` **全值, 不设任何上限** —— 早先+ * 这里封在 10s, 于是 `retry_after` 更大的 flood 窗口里重试必然二次失败(实测+ * 2026-08-04: 一个 11 分钟群轮次的终稿撞上 `retry after 26`, 只等 10s 就重试,+ * 再次 429 后整条答案丢失)。任何固定上限都只是把同一个 bug 往后挪: bot-wide+ * flood 的 retry_after 可以是几分钟, 60s 上限照样会提前重试。只有缺失/非法值+ * 才走 RETRY_AFTER_FALLBACK_MS。+ *+ * 退避必须绑定连接生命周期: 等待期可能长达一分钟, 期间实例完全可能被+ * dispose / 下线 / 换配置重连。等待本身用当前世代的 AbortSignal 取消(否则+ * 定时器会活过 dispose), 醒来后再核验一次仍是同一条连接 —— 少了这道核验,+ * 停止后仍会用**旧 api 客户端**补发一次请求, 且这次重试已经脱离调用方+ * (外层如 owner 通知的 4.5s 超时早就返回了), 变成没人收口的后台任务。+ */private async callSend<T>(method: string, params: Record<string, unknown>): Promise<T> {const api = this.requireApi();+ const generation = this.configVersion;+ const abortSignal = this.outboundAbortSignal();// 首条真实消息即将出现 — typing 使命完成(客户端收到消息也会自动清)。if (typeof params.chat_id === 'string' || typeof params.chat_id === 'number') {this.stopTypingLoopsForChat(String(params.chat_id));@@ -1530,13 +1639,73 @@ export class TelegramIM extends BaseIM implements ChannelIM {return await api.call<T>(method, params);} catch (err) {if (err instanceof TelegramApiError && err.errorCode === 429) {- await sleep(Math.min((err.retryAfterSec ?? 3) * 1000, 10_000));+ // sleep 在 abort 时提前 resolve(不 reject), 所以醒来后必须显式核验。+ await sleep(retryAfterWaitMs(err.retryAfterSec), abortSignal);+ // 已停止 → 放弃重试并抛回原始 429, 不再发出任何请求。+ if (!this.isLiveConnection(api, generation, abortSignal)) throw err;return api.call<T>(method, params);}throw err;}}+ /**+ * 旧回合还有权发新消息吗。生命周期取消(dispose)、配置换代、重连换客户端、+ * 换主人 —— 任一命中即判这个回合已死, 不得再以它的名义出站。+ *+ * `ownerUserId` 与 `generation` 都查: 换 owner 的分支两者一起变, 但显式写出+ * 主人这条能让"授权易主 → 旧内容不许再发"的意图留在代码里, 也兜住将来某条+ * 路径改了 owner 却忘了升世代。+ */+ private assertRoundStillLive(round: StreamRoundIdentity): void {+ if (this.disposing) throw new Error('telegram round abandoned: instance disposing');+ if (this.configVersion !== round.generation) {+ throw new Error('telegram round abandoned: config generation superseded');+ }+ if (this.api !== round.api) throw new Error('telegram round abandoned: api client replaced');+ if (this.ownerUserId !== round.ownerUserId) {+ throw new Error('telegram round abandoned: owner changed');+ }+ if (this.lifetimeAbort.signal.aborted) {+ throw new Error('telegram round abandoned: lifetime cancelled');+ }+ }++ /**+ * 新 init 世代重建生命周期取消源。只在已 abort 时重建: 未 abort 说明没经历+ * dispose, 此时换掉控制器会让在途退避失去被后续 dispose 取消的能力。+ */+ private resetLifetimeAbort(): void {+ if (!this.lifetimeAbort.signal.aborted) return;+ this.lifetimeAbort = new AbortController();+ }++ /**+ * 出站退避的取消信号: 轮询期用当前世代的 pollAbort(下线/重连即 abort),+ * 并始终叠加实例级 lifetimeAbort(覆盖没有轮询的出站窗口)。+ * 每次调用都重读字段 —— 不得缓存, 否则拿不到新 init 世代的控制器。+ */+ private outboundAbortSignal(): AbortSignal {+ const poll = this.pollAbort?.signal;+ if (poll === undefined) return this.lifetimeAbort.signal;+ return AbortSignal.any([poll, this.lifetimeAbort.signal]);+ }++ /**+ * 退避醒来后的重试前置校验: 仍是同一条连接、同一配置世代、未被取消、未在销毁。+ * `this.api !== api` 覆盖「重连换了客户端」——世代号相同也不能用旧客户端发。+ */+ private isLiveConnection(+ api: TelegramApiClient,+ generation: number,+ abortSignal: AbortSignal,+ ): boolean {+ if (this.disposing) return false;+ if (this.configVersion !== generation) return false;+ if (this.api !== api) return false;+ return !abortSignal.aborted;+ }+/*** Rich 原地定稿(editMessageText + rich_message, Bot API 10.1): 把流式占位* 消息一步升级成 rich 渲染(表格/标题/代码块/LaTeX 原生, 32768 上限免分段)。@@ -1562,13 +1731,24 @@ export class TelegramIM extends BaseIM implements ChannelIM {}}- /** 单段 markdown → HTML 发送; parse 失败回退纯文本(agent 输出偶发怪标记)。 */+ /**+ * 单段 markdown → HTML 发送; parse 失败回退纯文本(agent 输出偶发怪标记)。+ *+ * `reuseReplyTargetId` 给终稿补送用: 那一轮的回挂目标已经被过程消息消耗掉了+ * ('first' 档用后即耗), 补送是**替换那条消息**而不是新增一条输出, 所以要沿用+ * 同一个目标、且不再走 lease/commit(既不重新领取也不二次消耗)。传 null =+ * 本轮没有目标(如 replyQuote 档位为 off), 按不挂回处理。+ */private async sendRenderedChunk(userId: string,markdownChunk: string,+ reuseReplyTargetId?: string | null,): Promise<{ messageId: string; imageUrls: string[] }> {const target = this.targetOf(userId);- const { params: replyParams, lease } = this.leaseReplyTarget(userId);+ const reusing = reuseReplyTargetId !== undefined;+ const { params: replyParams, lease } = reusing+ ? { params: replyParamsFor(reuseReplyTargetId), lease: null }+ : this.leaseReplyTarget(userId);const { html, imageUrls } = markdownToTelegramHtml(markdownChunk);let sent: TgMessage;try {@@ -1662,8 +1842,17 @@ export class TelegramIM extends BaseIM implements ChannelIM {* 2 张起自动合成原生相册(sendMediaGroup, 每组 ≤10 — Telegram 上限),* 客户端渲染为整齐的图集而不是刷屏的一串独立消息; 单张走 sendPhoto;* 相册整组失败回落逐张(部分文件缺失/超限时不拖累其余)。+ *+ * `assertLive` 是**每次真实出站前**的回合核验(流式回合传入; 独立出站不传)。+ * 这里的循环会跨多个 await 打出多次 callForm —— >10 张的分组、以及整组失败后+ * 的逐张回落都是。只在进入本方法时查一次挡不住"第一组传完才换主人"的窗口,+ * 剩下的图片会照发到已失权的旧聊天。*/- private async uploadImages(messageId: string, imageRefs: string[]): Promise<void> {+ private async uploadImages(+ messageId: string,+ imageRefs: string[],+ assertLive?: () => void,+ ): Promise<void> {const api = this.api;if (!api || imageRefs.length === 0) return;// 图片以 reply 挂回答案锚点消息: 论坛 topic 内自动跟随该 topic(裸发会@@ -1693,14 +1882,19 @@ export class TelegramIM extends BaseIM implements ChannelIM {absPaths.push(absPath);}if (absPaths.length === 1) {+ assertLive?.();await this.sendSinglePhoto(chatId, absPaths[0], anchorReply);return;}for (let i = 0; i < absPaths.length; i += 10) {const group = absPaths.slice(i, i + 10);+ assertLive?.();const albumSent = group.length > 1 && (await this.sendPhotoAlbum(chatId, group, anchorReply));if (!albumSent) {- for (const absPath of group) await this.sendSinglePhoto(chatId, absPath, anchorReply);+ for (const absPath of group) {+ assertLive?.();+ await this.sendSinglePhoto(chatId, absPath, anchorReply);+ }}}}@@ -2065,7 +2259,18 @@ function botIdFromToken(token: string): number {return Number.isSafeInteger(n) && n > 0 ? n : 0;}+/**+ * 可取消等待。abort 时提前 resolve(不 reject) —— 调用方靠自己的世代/状态核验+ * 决定醒来后做什么。+ *+ * **进来时就已 aborted 必须立刻返回**: `addEventListener('abort')` 对已经发生过+ * 的 abort 不会再触发, 于是定时器会走满全程。这条路径是可达的 —— dispose() 先+ * 同步 abort 生命周期取消源, 再 `await stopPolling()`(那里要等 pollLoop 才把+ * this.api 置空), 落在这个窗口里的出站拿到的就是一个已取消的信号; 少了这行,+ * 一次 429 会在 dispose 之后干等满一整个退避周期。+ */function sleep(ms: number, signal?: AbortSignal): Promise<void> {+ if (signal?.aborted === true) return Promise.resolve();return new Promise((resolve) => {const timer = setTimeout(done, ms);function done(): void {diff --git a/packages/lizi-im/src/telegram/streamingText.ts b/packages/lizi-im/src/telegram/streamingText.tsindex 0adc59745d..2c90c4c719 100644--- a/packages/lizi-im/src/telegram/streamingText.ts+++ b/packages/lizi-im/src/telegram/streamingText.ts@@ -15,7 +15,10 @@* (对齐 turnRunner 的 CARD_PATCH_THROTTLE_MS, 双层节流冗余但无害);* - "message is not modified" 错误静默吞掉(内容未变的重复编辑);* - 中间态超过单条上限后停止编辑(终稿由 finalize 分段补发), 与 Discord- * 的 INTERMEDIATE_EDIT_LIMIT 行为一致。+ * 的 INTERMEDIATE_EDIT_LIMIT 行为一致;+ * - **终稿的原位编辑必须有兜底**: 长轮次会对同一条消息累计上百次编辑, 撞+ * flood 时最后那次(携带答案)最容易失败。finalize 因此在编辑失败后把答案+ * 新发一条消息承载, 见 finalizeInPlaceOrRepost。*/import type { StreamingTextHandle } from '../types.js';@@ -37,6 +40,17 @@ function isNoReply(text: string): boolean {export interface TelegramStreamingDeps {/** 发送一条 markdown 渲染消息, 返回编码 messageId。 */send: (markdown: string) => Promise<string>;+ /**+ * 终稿补送专用的发送(见 finalizeInPlaceOrRepost)。与 send 有两点不同, 都由实现方+ * (index.ts)负责, 本模块只负责在编辑失败时调用它:+ * 1. 沿用**本轮原始的回挂目标** —— 补送替换的是那条已经消耗掉目标的过程消息,+ * 重新领取只会拿到空目标, 群里的答案就此脱离提问脉络;+ * 2. 先核验**本轮身份仍然有效**(配置世代/api 客户端/主人未变、未被取消)。补送是+ * 一次全新的出站, 会按"当前"状态取连接 —— 换主人之后旧回合的答案绝不能照发。+ * 身份失效时本函数应当抛错: finalize 会据此抛回原始编辑错误并放弃整个收口, 后续+ * 分段与图片一并不发。未提供时回落 send。+ */+ repost?: (markdown: string) => Promise<string>;/** 用 markdown 渲染结果覆盖既有消息。 */edit: (messageId: string, markdown: string) => Promise<void>;/** 终稿里的受管图片旁路上传(sendPhoto)。 */@@ -168,14 +182,17 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {const upgraded = await this.deps.editFinal(this.messageIdValue, finalText);if (upgraded) return;}- if (firstChunk.trim().length > 0 && this.flushed !== firstChunk) {- await this.deps.edit(this.messageIdValue, firstChunk);- } else if (- firstChunk.trim().length === 0 &&- (imageUrls.length > 0 || this.extraImageAbsPaths.length > 0) &&- this.flushed !== IMAGE_ONLY_PLACEHOLDER- ) {- await this.deps.edit(this.messageIdValue, IMAGE_ONLY_PLACEHOLDER);+ // 原位定稿的目标文本(有正文用首段; 纯图轮次用占位符); null = 消息已是终态。+ const inPlaceText =+ firstChunk.trim().length > 0 && this.flushed !== firstChunk+ ? firstChunk+ : firstChunk.trim().length === 0 &&+ (imageUrls.length > 0 || this.extraImageAbsPaths.length > 0) &&+ this.flushed !== IMAGE_ONLY_PLACEHOLDER+ ? IMAGE_ONLY_PLACEHOLDER+ : null;+ if (inPlaceText !== null) {+ await this.finalizeInPlaceOrRepost(inPlaceText);}for (const chunk of chunks.slice(1)) {await this.deps.send(chunk);@@ -188,6 +205,50 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {]);}+ /**+ * 原位定稿(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;+ }+ this.flushed = text;+ }+ try {+ await this.deps.deleteMessage?.(staleMessageId);+ } catch {+ /* 删不掉(权限/已删)就留着, 不影响已送达的答案 */+ }+ }+private scheduleFlush(): void {if (this.pending || this.done) return;this.pending = setTimeout(() => {