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 回挂引用改为出站成功后才消耗 (#1435)
Chris Zhangd2d93f3f46d0
diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex 729736ee72..d9f09acc04 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -1201,6 +1201,224 @@ describe('TelegramIM', () => {expect((withReply[0].params.reply_parameters as { message_id: number }).message_id).toBe(95);});+ it('回挂目标成功才消耗: 首条出站失败后重试仍带 reply_parameters', async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'first', replyQuoteDm: 'first' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();+ api.pushUpdates([privateMessage('问个事', 111, 96)]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ // connect 的 linked 确认也发往 owner 私聊 —— 取基线后只看本例新增的出站。+ const dmSendsBefore = api.calls.filter(+ (c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID,+ ).length;++ // 首条 sendMessage 非 400 失败(网络类), 之后恢复 —— 回挂目标不能被那次失败吃掉。+ const originalCall = api.call.bind(api);+ let failedOnce = false;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage' && params?.chat_id === OWNER_ID && !failedOnce) {+ failedOnce = true;+ api.calls.push({ method, params: params ?? {} });+ throw new Error('socket hang up');+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ await expect(im.sendText(OWNER_ID, '第一条(会失败)')).rejects.toThrow();+ await im.sendText(OWNER_ID, '重试的第一条');+ // 已成功一条 → 'first' 档后续不再挂回+ await im.sendText(OWNER_ID, '第二条');+ const dmSends = api.calls+ .filter((c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID)+ .slice(dmSendsBefore);+ expect(dmSends).toHaveLength(3);+ // 失败那条 + 重试那条都带引用(引用只在成功后被消耗); 第三条不带+ for (const call of dmSends.slice(0, 2)) {+ expect((call.params.reply_parameters as { message_id: number } | undefined)?.message_id).toBe(+ 96,+ );+ }+ expect(dmSends[2].params.reply_parameters).toBeUndefined();+ });++ it('旧轮迟到成功不吃掉新轮目标(提交校身份)', async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'first', replyQuoteDm: 'first' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();++ // 第一轮触发(msg 300) → 开流 → 首条 send 挂在途(模拟慢请求/限流退避)+ api.pushUpdates([privateMessage('第一问', 111, 300)]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ 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) {+ api.calls.push({ method, params: params ?? {} });+ await new Promise<void>((resolve) => {+ releaseFirstSend = resolve;+ });+ return { message_id: 9001, chat: { id: 111, type: 'private' }, date: 1 } as never;+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];++ const firstHandle = await im.startStreamingText(OWNER_ID);+ const firstSend = firstHandle.finalize('第一轮答案');+ await vi.waitFor(() => expect(releaseFirstSend).not.toBeNull());++ // 旧请求还在途, 第二轮触发(msg 301)已 claim 新目标+ api.pushUpdates([privateMessage('第二问', 111, 301)]);+ await vi.waitFor(() => expect(events).toHaveLength(2));+ await im.startStreamingText(OWNER_ID);++ // 旧请求现在才成功 —— 不得删掉新轮的 301+ releaseFirstSend!();+ await firstSend;+ api.call = originalCall;+ const sendsBefore = api.calls.filter(+ (c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID,+ ).length;+ await im.sendText(OWNER_ID, '第二轮答案');+ const second = api.calls+ .filter((c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID)+ .slice(sendsBefore);+ expect(second).toHaveLength(1);+ expect((second[0].params.reply_parameters as { message_id: number } | undefined)?.message_id)+ .toBe(301);+ });++ it('领取过时槽位: 出站失败且调用方放弃后, 下一条回复不再落后一条', async () => {+ await im.dispose();+ im = new TelegramIM(ctx.host, {+ apiFactory: () => api,+ behavior: () => ({ emojiReactions: 'off', replyQuoteGroup: 'first', replyQuoteDm: 'first' }),+ });+ im.registerIpc();+ const events: IMMessageEvent[] = [];+ im.onMessage((e) => events.push(e));+ await connect();++ // 第一条触发(msg 400): 领取目标后出站失败, 调用方直接放弃(不重试)+ api.pushUpdates([privateMessage('一', 111, 400)]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const originalCall = api.call.bind(api);+ let failed = false;+ api.call = (async (method: string, params?: Record<string, unknown>, signal?: AbortSignal) => {+ if (method === 'sendMessage' && params?.chat_id === OWNER_ID && !failed) {+ failed = true;+ api.calls.push({ method, params: params ?? {} });+ throw new Error('socket hang up');+ }+ return originalCall(method, params, signal);+ }) as FakeApi['call'];+ await expect(im.sendText(OWNER_ID, '丢掉的回答')).rejects.toThrow();++ // 第二条触发(msg 401): 新目标必须能领到, 不能被上一轮残留的 400 堵死+ api.pushUpdates([privateMessage('二', 111, 401)]);+ await vi.waitFor(() => expect(events).toHaveLength(2));+ const sendsBefore = api.calls.filter(+ (c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID,+ ).length;+ await im.sendText(OWNER_ID, '第二条的回答');+ const reply = api.calls+ .filter((c) => c.method === 'sendMessage' && c.params.chat_id === OWNER_ID)+ .slice(sendsBefore);+ expect((reply[0].params.reply_parameters as { message_id: number } | undefined)?.message_id)+ .toBe(401);+ });++ 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: 60, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const lane = events[0].senderId;+ await im.startStreamingText(lane);+ await im.sendText(lane, '第一条');+ await im.sendText(lane, '第二条');+ 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(60);+ }+ });++ it("群 'all' 档: A 流式期间 B 排队发提示, A 剩下的答案不能改挂到 B", 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();++ // A 触发(msg 70) → 开流(回合持有目标 70)+ api.pushUpdates([groupMessage({ text: 'A 问', fromId: 222, messageId: 70, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(1));+ const lane = events[0].senderId;+ const handle = await im.startStreamingText(lane);+ handle.replace('A 的第一段');+ await vi.waitFor(+ () => {+ expect(+ api.calls.some(+ (c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200',+ ),+ ).toBe(true);+ },+ { timeout: 3_000, interval: 50 },+ );++ // B 在 A 流式期间到达并入队 → 排队提示走独立出站(sendMarkdownText)+ api.pushUpdates([groupMessage({ text: 'B 问', fromId: 333, messageId: 71, mentionBot: true })]);+ await vi.waitFor(() => expect(events).toHaveLength(2));+ await im.sendMarkdownText(lane, '你排在第 1 位');++ // A 继续输出并定稿 —— 仍须挂回 70, 不得变 71+ await handle.finalize('A 的最终答案');+ const quoted = api.calls+ .filter((c) => c.method === 'sendMessage' && String(c.params.chat_id) === '-100200')+ .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 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);+ expect((bSends[0].params.reply_parameters as { message_id: number } | undefined)?.message_id)+ .toBe(71);+ });+it('全响应·自主判断: always 群未召唤消息进 ambient turn, 表情静默, NO_REPLY 删占位', 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 196f8d7365..266103d70f 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -110,6 +110,23 @@ type CardActionHandler = (e: IMCardActionEvent) => void;type StatusHandler = (s: IMStatus) => void;type GroupWindowHandler = (entry: TelegramGroupWindowEntry) => void;+/**+ * 回挂目标的请求级凭据: 记住本次出站真正带上的那个目标身份。+ * null = 本次没挂回(无需提交)。提交必须凭它校身份, 不能按 userId 当前槽位盲删。+ */+type ReplyTargetLease = { userId: string; messageId: string } | null;++/**+ * 队列里是否存在比 current 更新的触发消息 —— Telegram 同一 chat 内 message_id+ * 单调递增, 因此更大的 id 就意味着槽位里那个已经过时。+ * current 解不出数字(不应发生)时不阴拦领取。+ */+function hasNewerTrigger(queue: Array<{ id: string }>, current: string): boolean {+ const currentId = Number(current);+ if (!Number.isFinite(currentId)) return true;+ return queue.some((entry) => Number(entry.id) > currentId);+}+/** settle 缓冲/处理中的相册(见 albumsInFlight 注释)。 */interface PendingAlbum {messages: TgMessage[];@@ -238,6 +255,16 @@ export class TelegramIM extends BaseIM implements ChannelIM {private readonly pendingReplyTargets = new Map<string, Array<{ id: string; at: number }>>();/** 当前轮的回挂目标(claimTurnReplyTarget 领取; 'first' 用后即耗, 'all' 整轮保留)。 */private readonly turnReplyTargets = new Map<string, string>();+ /**+ * 活动流式回合计数(userId → 未收口的 handle 数) —— 回挂目标槽位的**归属权**。+ *+ * 为何必需: A 回合正在流式输出时, B 消息到达会入队并立即发一条排队提示+ * (turnRunner 的 notifyQueuedPosition → sendMarkdownText)。若让那条独立出站按「队列+ * 里有更新的 id」接管槽位, A 剩下的 sendRenderedChunk 会改挂到 B 上 —— 群 'all'+ * 档要求目标整轮不变, 而「队列里有更新的消息」并不证明 A 已被放弃。+ * 所以领取要看归属: 回合活着就由它持有, 收口(finalize/close)后才允许替换。+ */+ private readonly activeStreamRounds = new Map<string, number>();/** 非 owner 礼貌回应的 per-user 冷却(userId → 上次回应 ts)。 */private readonly strangerNoticeAt = new Map<string, number>();/** ambient 触发的原生 messageId(`chatId|msgId`) — 表情回应抑制名单(FIFO 512)。 */@@ -616,13 +643,15 @@ export class TelegramIM extends BaseIM implements ChannelIM {this.claimTurnReplyTargetIfIdle(userId);const target = this.targetOf(userId);const { html, replyMarkup } = buildCardPayload(spec);+ const { params: replyParams, lease } = this.leaseReplyTarget(userId);const sent = await this.callSend<TgMessage>('sendMessage', {...target,- ...this.consumeReplyParams(userId),+ ...replyParams,text: html,parse_mode: 'HTML',...(replyMarkup ? { reply_markup: replyMarkup } : {}),});+ this.commitReplyTarget(lease);this.recordOwnEcho(userId, spec.title ? `[${spec.title}]` : spec.body.slice(0, 100), sent);return { messageId: encodeMessageId(String(sent.chat.id), String(sent.message_id)) };}@@ -645,8 +674,32 @@ export class TelegramIM extends BaseIM implements ChannelIM {// 私聊曾走 sendMessageDraft 草稿通道 —— 草稿只能承载一行纯文本, 工具调用// 在私聊里因此整体不可见, 与群聊形成两套体验(Chris 2026-08 点名);// 呈现规则不再按 DM / 群分叉。- // 一轮输出开始: 从待配对队列领取本轮的回挂目标(见 claimTurnReplyTarget)。+ // 一轮输出开始: 从待配对队列领取本轮的回挂目标(见 claimTurnReplyTarget), 并占住+ // 槽位归属直到本回合收口 —— 期间的排队提示等独立出站不得把它改向新消息。this.claimTurnReplyTarget(userId);+ this.beginStreamRound(userId);+ return this.startTrackedStreaming(userId, initial);+ }++ private async startTrackedStreaming(+ userId: string,+ initial?: string,+ ): Promise<StreamingTextHandle> {+ try {+ const handle = await this.createStreamingHandle(userId, initial);+ return this.trackStreamRound(userId, handle);+ } catch (err) {+ // 建 handle 就失败 → 本回合没有 finalize/close 可依靠, 当场退归属, 否则槽位+ // 会被一个不存在的回合永久锁住。+ this.endStreamRound(userId);+ throw err;+ }+ }++ private createStreamingHandle(+ userId: string,+ initial?: string,+ ): Promise<StreamingTextHandle> {return startTelegramStreaming({send: async (markdown) => {@@ -1276,31 +1329,127 @@ export class TelegramIM extends BaseIM implements ChannelIM {else this.turnReplyTargets.delete(userId);}- /** 独立输出入口用: 本轮没有已领取目标且队列有货时才领取(不动流式轮的语义)。 */+ /**+ * 独立输出入口用的领取: 队列有货, 且槽位为空 **或槽位已过时** 时领取。+ *+ * 为何不能拿「槽位非空」当忙: 槽位里的目标可能是上一轮的残留 —— 某轮领取后+ * 出站失败且调用方直接放弃(如 processOne 捕到 unsupportedOnly 后 return), 目标就会+ * 一直占着。旧判据下下一条入站消息领不到自己的新目标, 回复会持续落后一条。+ *+ * 过时判据不靠猜失败原因(传输层无法区分「调用方还会重试」与「已放弃」), 而是用+ * Telegram 的硬事实: 同一 chat 内 message_id 单调递增 —— 队列里出现更大的 id,+ * 就证明有更新的触发消息到达过, 槽位那个已经不是"当前该回的那条"。+ * 这比分类失败路径更嬽: 任何原因造成的残留都会在下一条入站消息处自愈。+ */private claimTurnReplyTargetIfIdle(userId: string): void {- if (this.turnReplyTargets.has(userId)) return;- if (!this.pendingReplyTargets.has(userId)) return;+ const queue = this.pendingReplyTargets.get(userId);+ if (!queue || queue.length === 0) return;+ const current = this.turnReplyTargets.get(userId);+ if (current !== undefined) {+ // 流式回合持有期间一律不接管: 排队提示这类独立出站不得把正在输出的+ // 回合改向新消息(群 'all' 档会把 A 剩下的答案挂到 B 上)。代价是该提示本身+ // 沿用回合目标或不挂回 —— 但 B 的目标因此留在队列里, B 自己的回合能领到。+ if (this.hasActiveStreamRound(userId)) return;+ // 无活动回合 = 槽位是上一轮残留; 队列里有更新的 id 即证明它过时。+ if (!hasNewerTrigger(queue, current)) return;+ }this.claimTurnReplyTarget(userId);}+ private hasActiveStreamRound(userId: string): boolean {+ return (this.activeStreamRounds.get(userId) ?? 0) > 0;+ }++ private beginStreamRound(userId: string): void {+ this.activeStreamRounds.set(userId, (this.activeStreamRounds.get(userId) ?? 0) + 1);+ }++ private endStreamRound(userId: string): void {+ const next = (this.activeStreamRounds.get(userId) ?? 0) - 1;+ if (next > 0) this.activeStreamRounds.set(userId, next);+ else this.activeStreamRounds.delete(userId);+ }+/**- * 本轮回挂目标 → reply_parameters(首条出站专用)。- * allow_sending_without_reply: 触发消息被删时降级为普通消息, 不让发送失败。+ * 给流式 handle 包上回合归属的生命周期: finalize / close 任一到达即收口(只计+ * 一次)。收口后槽位失去保护, 残留目标可被下一条入站消息覆盖领取(自愈)。*/- private consumeReplyParams(- userId: string,- ): { reply_parameters: { message_id: number; allow_sending_without_reply: true } } | Record<string, never> {+ private trackStreamRound(userId: string, inner: StreamingTextHandle): StreamingTextHandle {+ let ended = false;+ const end = (): void => {+ if (ended) return;+ ended = true;+ this.endStreamRound(userId);+ };+ const wrapped: StreamingTextHandle = {+ get messageId() {+ return inner.messageId;+ },+ append: (delta) => inner.append(delta),+ replace: (fullText) => inner.replace(fullText),+ finalize: async (finalText) => {+ try {+ await inner.finalize(finalText);+ } finally {+ end();+ }+ },+ close: () => {+ try {+ inner.close();+ } finally {+ end();+ }+ },+ // 只在底层真的支持时暴露 —— turnRunner 靠它是否存在判断能不能投图。+ ...(inner.addExtraImageAbsPath+ ? { addExtraImageAbsPath: (absPath: string) => inner.addExtraImageAbsPath?.(absPath) }+ : {}),+ };+ return wrapped;+ }++ /**+ * 租借本次出站的回挂目标: 同时返回 reply_parameters 与**请求级凭据**(lease),+ * **只读不消耗**。allow_sending_without_reply: 触发消息被删时降级为普通消息。+ *+ * 读与消耗分开的原因: 首条出站失败(网络/限流耗尽)时调用方会重试 —— 发前就消耗+ * 会让重试那条丢掉引用('first' 档于是整轮不再挂回)。旧 sendRichFinal 就是这么+ * 做的, DM 改走经典路径后该语义必须留在共用发送入口上。+ */+ private leaseReplyTarget(userId: string): {+ params:+ | { reply_parameters: { message_id: number; allow_sending_without_reply: true } }+ | Record<string, never>;+ lease: ReplyTargetLease;+ } {const target = this.turnReplyTargets.get(userId);- if (!target) return {};- // 群 'all' 档: 目标保留整轮(下一轮 claim 时被替换/清除), 每条出站都挂回。- const keepForAll =- decodeLaneUserId(userId) !== null && this.behaviorOf().replyQuoteGroup === 'all';- if (!keepForAll) this.turnReplyTargets.delete(userId);+ if (!target) return { params: {}, lease: null };return {- reply_parameters: { message_id: Number(target), allow_sending_without_reply: true },+ params: {+ reply_parameters: { message_id: Number(target), allow_sending_without_reply: true },+ },+ lease: { userId, messageId: target },};}+ /**+ * 出站确定成功后才消耗 —— 且只能消耗**本次请求真正带上的那个目标**。+ *+ * 身份校验不可省: 旧轮请求还在途时新一轮可能已 claim 了新目标写进同一个槽位,+ * 此时若按 userId 无条件删除, 旧请求的迟到成功会吃掉新轮的目标 —— 新轮首条+ * 答案于是丢引用(群里就是一条与提问脉络不上的回答)。不匹配 = 本次与当前槽位无关,+ * 什么都不做。+ */+ private commitReplyTarget(lease: ReplyTargetLease): void {+ if (!lease) return;+ if (this.turnReplyTargets.get(lease.userId) !== lease.messageId) return;+ // 群 'all' 档: 目标保留整轮(下一轮 claim 时被替换/清除), 每条出站都挂回。+ const keepForAll =+ decodeLaneUserId(lease.userId) !== null && this.behaviorOf().replyQuoteGroup === 'all';+ if (!keepForAll) this.turnReplyTargets.delete(lease.userId);+ }+private requireApi(): TelegramApiClient {if (!this.api) throw new Error('telegram api is not connected');@@ -1356,7 +1505,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {markdownChunk: string,): Promise<{ messageId: string; imageUrls: string[] }> {const target = this.targetOf(userId);- const replyParams = this.consumeReplyParams(userId);+ const { params: replyParams, lease } = this.leaseReplyTarget(userId);const { html, imageUrls } = markdownToTelegramHtml(markdownChunk);let sent: TgMessage;try {@@ -1379,6 +1528,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {throw err;}}+ this.commitReplyTarget(lease);this.recordOwnEcho(userId, markdownChunk, sent);return {messageId: encodeMessageId(String(sent.chat.id), String(sent.message_id)),@@ -1390,13 +1540,17 @@ export class TelegramIM extends BaseIM implements ChannelIM {const target = this.targetOf(userId);let firstMessageId = '';for (const chunk of chunkTelegramSource(text)) {+ // 只首条挂回: 后续分段不租借、也不提交(lease 为 null 时 commit 是 noop)。+ const { params: replyParams, lease } =+ firstMessageId === '' ? this.leaseReplyTarget(userId) : { params: {}, lease: null };const sent = await this.callSend<TgMessage>('sendMessage', {...target,- ...(firstMessageId === '' ? this.consumeReplyParams(userId) : {}),+ ...replyParams,text: chunk || '…',link_preview_options: { is_disabled: true },});if (!firstMessageId) {+ this.commitReplyTarget(lease);firstMessageId = encodeMessageId(String(sent.chat.id), String(sent.message_id));}this.recordOwnEcho(userId, chunk, sent);