Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 统一排队与处理状态表情并清理完成反馈 (#5417)
Dashebfe0a4f7ec6
diff --git a/apps/desktop/src/main/hook-control/__tests__/ackReactions.test.ts b/apps/desktop/src/main/hook-control/__tests__/ackReactions.test.tsindex ec73f219ee..e5498df201 100644--- a/apps/desktop/src/main/hook-control/__tests__/ackReactions.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/ackReactions.test.ts@@ -13,7 +13,7 @@ import {type HookMessage,type TelegramEmojiReactions,} from '@cindy/slack-hook-protocol';-import { EXPRESSIVE_DONE_POOL, EXPRESSIVE_ERROR_POOL } from '@cindy/im';+import { PROCESSING_REACTION_POOL, EXPRESSIVE_ERROR_POOL } from '@cindy/im';import { createAckReactions, type AckReactionTask } from '../ackReactions';@@ -67,7 +67,7 @@ function opOf(message: HookMessage): {}describe('官方 bot ack 表情', () => {- it('受理时打 👀, 收口时换 👍 —— 与个人 bot 的 minimal 档同语义', () => {+ it('受理时打 👀, 收口时撤销 —— 与个人 bot 的 minimal 档同语义', () => {const h = harness();h.reactions.onAccepted(TASK, h.send);h.reactions.onFinished(TASK, 'ok', h.send);@@ -77,17 +77,27 @@ describe('官方 bot ack 表情', () => {targetMessageId: '55',emoji: '👀',});- expect(opOf(h.sent[1]).action).toMatchObject({ emoji: '👍' });+ expect(opOf(h.sent[1]).action).toMatchObject({ emoji: '' });});- it('失败收口换 👎; 用户主动取消不算失败, 仍是 👍', () => {+ it('失败收口换 👎; 用户主动取消不算失败, 撤销表情', () => {const err = harness();err.reactions.onFinished(TASK, 'error', err.send);expect(opOf(err.sent[0]).action).toMatchObject({ emoji: '👎' });const cancelled = harness();cancelled.reactions.onFinished(TASK, 'cancelled', cancelled.send);- expect(opOf(cancelled.sent[0]).action).toMatchObject({ emoji: '👍' });+ expect(opOf(cancelled.sent[0]).action).toMatchObject({ emoji: '' });+ });++ it.each(PROCESSING_REACTION_POOL)('processing uses %s and completion clears it', (emoji) => {+ const index = PROCESSING_REACTION_POOL.indexOf(emoji);+ const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'minimal', () => index / 4);+ h.reactions.onAccepted(TASK, h.send);+ h.reactions.onStarted(TASK, h.send);+ h.reactions.onFinished(TASK, 'ok', h.send);+ expect(h.sent.map((m) => opOf(m).action.emoji)).toEqual(['👀', emoji, '']);+ expect(opOf(h.sent[1]).opId).toBe('req-1:processing');});it('幂等键由 requestId 派生 —— 断连重发不会重复打表情', () => {@@ -128,7 +138,7 @@ describe('官方 bot ack 表情', () => {expect(h.send).not.toHaveBeenCalled();});- it('minimal: 固定 👀 → 👍 / 👎', () => {+ it('minimal: 排队 👀,失败 👎', () => {const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'minimal');h.reactions.onAccepted(TASK, h.send);h.reactions.onFinished(TASK, 'error', h.send);@@ -136,14 +146,14 @@ describe('官方 bot ack 表情', () => {expect(opOf(h.sent[1]).action.emoji).toBe('👎');});- it('expressive: 终态取变体池, ack 仍是 👀 且正负池不串', () => {+ it('expressive: 成功撤销,失败取错误变体池', () => {// 生动档也不拿开场表情做文章 —— 与个人 bot 一致。正负分开是底线:// 成功不能随机出 👎 一类。const ok = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0.5);ok.reactions.onAccepted(TASK, ok.send);ok.reactions.onFinished(TASK, 'ok', ok.send);expect(opOf(ok.sent[0]).action.emoji).toBe('👀');- expect(EXPRESSIVE_DONE_POOL).toContain(opOf(ok.sent[1]).action.emoji);+ expect(opOf(ok.sent[1]).action.emoji).toBe('');const failed = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0.5);failed.reactions.onFinished(TASK, 'error', failed.send);@@ -160,11 +170,51 @@ describe('官方 bot ack 表情', () => {sent.push(m);return true;});- expect(opOf(sent[0]).action.emoji).toBe('👍');+ expect(opOf(sent[0]).action.emoji).toBe('');});});describe('断线与受限表情', () => {+ it.each(['minimal', 'expressive'] as const)('%s processing falls back once and never replays on reconnect', mode => {+ const h = harness([HOOK_FEATURE_MESSAGE_OPS], mode, () => 0.5);+ h.reactions.onAccepted(TASK, h.send);+ h.reactions.onStarted(TASK, h.send);+ h.reactions.onResult({ opId: 'req-1:processing', ok: false, error: 'REACTION_INVALID' }, () => h.send);+ expect(h.sent.map(m => opOf(m).action.emoji)).toEqual(['👀', '🤓', '👨💻']);+ expect(opOf(h.sent[2]).opId).toBe('req-1:processing-fallback');+ h.reactions.onResult({ opId: 'req-1:processing', ok: false, error: 'REACTION_INVALID' }, () => h.send);+ h.reactions.onResult({ opId: 'req-1:processing-fallback', ok: false, error: 'REACTION_INVALID' }, () => h.send);+ h.reactions.onReconnected(CONN, h.send);+ expect(h.sent).toHaveLength(3);+ h.reactions.onFinished(TASK, 'ok', h.send);+ expect(opOf(h.sent[3]).action.emoji).toBe('');+ });++ it.each(['ok', 'cancelled', 'error', 'teardown', 'reset', 'success', 'off'] as const)(+ 'does not apply a late processing fallback after %s', reason => {+ const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'minimal', () => 0.5);+ h.reactions.onStarted(TASK, h.send);+ if (reason === 'teardown') h.reactions.onAccountTeardown(() => h.send);+ else if (reason === 'reset') h.reactions.reset();+ else if (reason === 'success') h.reactions.onResult({ opId: 'req-1:processing', ok: true });+ else if (reason === 'off') h.setMode('off');+ else h.reactions.onFinished(TASK, reason, h.send);+ const count = h.sent.length;+ h.reactions.onResult({ opId: 'req-1:processing', ok: false, error: 'REACTION_INVALID' }, () => h.send);+ expect(h.sent).toHaveLength(count);+ },+ );++ it('does not retry a base processing emoji or an unsent variant', () => {+ for (const random of [0, 0.5]) {+ const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'minimal', () => random);+ h.reactions.onStarted(TASK, random === 0 ? h.send : () => false);+ const count = h.sent.length;+ h.reactions.onResult({ opId: 'req-1:processing', ok: false, error: 'REACTION_INVALID' }, () => h.send);+ expect(h.sent).toHaveLength(count);+ }+ });+it('终态送不出去 → 重连时补发, 不让消息永远挂着 👀', () => {const h = harness();const offline = vi.fn(() => false);@@ -174,7 +224,7 @@ describe('官方 bot ack 表情', () => {h.reactions.onReconnected(CONN, h.send);expect(h.sent).toHaveLength(2);- expect(opOf(h.sent[1]).action.emoji).toBe('👍');+ expect(opOf(h.sent[1]).action.emoji).toBe('');// 幂等键不变 —— 服务端据此去重, 补发不会打出第二个表情。expect(opOf(h.sent[1]).opId).toBe('req-1:final');});@@ -223,18 +273,18 @@ describe('官方 bot ack 表情', () => {// 群可以限制 available_reactions, 随机出的那款可能不在名单里。沿用旧// opId 会被服务端当成重复直接返回上一次的失败, 所以必须换键。const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0.5);- h.reactions.onFinished(TASK, 'ok', h.send);+ h.reactions.onFinished(TASK, 'error', h.send);const firstOpId = opOf(h.sent[0]).opId;h.reactions.onResult({ opId: firstOpId, ok: false, error: 'REACTION_INVALID' }, () => h.send);expect(h.sent).toHaveLength(2);- expect(opOf(h.sent[1]).action.emoji).toBe('👍');+ expect(opOf(h.sent[1]).action.emoji).toBe('👎');expect(opOf(h.sent[1]).opId).toBe('req-1:final-fallback');expect(opOf(h.sent[1]).opId).not.toBe(firstOpId);});it('基础款再被拒就认了 —— 不无限回落', () => {const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0.5);- h.reactions.onFinished(TASK, 'ok', h.send);+ h.reactions.onFinished(TASK, 'error', h.send);const firstOpId = opOf(h.sent[0]).opId;h.reactions.onResult({ opId: firstOpId, ok: false, error: 'x' }, () => h.send);h.reactions.onResult(@@ -246,7 +296,7 @@ describe('官方 bot ack 表情', () => {it('成功回执后出回落表 —— 不让跑完的任务长期占着内存', () => {const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0.5);- h.reactions.onFinished(TASK, 'ok', h.send);+ h.reactions.onFinished(TASK, 'error', h.send);h.reactions.onResult({ opId: 'req-1:final', ok: true, messageId: '55' }, () => h.send);// 出表后再来一条同 opId 的失败回执, 不该再触发回落。h.reactions.onResult({ opId: 'req-1:final', ok: false, error: 'x' }, () => h.send);@@ -356,7 +406,7 @@ describe('官方 bot ack 表情', () => {h.reactions.onAccountTeardown(() => h.send);expect(h.sent).toHaveLength(3);expect(opOf(h.sent[2]).opId).toBe('req-1:final'); // 同 opId, 服务端幂等- expect(opOf(h.sent[2]).action.emoji).toBe('👍');+ expect(opOf(h.sent[2]).action.emoji).toBe('');h.reactions.reset();});@@ -365,7 +415,7 @@ describe('官方 bot ack 表情', () => {// 本地表, 那一项永远收不了口。const h = harness([HOOK_FEATURE_MESSAGE_OPS], 'expressive', () => 0);h.reactions.onAccepted(TASK, h.send);- h.reactions.onFinished(TASK, 'ok', h.send);+ h.reactions.onFinished(TASK, 'error', h.send);// expressive 被群限制拒掉 → 回落基础款(此时回落发在待补发表里, 键是 :final-fallback)h.reactions.onResult({ opId: 'req-1:final', ok: false, messageId: null, error: 'REACTION_INVALID' },@@ -390,7 +440,7 @@ describe('官方 bot ack 表情', () => {for (let i = 0; i < 501; i += 1) {const task = { ...TASK, requestId: `bulk-${i}` };h.reactions.onAccepted(task, h.send);- h.reactions.onFinished(task, 'ok', h.send);+ h.reactions.onFinished(task, 'error', h.send);}// 第 0 条被淘汰出待收口表后, 它的回落记录也不能再触发回落发。const before = h.sent.length;@@ -415,7 +465,7 @@ describe('官方 bot ack 表情', () => {h.serverFeatures.set(CONN, [HOOK_FEATURE_MESSAGE_OPS]); // 快照到了h.reactions.onReconnected(CONN, h.send);expect(h.sent).toHaveLength(2);- expect(opOf(h.sent[1]).action.emoji).toBe('👍');+ expect(opOf(h.sent[1]).action.emoji).toBe('');});it('补发时又断了 → 留着下次重连再补, 不丢', () => {@@ -427,7 +477,7 @@ describe('官方 bot ack 表情', () => {expect(h.sent).toHaveLength(1);h.reactions.onReconnected(CONN, h.send);expect(h.sent).toHaveLength(2);- expect(opOf(h.sent[1]).action.emoji).toBe('👍');+ expect(opOf(h.sent[1]).action.emoji).toBe('');expect(opOf(h.sent[1]).opId).toBe('req-1:final');});diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.tsindex fe014d625e..98d5cd8214 100644--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts@@ -4705,8 +4705,8 @@ describe('官方 bot ack 表情(msg.op)', () => {await tick();expect(c.last('task.ack')?.payload).toMatchObject({ result: 'queued' });- // 两条各一次 👀: 立即受理的那条 + 排队的那条; 出队启动时不重复补发。- expect(reactionEmojis(c.sent)).toEqual(['👀', '👀']);+ // 第一条已经处理中,第二条仍显示排队。+ expect(reactionEmojis(c.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/), '👀']);});it('排队中被取消 → 👀 换成终态, 不永远挂着「在做」', async () => {@@ -4724,8 +4724,8 @@ describe('官方 bot ack 表情(msg.op)', () => {d.cancel('conn-1', 'to-cancel');await tick();- // 两条各打 👀, 被取消那条补一个终态 —— 用户主动停止不算失败, 仍是 👍。- expect(reactionEmojis(c.sent)).toEqual(['👀', '👀', '👍']);+ // 取消排队任务时清掉它的状态,不影响正在执行的任务。+ expect(reactionEmojis(c.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/), '👀', '']);});it('账号停用: 已打 👀 而终态没人发的任务, 停用时撤销那个 👀', async () => {@@ -4744,12 +4744,12 @@ describe('官方 bot ack 表情(msg.op)', () => {await tick();d.handleDispatch('conn-1', telegramDispatch({ requestId: 'queued' }), c.send);await tick();- expect(reactionEmojis(c.sent)).toEqual(['👀', '👀']); // 两条各一个在册+ expect(reactionEmojis(c.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/), '👀']); // 两条各一个在册const draining = d.deactivateAccount();await tick();// 两个 👀 都被撤销(空串), 没有任何一个被装成终态。- const after = reactionEmojis(c.sent).slice(2);+ const after = reactionEmojis(c.sent).slice(3);expect(after).toEqual(['', '']);// HookRunOutcome 只有 ok / error 两态, 取消由 dispatcher 侧改写。@@ -4766,7 +4766,7 @@ describe('官方 bot ack 表情(msg.op)', () => {d.setEmojiReactionsMode('minimal');d.handleDispatch('conn-1', telegramDispatch({ requestId: 'offline-final' }), online.send);await tick();- expect(reactionEmojis(online.sent)).toEqual(['👀']);+ expect(reactionEmojis(online.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/)]);d.onDisconnected('conn-1');fr.finish({ status: 'ok' });@@ -4775,7 +4775,7 @@ describe('官方 bot ack 表情(msg.op)', () => {const reconnected = collector();d.onConnected('conn-1', reconnected.send, [HOOK_FEATURE_MESSAGE_OPS]);await tick();- expect(reactionEmojis(reconnected.sent)).toEqual(['👍']);+ expect(reactionEmojis(reconnected.sent)).toEqual(['']);});it('老 server 没宣告 msg-op-v1 → 一帧 msg.op 都不发', async () => {@@ -4820,7 +4820,7 @@ describe('官方 bot ack 表情(msg.op)', () => {d.setEmojiReactionsMode('minimal');d.handleDispatch('conn-1', telegramDispatch({ requestId: 'hydrated' }), c.send);await tick();- expect(reactionEmojis(c.sent)).toEqual(['👀']);+ expect(reactionEmojis(c.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/)]);});it('账号切换后档位打回未知 —— 不拿上一位主人的选择顶上', async () => {@@ -4831,7 +4831,7 @@ describe('官方 bot ack 表情(msg.op)', () => {d.setEmojiReactionsMode('minimal');d.handleDispatch('conn-1', telegramDispatch({ requestId: 'first-owner' }), c.send);await tick();- expect(reactionEmojis(c.sent)).toEqual(['👀']);+ expect(reactionEmojis(c.sent)).toEqual(['👀', expect.stringMatching(/^(👨💻|🤔|🤓|✍)$/)]);const draining = d.deactivateAccount();fr.finish({ status: 'ok' });diff --git a/apps/desktop/src/main/hook-control/ackReactions.ts b/apps/desktop/src/main/hook-control/ackReactions.tsindex 6391ec47d4..2b8bf14489 100644--- a/apps/desktop/src/main/hook-control/ackReactions.ts+++ b/apps/desktop/src/main/hook-control/ackReactions.ts@@ -1,17 +1,6 @@-/**- * hook-control/ackReactions.ts — 官方 bot 的 ack 表情。- * ---------------------------------------------------------------------------- * 个人 Telegram bot 一直有这个动作: 收到消息先打 👀 表示「看到了, 在做」, 跑完- * 换成 👍 / 👎。官方 bot 没有 —— 用户在两个 bot 之间切换时, 这是最先被察觉的- * 差异之一(消息发出去后, 到第一条回复落地之前, 官方 bot 那边什么反馈都没有)。- *- * 补上它靠的是 msg.op(#1855 第二刀): 客户端说「给这条消息打这个表情」, 服务端- * 只做授权与执行。这也是 msg.op 的第一个真实使用点 —— 刻意挑了一个**纯增量、- * 失败无害**的动作打通链路: 表情没打上不影响任何消息、任何任务。- *- * 幂等键直接用 requestId 派生(`<requestId>:ack` / `<requestId>:final`)。断连- * 重发时同一个动作天然拿到同一个 opId, 不需要额外记账 —— Telegram 没有发送端- * 幂等键, opId 是服务端去重的唯一依据。+/** Official Telegram lifecycle feedback for servers that still execute desktop reactions.+ * New servers own this feedback; the same operations remain compatible with old servers.+ * Queue = eyes, processing = one work/thinking variant, success/cancel = clear.*/import {@@ -23,14 +12,14 @@ import {type TelegramEmojiReactions,} from '@cindy/slack-hook-protocol';import {- EXPRESSIVE_DONE_POOL,+ PROCESSING_REACTION_POOL,EXPRESSIVE_ERROR_POOL,pickExpressiveReaction,} from '@cindy/im';/** minimal 档 —— 与个人 bot 逐个对齐, 两个 bot 的表情语义不该各说各话。 */const ACK_EMOJI = '👀';-const OK_EMOJI = '👍';+const PROCESSING_EMOJI = '👨💻';const FAIL_EMOJI = '👎';export interface AckReactionTask {@@ -44,7 +33,9 @@ export interface AckReactionTask {export interface AckReactions {/** 任务被接下: 打 👀。 */onAccepted(task: AckReactionTask, send: (m: HookMessage) => boolean): void;- /** 任务收口: 换成 👍 / 👎。cancelled 与 ok 同档 —— 用户主动停止不是失败。 */+ /** 开始执行时随机选一个处理表情,不随进度刷新。 */+ onStarted(task: AckReactionTask, send: (m: HookMessage) => boolean): void;+ /** 任务完成或取消时撤销状态;失败保留错误表情。 */onFinished(task: AckReactionTask,status: 'ok' | 'error' | 'cancelled',@@ -132,7 +123,7 @@ export function createAckReactions(deps: {function react(task: AckReactionTask,- suffix: 'ack' | 'final' | 'final-fallback',+ suffix: 'ack' | 'processing' | 'processing-fallback' | 'final' | 'final-fallback',emoji: string,send: (m: HookMessage) => boolean,): ReactOutcome {@@ -206,12 +197,11 @@ export function createAckReactions(deps: {}}/**- * 可回落的终态表情: opId → 该轮的任务与成败。+ * 可回落的表情: opId → 该轮的任务与阶段。*- * 只有 expressive 档进这张表 —— 基础款 👍/👎 是 Telegram 的默认可用集, 被拒- * 也没有更基础的可退。+ * 处理中变体可回落一次;expressive 错误表情沿用原有终态回落规则。*/- const retryables = new Map<string, { task: AckReactionTask; failed: boolean }>();+ const retryables = new Map<string, { task: AckReactionTask; phase: 'processing' | 'error' }>();/*** 已经真的打出过 👀 的任务(requestId → 任务)。*@@ -224,6 +214,7 @@ export function createAckReactions(deps: {return {supports,onAccountTeardown(sendFor) {+ retryables.clear();// 终态在途(打出去了但回执没到): 尽力再发一次, opId 原样、服务端幂等。// 这一发之后就交给命运 —— 账号都没了, 没有下一次重连可等。for (const [opId, entry] of pendingFinals) {@@ -270,8 +261,8 @@ export function createAckReactions(deps: {// 之前断掉, 提前删掉就再也补不上了。opId 原样(可能是 :final-fallback),// 服务端按它去重。const outcome = reactWithOpId(entry.task, opId, entry.emoji, send);- if (outcome === 'sent' && modeOf() === 'expressive') {- retryables.set(opId, { task: entry.task, failed: entry.failed });+ if (outcome === 'sent' && entry.failed && entry.emoji !== '' && modeOf() === 'expressive') {+ retryables.set(opId, { task: entry.task, phase: 'error' });}}},@@ -280,30 +271,36 @@ export function createAckReactions(deps: {// 在重连后补上, 消息不会永远停在处理中。if (react(task, 'ack', ACK_EMOJI, send) === 'sent') acked.set(task.requestId, task);},+ onStarted(task, send) {+ const emoji = pickExpressiveReaction(PROCESSING_REACTION_POOL, random);+ if (react(task, 'processing', emoji, send) === 'sent') {+ acked.set(task.requestId, task);+ if (emoji !== PROCESSING_EMOJI) {+ retryables.set(`${task.requestId}:processing`, { task, phase: 'processing' });+ }+ }+ },onFinished(task, status, send) {+ // Late processing rejections must never resurrect status after completion.+ retryables.delete(`${task.requestId}:processing`);const failed = status === 'error';const mode = modeOf();const hadAck = acked.delete(task.requestId);// 任务跑到一半用户把表情关了: 没打过 👀 就什么都不做(用户要的就是「别打」),// 打过就必须收掉 —— 撤销(空串)而不是补一个终态, 否则等于无视用户的选择。if (mode === 'off' && !hadAck) return;- // expressive 只影响**终态**: ack 恒为 👀(与个人 bot 一致 —— 生动档也不- // 拿开场表情做文章), 正负池分开取, 成功不会随机出 👎 一类。- const emoji =- mode === 'off'- ? ''- : mode === 'expressive'- ? pickExpressiveReaction(failed ? EXPRESSIVE_ERROR_POOL : EXPRESSIVE_DONE_POOL, random)- : failed- ? FAIL_EMOJI- : OK_EMOJI;+ const emoji = mode === 'off' || !failed+ ? ''+ : mode === 'expressive'+ ? pickExpressiveReaction(EXPRESSIVE_ERROR_POOL, random)+ : FAIL_EMOJI;const opId = `${task.requestId}:final`;const outcome = react(task, 'final', emoji, send);// sent 与 failed 都要记: 前者只是进了本地 ws 缓冲, 服务端到底收没收到、// 执行没执行, 要等 msg.op.result。skipped 才是真的不需要收口。if (outcome !== 'skipped') rememberPendingFinal(opId, { task, emoji, failed });- if (outcome === 'sent' && mode === 'expressive') {- retryables.set(opId, { task, failed });+ if (outcome === 'sent' && failed && mode === 'expressive') {+ retryables.set(opId, { task, phase: 'error' });}},onResult(payload, sendFor) {@@ -314,15 +311,21 @@ export function createAckReactions(deps: {return;}const retry = retryables.get(payload.opId);+ retryables.delete(payload.opId);// 用这一轮自己记下的 connectionId 取发送函数 —— 不猜「当前哪条连接」。const send = retry !== undefined ? sendFor?.(retry.task.connectionId) : undefined;if (retry !== undefined && send !== undefined) {// 群可以限制 available_reactions —— expressive 随机出的那款可能不在名单// 里。回落基础款并换一个幂等键(服务端按 opId 去重, 沿用旧键会被当成重复// 直接返回上一次的失败)。只回落一次, 基础款再被拒就认了。- retryables.delete(payload.opId);pendingFinals.delete(payload.opId);- const fallback = retry.failed ? FAIL_EMOJI : OK_EMOJI;+ if (retry.phase === 'processing') {+ // Transient status is not replayed on reconnect. Only a live attempt+ // gets one base-emoji fallback, using its own idempotency key.+ react(retry.task, 'processing-fallback', PROCESSING_EMOJI, send);+ return;+ }+ const fallback = FAIL_EMOJI;const fallbackOpId = `${retry.task.requestId}:final-fallback`;log.info(`msg.op ${payload.opId} reaction rejected; retrying with the base emoji`);// 回落这一发同样要等它自己的回执, 所以接着进待收口表。@@ -330,7 +333,7 @@ export function createAckReactions(deps: {rememberPendingFinal(fallbackOpId, {task: retry.task,emoji: fallback,- failed: retry.failed,+ failed: true,});}return;diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.tsindex f138635232..e22a2318a1 100644--- a/apps/desktop/src/main/hook-control/dispatcher.ts+++ b/apps/desktop/src/main/hook-control/dispatcher.ts@@ -1722,6 +1722,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {}function startExecution(task: PendingTask): void {+ ackReactions.onStarted(ackTaskOf(task), sendFns.get(task.connectionId) ?? OFFLINE_SEND);const promise = execute(task);executing.add(promise);void promise.finally(() => executing.delete(promise));diff --git a/apps/desktop/src/main/im/dingtalk/adapter.ts b/apps/desktop/src/main/im/dingtalk/adapter.tsindex 89a10eaa3a..6fdd1ca551 100644--- a/apps/desktop/src/main/im/dingtalk/adapter.ts+++ b/apps/desktop/src/main/im/dingtalk/adapter.ts@@ -69,6 +69,7 @@ export function buildDingTalkAdapter(}),},processingEmoji: '',+ silentQueue: true,buildVendorOptions: (userId) => ({ dingtalkChatId: userId, source: 'dingtalk' }),handleTextInteraction: (userId, request, options) =>handleDingTalkTextInteraction(dingtalkIm, userId, request, options),diff --git a/apps/desktop/src/main/im/discord/__tests__/discordAdapter.test.ts b/apps/desktop/src/main/im/discord/__tests__/discordAdapter.test.tsindex f0533a5191..6b1e531ddb 100644--- a/apps/desktop/src/main/im/discord/__tests__/discordAdapter.test.ts+++ b/apps/desktop/src/main/im/discord/__tests__/discordAdapter.test.ts@@ -72,7 +72,8 @@ describe('discord ImChannelAdapter characterization', () => {it('title, generated title prefix, and processing emoji match Discord contract', () => {expect(adapter.sessions.defaultTitle('9876543210')).toBe('Discord · 543210');expect(adapter.sessions.generatedTitlePrefix).toBe('Discord · ');- expect(adapter.processingEmoji).toBe('👀');+ expect(adapter.processingEmoji).toBe('👨💻');+ expect(adapter.queuedEmoji).toBe('👀');});it('workingDir = userData/im-working-dir/discord-{appId}', () => {diff --git a/apps/desktop/src/main/im/discord/adapter.ts b/apps/desktop/src/main/im/discord/adapter.tsindex ea08fedc42..e198404fc2 100644--- a/apps/desktop/src/main/im/discord/adapter.ts+++ b/apps/desktop/src/main/im/discord/adapter.ts@@ -47,6 +47,7 @@ export function buildDiscordAdapter(}),},processingEmoji: PROCESSING_EMOJI,+ queuedEmoji: '👀',buildVendorOptions: (userId) => ({ discordChatId: userId, source: 'discord' }),};}diff --git a/apps/desktop/src/main/im/discord/uiText.ts b/apps/desktop/src/main/im/discord/uiText.tsindex 6c421dd462..5b7cd9c2d3 100644--- a/apps/desktop/src/main/im/discord/uiText.ts+++ b/apps/desktop/src/main/im/discord/uiText.ts@@ -189,4 +189,4 @@ export const ui = {},} satisfies ImUiTextPack;-export const PROCESSING_EMOJI = '👀';+export const PROCESSING_EMOJI = '👨💻';diff --git a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.tsindex cb35cbeaad..ce852638f5 100644--- a/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts+++ b/apps/desktop/src/main/im/feishu/__tests__/feishuAdapter.test.ts@@ -186,9 +186,9 @@ describe('feishu ImChannelAdapter characterization', () => {});});- it('默认 title 为 [飞书·DM] {openId 后 6 位}; ack emoji 为 SMUG', () => {+ it('默认 title 为 [飞书·DM] {openId 后 6 位}; ack emoji 为 Typing', () => {expect(adapter.sessions.defaultTitle('ou_1234567890')).toBe('[飞书·DM] 567890');- expect(adapter.processingEmoji).toBe('SMUG');+ expect(adapter.processingEmoji).toBe('Typing');});it('会话落「对话」分组(workspaceKind=dialogue) + oneshot 起名前缀 [飞书·DM]', () => {diff --git a/apps/desktop/src/main/im/feishu/adapter.ts b/apps/desktop/src/main/im/feishu/adapter.tsindex 96ca924811..648204a05e 100644--- a/apps/desktop/src/main/im/feishu/adapter.ts+++ b/apps/desktop/src/main/im/feishu/adapter.ts@@ -338,6 +338,7 @@ export function buildFeishuAdapter(},},processingEmoji: REACTION_PROCESSING,+ queuedEmoji: 'OneSecond',buildVendorOptions: (userId) => ({ feishuChatId: userId, source: 'feishu' }),// 群轮次(speaker 存在)统一挂强确认策略 — 群历史前缀携带成员可控文本,diff --git a/apps/desktop/src/main/im/feishu/uiText.ts b/apps/desktop/src/main/im/feishu/uiText.tsindex 35f6e46d28..2aaca0fca7 100644--- a/apps/desktop/src/main/im/feishu/uiText.ts+++ b/apps/desktop/src/main/im/feishu/uiText.ts@@ -256,5 +256,5 @@ export const ui = {// owned by the streaming-card subsystem there, not duplicated in host.} satisfies ImUiTextPack;-/** Feishu emoji_type for "I see this" reaction (most ack-friendly). */-export const REACTION_PROCESSING = 'SMUG';+/** Feishu native processing marker; the transport selects a work/thinking variant. */+export const REACTION_PROCESSING = 'Typing';diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex 70471e8746..16e08e84fe 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -2362,6 +2362,185 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ());});+ describe('queued message reactions', () => {+ beforeEach(() => {+ runner = createTurnRunner(+ {+ ...fakeAdapter,+ processingEmoji: '👨💻',+ queuedEmoji: '👀',+ terminalReactionEmoji: (kind) => (kind === 'error' ? '👎' : null),+ },+ fakeRepo,+ fakeCards,+ );+ mocks.feishuIm.reactToMessage.mockImplementation(async (_id: string, emoji: string) => emoji);+ });++ it('replaces waiting with processing then clears it without posting a queue notice or success reaction', async () => {+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn();+ await waitForAssertion(() => {+ expect(mocks.feishuIm.reactToMessage).toHaveBeenLastCalledWith('msg-user', '👀');+ });+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();++ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => {+ expect(h.send).toHaveBeenCalledTimes(1);+ expect(mocks.feishuIm.reactToMessage).toHaveBeenLastCalledWith('msg-user', '👨💻');+ });+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', '👀');++ mocks.feishuIm.removeMessageReaction.mockClear();+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => {+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', '👨💻');+ });+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalledWith('msg-user', '👍');+ });++ it.each(['done', 'stop'] as const)('retains a failed queue-reaction removal for %s cleanup', async terminal => {+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn();+ await waitForAssertion(() => expect(mocks.feishuIm.reactToMessage).toHaveBeenLastCalledWith('msg-user', '👀'));+ mocks.feishuIm.reactToMessage.mockClear();+ mocks.feishuIm.removeMessageReaction.mockClear();+ mocks.feishuIm.removeMessageReaction.mockRejectedValueOnce(new Error('delete failed'));+ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => {+ expect(h.send).toHaveBeenCalledTimes(1);+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', '👀');+ });+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalled();+ if (terminal === 'stop') {+ await getRunner().stopActiveTurn({ botContextId: 'cli_test_bot', userId: 'ou_user' });+ expect(h.abort).toHaveBeenCalledTimes(1);+ }+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledTimes(2));+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenLastCalledWith('msg-user', '👀');+ });++ it.each(['stop', 'dispose'] as const)(+ 'cleans a late waiting reaction on %s',+ async (operation) => {+ const waiting = deferred<string>();+ mocks.feishuIm.reactToMessage.mockImplementation(async (_id: string, emoji: string) =>+ emoji === '👀' ? waiting.promise : emoji,+ );+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn();+ await waitForAssertion(() => {+ expect(mocks.feishuIm.reactToMessage).toHaveBeenCalledWith('msg-user', '👀');+ });+ const cleanup =+ operation === 'stop'+ ? getRunner().stopActiveTurn({ botContextId: 'cli_test_bot', userId: 'ou_user' })+ : getRunner().disposeAllSessions();+ await flushMicrotasks();+ waiting.resolve('late-waiting');+ await cleanup;+ await waitForAssertion(() => {+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith(+ 'msg-user',+ 'late-waiting',+ );+ });+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalledWith('msg-user', '👍');+ },+ );++ it('does not restore waiting when the initial ack arrives after dispatch and completion', async () => {+ const ack = deferred<string>();+ mocks.feishuIm.reactToMessage.mockReturnValueOnce(ack.promise);+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ const completed = vi.fn();+ await runDefaultTurn(completed);+ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(h.send).toHaveBeenCalledTimes(1));+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(completed).toHaveBeenCalledTimes(1));+ ack.resolve('👨💻');+ await waitForAssertion(() => {+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', '👨💻');+ });+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalledWith('msg-user', '👍');+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalledWith('msg-user', '👀');+ });++ it('silently queues transports without retractable feedback and still dispatches later', async () => {+ runner = createTurnRunner({ ...fakeAdapter, processingEmoji: '', silentQueue: true }, fakeRepo, fakeCards);+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn();+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(h.send).toHaveBeenCalledTimes(1));+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ });++ it('does not fall back to a permanent queue notice when the message id is unavailable', async () => {+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn(vi.fn(), { userMessageId: '' });+ expect(h.send).not.toHaveBeenCalled();+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ });++ it('stays quiet when reactions are disabled or rejected', async () => {+ mocks.feishuIm.reactToMessage.mockResolvedValue(null);+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ await runDefaultTurn();+ await waitForAssertion(() => {+ expect(mocks.feishuIm.reactToMessage).toHaveBeenCalledWith('msg-user', '👀');+ });+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(h.send).toHaveBeenCalledTimes(1));+ h.emit({ type: 'done', data: {} });+ });++ it('returns to waiting after a dispatch race and removes it on a later dispatch failure', async () => {+ const busy = Object.assign(new Error('busy'), { code: 'SESSION_RUNNING' });+ const h = setupSession(async () => ({ accepted: true }));+ h.isTurnRunning.mockReturnValue(true);+ h.send.mockRejectedValueOnce(busy).mockRejectedValueOnce(new Error('startup failed'));+ const completed = vi.fn();+ await runDefaultTurn(completed);+ await waitForAssertion(() => {+ expect(mocks.feishuIm.reactToMessage).toHaveBeenLastCalledWith('msg-user', '👀');+ });+ mocks.feishuIm.reactToMessage.mockClear();+ h.isTurnRunning.mockReturnValue(false);+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => {+ expect(h.send).toHaveBeenCalledTimes(1);+ expect(mocks.feishuIm.reactToMessage).toHaveBeenLastCalledWith('msg-user', '👀');+ });+ expect(completed).not.toHaveBeenCalled();+ h.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(completed).toHaveBeenCalledTimes(1));+ expect(h.send).toHaveBeenCalledTimes(2);+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', '👀');+ expect(mocks.feishuIm.reactToMessage).not.toHaveBeenCalledWith('msg-user', '👍');+ expect(mocks.feishuIm.sendMarkdownText).not.toHaveBeenCalled();+ });+ });+it('queues a second message while the first turn is running and dispatches it after done', async () => {mocks.feishuIm.reactToMessage.mockImplementation(async (messageId: string) => `reaction-${messageId}`,diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex 8eca35c9e2..4c619f7225 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -1179,6 +1179,9 @@ export function createTurnRunner(// 过程区耗时基准取真实派发时刻 — TurnState 创建时可能还要在 sendQueue 里// 等上一轮跑完, 排队等待不该计入"第 N 步 · 耗时"显示item.turn.presenter.activity.startedAt = Date.now();+ if (item.notified && adapter.queuedEmoji) {+ replaceAckReaction(item.turn, adapter.processingEmoji);+ }state.queue.push(item.turn);log.info(`enqueued turn for session=${rowId.slice(-8)} queueDepth=${state.queue.length} pendingSends=${state.sendQueue.length}`,@@ -1671,12 +1674,18 @@ export function createTurnRunner(}, DISPATCH_RETRY_MS);}- /** 入队提示 — 每条消息只发一次(竞态 requeue 不重复提示)。失败 swallow。 */+ /** 入队反馈:表情跟随排队状态,文字提示每条消息只发一次。 */async function notifyQueuedPosition(userId: string,item: QueuedSend,position: number,): Promise<void> {+ if (adapter.silentQueue) return;+ if (adapter.queuedEmoji) {+ item.notified = true;+ replaceAckReaction(item.turn, adapter.queuedEmoji);+ return;+ }if (item.notified) return;item.notified = true;try {@@ -2253,6 +2262,31 @@ export function createTurnRunner(}}+ /** 复用 ack 句柄串接状态切换,迟到的表情仍由现有终态清理接管。 */+ function replaceAckReaction(turn: TurnState, emoji: string): void {+ const messageId = turn.userMessageId;+ if (!messageId) return;+ const previous = turn.ackReactionIdPromise;+ const next = Promise.resolve(previous)+ .catch(() => null)+ .then(async (reactionId) => {+ // 已被下一次状态切换或收口接管:把现有 token 交给接管者清理。+ if (turn.ackReactionIdPromise !== next) return reactionId;+ try {+ if (reactionId) await im.removeMessageReaction?.(messageId, reactionId);+ } catch {+ return reactionId;+ }+ if (turn.ackReactionIdPromise !== next) return null;+ try {+ return (await im.reactToMessage?.(messageId, emoji)) ?? null;+ } catch {+ return null;+ }+ });+ turn.ackReactionIdPromise = next;+ }+/*** 撤掉**调用方交进来的** ack 表情 —— 只用在 TurnState 还没建起来就 rejected* 的路径上(missing_auth)。那个表情是调用方在 dispatch 之前打的, 这里不撤就diff --git a/apps/desktop/src/main/im/shared/types.ts b/apps/desktop/src/main/im/shared/types.tsindex 0f0ec973cf..0abc0f51f9 100644--- a/apps/desktop/src/main/im/shared/types.ts+++ b/apps/desktop/src/main/im/shared/types.ts@@ -151,11 +151,14 @@ export interface ImChannelAdapter {config: ImOrchestratorConfig;ui: ImUiTextPack;sessions: ImSessionNamespace;- /** "已收到" ack 的 emoji(feishu: emoji_type 枚举名;slack: emoji 名)。 */+ /** 处理中表情的基础款(Feishu 使用原生 emoji_type 名)。 */processingEmoji: string;+ /** 用原消息表情表示排队,不另发排队提示;缺省保留文字提示。 */+ queuedEmoji?: string;+ /** 没有可撤销状态反馈的渠道静默排队,避免永久残留提示。 */+ silentQueue?: boolean;/**- * turn 终态时把 ack 表情替换成结果表情(官方 Telegram bot 习惯:- * 成功 👍 / 失败 👎)。返回 null = 该终态不放表情(按默认撤掉 ack);+ * turn 终态时可将状态替换为错误表情。返回 null = 该终态不放表情(撤掉 ack);* 缺省 = 全部按默认撤掉。仅真正跑过的 turn 生效, pre-dispatch 失败不放。*/terminalReactionEmoji?(kind: 'done' | 'aborted' | 'error'): string | null;diff --git a/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts b/apps/desktop/src/main/im/telegram/__tests__/adapter.test.tsindex 50fe1264f1..2fc8813c1b 100644--- a/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts+++ b/apps/desktop/src/main/im/telegram/__tests__/adapter.test.ts@@ -10,6 +10,12 @@ vi.mock('../behaviorStore', () => ({describe('Telegram group history access scope', () => {const adapter = buildTelegramAdapter({} as never, {} as never);+ it('clears successful and cancelled status reactions but retains an error signal', () => {+ expect(adapter.terminalReactionEmoji?.('done')).toBeNull();+ expect(adapter.terminalReactionEmoji?.('aborted')).toBeNull();+ expect(adapter.terminalReactionEmoji?.('error')).toBe('👎');+ });+it('saves the actual quoted text but excludes persona and technical instructions', async () => {const result = await adapter.prepareAgentTurnText?.({senderId: '123',diff --git a/apps/desktop/src/main/im/telegram/adapter.ts b/apps/desktop/src/main/im/telegram/adapter.tsindex b1f3b5aa76..4c6056c22c 100644--- a/apps/desktop/src/main/im/telegram/adapter.ts+++ b/apps/desktop/src/main/im/telegram/adapter.ts@@ -94,8 +94,10 @@ export function buildTelegramAdapter(}),},processingEmoji: PROCESSING_EMOJI,- // 官方 bot 的结果表情习惯: 成功 👍 / 失败 👎; 中止不放(撤回 👀 即可)。- terminalReactionEmoji: (kind) => (kind === 'done' ? '👍' : kind === 'error' ? '👎' : null),+ // 已收到、等待处理;开始执行后切换为 processingEmoji。+ queuedEmoji: '👀',+ // 正常完成由回复本身反馈,清除状态表情;失败保留提醒。+ terminalReactionEmoji: (kind) => (kind === 'error' ? '👎' : null),// /project: 从 Telegram 把当前会话切到 desktop 项目目录(bot 原生会话)。projectSwitching: true,buildVendorOptions: (userId) => ({ telegramChatId: userId, source: 'telegram' }),diff --git a/apps/desktop/src/main/im/telegram/uiText.ts b/apps/desktop/src/main/im/telegram/uiText.tsindex 33e4f334ff..2756a37cfb 100644--- a/apps/desktop/src/main/im/telegram/uiText.ts+++ b/apps/desktop/src/main/im/telegram/uiText.ts@@ -227,4 +227,4 @@ export const ui = {},} satisfies ImUiTextPack;-export const PROCESSING_EMOJI = '👀';+export const PROCESSING_EMOJI = '👨💻';diff --git a/apps/desktop/src/main/im/wecom/adapter.ts b/apps/desktop/src/main/im/wecom/adapter.tsindex ed06181cba..eeefe57177 100644--- a/apps/desktop/src/main/im/wecom/adapter.ts+++ b/apps/desktop/src/main/im/wecom/adapter.ts@@ -51,6 +51,7 @@ export function buildWecomAdapter(}),},processingEmoji: '',+ silentQueue: true,buildVendorOptions: (userId) => ({source: 'wecom',wecomConversationId: userId,diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex 0a44016c35..db863ac319 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -211,7 +211,13 @@ Hook 与本地 IM 共享消息级来源及上下文快照结构。本地所有| 3 | **终稿必达只有官方有** | 官方侧终稿先落盘、失败重试到送达或有界放弃(`xindong/cindy-server#348`)。个人 bot 的 `streamingText.finalize` 是进程内尽力而为,桌面进程挂掉那条终稿就没了。**两侧的「有界」各有一条明确边界、且不在同一层**:官方路径经桌面账本 `hook-control/requestLedger.ts`,客户端侧的投递时效是 `HOOK_TERMINAL_DELIVERY_TTL_MS ≈ 24h`,**规则无条件**——过线的终稿一律不再发出,不论是谁在要。覆盖的出口:持久出箱 `listPending`、ACK 退避重发、离线内存缓冲、ACK 缓冲的两个消费分支(`onConnected` 入口一次性清扫,含能力降级回落),以及 **server 显式重投**——那一支只回放 `task.ack` 后返回,不发终稿、也不把记录改回 `pending`。(重投一度有过 `origin='server-request'` 豁免,后被删除:它在持久记录里没有位置,每条路径都要手工传播,连续三轮 review 各找出一条漏掉的。)server 侧只丢掉一份它自己也已放弃发布的终稿——服务端 `OUTBOX_MAX_ATTEMPTS × OUTBOX_MAX_DELAY_MS ≈ 24h` 的发布放弃线与客户端刻意取同一个数,而结果总比请求更晚,所以它索取一份过线结果时自身 outbox 早已过放弃点;X 侧入口还另有 `x-hook-server` 的 `onMention` 陈旧守卫。**个人 bot 不经过这个账本**,既没有落盘也没有这条时效,它的边界就是「进程活着就尽力,挂了就没了」 | 待判:个人侧是否需要等价保障,还是接受「桌面挂了本来就没人在跑」。**注意两侧要判的不是同一件事**:官方已定「超过 24h 的终稿不再主动补发」,个人待定的是「要不要先落盘」 || 4 | 受保护群内容的隐私边界 | 个人侧已做(出站回流 fail-closed,任一分片带保护标即整条不回流)。官方侧是否等价**待核** | 待核 || 5 | 相册失败逐张回落 | 两侧都有实现,判据是否等价**待核** | 待核 |-| 6 | ack / 结果表情 | 两侧都有,判据(何时打、打什么、撤不撤)是否等价**待核** | 待核 |+| 6 | ack / 排队 / 结果表情 | 个人与官方 bot 都用 👀 表示排队;开始处理时从 👨💻 / 🤔 / 🤓 / ✍ 中随机选一个,两种开启档位均生效,不随进度轮换。正常完成和取消清除状态、不另加 👍;失败保留 👎(生动档沿用失败变体)。个人侧复用 `im/shared/turnRunner.ts` 的 ack 句柄,迟到回应由终态接管;官方新版 server 统一管理状态,鉴权后确认但不执行 Desktop 的自动 `:ack` / `:final` / `:final-fallback` 表情,`:processing` 只触发一次处理中状态,避免旧客户端重新加上 👍。表情关闭、ambient 或群不允许时静默;两种传输均为尽力反馈。 | 两仓配套实现。新版 server 可先发,旧 Desktop 的 accepted/首帧 progress 触发处理中;新版 Desktop 连旧 server 仍兼容 msg.op,但旧 server 的独立成功表情须升级 server 才能彻底消除。无协议字段、数据库或平台配置变更。 |++官方 Desktop 连旧 `msg-op-v1` server 时,处理中变体被拒后复用既有回落表,使用独立+`:processing-fallback` 幂等键尝试基础款 👨💻 一次;完成、取消或账号收口后丢弃迟到的+处理中回执,不在重连时补发处理中状态。新 server 成功确认 `:processing` 后不会触发此回落。+个人渠道切换表情时,删除失败向共享 turn runner 返回错误,保留旧 token 给终态再清理,+避免飞书/Discord 同时遗留旧排队表情和新处理中表情;最终清理仍是尽力而为。## 五、怎么用这张表diff --git a/packages/lizi-im/src/__tests__/processingReactions.test.ts b/packages/lizi-im/src/__tests__/processingReactions.test.tsnew file mode 100644index 0000000000..5ec649216f--- /dev/null+++ b/packages/lizi-im/src/__tests__/processingReactions.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { DiscordIM } from '../discord/index.js';+import { FeishuIM } from '../feishu/index.js';+import { TelegramIM } from '../telegram/index.js';+import * as feishuOutbound from '../feishu/outbound.js';++afterEach(() => vi.restoreAllMocks());++describe('processing reaction transport tokens', () => {+ it('propagates Discord and Telegram removal failures to the turn owner', async () => {+ const error = new Error('reaction removal failed');+ const discord = {+ fetchChannel: vi.fn(async () => ({ messages: { fetch: vi.fn(async () => ({+ reactions: { resolve: () => ({ users: { remove: vi.fn().mockRejectedValue(error) } }) },+ })) } })),+ gateway: { client: { user: { id: 'bot' } } },+ } as unknown as DiscordIM;+ await expect(DiscordIM.prototype.removeMessageReaction.call(discord, '123|456', '🤓')).rejects.toBe(error);+ const telegram = { api: { call: vi.fn().mockRejectedValue(error) } } as unknown as TelegramIM;+ await expect(TelegramIM.prototype.removeMessageReaction.call(telegram, '123|456')).rejects.toBe(error);+ });++ it.each(['👨💻', '🤔', '🤓', '✍'])(+ 'Discord removes the selected %s rather than the requested base emoji',+ async (emoji) => {+ const variants = ['👨💻', '🤔', '🤓', '✍'];+ vi.spyOn(Math, 'random').mockReturnValue(variants.indexOf(emoji) / 4);+ const remove = vi.fn();+ const resolve = vi.fn(() => ({ users: { remove } }));+ const react = vi.fn();+ const im = {+ fetchChannel: vi.fn(async () => ({+ messages: { fetch: vi.fn(async () => ({ react, reactions: { resolve } })) },+ })),+ gateway: { client: { user: { id: 'bot' } } },+ } as unknown as DiscordIM;+ const token = await DiscordIM.prototype.reactToMessage.call(im, '123|456', '👨💻');+ expect(react).toHaveBeenCalledWith(emoji);+ expect(token).toBe(emoji);+ await DiscordIM.prototype.removeMessageReaction.call(im, '123|456', token!);+ expect(resolve).toHaveBeenCalledWith(emoji);+ expect(remove).toHaveBeenCalledWith('bot');+ },+ );++ it.each(['Typing', 'THINKING', 'SMART', 'OnIt'])(+ 'Feishu uses native %s and removes its returned reaction id',+ async (emoji) => {+ const variants = ['Typing', 'THINKING', 'SMART', 'OnIt'];+ vi.spyOn(Math, 'random').mockReturnValue(variants.indexOf(emoji) / 4);+ const add = vi.spyOn(feishuOutbound, 'addReaction').mockResolvedValue('reaction-id');+ const remove = vi.spyOn(feishuOutbound, 'removeReaction').mockResolvedValue(undefined);+ const token = await FeishuIM.prototype.reactToMessage('message-id', 'Typing');+ expect(add).toHaveBeenCalledWith('message-id', emoji);+ await FeishuIM.prototype.removeMessageReaction('message-id', token!);+ expect(remove).toHaveBeenCalledWith('message-id', 'reaction-id');+ await FeishuIM.prototype.reactToMessage('message-id', 'OneSecond');+ expect(add).toHaveBeenLastCalledWith('message-id', 'OneSecond');+ },+ );+});diff --git a/packages/lizi-im/src/channelIM.ts b/packages/lizi-im/src/channelIM.tsindex 7437dfefeb..7bbf332377 100644--- a/packages/lizi-im/src/channelIM.ts+++ b/packages/lizi-im/src/channelIM.ts@@ -68,7 +68,7 @@ export interface TextChannelIM {*/reactToMessage?(messageId: string, emoji: string): Promise<string | null>;- /** 撤销 reactToMessage 加的回应;失败吞掉(清理是尽力而为)。 */+ /** 撤销回应;失败抛出供状态切换保留 token,终态调用方负责尽力清理。 */removeMessageReaction?(messageId: string, reactionToken: string): Promise<void>;// ── status ─────────────────────────────────────────────────────────────────diff --git a/packages/lizi-im/src/discord/index.ts b/packages/lizi-im/src/discord/index.tsindex 083ad46843..7035f6d052 100644--- a/packages/lizi-im/src/discord/index.ts+++ b/packages/lizi-im/src/discord/index.ts@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import { BaseIM } from '../BaseIM.js';+import { processingReaction } from '../processingReactions.js';import type { ChannelIM } from '../channelIM.js';import type {IMCardActionEvent,@@ -424,22 +425,19 @@ export class DiscordIM extends BaseIM implements ChannelIM {const { channelId, messageId: nativeMessageId } = decodeMessageId(messageId);const channel = await this.fetchChannel(channelId);const message = await channel.messages.fetch(nativeMessageId);- await message.react(emoji);- return emoji;+ const reaction = processingReaction(emoji);+ await message.react(reaction);+ return reaction;} catch {return null;}}async removeMessageReaction(messageId: string, reactionToken: string): Promise<void> {- try {- const { channelId, messageId: nativeMessageId } = decodeMessageId(messageId);- const channel = await this.fetchChannel(channelId);- const message = await channel.messages.fetch(nativeMessageId);- await message.reactions.resolve(reactionToken)?.users.remove(this.gateway.client?.user?.id);- } catch {- /* cleanup is best-effort */- }+ const { channelId, messageId: nativeMessageId } = decodeMessageId(messageId);+ const channel = await this.fetchChannel(channelId);+ const message = await channel.messages.fetch(nativeMessageId);+ await message.reactions.resolve(reactionToken)?.users.remove(this.gateway.client?.user?.id);}getStatus(): IMStatus {diff --git a/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.tsindex 839bad27b6..4189b83298 100644--- a/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/outboundFile.test.ts@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({createFile: vi.fn(),createImage: vi.fn(),+ deleteReaction: vi.fn(),createMessage: vi.fn(async () => ({ data: { message_id: 'om_sent' } })),}));@@ -16,7 +17,7 @@ vi.mock('@larksuiteoapi/node-sdk', () => ({im = {v1: {message: { create: mocks.createMessage },- messageReaction: { create: vi.fn(), delete: vi.fn() },+ messageReaction: { create: vi.fn(), delete: mocks.deleteReaction },image: { create: mocks.createImage },},file: { create: mocks.createFile },@@ -59,6 +60,21 @@ async function fileFixture(name: string, content: string): Promise<string> {return absPath;}+describe('Feishu reaction removal', () => {+ afterEach(() => outbound.unbindClient());++ it('propagates network and business failures, then permits successful cleanup', async () => {+ outbound.bindClient({ appId: 'cli_reaction_test', appSecret: 'secret', service: 'feishu' });+ const networkError = new Error('network unavailable');+ mocks.deleteReaction.mockRejectedValueOnce(networkError)+ .mockResolvedValueOnce({ code: 999, msg: 'rejected' })+ .mockResolvedValueOnce({ code: 0 });+ await expect(outbound.removeReaction('message-id', 'reaction-id')).rejects.toBe(networkError);+ await expect(outbound.removeReaction('message-id', 'reaction-id')).rejects.toThrow('code=999');+ await expect(outbound.removeReaction('message-id', 'reaction-id')).resolves.toBeUndefined();+ });+});+describe('Feishu parent-chat file reuse', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.tsindex 550466b4b4..9dc1542f47 100644--- a/packages/lizi-im/src/feishu/index.ts+++ b/packages/lizi-im/src/feishu/index.ts@@ -16,6 +16,7 @@*/import { BaseIM } from '../BaseIM.js';+import { processingReaction } from '../processingReactions.js';import type { ChannelIM } from '../channelIM.js';import type {IMHost,@@ -784,7 +785,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {* reasonable default.*/reactToMessage(messageId: string, emojiType: string): Promise<string | null> {- return outbound.addReaction(messageId, emojiType);+ return outbound.addReaction(messageId, processingReaction(emojiType));}/**diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex 659f77333c..e14e1cd052 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -1049,17 +1049,19 @@ export async function addReaction(messageId: string, emojiType: string): Promise/*** 撤销之前 addReaction 返回的 reaction_id 对应的表情。- * 失败 swallow,因为这是 ack 的清理动作,不应影响 turn 结束流程。+ * 失败向调用方抛出,让状态切换保留原 token;终态由编排层尽力清理。*/export async function removeReaction(messageId: string, reactionId: string): Promise<void> {- const log = getLog();try {- await ensureClient().im.v1.messageReaction.delete({+ const response = await ensureClient().im.v1.messageReaction.delete({path: { message_id: messageId, reaction_id: reactionId },});+ const rejected = feishuBusinessRejectReason(response);+ if (rejected) throw new Error(`removeReaction failed: ${rejected}`);} catch (err) {const msg = err instanceof Error ? err.message : String(err);- log.warn(`[feishu/outbound] removeReaction failed (non-fatal): ${msg}`);+ getLog().warn(`[feishu/outbound] removeReaction failed (non-fatal): ${msg}`);+ throw err;}}diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.tsindex 9ede48c670..9508adfc55 100644--- a/packages/lizi-im/src/index.ts+++ b/packages/lizi-im/src/index.ts@@ -56,6 +56,7 @@ export { TelegramIM, createTelegramIM } from './telegram/index.js';// expressive 档变体池 —— 官方 bot 的 ack 表情复用同一份, 两个 bot 的表情语义// 不该各说各话(#1855)。export {+ PROCESSING_REACTION_POOL,EXPRESSIVE_DONE_POOL,EXPRESSIVE_ERROR_POOL,pickExpressiveReaction,diff --git a/packages/lizi-im/src/processingReactions.ts b/packages/lizi-im/src/processingReactions.tsnew file mode 100644index 0000000000..19436a22a8--- /dev/null+++ b/packages/lizi-im/src/processingReactions.ts@@ -0,0 +1,14 @@+/** Processing variants shared by transports; select once when entering processing. */+export const PROCESSING_REACTION_POOL = ['👨💻', '🤔', '🤓', '✍'] as const;+// Feishu requires native emoji_type names rather than Unicode reactions.+const FEISHU_PROCESSING_REACTION_POOL = ['Typing', 'THINKING', 'SMART', 'OnIt'] as const;++export function processingReaction(emoji: string, random: () => number = Math.random): string {+ const pool =+ emoji === '👨💻'+ ? PROCESSING_REACTION_POOL+ : emoji === 'Typing'+ ? FEISHU_PROCESSING_REACTION_POOL+ : null;+ return pool === null ? emoji : pool[Math.floor(random() * pool.length)];+}diff --git a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.tsindex 9c35bd7d62..7e98a46258 100644--- a/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts+++ b/packages/lizi-im/src/telegram/__tests__/telegramIM.test.ts@@ -14,6 +14,7 @@ import type { IMCardActionEvent, IMHost, IMMessageEvent } from '../../types.js';import { TelegramApiError, type TelegramApiClient, type TgUpdate } from '../api.js';import { encodeCallbackData, encodeMessageId } from '../codec.js';import { TelegramIM, type TelegramGroupWindowEntry } from '../index.js';+import { PROCESSING_REACTION_POOL } from '../reactionPool.js';const BOT = { id: 999, is_bot: true, first_name: 'Cindy', username: 'my_cindy_bot' };const OWNER_ID = '111';@@ -1595,6 +1596,46 @@ describe('TelegramIM', () => {expect(api.calls.some((c) => c.method === 'deleteMyCommands')).toBe(true);});+ it('randomizes processing reactions quietly, keeps waiting fixed, and clears the actual variant', async () => {+ await connect();+ const random = vi.spyOn(Math, 'random');+ try {+ for (const [index, emoji] of PROCESSING_REACTION_POOL.entries()) {+ random.mockReturnValue((index + 0.5) / PROCESSING_REACTION_POOL.length);+ expect(await im.reactToMessage('111|5', '👨💻')).toBe(emoji);+ const sent = api.calls.filter((call) => call.method === 'setMessageReaction').at(-1)!;+ expect(sent.params.reaction).toEqual([{ type: 'emoji', emoji }]);+ expect(sent.params.is_big).toBeUndefined();+ }+ expect(await im.reactToMessage('111|5', '👀')).toBe('👀');+ await im.removeMessageReaction('111|5');+ expect(+ api.calls.filter((call) => call.method === 'setMessageReaction').at(-1)!.params.reaction,+ ).toEqual([]);+ } finally {+ random.mockRestore();+ }+ });++ it('falls back to the base processing reaction when the group rejects a random variant', async () => {+ await connect();+ const random = vi.spyOn(Math, 'random').mockReturnValue(0.999);+ try {+ api.failNextCall(+ 'setMessageReaction',+ new TelegramApiError('setMessageReaction', 400, 'REACTION_INVALID'),+ );+ expect(await im.reactToMessage('111|5', '👨💻')).toBe('👨💻');+ expect(+ api.calls+ .filter((call) => call.method === 'setMessageReaction')+ .map((call) => call.params.reaction),+ ).toEqual([[{ type: 'emoji', emoji: '✍' }], [{ type: 'emoji', emoji: '👨💻' }]]);+ } finally {+ random.mockRestore();+ }+ });+it('行为配置: emoji off 不放任何表情; DM replyQuote=first 首条回复挂回', async () => {await im.dispose();im = new TelegramIM(ctx.host, {@@ -1607,6 +1648,8 @@ describe('TelegramIM', () => {await connect();// emoji off: reactToMessage 直接返回 null, 不发 setMessageReactionexpect(await im.reactToMessage('111|5', '👍')).toBeNull();+ expect(await im.reactToMessage('111|5', '👨💻')).toBeNull();+ expect(await im.reactToMessage('111|5', '👀')).toBeNull();expect(api.calls.some((c) => c.method === 'setMessageReaction')).toBe(false);// DM replyQuote=first: 首条回复挂回触发消息, 第二条不挂api.pushUpdates([privateMessage('问个事', 111, 95)]);diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.tsindex 3bb66b32f2..517b587fc8 100644--- a/packages/lizi-im/src/telegram/index.ts+++ b/packages/lizi-im/src/telegram/index.ts@@ -57,6 +57,7 @@ import { TELEGRAM_PERSONAL_CAPABILITIES } from './presentationCapabilities.js';import {EXPRESSIVE_DONE_POOL,EXPRESSIVE_ERROR_POOL,+ PROCESSING_REACTION_POOL,pickExpressiveReaction,} from './reactionPool.js';import { startTelegramStreaming } from './streamingText.js';@@ -955,8 +956,11 @@ export class TelegramIM extends BaseIM implements ChannelIM {if (behavior.emojiReactions === 'off') return null;if (this.ambientTriggerIds.has(messageId)) return null; // ambient 全静默let effective = emoji;- if (behavior.emojiReactions === 'expressive') {- // 终态用变体池(生动档); ack(👀)保持稳重不随机。+ if (emoji === '👨💻') {+ // 每次开始处理选择一次,不随进度反复切换;排队 👀 保持固定。+ effective = pickExpressiveReaction(PROCESSING_REACTION_POOL);+ } else if (behavior.emojiReactions === 'expressive') {+ // 终态变体仍只在生动档启用。if (emoji === '👍') {effective = pickExpressiveReaction(EXPRESSIVE_DONE_POOL);} else if (emoji === '👎') {@@ -970,7 +974,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {chat_id: chatId,message_id: Number(nativeId),reaction: [{ type: 'emoji', emoji: value }],- // 终态表情放大动画; 过程 ack(👀)保持安静。+ // 终态表情放大动画;排队与处理中保持安静。...(isBig ? { is_big: true } : {}),});try {@@ -992,16 +996,12 @@ export class TelegramIM extends BaseIM implements ChannelIM {async removeMessageReaction(messageId: string): Promise<void> {const api = this.api;if (!api) return;- try {- const { chatId, messageId: nativeId } = decodeMessageId(messageId);- await api.call('setMessageReaction', {- chat_id: chatId,- message_id: Number(nativeId),- reaction: [],- });- } catch {- /* cleanup is best-effort */- }+ const { chatId, messageId: nativeId } = decodeMessageId(messageId);+ await api.call('setMessageReaction', {+ chat_id: chatId,+ message_id: Number(nativeId),+ reaction: [],+ });}getStatus(): IMStatus {diff --git a/packages/lizi-im/src/telegram/reactionPool.ts b/packages/lizi-im/src/telegram/reactionPool.tsindex 78fcc05992..e7d66568d3 100644--- a/packages/lizi-im/src/telegram/reactionPool.ts+++ b/packages/lizi-im/src/telegram/reactionPool.ts@@ -1,16 +1,19 @@/**- * telegram/reactionPool.ts — expressive 档 reaction 变体池(#1855 L1)。+ * telegram/reactionPool.ts — 处理中与 expressive 终态的 reaction 变体池。* ---------------------------------------------------------------------------* 生动档变体池的**单一客户端出处** — Telegram bot 可用标准 reaction 全集按语义* 分池(Chris: 能用的都随便用)。正/负分开是底线: 成功不能随机出 💩/🤡。选中* 表情在该群被限制时(available_reactions), setMessageReaction 会 400 — 调用方- * 回落基础款(👍/👎)重试一次。+ * 回落基础款(👨💻/👍/👎)重试一次。** emoji 档本身继续由各车道的 TelegramBehaviorConfig.emojiReactions 三字段直接- * 供给, L1 不为其带默认(#1855 replyQuote 勘误同源纪律): 本模块只提供 expressive- * 命中时的**变体池数据 + 选取原语**, 不做策略判定。+ * 供给, L1 不为其带默认(#1855 replyQuote 勘误同源纪律): 本模块只提供+ * **变体池数据 + 选取原语**, 不做策略判定。*/+/** 处理中随机选择工作、思考类表情;不混入排队、成功或失败信号。 */+export { PROCESSING_REACTION_POOL } from '../processingReactions.js';+/** expressive 终态(成功)变体池 — 35 款正向表情。 */export const EXPRESSIVE_DONE_POOL = ['👍', '❤', '🔥', '🥰', '👏', '😁', '🎉', '🤩', '🙏', '👌',