Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 抑制空回复并要求显式群召唤
Dashc587f10f1c15
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex 5b77fd36f7..f69895e217 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -3137,6 +3137,49 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()expect(unsub).toHaveBeenCalledTimes(1);});+ it.each([+ ['telegram', false], ['telegram', true], ['feishu', false],+ ['feishu', true], ['discord', false], ['discord', true],+ ] as const)('%s 空成功结果不补发占位(过程消息:%s)', async (channel, withProgress) => {+ const handle = {+ messageId: 'telegram-progress',+ append: vi.fn(), replace: vi.fn(), finalize: vi.fn(), close: vi.fn(),+ };+ mocks.feishuIm.startStreamingText.mockResolvedValue(handle);+ runner = createTurnRunner({ ...fakeAdapter, channel }, fakeRepo, fakeCards);+ const h = setupSession(async () => ({ accepted: true }));+ await runDefaultTurn();+ if (withProgress) {+ h.emit({ type: 'text', data: { text: ' \n ', isFinal: true } });+ await flushMicrotasks();+ }+ mocks.feishuIm.sendText.mockClear();+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => {+ expect(mocks.logger.info.mock.calls.some((c) => String(c[0]).includes('turn done'))).toBe(true);+ });+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();+ expect(mocks.feishuIm.consumePendingOpenerCard).not.toHaveBeenCalled();+ if (withProgress) expect(handle.finalize).toHaveBeenCalledWith('');+ else expect(handle.finalize).not.toHaveBeenCalled();+ });++ it.each(['wechat', 'wecom', 'dingtalk'] as const)('%s 空结果仍提交终态,不经过普通发消息兜底', async (channel) => {+ const commitFinal = vi.fn(async () => undefined);+ runner = createTurnRunner({+ ...fakeAdapter, channel,+ output: { kind: 'chunked-text', im: mocks.feishuIm as unknown as ChannelIM, commitFinal },+ }, fakeRepo, fakeCards);+ const h = setupSession(async () => ({ accepted: true }));+ await runDefaultTurn();+ mocks.feishuIm.sendText.mockClear();+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(commitFinal).toHaveBeenCalledWith(expect.objectContaining({+ userId: 'ou_user', text: '', terminal: 'done',+ })));+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();+ });+it('clears the retry notice when the retried turn succeeds with no output', async () => {// 不变量锁定(review #844 codex P1 提出的担心, 实测不成立但值得锁住):// 重投成功而那一轮零输出时, 没有任何进展 handler 会清掉"正在自动重试" —— 卡片@@ -3172,8 +3215,8 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()});const finalView = String(handle.finalize.mock.calls[0][0]);expect(finalView).not.toContain('正在自动重试');- // 过程区清空后应回落到空回复兜底, 而不是把状态行当正文。- expect(finalView).toContain('空回复');+ // 空正文交给传输层撤回进度卡,不把状态行当正文。+ expect(finalView).toBe('');});it('waits for the pending retry card before finalizing a terminal overload error', async () => {@@ -4385,7 +4428,7 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {);});- it('空正文 + 建卡失败:保留「本轮无文本输出」提示', async () => {+ it('空正文 + 建卡失败: 不补发占位提示', async () => {mocks.feishuIm.startStreamingText.mockRejectedValue(new Error('card create denied'));const h = setupSession(async () => ({ accepted: true }));const onTurnComplete = vi.fn();@@ -4400,15 +4443,11 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {h.emit({ type: 'done', data: {}, source: 'claude-code' });await waitForAssertion(() => {expect(onTurnComplete).toHaveBeenCalledTimes(1);- expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(- 'ou_user',- expect.stringContaining('本轮无文本输出'),- expect.anything(),- );+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();});});- it('无文本输出兜底发送认领暂存 opener', async () => {+ it('无文本输出清理本轮 opener,不另发兜底', async () => {mocks.feishuIm.startStreamingText.mockRejectedValue(new Error('card create denied'));mocks.feishuIm.getPendingOpenerTrigger.mockReturnValue('msg-user');mocks.feishuIm.consumePendingOpenerCard.mockResolvedValue(false);@@ -4424,11 +4463,8 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {await flushMicrotasks();h.emit({ type: 'done', data: {}, source: 'claude-code' });await waitForAssertion(() => {- expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(- 'ou_user',- expect.stringContaining('本轮无文本输出'),- expect.objectContaining({ fallbackOpenerId: 'om_deferred' }),- );+ expect(mocks.feishuIm.consumePendingOpenerCard).toHaveBeenCalledWith('ou_user', '');+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();});});@@ -4471,11 +4507,7 @@ describe('初始流式输出面创建失败的收口降级(#2164)', () => {await waitForAssertion(() => {expect(onTurnB).toHaveBeenCalledTimes(1);expect(mocks.feishuIm.consumePendingOpenerCard).toHaveBeenCalledTimes(1);- expect(mocks.feishuIm.sendText).toHaveBeenCalledWith(- 'ou_user',- expect.stringContaining('本轮无文本输出'),- expect.anything(),- );+ expect(mocks.feishuIm.sendText).not.toHaveBeenCalled();});});});diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex 52a55c0684..7b5fdd1ca1 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -1104,6 +1104,17 @@ describe('turnRunner 自动任务转播(scheduler turn → 远程控制 thread)'const withOrigin = (e: Partial<AgentEvent>): AgentEvent =>({ ...e, turnOrigin: schedulerOrigin }) as AgentEvent;+ it('successful background work without a reply removes the progress card and its title', async () => {+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ const h = await attachAndIdle();+ h.emit(withOrigin({ type: 'tool_use', data: { toolName: 'Read', input: { file_path: '/x/a.ts' } } }));+ await vi.waitFor(() => expect(mocks.slackIm.startStreamingText).toHaveBeenCalledTimes(1));+ h.emit(withOrigin({ type: 'done', data: {} }));+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledExactlyOnceWith(''));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledTimes(1);+ });+it('does not forward child output or settle on a child terminal during scheduled turns', async () => {const stub = streamingHandleStub();mocks.slackIm.startStreamingText.mockResolvedValue(stub);diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex fa3da50734..33ab51a031 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -3179,8 +3179,12 @@ export function createTurnRunner(// 它不置 turn.done, composeStreamingView 会把 activity 一起写进正文。clearRunningIndicators(t.activity);try {- // 没产出任何内容(无文本无步骤)且无错 → 不留空卡。- if (!t.streamingHandle && t.buffer.length === 0 && t.mediaAbsPaths.length === 0 && t.activity.totalSteps === 0 && !errMsg) {+ // 成功但没有正文或附件:标题、步骤不算回复,也不新建空卡。+ if (!t.buffer.trim() && t.mediaAbsPaths.length === 0 && !errMsg) {+ if (t.streamingHandlePromise) await t.streamingHandlePromise;+ if (sessionStates.get(state.makerSession.id) === state) {+ await t.streamingHandle?.finalize('');+ }return;}if (silenced && !t.streamingHandlePromise) return;@@ -3730,34 +3734,27 @@ export function createTurnRunner(// The terminal branch below handles the missing output surface.}}+ // 所有渠道共用空成功结果语义;文本渠道仍须提交终态(微信持久任务依赖它)。+ if (!turn.streamingHandle && turn.mediaAbsPaths.length > 0) {+ await ensureStreamingHandle(turn);+ }+ const finalView = composeStreamingView(turn);if (turn.streamingHandle) {- const finalView = composeStreamingView(turn) || '_(空回复)_';- await finalizeTurnStream(turn, finalView);- } else if (turn.presenter.wholeText().length === 0) {- // No streamed text at all — send a one-shot text so the user knows the- // turn ended. (Rare; normally agents emit at least one text block.)+ await finalizeTurnStream(turn, finalView.trim() ? finalView : '');+ } else if (!finalView.trim() && turn.mediaAbsPaths.length === 0) {try {if (output.kind === 'chunked-text') {await output.commitFinal({userId,- text: '✅ (本轮无文本输出)',+ text: '',terminal: turn.terminalKind,threadTs: turn.scopeKey,- ...(turn.mediaAbsPaths.length > 0 ? { mediaAbsPaths: turn.mediaAbsPaths } : {}),});} else {- // 群主流 @ 开话题但本轮无流式输出: pending opener 尚未被认领 —- // 仅当 opener 是本轮消息创建的(trigger 匹配)才消费, 否则另发- // (避免消费上一轮遗留的 opener 造成归属错乱)。+ // 只清除本轮自己的待认领开场白,不能消费别的轮次。const triggerId = output.im.getPendingOpenerTrigger?.(userId);- const isMyOpener = triggerId === turn.userMessageId;- const consumed =- isMyOpener- ? ((await output.im.consumePendingOpenerCard?.(userId, '✅ (本轮无文本输出)')) ??- false)- : false;- if (!consumed) {- await sendTextClaimingOpener(userId, '✅ (本轮无文本输出)', turn.scopeKey);+ if (triggerId && triggerId === turn.userMessageId) {+ await output.im.consumePendingOpenerCard?.(userId, '');}}} catch {diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.tsindex 738ee101e3..68174c9561 100644--- a/apps/desktop/src/main/im/wechat/WechatIM.ts+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts@@ -641,6 +641,8 @@ export class WechatIM extends BaseIM implements RichChannelIM {const active = this.#activeTasks.get(output.userId);if (!active) throw new Error('WECHAT_NO_ACTIVE_TASK');const chunks = chunkWechatText(normalizeFinalOutputText(output.text));+ // 持久终态需要一个 outbox 项;发送器跳过空 text,仍投递附件并确认任务完成。+ if (chunks.length === 0) chunks.push('');const kind =output.terminal === 'done'? ('final' as const)@@ -1962,7 +1964,7 @@ export function wechatPreDispatchFailureText(reason: string): string {}function normalizeFinalOutputText(text: string): string {- return filterWechatMarkdown(text) || '✅ (本轮无文本输出)';+ return filterWechatMarkdown(text).trim();}function hasWechatTaskContent(text: string, attachments: readonly WechatTaskAttachment[]): boolean {diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.tsindex 5dd22aca1e..f7ca78c2fa 100644--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts@@ -109,8 +109,9 @@ describe('WechatIM host boundary', () => {await expect(im.startStreamingText('peer')).rejects.toThrow('WECHAT_RICH_OUTPUT_UNSUPPORTED');});- it('uses the shared empty-output copy after filtering the final text', () => {- expect(__testing.normalizeFinalOutputText('')).toBe('✅ (本轮无文本输出)');+ it('preserves empty output after filtering the final text', () => {+ expect(__testing.normalizeFinalOutputText('')).toBe('');+ expect(__testing.normalizeFinalOutputText(' \n ')).toBe('');expect(__testing.normalizeFinalOutputText('hello')).toBe('hello');});diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.tsindex 76bcf65e35..a69b95adfc 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts@@ -20,6 +20,25 @@ afterEach(() => {});describe('WeChat reliable worker transactions', () => {+ it('settles an empty final outbox item without replaying the accepted task', () => {+ const db = createDb();+ activate(db, 'epoch-1', null);+ commitBatch(db, {+ bindingEpoch: 'epoch-1', expectedCursor: '', nextCursor: 'cursor-1',+ messages: [message('task-1', 'platform-1', 'session-1')],+ });+ lease(db, 'epoch-1', 200);+ runTx(db, 'wechatMarkAccepted', { bindingEpoch: 'epoch-1', taskId: 'task-1' });+ const terminal = { bindingEpoch: 'epoch-1', taskId: 'task-1', now: 300,+ outbox: [outbox('empty-final', 'client-empty', 0, '')] };+ expect(runTx(db, 'wechatCommitTerminal', terminal)).toEqual({ committed: true, alreadyCommitted: false });+ expect(runTx(db, 'wechatMarkOutboxDelivered', {+ bindingEpoch: 'epoch-1', outboxId: 'empty-final', deliveredAt: 301,+ })).toEqual({ changed: true, taskId: 'task-1', taskCompleted: true });+ expect(readTaskStatus(db, 'task-1')).toBe('completed');+ expect(runTx(db, 'wechatCommitTerminal', terminal)).toEqual({ committed: true, alreadyCommitted: true });+ expect(count(db, 'wechat_outbox')).toBe(1);+ });it('uses binding epoch and cursor CAS to reject stale callbacks', () => {const db = createDb();diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 8e4af93ac6..9a6194970a 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -96,6 +96,13 @@ Discord 传输层只放行主人,钉钉群里被 @ 时成员也能触发(成`im/shared/imBotBindingRuntime.ts` 与 `im/shared/turnRunner.ts`(落点解析)、`localDb/ipc/bots.ts`(专线创建);官方 Cindy bot、其它个人渠道与「代主人收发」沿后续分期接入同一骨架。+2026-10-17 空回复与群召唤:个人 bot 和伙伴自有 bot 复用同一套渠道规则。成功轮次没有正文与附件时+不补发「空回复」「本轮无文本输出」或只有任务标题的转播;Telegram、飞书、Discord 已有过程消息+尽力撤回。企业微信已开启的被动流仍须发送空白结束帧,但不另发完成占位;微信仍提交本地完成记录,+不发送空正文。只有图片、文件的结果继续正常投递,失败与取消仍给出既有提示。+默认群召唤模式下,只提伙伴名字不触发;Telegram 保留显式 `@显示名` 兼容入口。平台 @、回复 bot、+命令与用户主动开启的全响应模式遵循各渠道既有规则,全响应仍由辅助判断与主模型决定是否插话。+## 3. 长期会话生命周期### 3.1 稳定主任务diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex 2f4cadccdb..8e8c55ba55 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -11,6 +11,13 @@ Cindy 有两个 Telegram bot,用户看到的是同一个产品:两者是**两套架构**,不是同一份代码的两个开关。所以"统一"不等于"让两条代码路径长得一样",而是:**能同源的同源;不能同源的,差异必须写在这张表里、有裁决、有理由。**+2026-10-17 群触发与空回复:默认召唤模式下,仅提到显示名(包括句首的「Cindy 赞助」)+不触发。个人 bot 保留显式 `@显示名` 的兼容入口;平台提及、回复 bot、命令及用户主动+开启的全响应模式沿用原有规则。Telegram 成功轮次没有正文和附件时不补发「空回复」或+「本轮无文本输出」,已有过程消息尽力撤回;仅有附件的结果正常发送。+个人侧由 `im/shared/turnRunner.ts` 与 `telegram/streamingText.ts` 兑现;官方侧需配套+`telegram-hook-server` 空结果收口修复,客户端升级不能代替服务端部署。+额度说明的调用边界:IM 入口须显式传入 `surface` 才启用 bot 恢复指引;定时任务运行记录、通知与旁路转播未传入口时保留原有错误映射。个人渠道的 `/model` 指引只用于支持富卡的输出(包括个人 Telegram);钉钉、企业微信等纯文本输出指向在 Cindy 中打开当前任务换diff --git a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.tsindex 961547e731..085fb80862 100644--- a/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts+++ b/packages/lizi-im/src/dingtalk/__tests__/dingtalkIM.test.ts@@ -128,6 +128,16 @@ function directMessage(overrides: Record<string, unknown> = {}) {}describe("DingTalkIM", () => {+ it.each(['', ' \n '])('does not send an empty final %j', async (text) => {+ const { host } = makeHost();+ const fetcher = outboundImageFetcher();+ const im = new DingTalkIM(host, { clientFactory: () => new FakeClient(), fetcher });+ await im.init();+ fetcher.mockClear();+ await im.commitFinal({ userId: 'owner-1', text, terminal: 'done' });+ expect(fetcher).not.toHaveBeenCalled();+ await im.dispose();+ });it("clears the text waiter after a Desktop decision so the next message is ordinary input", async () => {const { host } = makeHost();const client = new FakeClient();diff --git a/packages/lizi-im/src/dingtalk/index.ts b/packages/lizi-im/src/dingtalk/index.tsindex 9e697fb4dd..ddf4aa5c46 100644--- a/packages/lizi-im/src/dingtalk/index.ts+++ b/packages/lizi-im/src/dingtalk/index.ts@@ -902,7 +902,7 @@ function defaultClientFactory(credentials: Credentials): DingTalkStreamClient {}function chunkText(text: string): string[] {- const normalized = text.trim() || "(空回复)";+ const normalized = text.trim();const chunks: string[] = [];let remaining = normalized;while (remaining.length > OUTBOUND_CHUNK_SIZE) {@@ -923,7 +923,7 @@ function chunkText(text: string): string[] {}function normalizeFinalText(text: string): string {- return text.trim() || "✅ 本轮已完成,没有文本输出。";+ return text.trim();}function safeConnectionError(error: unknown): string {diff --git a/packages/lizi-im/src/discord/__tests__/streamingText.test.ts b/packages/lizi-im/src/discord/__tests__/streamingText.test.tsindex 4226b6851e..758fa6de5e 100644--- a/packages/lizi-im/src/discord/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/discord/__tests__/streamingText.test.ts@@ -103,14 +103,16 @@ describe('discord streaming text', () => {expect(deps.uploadImages).toHaveBeenCalledWith('dm-1|m1', ['/tmp/abc123.png']);});- it('skips empty final edit when there is no text or image to send', async () => {+ it.each(['', ' \n '])('removes progress for an empty final %j', async (text) => {const deps = makeDeps();const handle = await startStreaming(deps);- await handle.finalize('');+ await handle.finalize(text);+ await handle.finalize(text);expect(deps.edit).not.toHaveBeenCalled();expect(deps.uploadImages).not.toHaveBeenCalled();+ expect(deps.remove).toHaveBeenCalledExactlyOnceWith('dm-1|m1');});it('close prevents future edits', async () => {@@ -135,6 +137,7 @@ function makeDeps() {edit: vi.fn(async (...args: [string, string]) => {void args;}),+ remove: vi.fn(async (_messageId: string) => {}),markdownToDiscord,chunk: chunkDiscordText,resolveImageUrl: vi.fn((url: string) => `/tmp/${url.replace('xdt-image://', '')}.png`),diff --git a/packages/lizi-im/src/discord/index.ts b/packages/lizi-im/src/discord/index.tsindex 856b509536..34a3a501b6 100644--- a/packages/lizi-im/src/discord/index.ts+++ b/packages/lizi-im/src/discord/index.ts@@ -392,6 +392,11 @@ export class DiscordIM extends BaseIM implements ChannelIM {async patchMarkdownCard(messageId: string, markdown: string): Promise<void> {const message = await this.fetchMessage(messageId);+ if (!markdown.trim()) {+ await message.delete();+ this.cardSpecs.delete(messageId);+ return;+ }const { text } = markdownToDiscord(markdown);await message.edit({content: text.slice(0, 2000),@@ -417,6 +422,10 @@ export class DiscordIM extends BaseIM implements ChannelIM {await message.edit(text);},markdownToDiscord,+ remove: async (messageId) => {+ const message = await this.fetchMessage(messageId);+ await message.delete();+ },chunk: chunkDiscordText,resolveImageUrl: this.opts.resolveImageUrl,uploadImages: (messageId, absPaths) => this.uploadImages(messageId, absPaths),@@ -973,6 +982,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {fetch(messageId: string): Promise<{react(emoji: string): Promise<unknown>;edit(payload: unknown): Promise<unknown>;+ delete(): Promise<unknown>;reactions: {resolve(token: string): { users: { remove(userId: string | undefined): Promise<unknown> } } | null;};@@ -991,6 +1001,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {fetch(messageId: string): Promise<{react(emoji: string): Promise<unknown>;edit(payload: unknown): Promise<unknown>;+ delete(): Promise<unknown>;reactions: {resolve(token: string): { users: { remove(userId: string | undefined): Promise<unknown> } } | null;};@@ -999,7 +1010,7 @@ export class DiscordIM extends BaseIM implements ChannelIM {};}- private async fetchMessage(messageId: string): Promise<{ edit(payload: unknown): Promise<unknown> }> {+ private async fetchMessage(messageId: string): Promise<{ edit(payload: unknown): Promise<unknown>; delete(): Promise<unknown> }> {const { channelId, messageId: nativeMessageId } = decodeMessageId(messageId);const channel = await this.fetchChannel(channelId);return channel.messages.fetch(nativeMessageId);diff --git a/packages/lizi-im/src/discord/streamingText.ts b/packages/lizi-im/src/discord/streamingText.tsindex e030ffd541..889895f159 100644--- a/packages/lizi-im/src/discord/streamingText.ts+++ b/packages/lizi-im/src/discord/streamingText.ts@@ -10,6 +10,7 @@ export function startStreaming(deps: {send: (text: string) => Promise<string>;edit: (messageId: string, text: string) => Promise<void>;+ remove: (messageId: string) => Promise<void>;markdownToDiscord: typeof markdownToDiscord;chunk: typeof chunkDiscordText;resolveImageUrl?: (url: string) => string;@@ -102,6 +103,9 @@ class DiscordStreamingTextHandle implements StreamingTextHandle {await this.deps.edit(this.messageId, firstChunk);} else if (imageAbsPaths.length > 0) {await this.deps.edit(this.messageId, IMAGE_ONLY_PLACEHOLDER);+ } else {+ await this.deps.remove(this.messageId);+ return;}for (const chunk of chunks.slice(1)) {await this.deps.send(chunk);diff --git a/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts b/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.tsindex 23a266f241..35a5472fa7 100644--- a/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/feishuOpenerConsume.test.ts@@ -531,6 +531,25 @@ describe('FeishuIM opener consumption failure semantics', () => {expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t');});+ it('empty opener final is recalled and subsequent replies use the trigger anchor', async () => {+ outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');+ await expect(im.consumePendingOpenerCard('g/oc_c/omt_t', '')).resolves.toBe(true);+ expect(streamingText.patchMarkdown).toHaveBeenCalledWith('om_opener', '');+ expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t');+ expect(outboundMocks.sendInteractive).not.toHaveBeenCalled();+ });++ it.each([false, true])('deferred empty opener never falls back to a blank card (initial recall fails=%s)', async (fails) => {+ outboundMocks.drainDeferredOpenerConsumes.mockReturnValueOnce([+ { userId: 'g/oc_c/omt_t', openerId: 'om_empty', markdown: '' },+ ]);+ if (fails) vi.mocked(streamingText.patchMarkdown).mockRejectedValueOnce(new Error('recall failed'));+ feishuEvents.emit('imStatus', { kind: 'connected', appId: 'cli' });+ await vi.waitFor(() => expect(outboundMocks.rearmAnchorToTrigger).toHaveBeenCalledWith('g/oc_c/omt_t'));+ expect(outboundMocks.sendInteractive).not.toHaveBeenCalled();+ expect(outboundMocks.sendText).not.toHaveBeenCalled();+ });+it('consumePendingOpenerCard: 撤回失败不回拨不另发, 重新暂存等重试', async () => {outboundMocks.claimPatchableOpener.mockReturnValue('om_opener');(streamingText.patchMarkdown as ReturnType<typeof vi.fn>).mockRejectedValueOnce(diff --git a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts b/packages/lizi-im/src/feishu/__tests__/streamingText.test.tsindex 7b865bde5a..233e250686 100644--- a/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/streamingText.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({patchCardRaw: vi.fn(),+ recallMessage: vi.fn(),sendCardRaw: vi.fn(),sendFile: vi.fn(),sendText: vi.fn(),@@ -21,7 +22,7 @@ vi.mock('../moduleScope.js', async (importOriginal) => ({}));import { messages } from '../messages.js';-import { FEISHU_CARD_REQUEST_MAX_BYTES, start } from '../streamingText.js';+import { FEISHU_CARD_REQUEST_MAX_BYTES, start, patchMarkdown } from '../streamingText.js';function markdownContent(card: unknown): string {return (card as { body: { elements: Array<{ content: string }> } }).body.elements[0].content;@@ -51,6 +52,31 @@ describe('feishu streaming text', () => {expect(markdownContent(mocks.patchCardRaw.mock.calls[0][1])).toBe('正常正文');});+ it.each(['', ' \n '])('recalls an empty final %j without a placeholder', async (text) => {+ const handle = await start('ou_owner');+ await handle.finalize(text);+ await handle.finalize(text);+ expect(mocks.recallMessage).toHaveBeenCalledExactlyOnceWith('om_stream');+ expect(mocks.patchCardRaw).not.toHaveBeenCalled();+ expect(mocks.sendText).not.toHaveBeenCalled();+ });++ it('recalls an existing interaction/opener card when its final is empty', async () => {+ await patchMarkdown('om_opener', ' \n ');+ expect(mocks.recallMessage).toHaveBeenCalledWith('om_opener');+ expect(mocks.patchCardRaw).not.toHaveBeenCalled();+ });++ it('keeps attachment-only finals', async () => {+ mocks.uploadImage.mockResolvedValue('image_key');+ const handle = await start('ou_owner');+ handle.addExtraImageAbsPath?.('/tmp/image.png');+ await handle.finalize('');+ expect(mocks.uploadImage).toHaveBeenCalledWith('/tmp/image.png');+ expect(mocks.patchCardRaw).toHaveBeenCalled();+ expect(mocks.recallMessage).not.toHaveBeenCalled();+ });+it('truncates an oversized final card within Feishu request limits', async () => {const handle = await start('ou_owner');const longMarkdown = [diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.tsindex 3768469440..c29658e883 100644--- a/packages/lizi-im/src/feishu/index.ts+++ b/packages/lizi-im/src/feishu/index.ts@@ -291,6 +291,11 @@ export class FeishuIM extends BaseIM implements ChannelIM {try {if ('markdown' in entry) {await streamingText.patchMarkdown(openerId, entry.markdown);+ if (!entry.markdown.trim()) {+ if (outbound.getAccountEpoch() === epoch) outbound.rearmAnchorToTrigger(entry.userId);+ resolveFlush(null);+ continue;+ }} else {await outbound.updateInteractive(openerId, entry.spec);outbound.registerCardLane(entry.userId, openerId);@@ -334,6 +339,10 @@ export class FeishuIM extends BaseIM implements ChannelIM {continue;}outbound.rearmAnchorToTrigger(entry.userId);+ if ('markdown' in entry && !entry.markdown.trim()) {+ resolveFlush(null);+ continue;+ }try {// 走 outbound 直发, 避免再进 sendWithDeferred 等待自己造成死锁。const sent =@@ -559,6 +568,9 @@ export class FeishuIM extends BaseIM implements ChannelIM {const epoch = outbound.getAccountEpoch();try {await streamingText.patchMarkdown(openerId, markdown);+ if (!markdown.trim() && outbound.getAccountEpoch() === epoch) {+ outbound.rearmAnchorToTrigger(userId);+ }return true;} catch (err) {const msg = err instanceof Error ? err.message : String(err);diff --git a/packages/lizi-im/src/feishu/streamingText.ts b/packages/lizi-im/src/feishu/streamingText.tsindex 24b27af04e..2857a392b4 100644--- a/packages/lizi-im/src/feishu/streamingText.ts+++ b/packages/lizi-im/src/feishu/streamingText.ts@@ -31,6 +31,7 @@ import {sendFile,sendText,claimPatchableOpener,+ recallMessage,} from './outbound.js';import { buildMarkdownCardV2, buildMixedMarkdownCardV2 } from './cards.js';import { resolveFeishuMediaUrl } from './mediaCache.js';@@ -223,6 +224,10 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {private async doFinalize(): Promise<void> {const log = getLog();const text = this.buffer;+ if (!text.trim() && this.extraImageAbsPaths.length === 0) {+ await recallMessage(this.messageId);+ return;+ }// 1. Upload all xdt-image URLs in parallel; missing entries get a "图片// 加载失败" placeholder in the final card.@@ -307,7 +312,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// a) text only → plain markdown card v2// b) text + images (markdown 内联 OR tool_result 追加) → mixed elements card// c) empty text + only files → "🎉 N 个文件已送达" placeholder- // d) totally empty → fallback "(空回复)"+ // d) extra images all failed → delivery failure (truly empty finals returned above)const hasAnyImage = imageUrls.length > 0 || extraImageKeys.length > 0;const fileOnly = cardTextTrimmed.length === 0 && !hasAnyImage && fileLinks.length > 0;try {@@ -320,7 +325,7 @@ class FeishuStreamingTextHandle implements StreamingTextHandle {// 兜底分支会塞 "(空回复)" — 但 hasAnyImage 时一定不为空, 所以不会触发。card = buildMixedMarkdownCardV2(cardText, imageMap, extraImageKeys);} else {- card = buildMarkdownCardV2(cardTextTrimmed.length > 0 ? cardText : transportMessages.streaming.emptyReply);+ card = buildMarkdownCardV2(cardTextTrimmed.length > 0 ? cardText : transportMessages.streaming.deliveryFailed);}card = fitCardToLimit(cardText, card, (visibleText) =>hasAnyImage@@ -370,5 +375,9 @@ export async function start(* 把 picker card 直接转成"已接管 + 总结"视图, 替代发两张独立消息。*/export async function patchMarkdown(messageId: string, markdown: string): Promise<void> {+ if (!markdown.trim()) {+ await recallMessage(messageId);+ return;+ }await patchCardRaw(messageId, buildMarkdownCardV2(markdown));}diff --git a/packages/lizi-im/src/telegram/__tests__/inbound.test.ts b/packages/lizi-im/src/telegram/__tests__/inbound.test.tsindex f60a9c719b..f73a2b1c31 100644--- a/packages/lizi-im/src/telegram/__tests__/inbound.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/inbound.test.ts@@ -18,6 +18,25 @@ function msg(overrides: Partial<TgMessage> = {}): TgMessage {}describe('detectGroupTrigger', () => {+ it.each(['Cindy 赞助', 'Cindy 现在也有', 'cindy 帮我看看', 'Cindy', ' Cindy?', '我问过 Cindy 了'])(+ '仅提到显示名不触发:%s',+ (text) => {+ expect(detectGroupTrigger(msg({ text }), BOT_ID, BOT_USERNAME, 'Cindy')).toBeNull();+ expect(+ detectGroupTrigger(msg({ text: undefined, caption: text }), BOT_ID, BOT_USERNAME, 'Cindy'),+ ).toBeNull();+ },+ );++ it.each(['@CindyOther', '@Cindy_bot', '@Cindy2'])('提及以显示名开头的其它账号不触发:%s', (text) => {+ expect(detectGroupTrigger(msg({ text }), BOT_ID, BOT_USERNAME, 'Cindy')).toBeNull();+ });++ it('保留显式 @显示名的兼容入口', () => {+ expect(detectGroupTrigger(msg({ text: '@Cindy 帮我看看' }), BOT_ID, BOT_USERNAME, 'Cindy'))+ .toEqual({ text: '帮我看看' });+ });+it('@bot 提及触发并剥掉提及', () => {const m = msg({text: `@${BOT_USERNAME} 部署一下`,diff --git a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts b/packages/lizi-im/src/telegram/__tests__/streamingText.test.tsindex e981c34e9a..1d359649f4 100644--- a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts@@ -86,6 +86,35 @@ function makeHarness(}describe('telegram streaming finalize — 新鲜终稿与 Rich 降级', () => {+ it.each(['', ' \n\t '])('空终稿 %j 不发送消息,并撤掉已有过程消息', async (text) => {+ const h = makeHarness();+ const handle = await startTelegramStreaming(h.deps, '工作中');+ await handle.finalize(text);+ await handle.finalize(text);+ expect(h.calls).toEqual(['send:工作中', 'delete:msg-1']);+ });++ it('未建过程消息的空终稿没有任何出站动作', async () => {+ const h = makeHarness();+ const handle = await startTelegramStreaming(h.deps);+ await handle.finalize('');+ expect(h.calls).toEqual([]);+ });++ it('没有文字但有图片的终稿仍发送附件', async () => {+ const uploadImages = vi.fn(async () => undefined);+ const h = makeHarness();+ const handle = await startTelegramStreaming({ ...h.deps, uploadImages });+ handle.addExtraImageAbsPath!('/tmp/telegram-test-image.png');+ await handle.finalize('');+ expect(uploadImages).toHaveBeenCalledWith(+ expect.any(String),+ ['abs:/tmp/telegram-test-image.png'],+ expect.objectContaining({ startIndex: 0 }),+ );+ expect(h.reposted.join('')).not.toContain('空回复');+ });+it('过程消息存在时终稿始终新发,随后才删除旧消息', async () => {const h = makeHarness();const handle = await startTelegramStreaming(h.deps, '⚙️ 工作中 · 3s');diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex e593dedce8..8e8d07e282 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -342,7 +342,7 @@ describe('TelegramIM', () => {expect(events[1]).toMatchObject({ senderId: 'g/-100200', text: '/nonsense extra args' });});- it('名字召唤: 手打 "@显示名" 与句首裸名字都触发(非 username), 句中提到不触发', async () => {+ it('手打 @显示名触发,只有名字无论句首还是句中都不触发', async () => {const events: IMMessageEvent[] = [];im.onMessage((e) => events.push(e));await connect();@@ -351,10 +351,11 @@ describe('TelegramIM', () => {groupMessage({ text: '@Cindy 你在?', fromId: 111, messageId: 30 }),groupMessage({ text: 'cindy 帮我看看这个', fromId: 222, messageId: 31 }),groupMessage({ text: '我问过 Cindy 了不用管', fromId: 111, messageId: 32 }),+ groupMessage({ text: '明确召唤', fromId: 111, messageId: 34, mentionBot: true }),]);await vi.waitFor(() => expect(events).toHaveLength(2));expect(events[0]).toMatchObject({ senderId: 'g/-100200', text: '你在?' });- expect(events[1]).toMatchObject({ senderId: 'g/-100200', text: '帮我看看这个' });+ expect(events[1]).toMatchObject({ senderId: 'g/-100200', text: '明确召唤' });});it('纯 @bot 无正文仍召唤一轮,单独传递 invoked', async () => {diff --git a/packages/lizi-im/src/telegram/inbound.ts b/packages/lizi-im/src/telegram/inbound.tsindex 69eecbcf24..9eed703c2d 100644--- a/packages/lizi-im/src/telegram/inbound.ts+++ b/packages/lizi-im/src/telegram/inbound.ts@@ -121,9 +121,7 @@ export function detectGroupTrigger(}const repliedToBot = m.reply_to_message?.from?.id === botId;if (!mentioned && !repliedToBot) {- // 名字召唤(OpenClaw 习惯, Chris 2026-07-30 实测踩坑): 显示名不是- // username, 手打 "@Ivy" 或开头喊 "Ivy ..." 不构成 Telegram mention,- // 但用户预期就是在叫 bot — 按显示名匹配补上这类召唤。+ // 兼容手打 @显示名;单纯聊到名字(即使在句首)不是召唤。const summoned = botName ? matchNameSummon(sourceText, botName) : null;if (summoned === null) return null;return { text: summoned };@@ -138,26 +136,17 @@ export function detectGroupTrigger(/*** 显示名召唤匹配:* - `@显示名` 任意位置(如 "@Ivy 你在?" — 大小写不敏感, 后面不能紧跟字母数字);- * - 裸显示名在**句首**且后跟分隔符/结尾(如 "Ivy 帮我看看" / "ivy?")。- * 句中出现名字(如 "我问过 Ivy 了")不算召唤 — 只是聊到它, 避免误触发。+ * 没有 @ 的显示名无论在句首、句中还是独占一条都不算召唤。* 命中后剥掉召唤 token;空正文由事件的 invoked 标记保留召唤事实。*/function matchNameSummon(sourceText: string, botName: string): string | null {const name = botName.trim();if (name.length < 2) return null;const esc = escapeRegExp(name);- const SEP = '[\\s,,。::、!!??~〜]';- const atRe = new RegExp(`@${esc}(?![\\w])`, 'gi');- const leadRe = new RegExp(`^\\s*${esc}(?=$|${SEP})`, 'i');- let cleaned: string | null = null;+ const atRe = new RegExp(`@${esc}(?![A-Za-z0-9_])`, 'gi');const atStripped = sourceText.replace(atRe, ' ');- if (atStripped !== sourceText) {- cleaned = atStripped;- } else if (leadRe.test(sourceText)) {- cleaned = sourceText.replace(leadRe, '').replace(new RegExp(`^${SEP}+`), '');- }- if (cleaned === null) return null;- const text = cleaned.replace(/[ \t]{2,}/g, ' ').trim();+ if (atStripped === sourceText) return null;+ const text = atStripped.replace(/[ \t]{2,}/g, ' ').trim();return text;}diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.tsindex f9e7730df3..deeb61eda4 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -920,6 +920,12 @@ export class TelegramIM extends BaseIM implements ChannelIM {async patchMarkdownCard(messageId: string, markdown: string): Promise<void> {const { chatId, messageId: nativeId } = decodeMessageId(messageId);+ if (!markdown.trim()) {+ await this.requireApi().call('deleteMessage', {+ chat_id: chatId, message_id: Number(nativeId),+ });+ return;+ }const { html } = markdownToTelegramHtml(markdown);await this.editHtml(chatId, nativeId, html, undefined);}diff --git a/packages/lizi-im/src/telegram/streamingText.ts b/packages/lizi-im/src/telegram/streamingText.tsindex 1300102627..314e9ced0a 100644--- a/packages/lizi-im/src/telegram/streamingText.ts+++ b/packages/lizi-im/src/telegram/streamingText.ts@@ -402,19 +402,6 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {// 重试再读它就会把终稿当成待清理的旧消息(见 carrierMessageId 的说明)。this.carrierMessageId ??= this.messageIdValue;const staleMessageId = this.carrierMessageId;- if (isNoReply(finalText)) {- // 惰性占位下通常从未发过消息(真零痕迹); 已建过程消息则尽力清掉。- this.lifecycle.cancel();- if (staleMessageId) {- try {- await this.deps.deleteMessage?.(staleMessageId);- } catch {- /* 删除失败(权限等)保留占位, 不抛错 */- }- }- return;- }-const imageUrls = this.deps.extractImageUrls(finalText);const chunks = this.deps.chunk(finalText);const firstChunk = chunks[0] ?? '';@@ -424,8 +411,16 @@ class TelegramStreamingTextHandle implements StreamingTextHandle {: imageUrls.length > 0 || this.extraImageAbsPaths.length > 0? IMAGE_ONLY_PLACEHOLDER: '';- if (seed === '') {+ if (isNoReply(finalText) || seed === '') {+ // 惰性占位下通常从未发过消息(真零痕迹); 已建过程消息则尽力清掉。this.lifecycle.cancel();+ if (staleMessageId) {+ try {+ await this.deps.deleteMessage?.(staleMessageId);+ } catch {+ /* 删除失败(权限等)保留占位, 不抛错 */+ }+ }return;}diff --git a/packages/lizi-im/src/wecom/__tests__/codec.test.ts b/packages/lizi-im/src/wecom/__tests__/codec.test.tsindex 4483a30767..1800c46472 100644--- a/packages/lizi-im/src/wecom/__tests__/codec.test.ts+++ b/packages/lizi-im/src/wecom/__tests__/codec.test.ts@@ -43,7 +43,7 @@ describe("WeCom markdown chunking", () => {});it("normalizes an empty final response", () => {- expect(chunkWecomMarkdown(" \r\n ")).toEqual(["✅ (本轮无文本输出)"]);+ expect(chunkWecomMarkdown(" \r\n ")).toEqual([]);});it("preserves code fences and line boundaries in long Markdown replies", () => {diff --git a/packages/lizi-im/src/wecom/__tests__/index.test.ts b/packages/lizi-im/src/wecom/__tests__/index.test.tsindex d088c408e8..9bdb58f61b 100644--- a/packages/lizi-im/src/wecom/__tests__/index.test.ts+++ b/packages/lizi-im/src/wecom/__tests__/index.test.ts@@ -249,6 +249,23 @@ describe("WecomIM routing and ownership", () => {expect(client.sendMessage).not.toHaveBeenCalled();});+ it.each([false, true])('empty final does not send a placeholder (passive=%s)', async (passive) => {+ const { host, secrets } = createHost();+ secrets.set('wecom-owner-user-id', 'owner');+ const client = new FakeClient();+ const im = new WecomIM(host, { clientFactory: () => client as never, now: () => 1_000 });+ await im.init();+ const frame = message({ id: 'm-empty', sender: 'owner', text: 'task' });+ client.emit('message.text', frame);+ await flush();+ if (passive) await im.beginReply('owner');+ await im.commitFinal({ userId: 'owner', text: ' \n ', terminal: 'done' });+ expect(client.sendMessage).not.toHaveBeenCalled();+ if (passive) expect(client.replyStream).toHaveBeenLastCalledWith(frame, expect.any(String), ' ', true);+ else expect(client.replyStream).not.toHaveBeenCalled();+ await im.dispose();+ });+it("keeps later inbound frames available while terminal attachments use active send", async () => {const { host, secrets } = createHost();secrets.set("wecom-owner-user-id", "owner");diff --git a/packages/lizi-im/src/wecom/codec.ts b/packages/lizi-im/src/wecom/codec.tsindex 2e1f27d357..6b26a48e7f 100644--- a/packages/lizi-im/src/wecom/codec.ts+++ b/packages/lizi-im/src/wecom/codec.ts@@ -38,7 +38,7 @@ export function decodeWecomLane(userId: string): WecomLane {export function chunkWecomMarkdown(source: string): string[] {const normalized = source.replace(/\r\n?/g, "\n").trim();- if (!normalized) return ["✅ (本轮无文本输出)"];+ if (!normalized) return [];if (Buffer.byteLength(normalized, "utf8") <= MAX_MESSAGE_BYTES) return [normalized];// UTF-8 uses at most three bytes per UTF-16 code unit. Include the reopeneddiff --git a/packages/lizi-im/src/wecom/index.ts b/packages/lizi-im/src/wecom/index.tsindex 52ef1f884c..04631b2c71 100644--- a/packages/lizi-im/src/wecom/index.ts+++ b/packages/lizi-im/src/wecom/index.ts@@ -462,7 +462,7 @@ export class WecomIM extends BaseIM implements TextChannelIM {.filter(Boolean).join("\n\n");const chunks = chunkWecomMarkdown(- visibleText || (attachments.length > 0 ? "📎 附件如下" : "_(空回复)_"),+ visibleText || (attachments.length > 0 ? "📎 附件如下" : ""),);await this.sendFinalChunks(output.userId, chunks);let failedAttachmentCount = 0;