Skip to content

armgit / cindy

Public Imported from GitHub
0

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

refactor(im): extract shared TurnPresenter (#2034)

Chris Zhangc4594debbf7d
diff --git a/apps/desktop/src/main/hook-control/turnObserver.ts b/apps/desktop/src/main/hook-control/turnObserver.ts
index 1786cc48c0..b0b9e98614 100644
--- a/apps/desktop/src/main/hook-control/turnObserver.ts
+++ b/apps/desktop/src/main/hook-control/turnObserver.ts
@@ -23,21 +23,9 @@
import type { AgentEvent, TurnContinuationState } from '@cindy/maker-core';
import { isTerminalAgentErrorEvent } from '@cindy/maker-core';
-import {
- buildMessageRenderItems,
- type MessageRenderNormalizedMessage,
-} from '@cindy/maker-shared/message-render';
-import {
- createTurnActivity,
- markActivityWriting,
- pushThinkingStep,
- pushToolStep,
- renderActivity,
- setActivityNotice,
- setInteractionNotice,
-} from '../im/shared/turnActivity.js';
-import { overloadFailureNotice, turnRetryNotice } from '../im/shared/turnRetryNotice.js';
+import { createTurnPresenter } from '../im/shared/turnPresenter.js';
+import { overloadFailureNotice } from '../im/shared/turnRetryNotice.js';
/*
* ── 为什么这里**没有**整轮静默兜底 ──────────────────────────────────────────
@@ -64,75 +52,6 @@ import { overloadFailureNotice, turnRetryNotice } from '../im/shared/turnRetryNo
* 同一条不变量在两处判定, 弱的那处只会先开火。已删除。
*/
-/**
- * 进度快照节流(trailing-edge): 事件密集时最多每 1.5s 发一帧, 与 IM 流式卡的
- * chat.update 节流(1300ms)同量级 —— server 侧每帧一次 chat.update(Tier 3
- * ~50/min/频道), 这个间隔留有安全余量。
- */
-const PROGRESS_THROTTLE_MS = 1500;
-/** 无新事件时的低频刷新(过程区耗时行"第 N 步 · 42s"不冻结)。 */
-const PROGRESS_TICK_MS = 5000;
-/** 单帧快照长度上限: 头部截断 —— server 侧占位消息本就 3900 上限, 中间帧
- * 开头(过程区 + 正文起始)信息量最大, 收口后 turn.end 会带完整文本。 */
-const PROGRESS_SNAPSHOT_MAX_CHARS = 3800;
-
-/**
- * 进度快照发射器: 合成「过程区时间线 + 部分正文」并按 trailing-edge 节流回调。
- * 纯定时器逻辑, 不做 IO —— 真正的发送(turn.progress 帧)由调用方注入的
- * onProgress 承担。stop() 后不再发射(收口后的迟到事件被丢弃)。
- */
-function createProgressEmitter(
- emit: (text: string) => void,
- compose: () => string,
-): { schedule: () => void; ensureTicker: () => void; stop: () => void } {
- let lastEmitAt = 0;
- let lastEmittedText = '';
- let pending: NodeJS.Timeout | null = null;
- let ticker: NodeJS.Timeout | null = null;
- let stopped = false;
-
- const fire = (): void => {
- if (stopped) return;
- const text = compose();
- if (text.length === 0) return;
- const snapshot =
- text.length > PROGRESS_SNAPSHOT_MAX_CHARS
- ? `${text.slice(0, PROGRESS_SNAPSHOT_MAX_CHARS - 1)}…`
- : text;
- // The low-frequency activity ticker can fire while the user-visible
- // answer is unchanged. Do not spend provider API calls on identical
- // full snapshots (and, for Telegram, do not re-animate the same draft).
- if (snapshot === lastEmittedText) return;
- lastEmitAt = Date.now();
- lastEmittedText = snapshot;
- emit(snapshot);
- };
- const schedule = (): void => {
- if (stopped || pending !== null) return;
- const wait = Math.max(0, lastEmitAt + PROGRESS_THROTTLE_MS - Date.now());
- pending = setTimeout(() => {
- pending = null;
- fire();
- }, wait);
- pending.unref?.();
- };
- return {
- schedule,
- ensureTicker(): void {
- if (stopped || ticker !== null) return;
- ticker = setInterval(schedule, PROGRESS_TICK_MS);
- ticker.unref?.();
- },
- stop(): void {
- stopped = true;
- if (pending !== null) clearTimeout(pending);
- if (ticker !== null) clearInterval(ticker);
- pending = null;
- ticker = null;
- },
- };
-}
-
/** 观察器需要 session 的这几样东西(测试可注入最小假实现)。 */
export interface ObservableSession {
readonly id: string;
@@ -206,135 +125,13 @@ export function observeHookTurn(
deps: HookTurnObserverDeps,
): HookTurnObserver {
const { onProgress, onToolResult, onTurnTerminal, onSilentStopSettled, log } = deps;
- // 文本累积语义(2026-07-28 修订): translator 的 isFinal 是**逐条**
- // agent_message 的完成信号(每条完成都携带该条全文), 不是整个 turn 的
- // 终稿 —— 用它整体替换累积文本, 会让"先回一句 → 思考 → 终答"的多消息
- // turn 只剩最后被替换的那条(实踩: Telegram 群里最终答案丢失)。
- // 正确姿势: isFinal 把该条追加进已定稿段, 流式增量走尾部缓冲。
- // 定稿段**按消息切开存**(而不是直接拼成一个串): 完成态需要把消息边界
- // 投影给 buildMessageRenderItems。join('\n\n') 与此前的逐段拼接完全等价
- // (同一条消息的相邻块在入栈时已连拼, 段内不含分隔)。
- const finalizedSegments: string[] = [];
- /** finalizedSegments 在共享消息投影里的对应下标(同消息多 block 原位更新)。 */
- const finalizedRenderIndexes: number[] = [];
- let streamTail = '';
- let assistantText = '';
- /** 最近一次定稿段所属的 claude 消息标识(uuid, 缺失时退到 requestId)。 */
- let lastFinalUuid: string | undefined;
- const recomputeAssistantText = (): void => {
- const finalizedText = finalizedSegments.join('\n\n');
- // trim 只用于判空(纯空白尾巴不该拼出悬空分隔), 拼接用原文 ——
- // 首行缩进/换行是内容(markdown 代码块等), 不得被裁掉。
- const hasTail = streamTail.trim().length > 0;
- assistantText = hasTail
- ? finalizedText
- ? `${finalizedText}\n\n${streamTail}`
- : streamTail
- : finalizedText;
- };
- // 完成态正文不在 hook 自造一套「最后一段」启发式,而是把本轮事件投影成
- // maker-shared 的 normalized messages,交给桌面 / Mobile 共用的
- // buildMessageRenderItems 判定哪些过程文字折叠、哪些交付正文保持展开。
- const renderMessages: MessageRenderNormalizedMessage[] = [];
- const thinkingRenderIndexes = new Map<string, number>();
- const renderClockBase = Date.now();
- let renderSequence = 0;
- let currentTurnRenderStart = 0;
- const nextRenderIdentity = (prefix: string): { key: string; createdAt: string } => {
- const sequence = renderSequence++;
- return {
- key: `hook-${prefix}-${sequence}`,
- // 单个 observer 内只需要稳定顺序;用单调毫秒避免真实长 turn 被历史窗口
- // gap 规则误切成另一轮(这里本来就只观察同一轮及其自动续 turn)。
- createdAt: new Date(renderClockBase + sequence).toISOString(),
- };
- };
- const pushRenderMessage = (
- kind: MessageRenderNormalizedMessage['kind'],
- body: string,
- sourceExtra: Partial<MessageRenderNormalizedMessage['source']> = {},
- ): number => {
- const { key, createdAt } = nextRenderIdentity(kind);
- renderMessages.push({
- key,
- source: {
- id: key,
- clientId: key,
- role: kind === 'tool' ? 'tool_use' : kind,
- createdAt,
- ...sourceExtra,
- },
- kind,
- label: kind,
- body,
- createdAt,
- });
- return renderMessages.length - 1;
- };
- const pushFinalizedSegment = (segment: string, sameMessage: boolean): void => {
- if (sameMessage && finalizedSegments.length > 0) {
- const segmentIndex = finalizedSegments.length - 1;
- finalizedSegments[segmentIndex] += segment;
- const renderIndex = finalizedRenderIndexes[segmentIndex];
- const rendered = renderMessages[renderIndex];
- if (rendered) rendered.body = finalizedSegments[segmentIndex];
- return;
- }
- finalizedSegments.push(segment);
- finalizedRenderIndexes.push(pushRenderMessage('assistant', segment));
- };
- const finalizeStreamTail = (): void => {
- if (streamTail.trim().length === 0) return;
- pushFinalizedSegment(streamTail, false);
- streamTail = '';
- lastFinalUuid = undefined;
- recomputeAssistantText();
- };
- const sealCurrentTurn = (): void => {
- // 极端 adapter 路径可能只有增量没有 isFinal;done 仍是确定边界,此时把尾段
- // 物化成一条 assistant message,和桌面 main 在 done 前落最后正文同口径。
- finalizeStreamTail();
- for (let index = renderMessages.length - 1; index >= currentTurnRenderStart; index--) {
- const message = renderMessages[index];
- if (message.kind !== 'assistant' || message.body.trim().length === 0) continue;
- message.turnCompleted = true;
- break;
- }
- currentTurnRenderStart = renderMessages.length;
- // `turnCompleted` seal 之后,即使 provider 复用同一个上游 message id,
- // 下一 SDK turn 也必须从新的 assistant message 开始。
- lastFinalUuid = undefined;
- };
- const progressAssistantText = (): string => {
- if (streamTail.trim().length > 0) return streamTail;
- return finalizedSegments[finalizedSegments.length - 1] ?? '';
- };
- const finalAnswerText = (): string => {
- const visible = buildMessageRenderItems(renderMessages, { isSessionStreaming: false })
- .flatMap((item) =>
- item.type === 'message'
- && item.message.kind === 'assistant'
- && item.message.body.trim().length > 0
- ? [item.message.body]
- : [],
- )
- .join('\n\n');
- return visible.trim().length > 0 ? visible : assistantText;
- };
- // 进度快照(turn.progress 链路): 过程区时间线与 IM 流式卡同一套纯逻辑
- // (turnActivity), 合成规则同 composeStreamingView —— 有正文时过程区在
- // 上正文在下, done/error 后 stop, 不再发射。
- const activity = createTurnActivity(Date.now());
- const progress = onProgress
- ? createProgressEmitter(onProgress, () => {
- const act = renderActivity(activity, Date.now());
- // 运行中只展示当前 / 最后一条 assistant 消息。更早的旁白已经进入桌面
- // 同款「工作过程」语义,不能继续堆在 Slack 正文里随每帧重放。
- const currentText = progressAssistantText();
- if (!act) return currentText;
- return currentText ? `${act}\n\n${currentText}` : act;
- })
- : null;
+ // 呈现大脑(正文累积 / render 投影 / 过程区合成 / trailing-edge 快照)抽到
+ // im/shared/turnPresenter, 与个人 IM 渠道共用同一实现。这里用 finalized-segments
+ // 策略: isFinal 逐条契约、定稿段按消息切开、claude fallbackTail 自成段、uuid 缺失
+ // 退 requestId、完成态经 buildMessageRenderItems 折叠 —— #1272/#1636/#1703 的实踩
+ // 教训随代码留在该模块。收口(何时结束)刻意**不在** presenter: 见下面 done /
+ // silentStop / onStatusChange 三条出口, 只有它们能让本观察器 settle。
+ const presenter = createTurnPresenter({ mode: 'finalized-segments', onProgress });
let stopListening: (() => void) | undefined;
const finished = new Promise<void>((resolve, reject) => {
@@ -360,7 +157,7 @@ export function observeHookTurn(
pendingSettleUnsub = undefined;
pendingContinuationUnsub?.();
pendingContinuationUnsub = undefined;
- progress?.stop();
+ presenter.stopProgress();
off();
offStatus();
stopListening = undefined;
@@ -383,151 +180,38 @@ export function observeHookTurn(
});
const off = session.onEvent((ev: AgentEvent) => {
if (ev.type === 'text') {
- const data = ev.data as { text?: string; isFinal?: boolean } | null;
- if (data && typeof data.text === 'string') {
- if (data.isFinal) {
- // isFinal 形态按 translator 契约区分, 不做内容猜测(前缀
- // 启发式在"尾段恰好以已流增量开头"时会误判丢正文):
- // ① claude 块终稿(带 agentMeta): data.text 是该块全文, 覆盖
- // 已流增量; 同一条消息(同 uuid)的相邻文本块按原文连拼
- // (renderer 同款 raw concat), 不同消息之间空行分隔。
- // ② claude result 兜底 fallbackTail(刻意不带 agentMeta):
- // 只含 UI 缺的尾段, 与已流增量原样接上。
- // ③ codex item.completed / pi message_end:该条全文,覆盖已流增量。
- // ④ 未知 source: 保守用前缀启发式。
- const src = (ev as { source?: string }).source;
- const meta = (ev as { agentMeta?: { uuid?: unknown; requestId?: unknown } }).agentMeta;
- const claudeTail = src === 'claude-code' && meta === undefined;
- const segment = claudeTail
- ? streamTail + data.text
- : src === 'claude-code' || src === 'codex' || src === 'pi'
- ? data.text
- : data.text.startsWith(streamTail)
- ? data.text
- : streamTail + data.text;
- // 消息边界标识。uuid 是 envelope 顶层的可选字段, **确实会缺**
- // (extractAssistantMeta 允许它缺); 缺了就退到 requestId —— 那是
- // Anthropic 的 message id(`msg_...`), 同一条消息的各 text block 共享、
- // 不同消息不同, 正好是这里要的语义。
- //
- // 少了这道回退, 一条含多个 text block 的消息会被拆成多个"消息"。
- // finalText() 会按桌面消息语义识别正式正文; 不能因为某个渠道最终只
- // 允许一条消息, 就在这里把同一条消息的内容拆成「最后一段」。
- const messageId =
- src === 'claude-code'
- ? typeof meta?.uuid === 'string'
- ? meta.uuid
- : typeof meta?.requestId === 'string'
- ? meta.requestId
- : undefined
- : undefined;
- // claudeTail(claude result 的 fallbackTail)**自成一段**, 不并入上一条。
- //
- // 它刻意不带 agentMeta(translator 的原话: 补推文本是"孤儿正文",
- // 拿 lastAssistantMeta 当锚点会污染 fork/rewind), 所以 hook 层**拿不到
- // 它属于哪条消息** —— 这个歧义是结构性的, 不是这里少判了一个条件。
- //
- // 两种真实情形都存在, 从这里看完全一样:
- // ① 它续的是上一条(该消息有多个 block, 只流了前一个);
- // ② 它是**新的一条**: translator 明写覆盖"前面 call 推过旁白、最后
- // 一次 call 的最终回复被截断"(见 translator.ts 的 fallbackTail 注释)。
- //
- // 选 ②(自成一段)是因为两侧代价不对称: 按 ② 处理而实为 ① 时, X 发出
- // 的是尾段 —— 而尾段按构造就是整轮文本的**结尾**, 结论在里面; 按 ① 处理
- // 而实为 ② 时, 旁白会被粘进公开回帖一起发出去。何况 ② 才是 translator
- // 文档里点名的那个场景(PR #1272 review 指出, 推翻了上一版的无条件并入)。
- const sameMessage = messageId !== undefined && messageId === lastFinalUuid;
- pushFinalizedSegment(segment, sameMessage);
- lastFinalUuid = messageId;
- streamTail = '';
- } else {
- streamTail += data.text;
- }
- recomputeAssistantText();
- markActivityWriting(activity);
- progress?.schedule();
- }
+ // 正文累积(isFinal 逐条契约 / 定稿段按消息切开 / fallbackTail 自成段 /
+ // uuid 缺失退 requestId)都在 presenter 的 finalized-segments 策略里。
+ if (presenter.applyText(ev)) presenter.scheduleProgress();
return;
}
if (ev.type === 'thinking') {
- // Desktop 不把 thinking 当 assistant block 边界:同一条消息可以在
- // thinking 前后继续输出文字。这里只投影思考活动本身,不能 flush 正文。
- // 同一个 blockId 的 start/delta/final 原位更新,和 renderer 消息模型一致。
- const data = ev.data as {
- stage?: unknown;
- blockId?: unknown;
- text?: unknown;
- durationMs?: unknown;
- startedAt?: unknown;
- } | null;
- const blockId = typeof data?.blockId === 'string'
- ? data.blockId
- : `anonymous-${renderSequence}`;
- const content = data?.stage === 'redacted'
- ? { isRedacted: true }
- : {
- ...(typeof data?.text === 'string' ? { text: data.text } : {}),
- ...(typeof data?.durationMs === 'number' ? { durationMs: data.durationMs } : {}),
- };
- const existingIndex = thinkingRenderIndexes.get(blockId);
- if (existingIndex === undefined) {
- const renderIndex = pushRenderMessage('thinking', '', {
- clientId: blockId,
- content,
- ...(typeof data?.startedAt === 'number'
- ? { createdAt: new Date(data.startedAt).toISOString() }
- : {}),
- });
- thinkingRenderIndexes.set(blockId, renderIndex);
- } else {
- const rendered = renderMessages[existingIndex];
- if (rendered) rendered.source.content = content;
- }
- if (pushThinkingStep(activity, ev.data)) {
- progress?.ensureTicker();
- progress?.schedule();
+ // Desktop 不把 thinking 当 assistant block 边界: presenter 只投影思考活动
+ // 本身、不 flush 正文; pushThinkingStep 变化时才刷帧。
+ if (presenter.applyThinking(ev)) {
+ presenter.ensureProgressTicker();
+ presenter.scheduleProgress();
}
return;
}
if (ev.type === 'tool_use') {
// 过程展示: 与 IM 流式卡同款滚动时间线(turnActivity), 让 Slack 侧
- // 在长 agentic turn 里看到"正在干什么", 而不是盯着 👀 表情干等
- const data = ev.data as {
- toolName?: unknown;
- toolUseId?: unknown;
- input?: unknown;
- } | null;
- if (data && typeof data.toolName === 'string') {
- // tool_use 是明确的 assistant 消息边界,与桌面
- // messagePersistBroadcaster.flushAssistantBlock 同口径。
- finalizeStreamTail();
- lastFinalUuid = undefined;
- pushRenderMessage('tool', '', {
- toolName: data.toolName,
- toolInput: data.input,
- ...(typeof data.toolUseId === 'string' ? { toolUseId: data.toolUseId } : {}),
- });
- pushToolStep(
- activity,
- data.toolName,
- data.input,
- typeof data.toolUseId === 'string' ? data.toolUseId : undefined,
- );
- progress?.ensureTicker();
- progress?.schedule();
+ // 在长 agentic turn 里看到"正在干什么", 而不是盯着 👀 表情干等。
+ // tool_use 是明确的 assistant 消息边界(presenter 封存尾段并投影 tool 消息)。
+ if (presenter.applyToolUse(ev)) {
+ presenter.ensureProgressTicker();
+ presenter.scheduleProgress();
}
return;
}
if (ev.type === 'error' && !isTerminalAgentErrorEvent(ev)) {
// 非终止 error = agent 正在自愈(仅透已有本地化契约的自动重试)。turn 没
// 结束, 不收口; 但必须在过程区留一行, 否则零产出的退避窗口里渠道那
- // 条消息整段静止(见 turnRetryNotice.ts 的模块注释)。
- const notice = turnRetryNotice(ev.data);
- if (notice !== null && setActivityNotice(activity, notice)) {
- // ticker 让"第 N 步 · 42s"与这行状态一起走时间, 重试期间没有任何
- // 新事件也能看出还在动。
- progress?.ensureTicker();
- progress?.schedule();
+ // 条消息整段静止(见 turnRetryNotice.ts 的模块注释)。ticker 让
+ // "第 N 步 · 42s"与这行状态一起走时间, 重试期间没有任何新事件也能看出还在动。
+ if (presenter.applyRetryNotice(ev)) {
+ presenter.ensureProgressTicker();
+ presenter.scheduleProgress();
}
return;
}
@@ -550,7 +234,7 @@ export function observeHookTurn(
});
return;
}
- sealCurrentTurn();
+ presenter.seal();
// done 是 SDK turn 的权威完成事件;只有 provider 明确锁存了会自动
// 唤醒下一 turn 的任务时,它才是中间边界。agent_task_update 只是 UI
// 任务卡事件,Codex / Pi 子代理和 local_bash 都没有资格阻塞收口。
@@ -615,25 +299,23 @@ export function observeHookTurn(
markInteractionBoundary(): void {
// main 的任一 interaction 请求会先封存 assistant block,再落交互消息。
// 这只在请求首次出现时调用;剩余等待文案的切换不是新边界。
- finalizeStreamTail();
- lastFinalUuid = undefined;
- pushRenderMessage('system', '', { role: 'system', content: { kind: 'interaction' } });
+ presenter.markInteractionBoundary();
},
setNotice(notice: string | null): void {
// 走**独立**的等交互通道, 不是瞬态 notice: 后者会被 pushToolStep /
// pushThinkingStep / markActivityWriting 的 clearNotice 抹掉, 而挂起期间
// agent 的其它子任务照样在吐这些事件。
- if (!setInteractionNotice(activity, notice)) return;
+ if (!presenter.setInteractionNotice(notice)) return;
// ticker 让过程区的「第 N 步 · 42s」继续走时间: 等授权期间没有任何 agent
// 事件, 不续 ticker 那条消息会连耗时都冻住。
- progress?.ensureTicker();
- progress?.schedule();
+ presenter.ensureProgressTicker();
+ presenter.scheduleProgress();
},
text(): string {
- return assistantText;
+ return presenter.wholeText();
},
finalText(): string {
- return finalAnswerText();
+ return presenter.finalText();
},
};
}
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnPresenter.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnPresenter.test.ts
new file mode 100644
index 0000000000..b04252fce7
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/turnPresenter.test.ts
@@ -0,0 +1,571 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { TELEGRAM_PERSONAL_CAPABILITIES } from '@cindy/im';
+import type { AgentEvent } from '@cindy/maker-core';
+
+import {
+ composeProgressView,
+ createProgressEmitter,
+ createTurnPresenter,
+ DEFAULT_PRESENTER_POLICY,
+ PERSONAL_DRIVER_CAPABILITIES,
+ PROGRESS_SNAPSHOT_MAX_CHARS,
+ PROGRESS_THROTTLE_MS,
+ progressDedupeBaseline,
+ shouldEmitProgressFrame,
+} from '../turnPresenter';
+
+/** 造一个 text 事件(带可选 source / agentMeta), 保持与 translator 透出的形状一致。 */
+function text(
+ body: string,
+ isFinal: boolean,
+ extra: { source?: string; agentMeta?: { uuid?: string; requestId?: string } } = {},
+): AgentEvent {
+ return { type: 'text', data: { text: body, isFinal }, ...extra } as unknown as AgentEvent;
+}
+
+function toolUse(toolName: string, toolUseId: string): AgentEvent {
+ return { type: 'tool_use', data: { toolName, toolUseId, input: {} } } as unknown as AgentEvent;
+}
+
+describe('composeProgressView — 过程区/正文合成骨架(两侧共用)', () => {
+ it('有过程区时过程区在上、正文在下', () => {
+ expect(composeProgressView('⚙️ 工作中', '答案')).toBe('⚙️ 工作中\n\n答案');
+ });
+ it('无过程区时只留正文', () => {
+ expect(composeProgressView('', '答案')).toBe('答案');
+ });
+ it('有过程区、无正文时只留过程区', () => {
+ expect(composeProgressView('⚙️ 工作中', '')).toBe('⚙️ 工作中');
+ });
+});
+
+describe('createTurnPresenter — buffer-replace 策略(个人 IM 渠道现有行为)', () => {
+ it('isFinal 用该条全文整体替换缓冲, 流式增量追加', () => {
+ const p = createTurnPresenter({ mode: 'buffer-replace' });
+ p.applyText(text('前半', false));
+ p.applyText(text('前半后半', true));
+ p.applyText(text(',继续', false));
+ expect(p.wholeText()).toBe('前半后半,继续');
+ // buffer 模式下 finalText / progressBody 都是整段缓冲。
+ expect(p.finalText()).toBe('前半后半,继续');
+ expect(p.progressBody()).toBe('前半后半,继续');
+ });
+
+ it('applyText 对非字符串 text 返回 false, 不落正文', () => {
+ const p = createTurnPresenter({ mode: 'buffer-replace' });
+ expect(p.applyText({ type: 'text', data: {} } as unknown as AgentEvent)).toBe(false);
+ expect(p.wholeText()).toBe('');
+ });
+
+ it('replaceBody 整体替换(本地图片物化回写 / 收口重置)', () => {
+ const p = createTurnPresenter({ mode: 'buffer-replace' });
+ p.applyText(text('原文', true));
+ p.replaceBody('物化后的文本');
+ expect(p.wholeText()).toBe('物化后的文本');
+ p.replaceBody('');
+ expect(p.wholeText()).toBe('');
+ });
+
+ it('seal / markInteractionBoundary 在 buffer 模式下不改变正文(无消息边界切分)', () => {
+ const p = createTurnPresenter({ mode: 'buffer-replace' });
+ p.applyText(text('结论', true));
+ // buffer 模式没有定稿段/render 投影, seal 与交互边界都是正文层面的 no-op。
+ p.seal();
+ p.markInteractionBoundary();
+ expect(p.wholeText()).toBe('结论');
+ expect(p.finalText()).toBe('结论');
+ // 注: turnRunner 的事件分发对 thinking 直接 return, 从不把 thinking 路由给
+ // presenter —— 故 buffer 模式的正文永远不受 thinking 影响。
+ });
+});
+
+describe('createTurnPresenter — finalized-segments 策略(官方 bot 现有行为)', () => {
+ it('isFinal 逐条追加进已定稿段, 不整体替换; 多消息 turn 的正文全部保留', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('先回一句。', true, { source: 'codex' }));
+ p.applyText(text('最终结论。', true, { source: 'codex' }));
+ // wholeText 保留两段(整段拼接), 不会只剩最后一条。
+ expect(p.wholeText()).toBe('先回一句。\n\n最终结论。');
+ });
+
+ it('progressBody 只展示当前 / 最后一条消息, 而非整轮', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('第一段。', true, { source: 'codex' }));
+ p.applyText(text('第二段。', true, { source: 'codex' }));
+ expect(p.progressBody()).toBe('第二段。');
+ });
+
+ it('claude 同一条消息(同 uuid)的相邻文本块连拼, 不同消息空行分隔', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('前半', true, { source: 'claude-code', agentMeta: { uuid: 'm1' } }));
+ p.applyText(text('后半。', true, { source: 'claude-code', agentMeta: { uuid: 'm1' } }));
+ p.applyText(text('第二条。', true, { source: 'claude-code', agentMeta: { uuid: 'm2' } }));
+ p.seal();
+ expect(p.finalText()).toBe('前半后半。\n\n第二条。');
+ });
+
+ it('envelope 缺 uuid 时按 requestId 认消息边界', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('结论: 分两块。', true, { source: 'claude-code', agentMeta: { requestId: 'msg_b' } }));
+ p.applyText(text('第二块同一条。', true, { source: 'claude-code', agentMeta: { requestId: 'msg_b' } }));
+ p.seal();
+ // 同 requestId → 同一条消息, 两块连拼成一段。
+ expect(p.wholeText()).toBe('结论: 分两块。第二块同一条。');
+ });
+
+ it('claude result 的 fallbackTail(无 agentMeta)与已流增量原样接上, 不误判前缀', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('最终答案是 4', false)); // 流式增量
+ p.applyText(text('2。', true, { source: 'claude-code' })); // fallbackTail: 只含缺失尾段
+ p.seal();
+ expect(p.wholeText()).toContain('最终答案是 42。');
+ expect(p.wholeText()).not.toContain('4\n\n2');
+ });
+
+ it('finalText 按桌面消息流折叠动作前的短旁白, 保留动作后的正式答复', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ p.applyText(text('我先看看这个链接。', true, { source: 'claude-code', agentMeta: { uuid: 'a' } }));
+ p.applyToolUse(toolUse('WebFetch', 'u1'));
+ p.applyText(text('结论: 已停止维护。', true, { source: 'claude-code', agentMeta: { uuid: 'b' } }));
+ p.seal();
+ expect(p.finalText()).toBe('结论: 已停止维护。');
+ // wholeText 仍是整轮(出站引用扫描范围, 与"发什么"无关)。
+ expect(p.wholeText()).toContain('我先看看这个链接。');
+ });
+
+ it('replaceBody 在 finalized-segments 下不受支持, 显式失败', () => {
+ const p = createTurnPresenter({ mode: 'finalized-segments' });
+ expect(() => p.replaceBody('x')).toThrow(/does not support replaceBody/);
+ });
+});
+
+describe('createProgressEmitter — trailing-edge 1.5s 节流骨架', () => {
+ it('密集事件按 1.5s trailing-edge 合帧, 相同快照不重复发', () => {
+ vi.useFakeTimers();
+ try {
+ const frames: string[] = [];
+ let body = '';
+ const emitter = createProgressEmitter(
+ (t) => void frames.push(t),
+ () => body,
+ );
+ body = 'a';
+ emitter.schedule();
+ body = 'ab';
+ emitter.schedule(); // 节流窗口内, 不额外排帧
+ vi.advanceTimersByTime(1500);
+ expect(frames).toEqual(['ab']); // 只发一帧, 取窗口末的最新内容
+
+ // 内容未变时 ticker 触发也不重复发。
+ emitter.ensureTicker();
+ vi.advanceTimersByTime(5000);
+ expect(frames).toEqual(['ab']);
+
+ body = 'abc';
+ emitter.schedule();
+ vi.advanceTimersByTime(1500);
+ expect(frames).toEqual(['ab', 'abc']);
+
+ emitter.stop();
+ body = 'abcd';
+ emitter.schedule();
+ vi.advanceTimersByTime(5000);
+ expect(frames).toEqual(['ab', 'abc']); // stop 后不再发射
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('空快照不发帧', () => {
+ vi.useFakeTimers();
+ try {
+ const frames: string[] = [];
+ const emitter = createProgressEmitter(
+ (t) => void frames.push(t),
+ () => '',
+ );
+ emitter.schedule();
+ vi.advanceTimersByTime(1500);
+ expect(frames).toEqual([]);
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('DEFAULT_PRESENTER_POLICY — 两侧单一出处默认', () => {
+ it('默认值 = 现有常量(零行为变化): 1500 trailing / 3800 max / lazy', () => {
+ expect(DEFAULT_PRESENTER_POLICY.intermediateThrottleMs).toBe(PROGRESS_THROTTLE_MS);
+ expect(DEFAULT_PRESENTER_POLICY.intermediateThrottleMs).toBe(1500);
+ expect(DEFAULT_PRESENTER_POLICY.intermediateMaxRenderedChars).toBe(PROGRESS_SNAPSHOT_MAX_CHARS);
+ expect(DEFAULT_PRESENTER_POLICY.intermediateMaxRenderedChars).toBe(3800);
+ expect(DEFAULT_PRESENTER_POLICY.lazyPlaceholder).toBe(true);
+ });
+});
+
+describe('PERSONAL_DRIVER_CAPABILITIES — 个人车道能力基线契约锚定', () => {
+ it('声明个人车道现值(非官方默认, 车道差异见字段 TODO)', () => {
+ expect(PERSONAL_DRIVER_CAPABILITIES).toEqual({
+ progressSilent: true,
+ typingKeepaliveMs: 4500,
+ typingKeepaliveMaxMs: 5 * 60_000,
+ linkPreviewDisabled: true,
+ noReplyScope: 'all-turns',
+ messageEffectIdSupported: false,
+ threadIdDualSemantics: true,
+ laneModel: 'per-chat',
+ });
+ });
+
+ it('是 @cindy/im 的 re-export(单一出处, 不是复制的字面量)', () => {
+ // 同一引用 → desktop 侧与 driver 侧读到的是同一份契约, 无第二真相源。
+ expect(PERSONAL_DRIVER_CAPABILITIES).toBe(TELEGRAM_PERSONAL_CAPABILITIES);
+ });
+
+ it('NO_REPLY 生效范围为 all-turns(哨兵在任何轮次都静默)', () => {
+ expect(PERSONAL_DRIVER_CAPABILITIES.noReplyScope).toBe('all-turns');
+ });
+
+ it('typing 保活 4.5s 重发 / 5min 上限', () => {
+ expect(PERSONAL_DRIVER_CAPABILITIES.typingKeepaliveMs).toBe(4500);
+ expect(PERSONAL_DRIVER_CAPABILITIES.typingKeepaliveMaxMs).toBe(300_000);
+ });
+});
+
+describe('progress 三槽去重基线 — pending ?? sending ?? lastSent(严格顺序)', () => {
+ it('baseline 严格按 pending → sending → lastSent 取', () => {
+ expect(progressDedupeBaseline({ pending: 'p', sending: 's', lastSent: 'l' })).toBe('p');
+ expect(progressDedupeBaseline({ sending: 's', lastSent: 'l' })).toBe('s');
+ expect(progressDedupeBaseline({ lastSent: 'l' })).toBe('l');
+ expect(progressDedupeBaseline({})).toBeUndefined();
+ });
+
+ it('只完全相等才判重复(不发); 其余一律发', () => {
+ expect(shouldEmitProgressFrame('ab', { lastSent: 'ab' })).toBe(false);
+ expect(shouldEmitProgressFrame('abc', { lastSent: 'ab' })).toBe(true);
+ });
+
+ it('绝无前缀判据: 候选是基线前缀 / 基线是候选前缀都必须发', () => {
+ // 候选是基线的前缀
+ expect(shouldEmitProgressFrame('ab', { lastSent: 'abc' })).toBe(true);
+ // 基线是候选的前缀(流式增量的常见形态)
+ expect(shouldEmitProgressFrame('abc', { lastSent: 'ab' })).toBe(true);
+ });
+
+ it('去重比对的是 pending 槽而非 lastSent(基线优先级生效)', () => {
+ // pending 与候选相等 → 不发, 即便 lastSent 不同
+ expect(shouldEmitProgressFrame('x', { pending: 'x', lastSent: 'y' })).toBe(false);
+ // pending 与候选不同 → 发, 即便候选等于 lastSent
+ expect(shouldEmitProgressFrame('y', { pending: 'x', lastSent: 'y' })).toBe(true);
+ });
+});
+
+describe('createProgressEmitter — 自定义 policy(节流/上限/惰性)', () => {
+ it('自定义 throttle 生效(第二帧受 500ms 窗口约束)', () => {
+ vi.useFakeTimers();
+ try {
+ const frames: string[] = [];
+ let body = '';
+ const emitter = createProgressEmitter((t) => void frames.push(t), () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 500,
+ });
+ // 首帧总是立即起飞(lastEmitAt=0), 借它把节流基准点拉到"现在"。
+ body = 'a';
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ expect(frames).toEqual(['a']);
+ // 第二帧受 500ms 窗口约束: 499ms 未到不发, 500ms 发。
+ body = 'ab';
+ emitter.schedule();
+ vi.advanceTimersByTime(499);
+ expect(frames).toEqual(['a']);
+ vi.advanceTimersByTime(1);
+ expect(frames).toEqual(['a', 'ab']);
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('自定义 max 头部截断加省略号', () => {
+ vi.useFakeTimers();
+ try {
+ const frames: string[] = [];
+ let body = '';
+ const emitter = createProgressEmitter((t) => void frames.push(t), () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateMaxRenderedChars: 5,
+ });
+ body = 'abcdefgh';
+ emitter.schedule();
+ vi.advanceTimersByTime(1500);
+ expect(frames).toEqual(['abcd…']); // slice(0, 4) + …
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('lazyPlaceholder=false 时正文清空会发空帧(lazy=true 则不发)', () => {
+ vi.useFakeTimers();
+ try {
+ // lazy=false: 先发 'a', 正文清空后空帧不再被惰性拦截 → 发 '' 清屏。
+ const eager: string[] = [];
+ let eagerBody = 'a';
+ const eagerEmitter = createProgressEmitter((t) => void eager.push(t), () => eagerBody, {
+ ...DEFAULT_PRESENTER_POLICY,
+ lazyPlaceholder: false,
+ });
+ eagerEmitter.schedule();
+ vi.advanceTimersByTime(1500);
+ eagerBody = '';
+ eagerEmitter.schedule();
+ vi.advanceTimersByTime(1500);
+ expect(eager).toEqual(['a', '']);
+ eagerEmitter.stop();
+
+ // lazy=true(默认): 同样序列下空帧被惰性拦截, 只保留 'a'。
+ const lazy: string[] = [];
+ let lazyBody = 'a';
+ const lazyEmitter = createProgressEmitter((t) => void lazy.push(t), () => lazyBody);
+ lazyEmitter.schedule();
+ vi.advanceTimersByTime(1500);
+ lazyBody = '';
+ lazyEmitter.schedule();
+ vi.advanceTimersByTime(1500);
+ expect(lazy).toEqual(['a']);
+ lazyEmitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('createProgressEmitter — 异步 sink 的真实三槽(pending/sending/lastSent)', () => {
+ /** 手动控制 settle 的异步 emit sink: 记录每次 emit 的文本与它的 resolver。 */
+ function asyncSink() {
+ const emitted: string[] = [];
+ const resolvers: Array<() => void> = [];
+ const emit = (t: string): Promise<void> => {
+ emitted.push(t);
+ return new Promise<void>((resolve) => resolvers.push(() => resolve()));
+ };
+ return { emit, emitted, resolvers };
+ }
+
+ it('in-flight 期间到来的多帧压 pending 并只保留最新, settle 后提升发出', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = asyncSink();
+ let body = '';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+
+ // 首帧 F1 起飞(wait=0), sending='F1' 且尚未 settle。
+ body = 'F1';
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ expect(sink.emitted).toEqual(['F1']);
+
+ // in-flight 期间连来两帧 → 压 pending, 只保留最新 F3, 不额外 emit。
+ body = 'F2';
+ emitter.schedule();
+ vi.advanceTimersByTime(100);
+ body = 'F3';
+ emitter.schedule();
+ vi.advanceTimersByTime(100);
+ expect(sink.emitted).toEqual(['F1']); // 仍只发了 F1
+
+ // F1 settle → 提升 lastSent='F1', 冲刷 pending → 发最新的 F3(跳过被覆盖的 F2)。
+ sink.resolvers[0]();
+ await Promise.resolve();
+ expect(sink.emitted).toEqual(['F1', 'F3']);
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('pending 与基线相等则不重发(三槽去重贯穿 in-flight)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = asyncSink();
+ let body = '';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ body = 'X';
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ expect(sink.emitted).toEqual(['X']); // sending='X'
+
+ // in-flight 期间内容没变(仍 'X') → 去重命中 sending, 不压 pending。
+ emitter.schedule();
+ vi.advanceTimersByTime(100);
+ sink.resolvers[0]();
+ await Promise.resolve();
+ // 没有 pending 需要冲刷, 依旧只发过一帧。
+ expect(sink.emitted).toEqual(['X']);
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stop 后 in-flight settle 不再冲刷 pending(收口丢弃迟到帧)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = asyncSink();
+ let body = '';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ body = 'A';
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ body = 'B';
+ emitter.schedule();
+ vi.advanceTimersByTime(100); // B 压 pending(A 仍 in-flight)
+
+ emitter.stop(); // 收口: 丢弃 pending
+ sink.resolvers[0]();
+ await Promise.resolve();
+ expect(sink.emitted).toEqual(['A']); // B 不再发出
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('createProgressEmitter — async emit 失败/重试状态机(P2: reject 不污染 lastSent)', () => {
+ /** 可分别 resolve / reject 每次出站的异步 sink。 */
+ function controllableSink() {
+ const emitted: string[] = [];
+ const settlers: Array<{ resolve: () => void; reject: () => void }> = [];
+ const emit = (t: string): Promise<void> => {
+ emitted.push(t);
+ return new Promise<void>((resolve, reject) => {
+ settlers.push({ resolve: () => resolve(), reject: () => reject(new Error('emit failed')) });
+ });
+ };
+ return { emit, emitted, settlers };
+ }
+ /** 冲刷 .then(onReject) 这层微任务(reject 已被第二参数处理, 不产生 unhandledRejection)。 */
+ const flush = async (): Promise<void> => {
+ await Promise.resolve();
+ await Promise.resolve();
+ };
+
+ it('reject 不把失败帧记入 lastSent, 相同快照可重试(核心 P2)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = controllableSink();
+ let body = 'F1';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ expect(sink.emitted).toEqual(['F1']); // sending='F1' in-flight
+
+ // 出站失败: 清 in-flight、保留 lastSent(仍 undefined), 不把 F1 记作已送达。
+ sink.settlers[0].reject();
+ await flush();
+
+ // 内容未变仍是 F1 → 下一次 schedule 判为"与基线不等"(F1 !== lastSent)重新起飞。
+ emitter.schedule();
+ vi.advanceTimersByTime(100);
+ expect(sink.emitted).toEqual(['F1', 'F1']); // 同一帧成功重试, 未被去重吞掉
+ sink.settlers[1].resolve();
+ await flush();
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('成功送达后相同快照被去重(与失败重试相反, 证明 lastSent 是去重支点)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = controllableSink();
+ let body = 'X';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ sink.settlers[0].resolve(); // 成功 → lastSent='X'
+ await flush();
+
+ // 相同内容再次 schedule → 命中 lastSent 去重, 不重发。
+ emitter.schedule();
+ vi.advanceTimersByTime(100);
+ expect(sink.emitted).toEqual(['X']);
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('reject 时仍冲刷 in-flight 期间压入的 pending(更新帧发出, 不残留孤儿)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = controllableSink();
+ let body = 'A';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ expect(sink.emitted).toEqual(['A']); // sending='A'
+
+ body = 'B';
+ emitter.schedule();
+ vi.advanceTimersByTime(100); // 'B' 压 pending(A 仍 in-flight)
+
+ // A 失败: 不记 lastSent, 但要冲刷 pending → 发更新的 B。
+ sink.settlers[0].reject();
+ await flush();
+ expect(sink.emitted).toEqual(['A', 'B']);
+ sink.settlers[1].resolve();
+ await flush();
+ emitter.stop();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('stop 后 in-flight reject 不冲刷 pending、不重试(收口丢弃)', async () => {
+ vi.useFakeTimers();
+ try {
+ const sink = controllableSink();
+ let body = 'A';
+ const emitter = createProgressEmitter(sink.emit, () => body, {
+ ...DEFAULT_PRESENTER_POLICY,
+ intermediateThrottleMs: 100,
+ });
+ emitter.schedule();
+ vi.advanceTimersByTime(0);
+ body = 'B';
+ emitter.schedule();
+ vi.advanceTimersByTime(100); // pending='B'
+
+ emitter.stop();
+ sink.settlers[0].reject(); // 收口后失败: 既不发 B, 也不重试 A
+ await flush();
+ expect(sink.emitted).toEqual(['A']);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index 90993aec2c..29ff6acb65 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -1276,6 +1276,72 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
}
});
+ // #1855 L1 契约锚定: 终态 reaction 替换失败必须回落撤销 ack(👀), 否则眼睛永久卡住。
+ // fakeAdapter 无 terminalReactionEmoji(上面的用例走"直接撤 ack"分支); 这里用带
+ // terminalReactionEmoji 的变体 adapter 精确覆盖"替换成功不撤 / 替换失败撤"两条分支。
+ describe('终态 reaction 替换与撤眼睛(terminalReactionEmoji 分支)', () => {
+ const terminalAdapter: ImChannelAdapter = {
+ ...fakeAdapter,
+ terminalReactionEmoji: (kind) => (kind === 'done' ? '👍' : kind === 'error' ? '👎' : null),
+ };
+
+ async function runTerminalTurn(): Promise<{
+ localRunner: ImTurnRunner;
+ onTurnComplete: ReturnType<typeof vi.fn>;
+ h: SessionHarness;
+ }> {
+ const localRunner = createTurnRunner(terminalAdapter, fakeRepo, fakeCards);
+ const h = setupSession(async () => ({ accepted: true }));
+ const onTurnComplete = vi.fn();
+ const turnPromise = localRunner.runAgentTurn({
+ botContextId: 'cli_test_bot',
+ userId: 'ou_user',
+ userMessageId: 'msg-user',
+ text: 'hi',
+ attachments: [],
+ onTurnComplete,
+ });
+ await turnPromise;
+ h.emit({ type: 'text', data: { text: 'final answer', isFinal: true } });
+ h.emit({ type: 'done', data: {} });
+ return { localRunner, onTurnComplete, h };
+ }
+
+ it('替换成功(渠道放行)时顶掉 ack, 不再撤销', async () => {
+ // ack 用 processingEmoji(SMUG)拿 token; 终态 👍 替换返回 token = 顶掉成功。
+ mocks.feishuIm.reactToMessage.mockImplementation(async (_id: string, emoji: string) =>
+ emoji === 'SMUG' ? 'ack-eyes' : 'done-token',
+ );
+ const { localRunner, onTurnComplete } = await runTerminalTurn();
+ try {
+ await waitForAssertion(() => expect(onTurnComplete).toHaveBeenCalledTimes(1));
+ expect(mocks.feishuIm.reactToMessage).toHaveBeenCalledWith('msg-user', '👍');
+ // 替换成功 → 绝不再撤 ack(否则会把刚放上去的结果表情也撤了)。
+ expect(mocks.feishuIm.removeMessageReaction).not.toHaveBeenCalled();
+ } finally {
+ await localRunner.disposeAllSessions();
+ }
+ });
+
+ it('替换失败(渠道拒放, 返回 null)时回落撤销 ack, 不让 👀 卡住', async () => {
+ // ack 拿 token; 终态 👍 替换返回 null(如 turn 进行中被切到 emoji off)。
+ mocks.feishuIm.reactToMessage.mockImplementation(async (_id: string, emoji: string) =>
+ emoji === 'SMUG' ? 'ack-eyes' : null,
+ );
+ const { localRunner, onTurnComplete } = await runTerminalTurn();
+ try {
+ await waitForAssertion(() => expect(onTurnComplete).toHaveBeenCalledTimes(1));
+ expect(mocks.feishuIm.reactToMessage).toHaveBeenCalledWith('msg-user', '👍');
+ // 替换失败 → 回落撤掉原始 ack token(撤眼睛)。
+ await waitForAssertion(() =>
+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledWith('msg-user', 'ack-eyes'),
+ );
+ } finally {
+ await localRunner.disposeAllSessions();
+ }
+ });
+ });
+
it('redacts user identity from send failure log session fields', async () => {
const sensitiveSessionId = 'feishu_cli_test_bot_ou_sensitive_openid';
setupSessionWithId(sensitiveSessionId, async () => ({
diff --git a/apps/desktop/src/main/im/shared/turnPresenter.ts b/apps/desktop/src/main/im/shared/turnPresenter.ts
new file mode 100644
index 0000000000..64e6ffa5d4
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/turnPresenter.ts
@@ -0,0 +1,722 @@
+/**
+ * im/shared/turnPresenter.ts
+ * ---------------------------------------------------------------------------
+ * 一轮 turn 的**呈现大脑**(纯逻辑, 不做 IO): 正文累积、过程区时间线合成、进度
+ * 快照的 trailing-edge 节流骨架。两个消费方共用同一实现:
+ *
+ * 1. hook-control/turnObserver —— 官方 bot(Slack / 官方 Telegram / X);
+ * 2. im/shared/turnRunner —— 个人 IM 渠道(Telegram / 飞书 / Discord …)。
+ *
+ * 两侧的**正文累积语义天生不同**, 所以做成显式参数(`mode`), 不强行统一:
+ * - `finalized-segments`(observer): isFinal 是**逐条** agent_message 的完成
+ * 信号, 追加进已定稿段(按消息边界切开), 流式增量走尾部缓冲; claude result
+ * 的 fallbackTail 自成一段; 消息边界用 uuid 缺失时退到 requestId。完成态正文
+ * 投影成 maker-shared 的 normalized messages, 交给桌面 / Mobile 共用的
+ * buildMessageRenderItems 判定折叠。#1272 / #1636 / #1703 的实踩教训嵌在下面
+ * 的注释里, 搬运时原样保留。
+ * - `buffer-replace`(turnRunner): isFinal 用该条全文**整体替换**累积缓冲,
+ * 流式增量追加。这是个人 IM 渠道现有行为, 本次抽取显式保留、不修旧账。
+ *
+ * 收口(何时结束)**不在这里** —— 由各消费方(observer 的 done/silentStop/
+ * onStatusChange/settle 三出口、runner 的队列收口)自己负责。本模块只管"这一刻
+ * 该显示什么", 不管"这一轮何时收口"。
+ *
+ * #1855 L1: 呈现策略集中为 PresenterPolicy(纯, presenter 可兑现)与
+ * DriverPresentationCapabilities(声明车道能力, 由各 driver 出站时兑现, presenter
+ * 不做 IO); 进度帧去重统一到 shouldEmitProgressFrame 的三槽基线(严格
+ * pending ?? sending ?? lastSent, 只判完全相等, 绝无前缀判据)。**均不含 replyQuote**
+ * —— 那三档由各车道 TelegramBehaviorConfig 直接供给, L1 不带默认(replyQuote 勘误)。
+ */
+
+import {
+ TELEGRAM_PERSONAL_CAPABILITIES,
+ type TelegramDriverCapabilities,
+} from '@cindy/im';
+import type { AgentEvent } from '@cindy/maker-core';
+import {
+ buildMessageRenderItems,
+ type MessageRenderNormalizedMessage,
+} from '@cindy/maker-shared/message-render';
+
+import {
+ createTurnActivity,
+ markActivityWriting,
+ pushThinkingStep,
+ pushToolStep,
+ renderActivity,
+ setActivityNotice,
+ setInteractionNotice,
+ type TurnActivityState,
+} from './turnActivity.js';
+import { turnRetryNotice } from './turnRetryNotice.js';
+
+/**
+ * 进度快照节流(trailing-edge): 事件密集时最多每 1.5s 发一帧, 与 IM 流式卡的
+ * chat.update 节流(1300ms)同量级 —— server 侧每帧一次 chat.update(Tier 3
+ * ~50/min/频道), 这个间隔留有安全余量。
+ */
+export const PROGRESS_THROTTLE_MS = 1500;
+/** 无新事件时的低频刷新(过程区耗时行"第 N 步 · 42s"不冻结)。 */
+export const PROGRESS_TICK_MS = 5000;
+/** 单帧快照长度上限: 头部截断 —— server 侧占位消息本就 3900 上限, 中间帧
+ * 开头(过程区 + 正文起始)信息量最大, 收口后 turn.end 会带完整文本。 */
+export const PROGRESS_SNAPSHOT_MAX_CHARS = 3800;
+
+/**
+ * 纯呈现策略(#1855 L1)。无 IO —— 只放 presenter 能自己兑现的项, 两消费方共用
+ * **同一规格与同一默认值**(DEFAULT_PRESENTER_POLICY 单一出处): 官方 turnObserver 走
+ * 本模块的 trailing-edge 发射器兑现该规格; 个人 turnRunner 的过程区节流(patchMarkdownCard)
+ * **保留自己的实现**, 只引用同一默认间隔 —— 是"同一规格/同一数值", 不是"同一份代码"。
+ *
+ * **不含 replyQuote**: emoji/回复引用三档(emojiReactions / replyQuoteGroup /
+ * replyQuoteDm)由各车道的 TelegramBehaviorConfig 直接供给, presenter/L1 既不持有
+ * 也不带出厂默认(#1855 replyQuote 勘误)。需要真正出站/渠道能力才能兑现的策略见
+ * DriverPresentationCapabilities。
+ */
+export interface PresenterPolicy {
+ /**
+ * 过程区快照 trailing-edge 节流间隔(ms)。两侧共用**同一数值规格**(密集事件在一个
+ * 窗口内合帧, 窗口末取最新内容发一帧); 官方发射器与个人 patchMarkdownCard 各自实现
+ * 这条尾沿语义, 只从这里取同一间隔 —— 统一的是规格与默认值, 不是同一份代码。
+ */
+ intermediateThrottleMs: number;
+ /** 单帧过程快照渲染长度上限; 超限头部截断(收口后由 turn.end 带完整文本)。 */
+ intermediateMaxRenderedChars: number;
+ /**
+ * 惰性占位: true = 无真实正文时不发过程帧(默认, 现有行为)。presenter 侧兑现为
+ * "空合成视图不发帧"; driver 侧兑现为"有正文才建消息"(streamingText 现状)。
+ */
+ lazyPlaceholder: boolean;
+}
+
+/** 默认策略 = 现有两侧常量, 保证零行为变化, 且是两消费方引用的**单一出处**。 */
+export const DEFAULT_PRESENTER_POLICY: PresenterPolicy = {
+ intermediateThrottleMs: PROGRESS_THROTTLE_MS,
+ intermediateMaxRenderedChars: PROGRESS_SNAPSHOT_MAX_CHARS,
+ lazyPlaceholder: true,
+};
+
+/**
+ * 需要真正出站 / 渠道能力才能兑现的呈现能力契约(#1855 L1 §B/§D/§E)。
+ *
+ * **单一真相源在 @cindy/im**(`telegram/presentationCapabilities.ts`),这里只做
+ * **re-export**:契约值由同包 driver(index.ts)真正消费(typing 续命间隔/上限、
+ * link preview 全档关闭都直接引用它,不再各写字面量);desktop 侧沿用旧名
+ * `DriverPresentationCapabilities` / `PERSONAL_DRIVER_CAPABILITIES` 作为 L1 呈现层的
+ * 能力声明锚,依赖方向 desktop → @cindy/im 不成环。presenter 本体不做任何 IO。
+ *
+ * **不含 replyQuote**: 见 PresenterPolicy 注释与契约模块头。
+ */
+export type DriverPresentationCapabilities = TelegramDriverCapabilities;
+
+/** 个人 IM 车道能力基线(re-export 自 @cindy/im 单一出处)。**不是官方默认**。 */
+export const PERSONAL_DRIVER_CAPABILITIES: DriverPresentationCapabilities =
+ TELEGRAM_PERSONAL_CAPABILITIES;
+
+/**
+ * 进度帧去重基线(#1855 L1, 与 server controller.ts 3423-3461 的三槽语义对齐)。
+ * 候选帧要不要真的发出去, 只跟"最近一次已知的帧文本"比 —— 而"最近一次已知"
+ * **严格**按 `pending ?? sending ?? lastSent` 取:
+ * - pending: 已排队但尚未起飞的帧(有就是它最新);
+ * - sending: 正在 in-flight 的那一帧;
+ * - lastSent: 已确认送达的上一帧。
+ *
+ * `createProgressEmitter` 真正维护这三槽:emit 返回 Promise 时,in-flight 期间新帧压
+ * pending、settle 后提升(见该函数)。emit 同步返回时 sending/pending 瞬时坍缩,只有
+ * lastSent 是活的 —— 这是同步 sink 的真实形态,不伪造额外槽;三槽机制对异步 sink
+ * (会 await 出站的三槽拥有者)完整生效。
+ */
+export interface ProgressDedupeSlots {
+ /** 已排队未起飞的帧文本(有 in-flight 发送时,新候选压这里,取最新)。 */
+ pending?: string;
+ /** 正在 in-flight 的那一帧文本(emit 返回的 Promise 未 settle)。 */
+ sending?: string;
+ /** 已确认送达的上一帧文本。 */
+ lastSent?: string;
+}
+
+/** 三槽基线: pending ?? sending ?? lastSent(严格此顺序)。 */
+export function progressDedupeBaseline(slots: ProgressDedupeSlots): string | undefined {
+ return slots.pending ?? slots.sending ?? slots.lastSent;
+}
+
+/**
+ * 候选帧与基线**完全相等**才判重复(不发); 其余一律发。
+ *
+ * **绝不做前缀判据**(候选是基线前缀 / 基线是候选前缀都照发)—— server 侧实踩
+ * (controller.ts 3423-3461): 前缀判据会在"流式增量恰好以上一帧开头"时把真实
+ * 新内容判成重复吞掉, 用户看到过程区卡死。
+ */
+export function shouldEmitProgressFrame(candidate: string, slots: ProgressDedupeSlots): boolean {
+ return candidate !== progressDedupeBaseline(slots);
+}
+
+/** trailing-edge 节流发射器的公开形态。 */
+export interface ProgressEmitter {
+ schedule(): void;
+ ensureTicker(): void;
+ stop(): void;
+}
+
+/**
+ * 进度快照发射器: 合成「过程区时间线 + 部分正文」并按 trailing-edge 节流回调。
+ * 纯定时器逻辑, 不做 IO —— 真正的发送(turn.progress 帧)由调用方注入的
+ * emit 承担。stop() 后不再发射(收口后的迟到事件被丢弃)。
+ *
+ * **三槽去重(#1855 L1)**:发射器真正维护 `ProgressDedupeSlots`
+ * (pending ?? sending ?? lastSent),候选帧与该基线**完全相等**才丢弃。
+ * - emit 同步返回(observer 的 turn.progress 现状,尽力而为、不 await):send 瞬时
+ * 完成,sending→lastSent 立刻坍缩,pending 用不上 —— 时序与旧实现逐字等价
+ * (首帧立即、窗口内 trailing、内容不变不重发)。
+ * - emit 返回 Promise(会 await 出站的三槽拥有者,如带网络回压的卡片编辑):in-flight
+ * 期间到来的新帧压 pending 并去重,settle 后提升为下一次 send。这样三槽名副其实,
+ * 而非空占位。
+ */
+export function createProgressEmitter(
+ emit: (text: string) => void | Promise<void>,
+ compose: () => string,
+ policy: PresenterPolicy = DEFAULT_PRESENTER_POLICY,
+): ProgressEmitter {
+ let lastEmitAt = 0;
+ // 三槽真实状态(见 ProgressDedupeSlots):去重基线严格 pending ?? sending ?? lastSent。
+ const slots: ProgressDedupeSlots = {};
+ let pending: NodeJS.Timeout | null = null;
+ let ticker: NodeJS.Timeout | null = null;
+ let stopped = false;
+
+ /**
+ * 一次出站结束后的状态推进(无论成功/失败都要解除 in-flight, 再冲刷窗口内压入的 pending):
+ * - 成功: sending→lastSent —— 该帧已送达, 成为新的去重基线;
+ * - 失败(async emit reject): **绝不**把没送达的帧记进 lastSent。否则同一快照重试时会被
+ * shouldEmitProgressFrame 判等去重吞掉、永远发不出去。只清 sending 解除 in-flight、
+ * **保留原 lastSent**, 于是相同内容在下一次 schedule / ticker 触发时仍判为"与基线不等"
+ * 而重新起飞(重试)。
+ * 两种情况都要把 in-flight 期间压入的 pending(更新的一帧)冲刷出去, 否则会残留孤儿帧,
+ * 被后续 settle 误当"最新"发出。
+ */
+ const finishSend = (failed: boolean): void => {
+ if (!failed && slots.sending !== undefined) slots.lastSent = slots.sending;
+ slots.sending = undefined;
+ if (stopped) {
+ slots.pending = undefined;
+ return;
+ }
+ if (slots.pending !== undefined) {
+ const next = slots.pending;
+ slots.pending = undefined;
+ // pending 压入时已对当时基线去重; 基线变化(lastSent 可能刚提升)后再核一次, 相等则不重发。
+ if (shouldEmitProgressFrame(next, slots)) startSend(next);
+ }
+ };
+
+ /**
+ * 起飞一帧: 标记 sending(in-flight), 记节流基准, 调 emit。同步返回即视为立即送达
+ * (observer turn.progress 现状, 逐字等价旧实现); 异步按 resolve/reject 分别推进 ——
+ * reject 走失败分支, 不污染 lastSent(见 finishSend)。
+ */
+ const startSend = (snapshot: string): void => {
+ slots.sending = snapshot;
+ lastEmitAt = Date.now();
+ const result = emit(snapshot);
+ if (result && typeof (result as Promise<void>).then === 'function') {
+ (result as Promise<void>).then(
+ () => finishSend(false),
+ () => finishSend(true),
+ );
+ } else {
+ finishSend(false);
+ }
+ };
+
+ const fire = (): void => {
+ if (stopped) return;
+ const text = compose();
+ // 惰性占位: 空合成视图不发帧(默认)。driver 侧同一策略兑现为"有正文才建消息"。
+ if (policy.lazyPlaceholder && text.length === 0) return;
+ const max = policy.intermediateMaxRenderedChars;
+ const snapshot = text.length > max ? `${text.slice(0, max - 1)}…` : text;
+ // The low-frequency activity ticker can fire while the user-visible
+ // answer is unchanged. Do not spend provider API calls on identical
+ // full snapshots (and, for Telegram, do not re-animate the same draft).
+ // 三槽基线去重: 与 pending ?? sending ?? lastSent **完全相等**才不发, 绝无前缀判据。
+ if (!shouldEmitProgressFrame(snapshot, slots)) return;
+ // 有 in-flight 发送时压 pending(trailing: 保留最新一帧); 否则直接起飞。
+ if (slots.sending !== undefined) {
+ slots.pending = snapshot;
+ return;
+ }
+ startSend(snapshot);
+ };
+ const schedule = (): void => {
+ if (stopped || pending !== null) return;
+ const wait = Math.max(0, lastEmitAt + policy.intermediateThrottleMs - Date.now());
+ pending = setTimeout(() => {
+ pending = null;
+ fire();
+ }, wait);
+ pending.unref?.();
+ };
+ return {
+ schedule,
+ ensureTicker(): void {
+ if (stopped || ticker !== null) return;
+ ticker = setInterval(schedule, PROGRESS_TICK_MS);
+ ticker.unref?.();
+ },
+ stop(): void {
+ stopped = true;
+ if (pending !== null) clearTimeout(pending);
+ if (ticker !== null) clearInterval(ticker);
+ pending = null;
+ ticker = null;
+ // 收口后丢弃尚未起飞的 pending; in-flight 的 sending 由 finishSend 的 stopped 分支清理。
+ slots.pending = undefined;
+ },
+ };
+}
+
+/**
+ * 过程区 + 正文的合成骨架: 有过程区时"过程区在上、正文在下", 无过程区时只留
+ * 正文。两侧运行中视图共用这一条 —— observer 的进度快照与 turnRunner 的
+ * composeStreamingView(非收口态)逐字一致。
+ */
+export function composeProgressView(activityText: string, body: string): string {
+ if (!activityText) return body;
+ return body ? `${activityText}\n\n${body}` : activityText;
+}
+
+/** 正文累积策略。见模块头。 */
+export type TurnPresenterMode = 'finalized-segments' | 'buffer-replace';
+
+export interface TurnPresenterOptions {
+ mode: TurnPresenterMode;
+ /** 过程区耗时基准(activity.startedAt); 缺省取当前时刻。 */
+ startedAt?: number;
+ /** 注入后启用 trailing-edge 进度发射器(observer 路径); 省略 = 零开销, 无发射器。 */
+ onProgress?: (text: string) => void;
+ /** 纯呈现策略(节流/长度上限/惰性占位); 省略 = DEFAULT_PRESENTER_POLICY(两侧同值)。 */
+ policy?: PresenterPolicy;
+}
+
+export interface TurnPresenter {
+ /** 过程区时间线状态(turnActivity), 直接暴露供消费方做既有的直接调用。 */
+ readonly activity: TurnActivityState;
+
+ /** 累积一个 text 事件。返回是否真的落了正文(供消费方决定要不要刷新)。 */
+ applyText(ev: AgentEvent): boolean;
+ /** tool_use 边界: 记一步(+ segments: 封存尾段并投影 tool 消息)。返回是否落了一步。 */
+ applyToolUse(ev: AgentEvent): boolean;
+ /** thinking 事件: segments 投影 + 记一步; buffer 忽略。返回过程区是否变化。 */
+ applyThinking(ev: AgentEvent): boolean;
+ /** 非终止重试 error → 单行状态说明。返回状态行是否变化。 */
+ applyRetryNotice(ev: AgentEvent): boolean;
+ /** done: 封存本轮尾段(segments); buffer 无操作。 */
+ seal(): void;
+ /** 新交互请求边界(segments); buffer 无操作。 */
+ markInteractionBoundary(): void;
+ /** 设/清「在等你确认」那一行。返回是否变化。 */
+ setInteractionNotice(notice: string | null): boolean;
+
+ /** 运行中快照展示的正文(segments: 仅当前/最后一条消息; buffer: 整段缓冲)。 */
+ progressBody(): string;
+ /** 整轮累积的助手正文。 */
+ wholeText(): string;
+ /** 正式答复正文(segments: 桌面消息流折叠; buffer: 整段缓冲)。 */
+ finalText(): string;
+ /** 整体替换正文(buffer 模式: 本地图片物化后回写 / 收口重置)。segments 无此语义。 */
+ replaceBody(text: string): void;
+
+ /** 过程区(renderActivity, 取当前时刻) + 给定正文 的运行中合成。 */
+ composeRunning(body: string): string;
+
+ // ── trailing-edge 发射器(仅当注入 onProgress 时有效, 否则均为 no-op) ──
+ scheduleProgress(): void;
+ ensureProgressTicker(): void;
+ stopProgress(): void;
+}
+
+/** 正文累积引擎的内部契约(两种 mode 各一份实现)。 */
+interface BodyEngine {
+ /** 累积一个 text 事件的正文(不碰 activity)。调用前已保证 data.text 是 string。 */
+ applyText(ev: AgentEvent): void;
+ /** tool_use 边界的正文投影(segments: 封存尾段 + 投影 tool 消息; buffer: 无)。 */
+ projectToolUse(toolName: string, input: unknown, toolUseId: string | undefined): void;
+ /** thinking 的正文投影(segments: 原位更新 render 消息; buffer: 无)。 */
+ projectThinking(ev: AgentEvent): void;
+ /** done 封存尾段。 */
+ seal(): void;
+ /** 新交互请求边界的正文投影。 */
+ projectInteractionBoundary(): void;
+ progressBody(): string;
+ wholeText(): string;
+ finalText(): string;
+ /** 整体替换正文(buffer 模式)。segments 无单一缓冲, 不支持。 */
+ replaceBody(text: string): void;
+}
+
+/**
+ * buffer-replace 引擎(turnRunner 现有行为): isFinal 用该条全文整体替换累积缓冲,
+ * 流式增量追加。刻意保留个人 IM 渠道旧账 —— 不投影 render 消息, 无消息边界切分,
+ * finalText 即整段缓冲。
+ */
+function createBufferEngine(): BodyEngine {
+ let buffer = '';
+ return {
+ applyText(ev: AgentEvent): void {
+ const data = ev.data as { text: string; isFinal?: boolean };
+ // Final block — replace buffer with canonical text; deltas append.
+ if (data.isFinal) buffer = data.text;
+ else buffer += data.text;
+ },
+ projectToolUse(): void {
+ // buffer 模式不做消息边界投影。
+ },
+ projectThinking(): void {
+ // 个人 IM 渠道不把 thinking 投到正文(turnRunner 的 case 'thinking' 直接 return)。
+ },
+ seal(): void {
+ // buffer 已是 canonical 全文, 无尾段需要封存。
+ },
+ projectInteractionBoundary(): void {
+ // buffer 模式无 render 投影。
+ },
+ progressBody(): string {
+ return buffer;
+ },
+ wholeText(): string {
+ return buffer;
+ },
+ finalText(): string {
+ return buffer;
+ },
+ replaceBody(text: string): void {
+ buffer = text;
+ },
+ };
+}
+
+/**
+ * finalized-segments 引擎(turnObserver 现有行为)。
+ *
+ * 文本累积语义(2026-07-28 修订): translator 的 isFinal 是**逐条**
+ * agent_message 的完成信号(每条完成都携带该条全文), 不是整个 turn 的
+ * 终稿 —— 用它整体替换累积文本, 会让"先回一句 → 思考 → 终答"的多消息
+ * turn 只剩最后被替换的那条(实踩: Telegram 群里最终答案丢失)。
+ * 正确姿势: isFinal 把该条追加进已定稿段, 流式增量走尾部缓冲。
+ * 定稿段**按消息切开存**(而不是直接拼成一个串): 完成态需要把消息边界
+ * 投影给 buildMessageRenderItems。join('\n\n') 与此前的逐段拼接完全等价
+ * (同一条消息的相邻块在入栈时已连拼, 段内不含分隔)。
+ */
+function createSegmentsEngine(): BodyEngine {
+ const finalizedSegments: string[] = [];
+ /** finalizedSegments 在共享消息投影里的对应下标(同消息多 block 原位更新)。 */
+ const finalizedRenderIndexes: number[] = [];
+ let streamTail = '';
+ let assistantText = '';
+ /** 最近一次定稿段所属的 claude 消息标识(uuid, 缺失时退到 requestId)。 */
+ let lastFinalUuid: string | undefined;
+ const recomputeAssistantText = (): void => {
+ const finalizedText = finalizedSegments.join('\n\n');
+ // trim 只用于判空(纯空白尾巴不该拼出悬空分隔), 拼接用原文 ——
+ // 首行缩进/换行是内容(markdown 代码块等), 不得被裁掉。
+ const hasTail = streamTail.trim().length > 0;
+ assistantText = hasTail
+ ? finalizedText
+ ? `${finalizedText}\n\n${streamTail}`
+ : streamTail
+ : finalizedText;
+ };
+ // 完成态正文不在 hook 自造一套「最后一段」启发式,而是把本轮事件投影成
+ // maker-shared 的 normalized messages,交给桌面 / Mobile 共用的
+ // buildMessageRenderItems 判定哪些过程文字折叠、哪些交付正文保持展开。
+ const renderMessages: MessageRenderNormalizedMessage[] = [];
+ const thinkingRenderIndexes = new Map<string, number>();
+ const renderClockBase = Date.now();
+ let renderSequence = 0;
+ let currentTurnRenderStart = 0;
+ const nextRenderIdentity = (prefix: string): { key: string; createdAt: string } => {
+ const sequence = renderSequence++;
+ return {
+ key: `hook-${prefix}-${sequence}`,
+ // 单个 observer 内只需要稳定顺序;用单调毫秒避免真实长 turn 被历史窗口
+ // gap 规则误切成另一轮(这里本来就只观察同一轮及其自动续 turn)。
+ createdAt: new Date(renderClockBase + sequence).toISOString(),
+ };
+ };
+ const pushRenderMessage = (
+ kind: MessageRenderNormalizedMessage['kind'],
+ body: string,
+ sourceExtra: Partial<MessageRenderNormalizedMessage['source']> = {},
+ ): number => {
+ const { key, createdAt } = nextRenderIdentity(kind);
+ renderMessages.push({
+ key,
+ source: {
+ id: key,
+ clientId: key,
+ role: kind === 'tool' ? 'tool_use' : kind,
+ createdAt,
+ ...sourceExtra,
+ },
+ kind,
+ label: kind,
+ body,
+ createdAt,
+ });
+ return renderMessages.length - 1;
+ };
+ const pushFinalizedSegment = (segment: string, sameMessage: boolean): void => {
+ if (sameMessage && finalizedSegments.length > 0) {
+ const segmentIndex = finalizedSegments.length - 1;
+ finalizedSegments[segmentIndex] += segment;
+ const renderIndex = finalizedRenderIndexes[segmentIndex];
+ const rendered = renderMessages[renderIndex];
+ if (rendered) rendered.body = finalizedSegments[segmentIndex];
+ return;
+ }
+ finalizedSegments.push(segment);
+ finalizedRenderIndexes.push(pushRenderMessage('assistant', segment));
+ };
+ const finalizeStreamTail = (): void => {
+ if (streamTail.trim().length === 0) return;
+ pushFinalizedSegment(streamTail, false);
+ streamTail = '';
+ lastFinalUuid = undefined;
+ recomputeAssistantText();
+ };
+ const progressAssistantText = (): string => {
+ if (streamTail.trim().length > 0) return streamTail;
+ return finalizedSegments[finalizedSegments.length - 1] ?? '';
+ };
+ const finalAnswerText = (): string => {
+ const visible = buildMessageRenderItems(renderMessages, { isSessionStreaming: false })
+ .flatMap((item) =>
+ item.type === 'message'
+ && item.message.kind === 'assistant'
+ && item.message.body.trim().length > 0
+ ? [item.message.body]
+ : [],
+ )
+ .join('\n\n');
+ return visible.trim().length > 0 ? visible : assistantText;
+ };
+
+ return {
+ applyText(ev: AgentEvent): void {
+ const data = ev.data as { text: string; isFinal?: boolean };
+ if (data.isFinal) {
+ // isFinal 形态按 translator 契约区分, 不做内容猜测(前缀
+ // 启发式在"尾段恰好以已流增量开头"时会误判丢正文):
+ // ① claude 块终稿(带 agentMeta): data.text 是该块全文, 覆盖
+ // 已流增量; 同一条消息(同 uuid)的相邻文本块按原文连拼
+ // (renderer 同款 raw concat), 不同消息之间空行分隔。
+ // ② claude result 兜底 fallbackTail(刻意不带 agentMeta):
+ // 只含 UI 缺的尾段, 与已流增量原样接上。
+ // ③ codex item.completed / pi message_end:该条全文,覆盖已流增量。
+ // ④ 未知 source: 保守用前缀启发式。
+ const src = (ev as { source?: string }).source;
+ const meta = (ev as { agentMeta?: { uuid?: unknown; requestId?: unknown } }).agentMeta;
+ const claudeTail = src === 'claude-code' && meta === undefined;
+ const segment = claudeTail
+ ? streamTail + data.text
+ : src === 'claude-code' || src === 'codex' || src === 'pi'
+ ? data.text
+ : data.text.startsWith(streamTail)
+ ? data.text
+ : streamTail + data.text;
+ // 消息边界标识。uuid 是 envelope 顶层的可选字段, **确实会缺**
+ // (extractAssistantMeta 允许它缺); 缺了就退到 requestId —— 那是
+ // Anthropic 的 message id(`msg_...`), 同一条消息的各 text block 共享、
+ // 不同消息不同, 正好是这里要的语义。
+ //
+ // 少了这道回退, 一条含多个 text block 的消息会被拆成多个"消息"。
+ // finalText() 会按桌面消息语义识别正式正文; 不能因为某个渠道最终只
+ // 允许一条消息, 就在这里把同一条消息的内容拆成「最后一段」。
+ const messageId =
+ src === 'claude-code'
+ ? typeof meta?.uuid === 'string'
+ ? meta.uuid
+ : typeof meta?.requestId === 'string'
+ ? meta.requestId
+ : undefined
+ : undefined;
+ // claudeTail(claude result 的 fallbackTail)**自成一段**, 不并入上一条。
+ //
+ // 它刻意不带 agentMeta(translator 的原话: 补推文本是"孤儿正文",
+ // 拿 lastAssistantMeta 当锚点会污染 fork/rewind), 所以 hook 层**拿不到
+ // 它属于哪条消息** —— 这个歧义是结构性的, 不是这里少判了一个条件。
+ //
+ // 两种真实情形都存在, 从这里看完全一样:
+ // ① 它续的是上一条(该消息有多个 block, 只流了前一个);
+ // ② 它是**新的一条**: translator 明写覆盖"前面 call 推过旁白、最后
+ // 一次 call 的最终回复被截断"(见 translator.ts 的 fallbackTail 注释)。
+ //
+ // 选 ②(自成一段)是因为两侧代价不对称: 按 ② 处理而实为 ① 时, X 发出
+ // 的是尾段 —— 而尾段按构造就是整轮文本的**结尾**, 结论在里面; 按 ① 处理
+ // 而实为 ② 时, 旁白会被粘进公开回帖一起发出去。何况 ② 才是 translator
+ // 文档里点名的那个场景(PR #1272 review 指出, 推翻了上一版的无条件并入)。
+ const sameMessage = messageId !== undefined && messageId === lastFinalUuid;
+ pushFinalizedSegment(segment, sameMessage);
+ lastFinalUuid = messageId;
+ streamTail = '';
+ } else {
+ streamTail += data.text;
+ }
+ recomputeAssistantText();
+ },
+ projectToolUse(toolName: string, input: unknown, toolUseId: string | undefined): void {
+ // tool_use 是明确的 assistant 消息边界,与桌面
+ // messagePersistBroadcaster.flushAssistantBlock 同口径。
+ finalizeStreamTail();
+ lastFinalUuid = undefined;
+ pushRenderMessage('tool', '', {
+ toolName,
+ toolInput: input,
+ ...(toolUseId !== undefined ? { toolUseId } : {}),
+ });
+ },
+ projectThinking(ev: AgentEvent): void {
+ // Desktop 不把 thinking 当 assistant block 边界:同一条消息可以在
+ // thinking 前后继续输出文字。这里只投影思考活动本身,不能 flush 正文。
+ // 同一个 blockId 的 start/delta/final 原位更新,和 renderer 消息模型一致。
+ const data = ev.data as {
+ stage?: unknown;
+ blockId?: unknown;
+ text?: unknown;
+ durationMs?: unknown;
+ startedAt?: unknown;
+ } | null;
+ const blockId = typeof data?.blockId === 'string'
+ ? data.blockId
+ : `anonymous-${renderSequence}`;
+ const content = data?.stage === 'redacted'
+ ? { isRedacted: true }
+ : {
+ ...(typeof data?.text === 'string' ? { text: data.text } : {}),
+ ...(typeof data?.durationMs === 'number' ? { durationMs: data.durationMs } : {}),
+ };
+ const existingIndex = thinkingRenderIndexes.get(blockId);
+ if (existingIndex === undefined) {
+ const renderIndex = pushRenderMessage('thinking', '', {
+ clientId: blockId,
+ content,
+ ...(typeof data?.startedAt === 'number'
+ ? { createdAt: new Date(data.startedAt).toISOString() }
+ : {}),
+ });
+ thinkingRenderIndexes.set(blockId, renderIndex);
+ } else {
+ const rendered = renderMessages[existingIndex];
+ if (rendered) rendered.source.content = content;
+ }
+ },
+ seal(): void {
+ // 极端 adapter 路径可能只有增量没有 isFinal;done 仍是确定边界,此时把尾段
+ // 物化成一条 assistant message,和桌面 main 在 done 前落最后正文同口径。
+ finalizeStreamTail();
+ for (let index = renderMessages.length - 1; index >= currentTurnRenderStart; index--) {
+ const message = renderMessages[index];
+ if (message.kind !== 'assistant' || message.body.trim().length === 0) continue;
+ message.turnCompleted = true;
+ break;
+ }
+ currentTurnRenderStart = renderMessages.length;
+ // `turnCompleted` seal 之后,即使 provider 复用同一个上游 message id,
+ // 下一 SDK turn 也必须从新的 assistant message 开始。
+ lastFinalUuid = undefined;
+ },
+ projectInteractionBoundary(): void {
+ // main 的任一 interaction 请求会先封存 assistant block,再落交互消息。
+ // 这只在请求首次出现时调用;剩余等待文案的切换不是新边界。
+ finalizeStreamTail();
+ lastFinalUuid = undefined;
+ pushRenderMessage('system', '', { role: 'system', content: { kind: 'interaction' } });
+ },
+ progressBody(): string {
+ return progressAssistantText();
+ },
+ wholeText(): string {
+ return assistantText;
+ },
+ finalText(): string {
+ return finalAnswerText();
+ },
+ replaceBody(): void {
+ // finalized-segments 没有单一缓冲可整体替换(正文是按消息切开的定稿段 +
+ // 流式尾部)。observer 从不调用它; 调到即接线错误, 显式失败而不是静默吞掉。
+ throw new Error('finalized-segments presenter does not support replaceBody');
+ },
+ };
+}
+
+export function createTurnPresenter(options: TurnPresenterOptions): TurnPresenter {
+ const startedAt = options.startedAt ?? Date.now();
+ const policy = options.policy ?? DEFAULT_PRESENTER_POLICY;
+ const body: BodyEngine =
+ options.mode === 'finalized-segments' ? createSegmentsEngine() : createBufferEngine();
+ const activity = createTurnActivity(startedAt);
+ const composeRunning = (b: string): string =>
+ composeProgressView(renderActivity(activity, Date.now()), b);
+ const emitter = options.onProgress
+ ? createProgressEmitter(options.onProgress, () => composeRunning(body.progressBody()), policy)
+ : null;
+
+ return {
+ activity,
+ applyText(ev: AgentEvent): boolean {
+ const data = ev.data as { text?: string } | null;
+ if (!data || typeof data.text !== 'string') return false;
+ body.applyText(ev);
+ markActivityWriting(activity);
+ return true;
+ },
+ applyToolUse(ev: AgentEvent): boolean {
+ const data = ev.data as { toolName?: unknown; toolUseId?: unknown; input?: unknown } | null;
+ if (!data || typeof data.toolName !== 'string') return false;
+ const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : undefined;
+ body.projectToolUse(data.toolName, data.input, toolUseId);
+ pushToolStep(activity, data.toolName, data.input, toolUseId);
+ return true;
+ },
+ applyThinking(ev: AgentEvent): boolean {
+ body.projectThinking(ev);
+ return pushThinkingStep(activity, ev.data);
+ },
+ applyRetryNotice(ev: AgentEvent): boolean {
+ const notice = turnRetryNotice(ev.data);
+ if (notice === null) return false;
+ return setActivityNotice(activity, notice);
+ },
+ seal(): void {
+ body.seal();
+ },
+ markInteractionBoundary(): void {
+ body.projectInteractionBoundary();
+ },
+ setInteractionNotice(notice: string | null): boolean {
+ return setInteractionNotice(activity, notice);
+ },
+ progressBody(): string {
+ return body.progressBody();
+ },
+ wholeText(): string {
+ return body.wholeText();
+ },
+ finalText(): string {
+ return body.finalText();
+ },
+ replaceBody(text: string): void {
+ body.replaceBody(text);
+ },
+ composeRunning,
+ scheduleProgress(): void {
+ emitter?.schedule();
+ },
+ ensureProgressTicker(): void {
+ emitter?.ensureTicker();
+ },
+ stopProgress(): void {
+ emitter?.stop();
+ },
+ };
+}
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 4e165e9f78..c012293376 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -126,6 +126,7 @@ import {
type TurnActivityState,
} from './turnActivity';
import { terminalErrorText, turnRetryNotice } from './turnRetryNotice';
+import { createTurnPresenter, DEFAULT_PRESENTER_POLICY, type TurnPresenter } from './turnPresenter';
import {
toCoreAgentKind,
readPermissionMode,
@@ -161,15 +162,17 @@ interface TurnState {
* Without it we get one card per delta — a flood of orphan cards.
*/
streamingHandlePromise: Promise<StreamingTextHandle> | null;
- /** Real assistant text accumulated this turn. */
- buffer: string;
+ /**
+ * 呈现大脑(正文累积 / 过程区合成), 与官方 bot 共用 im/shared/turnPresenter。
+ * buffer-replace 策略: 保留个人 IM 渠道现有行为 —— isFinal 用该条全文整体替换
+ * 累积缓冲, 流式增量追加。过程区时间线状态经 presenter.activity 暴露。
+ */
+ presenter: TurnPresenter;
/** Managed images discovered in tool output for durable text channels. */
mediaAbsPaths: string[];
/** Current session root used to confine model-authored local file links. */
workingDir: string;
done: boolean;
- /** 过程展示(tool_use 时间线)状态 — 见 turnActivity.ts。 */
- activity: TurnActivityState;
/** 过程区耗时刷新的低频 ticker(首个 tool_use 启动, 收口清除)。 */
activityTicker: ReturnType<typeof setInterval> | null;
outputCardMessageId: string | null;
@@ -440,8 +443,11 @@ export function createTurnRunner(
* patchMarkdownCard 的尾随节流间隔 — 对齐渠道 streamingText 的安全水位
* (slack chat.update 1.3s / feishu patch 1.5s, 取保守值)。此前这里每个
* delta 直接打一次 patch, 文本快答没事, 接入过程事件后会撞渠道限流。
+ *
+ * #1855 L1: 引用 PresenterPolicy 的单一出处 —— 与官方 turnObserver 的
+ * trailing-edge 发射器同值同语义, 不再各写一个 1500 magic number。
*/
- const CARD_PATCH_THROTTLE_MS = 1500;
+ const CARD_PATCH_THROTTLE_MS = DEFAULT_PRESENTER_POLICY.intermediateThrottleMs;
const log = createLogger(`im:${channel}:turn`);
@@ -656,11 +662,10 @@ export function createTurnRunner(
initialMessageText: text,
streamingHandle: null,
streamingHandlePromise: null,
- buffer: '',
+ presenter: createTurnPresenter({ mode: 'buffer-replace' }),
mediaAbsPaths: [],
workingDir: row.workingDir,
done: false,
- activity: createTurnActivity(Date.now()),
activityTicker: null,
outputCardMessageId: args.outputCardMessageId ?? null,
outputCardPrefix: args.outputCardPrefix ?? '',
@@ -816,7 +821,7 @@ export function createTurnRunner(
await beginChunkedReply(item.turn);
// 过程区耗时基准取真实派发时刻 — TurnState 创建时可能还要在 sendQueue 里
// 等上一轮跑完, 排队等待不该计入"第 N 步 · 耗时"显示
- item.turn.activity.startedAt = Date.now();
+ item.turn.presenter.activity.startedAt = Date.now();
state.queue.push(item.turn);
log.info(
`enqueued turn for session=${rowId.slice(-8)} queueDepth=${state.queue.length} pendingSends=${state.sendQueue.length}`,
@@ -1826,30 +1831,21 @@ export function createTurnRunner(
* 纯文本快答没有 tool_use, renderActivity 返回空串, 视图与旧行为逐字一致。
*/
function composeStreamingView(turn: TurnState): string {
- const rawBody = turn.outputCardPrefix ? turn.outputCardPrefix + turn.buffer : turn.buffer;
+ const rawBody = turn.outputCardPrefix
+ ? turn.outputCardPrefix + turn.presenter.wholeText()
+ : turn.presenter.wholeText();
// External-channel safeguard: maker-core normally strips these tokens,
// while this boundary also protects old continuations and future adapters.
const body = stripInternalWebCitations(rawBody);
if (turn.done) return body;
- const act = renderActivity(turn.activity, Date.now());
- if (!act) return body;
- return body ? `${act}\n\n${body}` : act;
+ // 过程区在上、正文在下的合成骨架与官方 bot 共用(presenter.composeRunning →
+ // composeProgressView); 纯文本快答无 tool_use 时过程区为空, 视图与旧行为逐字一致。
+ return turn.presenter.composeRunning(body);
}
/** tool_use → 过程区时间线推进 + 卡片刷新(渠道 handle 自带节流兜底)。 */
function handleToolUseEvent(turn: TurnState, event: AgentEvent): void {
- const data = event.data as {
- toolName?: unknown;
- toolUseId?: unknown;
- input?: unknown;
- } | null;
- if (!data || typeof data.toolName !== 'string') return;
- pushToolStep(
- turn.activity,
- data.toolName,
- data.input,
- typeof data.toolUseId === 'string' ? data.toolUseId : undefined,
- );
+ if (!turn.presenter.applyToolUse(event)) return;
ensureActivityTicker(turn);
void ensureStreamingHandle(turn).then((h) => h.replace(composeStreamingView(turn)));
}
@@ -1867,9 +1863,7 @@ export function createTurnRunner(
* 同一张卡上, 重试耗尽时 handleTurnErrorAsync 会把它 finalize 成失败说明。
*/
function handleRetryNoticeEvent(turn: TurnState, event: AgentEvent): void {
- const notice = turnRetryNotice(event.data);
- if (notice === null) return;
- if (!setActivityNotice(turn.activity, notice)) return;
+ if (!turn.presenter.applyRetryNotice(event)) return;
ensureActivityTicker(turn);
void ensureStreamingHandle(turn).then((h) => h.replace(composeStreamingView(turn)));
}
@@ -2118,7 +2112,7 @@ export function createTurnRunner(
turn.resolveTerminal = null;
resolve({
kind: turn.terminalKind,
- text: turn.buffer,
+ text: turn.presenter.wholeText(),
completedAt: Date.now(),
...(turn.terminalErrorCode ? { errorCode: turn.terminalErrorCode } : {}),
});
@@ -2314,20 +2308,12 @@ export function createTurnRunner(
}
function handleTextEvent(turn: TurnState, event: AgentEvent): void {
- const data = event.data as { text?: string; isFinal?: boolean } | null;
- if (!data || typeof data.text !== 'string') return;
- markActivityWriting(turn.activity);
- if (data.isFinal) {
- // Final block — replace buffer with canonical text. 也立刻 replace 卡片 ——
- // 之前依赖 done 时 finalize 才把内容写进卡片, 但 SDK 在某些场景 (短回复 /
- // reasoning models / oneshot summary) 只会发 isFinal=true 不走 deltas,
- // 这时卡片会一直停在 "灵感正在路上..." placeholder 直到 done; done 之间
- // 几秒延迟里用户看着像 stuck。replace 一次保证用户即时看到回复内容。
- turn.buffer = data.text;
- void ensureStreamingHandle(turn).then((h) => h.replace(composeStreamingView(turn)));
- return;
- }
- turn.buffer += data.text;
+ // 正文累积(isFinal 用该条全文整体替换缓冲 / 增量追加)与 markActivityWriting
+ // 都在 presenter 的 buffer-replace 策略里。也立刻 replace 卡片 —— SDK 在某些
+ // 场景(短回复 / reasoning models / oneshot summary)只发 isFinal=true 不走
+ // deltas, 这时卡片会一直停在 "灵感正在路上..." placeholder 直到 done; done 之间
+ // 几秒延迟里用户看着像 stuck。replace 一次保证用户即时看到回复内容。
+ if (!turn.presenter.applyText(event)) return;
void ensureStreamingHandle(turn).then((h) => h.replace(composeStreamingView(turn)));
}
@@ -2459,7 +2445,7 @@ export function createTurnRunner(
`streamingHandle.finalize failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`,
);
}
- } else if (turn.buffer.length === 0) {
+ } 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.)
try {
@@ -2517,7 +2503,7 @@ export function createTurnRunner(
// 清掉"正在自动重试"这类瞬态说明:重试耗尽后走到这里时它还挂在 activity 上,
// 而下面 composeStreamingView 会把它一起写进 finalize 的正文——最终卡片会在
// 失败说明的正上方永久显示"仍在重试"(review #844 codex P1)。
- if (turn) setActivityNotice(turn.activity, null);
+ if (turn) setActivityNotice(turn.presenter.activity, null);
if (turn) await materializeTurnLocalImages(state, turn);
// 建卡请求可能还在飞: 过载重试提示会惰性建一张进度卡(handleRetryNoticeEvent),
// 而终态错误可能恰好在 startStreamingText 回来之前到达。此时 streamingHandle
@@ -2567,16 +2553,16 @@ export function createTurnRunner(
}
async function materializeTurnLocalImages(state: SessionState, turn: TurnState): Promise<void> {
- if (output.kind !== 'chunked-text' || !turn.buffer.includes('![')) return;
+ if (output.kind !== 'chunked-text' || !turn.presenter.wholeText().includes('![')) return;
try {
const materialized = await materializeLocalMarkdownImages({
- text: turn.buffer,
+ text: turn.presenter.wholeText(),
workingDir: state.workingDir,
sessionId: state.makerSession.id,
maxImages: 4,
existingAbsPaths: [...turn.mediaAbsPaths],
});
- turn.buffer = materialized.text;
+ turn.presenter.replaceBody(materialized.text);
for (const absPath of materialized.absPaths) {
if (!turn.mediaAbsPaths.includes(absPath)) turn.mediaAbsPaths.push(absPath);
}
@@ -2789,7 +2775,7 @@ export function createTurnRunner(
}
turn.streamingHandle = null;
turn.streamingHandlePromise = null;
- turn.buffer = '';
+ turn.presenter.replaceBody('');
}
// ── cleanup (binding detach / dispose) ──────────────────────────────────────
diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.ts
index f8977e12f8..7b454184f8 100644
--- a/packages/lizi-im/src/index.ts
+++ b/packages/lizi-im/src/index.ts
@@ -45,6 +45,8 @@ export { TelegramIM, createTelegramIM } from './telegram/index.js';
export type { TelegramIMOptions, TelegramGroupWindowEntry } from './telegram/index.js';
export { TELEGRAM_DEFAULT_BEHAVIOR } from './telegram/index.js';
export type { TelegramBehaviorConfig } from './telegram/index.js';
+export { TELEGRAM_PERSONAL_CAPABILITIES } from './telegram/presentationCapabilities.js';
+export type { TelegramDriverCapabilities } from './telegram/presentationCapabilities.js';
export { WecomIM, createWecomIM } from './wecom/index.js';
export type { WecomIMOptions } from './wecom/index.js';
export {
diff --git a/packages/lizi-im/src/telegram/__tests__/cardLayout.test.ts b/packages/lizi-im/src/telegram/__tests__/cardLayout.test.ts
new file mode 100644
index 0000000000..5d5ccc7080
--- /dev/null
+++ b/packages/lizi-im/src/telegram/__tests__/cardLayout.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { TELEGRAM_CARD_LAYOUT } from '../cardLayout.js';
+
+describe('TELEGRAM_CARD_LAYOUT', () => {
+ it('取个人车道现值(behavior-preserving 64/12/3800), 不采用官方旧 60/4000', () => {
+ expect(TELEGRAM_CARD_LAYOUT.buttonLabelMax).toBe(64);
+ expect(TELEGRAM_CARD_LAYOUT.pairLabelMax).toBe(12);
+ expect(TELEGRAM_CARD_LAYOUT.cardTextMax).toBe(3800);
+ });
+
+ it('pairLabelMax 严格小于 buttonLabelMax(并排阈值不超过截断上限)', () => {
+ expect(TELEGRAM_CARD_LAYOUT.pairLabelMax).toBeLessThan(TELEGRAM_CARD_LAYOUT.buttonLabelMax);
+ });
+});
diff --git a/packages/lizi-im/src/telegram/__tests__/htmlCap.test.ts b/packages/lizi-im/src/telegram/__tests__/htmlCap.test.ts
new file mode 100644
index 0000000000..a2165d38d7
--- /dev/null
+++ b/packages/lizi-im/src/telegram/__tests__/htmlCap.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { capRenderedText } from '../htmlCap.js';
+
+describe('capRenderedText', () => {
+ it('长度不超上限时原样返回', () => {
+ expect(capRenderedText('<b>hi</b>', 100)).toBe('<b>hi</b>');
+ });
+
+ it('截点落在标签内部时回退到标签前, 不产生残缺 <', () => {
+ const html = `${'x'.repeat(20)}<a href="https://example.com/very/long">link</a>`;
+ const out = capRenderedText(html, 30);
+ expect(out.lastIndexOf('<')).toBeLessThanOrEqual(out.lastIndexOf('>'));
+ });
+
+ it('未配对开标签在截断处补闭合(open/close 计数一致)', () => {
+ const html = `<b>${'a'.repeat(50)}</b>`;
+ const out = capRenderedText(html, 20);
+ expect((out.match(/<b>/g) ?? []).length).toBe((out.match(/<\/b>/g) ?? []).length);
+ expect(out).toContain('</b>');
+ expect(out).toContain('…');
+ });
+
+ it('截点落在实体中间时回退到 & 前', () => {
+ const html = `${'y'.repeat(18)}&amp;more`;
+ const out = capRenderedText(html, 22);
+ const amp = out.lastIndexOf('&');
+ if (amp !== -1) expect(out.slice(amp)).toContain(';');
+ });
+
+ it('嵌套标签按栈序逆序闭合', () => {
+ const html = `<b><i>${'z'.repeat(40)}</i></b>`;
+ const out = capRenderedText(html, 15);
+ // 先闭合内层 i 再闭合外层 b
+ expect(out.endsWith('…</i></b>')).toBe(true);
+ });
+});
diff --git a/packages/lizi-im/src/telegram/__tests__/presentationCapabilities.test.ts b/packages/lizi-im/src/telegram/__tests__/presentationCapabilities.test.ts
new file mode 100644
index 0000000000..54e0054002
--- /dev/null
+++ b/packages/lizi-im/src/telegram/__tests__/presentationCapabilities.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { TELEGRAM_PERSONAL_CAPABILITIES } from '../presentationCapabilities.js';
+
+/**
+ * 呈现能力契约的单一真相源锚定(#1855 L1)。可兑现字段的**实际消费**由 index.ts
+ * 编译期强制(typing 续命间隔/上限、link preview 直接引用本常量,若改名/删除则 tsc
+ * 失败);本文件锚定契约值本身,防止有人把值改回第二真相源。
+ */
+describe('TELEGRAM_PERSONAL_CAPABILITIES — 个人车道能力契约(单一出处)', () => {
+ it('声明个人车道现值(driver 直接消费的可兑现字段 + 声明车道差异)', () => {
+ expect(TELEGRAM_PERSONAL_CAPABILITIES).toEqual({
+ progressSilent: true,
+ typingKeepaliveMs: 4_500,
+ typingKeepaliveMaxMs: 5 * 60_000,
+ linkPreviewDisabled: true,
+ noReplyScope: 'all-turns',
+ messageEffectIdSupported: false,
+ threadIdDualSemantics: true,
+ laneModel: 'per-chat',
+ });
+ });
+
+ it('typing 续命 4.5s < 上限 5min(续命间隔远小于兜底上限)', () => {
+ expect(TELEGRAM_PERSONAL_CAPABILITIES.typingKeepaliveMs).toBeLessThan(
+ TELEGRAM_PERSONAL_CAPABILITIES.typingKeepaliveMaxMs,
+ );
+ });
+
+ it('NO_REPLY 生效范围为 all-turns(与 streamingText.finalize 的无 ambient 门控一致)', () => {
+ expect(TELEGRAM_PERSONAL_CAPABILITIES.noReplyScope).toBe('all-turns');
+ });
+});
diff --git a/packages/lizi-im/src/telegram/__tests__/reactionPool.test.ts b/packages/lizi-im/src/telegram/__tests__/reactionPool.test.ts
new file mode 100644
index 0000000000..f7a4ca2055
--- /dev/null
+++ b/packages/lizi-im/src/telegram/__tests__/reactionPool.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ EXPRESSIVE_DONE_POOL,
+ EXPRESSIVE_ERROR_POOL,
+ pickExpressiveReaction,
+} from '../reactionPool.js';
+
+describe('expressive reaction pools', () => {
+ it('池规模为 35(正) + 10(负)', () => {
+ expect(EXPRESSIVE_DONE_POOL).toHaveLength(35);
+ expect(EXPRESSIVE_ERROR_POOL).toHaveLength(10);
+ });
+
+ it('正/负池不相交(成功不会随机出负向表情)', () => {
+ const neg = new Set<string>(EXPRESSIVE_ERROR_POOL);
+ for (const e of EXPRESSIVE_DONE_POOL) expect(neg.has(e)).toBe(false);
+ });
+
+ it('基础款仍在各自池首位(回落安全)', () => {
+ expect(EXPRESSIVE_DONE_POOL[0]).toBe('👍');
+ expect(EXPRESSIVE_ERROR_POOL[0]).toBe('👎');
+ });
+
+ it('pickExpressiveReaction 按注入 random 确定取值', () => {
+ expect(pickExpressiveReaction(EXPRESSIVE_DONE_POOL, () => 0)).toBe('👍');
+ expect(pickExpressiveReaction(EXPRESSIVE_ERROR_POOL, () => 0)).toBe('👎');
+ // random 接近 1 时取末位
+ expect(pickExpressiveReaction(EXPRESSIVE_DONE_POOL, () => 0.999)).toBe(
+ EXPRESSIVE_DONE_POOL[EXPRESSIVE_DONE_POOL.length - 1],
+ );
+ });
+});
diff --git a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
index f2307ec57b..362e0c2144 100644
--- a/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/streamingText.test.ts
@@ -212,4 +212,20 @@ describe('telegram streaming finalize — 原位定稿与 flood 兜底', () => {
expect(h.deleted).toEqual(['msg-1']);
expect(h.sent).toEqual(['⚙️ 工作中 · 8s']);
});
+
+ // #1855 L1: NO_REPLY 生效范围 = all-turns。streamingText 层不认识 ambient/非 ambient,
+ // finalize 的 isNoReply 判定对任何轮次一视同仁 —— 惰性占位下(未建过消息)整条
+ // NO_REPLY 从头到尾零出站零删除, 与 TELEGRAM_PERSONAL_CAPABILITIES.noReplyScope 一致。
+ it('NO_REPLY(惰性占位, 未建消息)零出站零删除 — 任何轮次一视同仁(all-turns)', async () => {
+ const h = makeHarness();
+ const handle = await startTelegramStreaming(h.deps); // 无初始占位
+
+ await handle.finalize('NO_REPLY');
+
+ expect(h.sent).toEqual([]);
+ expect(h.reposted).toEqual([]);
+ expect(h.deleted).toEqual([]);
+ expect(h.calls).toEqual([]);
+ expect(handle.messageId).toBe('');
+ });
});
diff --git a/packages/lizi-im/src/telegram/cardLayout.ts b/packages/lizi-im/src/telegram/cardLayout.ts
new file mode 100644
index 0000000000..7cebc76c04
--- /dev/null
+++ b/packages/lizi-im/src/telegram/cardLayout.ts
@@ -0,0 +1,31 @@
+/**
+ * telegram/cardLayout.ts — Telegram 交互卡的**渲染布局/尺寸**参数(#1855 L1)。
+ * ---------------------------------------------------------------------------
+ * `buildCardPayload` 的**唯一** label/body 尺寸与排布阈值来源(传输层渲染)。
+ *
+ * **与 desktop 的语义模型分层,勿混**:`apps/desktop/src/main/im/shared/
+ * interactionCardModel.ts`(#1925)是跨渠道的**语义层**单一出处(选项集 / 决策对象 /
+ * header-body 拆分,含产品级 `BTN_LABEL_MAX=30` 截断)。本模块只管 @cindy/im 传输层
+ * 把 `InteractiveCardSpec` 渲染成 Telegram HTML + inline keyboard 时的**物理尺寸**:
+ * 按钮文案的 Telegram 硬上限、并排阈值、正文 HTML 截断长度。两者不同层、不同包
+ * (`@cindy/im` 不得依赖 `apps/desktop`),故各持一份、名字刻意区分开。
+ *
+ * **刻意不采用官方旧 label60 / 正文4000** —— 那是待退役的服务端渲染栈的值, 合同
+ * 明确不得成为共享参数源。本参数取个人车道现值(behavior-preserving: 64 / 12 /
+ * 3800), 官方旧值不进来。不统一两侧 builder(hook 侧中立 buttonId、个人侧 inline
+ * keyboard 排布各自保留 —— 参见合同 §B / §6)。
+ */
+export interface TelegramCardLayout {
+ /** 按钮 label 截断上限(字符;Telegram 传输层硬上限)。 */
+ buttonLabelMax: number;
+ /** label 短于此值时允许两键并排。 */
+ pairLabelMax: number;
+ /** 卡片正文 HTML 截断上限(交由 capRenderedText 做标签栈安全闭合)。 */
+ cardTextMax: number;
+}
+
+export const TELEGRAM_CARD_LAYOUT: TelegramCardLayout = {
+ buttonLabelMax: 64,
+ pairLabelMax: 12,
+ cardTextMax: 3800,
+};
diff --git a/packages/lizi-im/src/telegram/components.ts b/packages/lizi-im/src/telegram/components.ts
index 8d7dc18be3..8b25a1ff41 100644
--- a/packages/lizi-im/src/telegram/components.ts
+++ b/packages/lizi-im/src/telegram/components.ts
@@ -12,13 +12,10 @@
import type { IMCardActionEvent, InteractiveCardSpec } from '../types.js';
import type { TgCallbackQuery } from './api.js';
import { decodeCallbackData, encodeCallbackData, encodeMessageId, encodeLaneUserId } from './codec.js';
+import { TELEGRAM_CARD_LAYOUT } from './cardLayout.js';
+import { capRenderedText } from './htmlCap.js';
import { markdownToTelegramHtml } from './markdown.js';
-const BUTTON_LABEL_MAX = 64;
-/** label 短于此值时允许两键并排。 */
-const PAIR_LABEL_MAX = 12;
-const CARD_TEXT_MAX = 3800;
-
export interface TelegramInlineKeyboardButton {
text: string;
callback_data: string;
@@ -30,7 +27,7 @@ export function buildCardPayload(spec: InteractiveCardSpec): {
} {
const title = spec.title ? `<b>${escapeTitle(spec.title)}</b>\n\n` : '';
const { html: body } = markdownToTelegramHtml(spec.body);
- const html = capCardText(`${title}${body}`);
+ const html = capRenderedText(`${title}${body}`, TELEGRAM_CARD_LAYOUT.cardTextMax);
// 无按钮时必须显式下发空键盘: 省略 reply_markup 只会改文本, Telegram 保留旧键盘,
// 于是已收口的卡片(过期/已解决)仍带着可点的按钮。
@@ -40,10 +37,10 @@ export function buildCardPayload(spec: InteractiveCardSpec): {
let pendingPair: TelegramInlineKeyboardButton | null = null;
for (const button of spec.buttons) {
const rendered: TelegramInlineKeyboardButton = {
- text: button.label.slice(0, BUTTON_LABEL_MAX),
+ text: button.label.slice(0, TELEGRAM_CARD_LAYOUT.buttonLabelMax),
callback_data: encodeCallbackData(button.id, button.payload ?? {}),
};
- if (button.label.length <= PAIR_LABEL_MAX) {
+ if (button.label.length <= TELEGRAM_CARD_LAYOUT.pairLabelMax) {
if (pendingPair) {
rows.push([pendingPair, rendered]);
pendingPair = null;
@@ -114,36 +111,3 @@ export function parseCallbackQuery(q: TgCallbackQuery): IMCardActionEvent | null
function escapeTitle(title: string): string {
return title.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
-
-/**
- * HTML 安全截断: 纯字符切片可能切在标签(<a href=...)或实体(&amp;)中间,
- * parse_mode=HTML 的 sendMessage 会 400 整条失败。截点回退到完整边界,
- * 再栈扫描闭合未配对标签(Telegram HTML 子集无自闭合标签)。
- */
-function capCardText(html: string): string {
- if (html.length <= CARD_TEXT_MAX) return html;
- let cut = html.slice(0, CARD_TEXT_MAX - 1);
- const lastOpen = cut.lastIndexOf('<');
- if (lastOpen > cut.lastIndexOf('>')) cut = cut.slice(0, lastOpen);
- const lastAmp = cut.lastIndexOf('&');
- if (lastAmp !== -1 && !cut.slice(lastAmp).includes(';') && cut.length - lastAmp <= 10) {
- cut = cut.slice(0, lastAmp);
- }
- const stack: string[] = [];
- const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)(?:\s[^>]*)?>/g;
- let m: RegExpExecArray | null;
- while ((m = tagRe.exec(cut)) !== null) {
- const name = m[2].toLowerCase();
- if (m[1]) {
- const idx = stack.lastIndexOf(name);
- if (idx !== -1) stack.splice(idx, 1);
- } else {
- stack.push(name);
- }
- }
- const closers = stack
- .reverse()
- .map((name) => `</${name}>`)
- .join('');
- return `${cut}…${closers}`;
-}
diff --git a/packages/lizi-im/src/telegram/htmlCap.ts b/packages/lizi-im/src/telegram/htmlCap.ts
new file mode 100644
index 0000000000..9cb8779d2f
--- /dev/null
+++ b/packages/lizi-im/src/telegram/htmlCap.ts
@@ -0,0 +1,43 @@
+/**
+ * telegram/htmlCap.ts — HTML 安全截断(标签栈闭合)。
+ * ---------------------------------------------------------------------------
+ * #1855 L1: 从 components.capCardText 提取为**导出的通用原语** `capRenderedText`,
+ * 供交互卡正文与其它 Telegram HTML 出站复用(官方旧路径裸 truncate(4000) 会切在
+ * 标签中间整卡 400 —— 统一到这条安全截断)。
+ *
+ * 纯字符切片可能切在标签(`<a href=...`)或实体(`&amp;`)中间, parse_mode=HTML
+ * 的 sendMessage 会 400 整条失败。截点先回退到完整边界, 再栈扫描闭合未配对的
+ * 开标签(Telegram HTML 子集无自闭合标签)。
+ */
+
+/**
+ * 把 `html` 安全截断到不超过 `maxChars`(含尾部省略号与补闭合标签)。
+ * `html.length <= maxChars` 时原样返回。
+ */
+export function capRenderedText(html: string, maxChars: number): string {
+ if (html.length <= maxChars) return html;
+ let cut = html.slice(0, maxChars - 1);
+ const lastOpen = cut.lastIndexOf('<');
+ if (lastOpen > cut.lastIndexOf('>')) cut = cut.slice(0, lastOpen);
+ const lastAmp = cut.lastIndexOf('&');
+ if (lastAmp !== -1 && !cut.slice(lastAmp).includes(';') && cut.length - lastAmp <= 10) {
+ cut = cut.slice(0, lastAmp);
+ }
+ const stack: string[] = [];
+ const tagRe = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)(?:\s[^>]*)?>/g;
+ let m: RegExpExecArray | null;
+ while ((m = tagRe.exec(cut)) !== null) {
+ const name = m[2].toLowerCase();
+ if (m[1]) {
+ const idx = stack.lastIndexOf(name);
+ if (idx !== -1) stack.splice(idx, 1);
+ } else {
+ stack.push(name);
+ }
+ }
+ const closers = stack
+ .reverse()
+ .map((name) => `</${name}>`)
+ .join('');
+ return `${cut}…${closers}`;
+}
diff --git a/packages/lizi-im/src/telegram/index.ts b/packages/lizi-im/src/telegram/index.ts
index ae32d8547a..880c4b4f3d 100644
--- a/packages/lizi-im/src/telegram/index.ts
+++ b/packages/lizi-im/src/telegram/index.ts
@@ -53,6 +53,12 @@ import {
type TelegramGroupWindowEntry,
} from './inbound.js';
import { markdownToTelegramHtml, stripTelegramHtmlTags } from './markdown.js';
+import { TELEGRAM_PERSONAL_CAPABILITIES } from './presentationCapabilities.js';
+import {
+ EXPRESSIVE_DONE_POOL,
+ EXPRESSIVE_ERROR_POOL,
+ pickExpressiveReaction,
+} from './reactionPool.js';
import { startTelegramStreaming } from './streamingText.js';
const TOKEN_SECRET_KEY = 'telegram-bot-token';
@@ -100,10 +106,17 @@ function retryAfterWaitMs(retryAfterSec: number | undefined): number {
}
const MAX_OUTBOUND_FILE_BYTES = 50 * 1024 * 1024;
const OWNER_NOTICE_TIMEOUT_MS = 4_500;
-/** typing 状态原生只持续 ~5s — 按 4.5s 续命直到首条真实消息发出。 */
-const TYPING_REFRESH_MS = 4_500;
-/** typing 循环兜底上限(turn 异常悬挂时不无限打 API)。 */
-const TYPING_LOOP_MAX_MS = 5 * 60_000;
+/**
+ * typing 续命间隔/上限:引用呈现能力契约的**单一出处**(#1855 L1),不再本地
+ * 硬编码 —— 与 desktop turnPresenter re-export 的 PERSONAL_DRIVER_CAPABILITIES 同源。
+ * (原生 typing 只持续 ~5s,按 keepaliveMs 续命;keepaliveMaxMs 是异常悬挂兜底上限。)
+ */
+const TYPING_REFRESH_MS = TELEGRAM_PERSONAL_CAPABILITIES.typingKeepaliveMs;
+const TYPING_LOOP_MAX_MS = TELEGRAM_PERSONAL_CAPABILITIES.typingKeepaliveMaxMs;
+/** link preview 关闭:全档出站/编辑共用,取自能力契约单一出处(见 linkPreviewDisabled)。 */
+const LINK_PREVIEW_OPTIONS = {
+ is_disabled: TELEGRAM_PERSONAL_CAPABILITIES.linkPreviewDisabled,
+} as const;
const SECRET_WRITE_FAILED_REASON = '无法安全保存凭证(系统安全存储不可用)';
const DEFAULT_EXPIRED_CARD_NOTICE = '卡片已过期';
@@ -228,22 +241,6 @@ export const TELEGRAM_DEFAULT_BEHAVIOR: TelegramBehaviorConfig = {
replyQuoteDm: 'off',
};
-/**
- * 生动档变体池 — Telegram bot 可用标准 reaction 全集按语义分池(Chris:
- * 能用的都随便用)。正/负分开是底线: 成功不能随机出 💩/🤡。选中表情在该
- * 群被限制时(available_reactions), setMessageReaction 会 400 — 回落基础款
- * 重试一次。
- */
-const EXPRESSIVE_DONE_POOL = [
- '👍', '❤', '🔥', '🥰', '👏', '😁', '🎉', '🤩', '🙏', '👌',
- '😍', '❤‍🔥', '💯', '🤣', '⚡', '🏆', '🍾', '🤗', '🫡', '😇',
- '🤝', '💅', '🆒', '💘', '😎', '🦄', '🕊', '🐳', '🍓', '💋',
- '😘', '🎃', '👾', '🍌', '🌭',
-] as const;
-const EXPRESSIVE_ERROR_POOL = [
- '👎', '😱', '😢', '💔', '😨', '🤯', '🥴', '🙈', '😐', '🗿',
-] as const;
-
export interface TelegramIMOptions {
/** cindy-media:// / xdt-image:// → 本地绝对路径(出站图片上传用)。 */
resolveImageUrl?: (url: string) => string;
@@ -932,10 +929,9 @@ export class TelegramIM extends BaseIM implements ChannelIM {
if (behavior.emojiReactions === 'expressive') {
// 终态用变体池(生动档); ack(👀)保持稳重不随机。
if (emoji === '👍') {
- effective = EXPRESSIVE_DONE_POOL[Math.floor(Math.random() * EXPRESSIVE_DONE_POOL.length)];
+ effective = pickExpressiveReaction(EXPRESSIVE_DONE_POOL);
} else if (emoji === '👎') {
- effective =
- EXPRESSIVE_ERROR_POOL[Math.floor(Math.random() * EXPRESSIVE_ERROR_POOL.length)];
+ effective = pickExpressiveReaction(EXPRESSIVE_ERROR_POOL);
}
}
const { chatId, messageId: nativeId } = decodeMessageId(messageId);
@@ -1780,7 +1776,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
...replyParams,
text: html || '…',
parse_mode: 'HTML',
- link_preview_options: { is_disabled: true },
+ link_preview_options: LINK_PREVIEW_OPTIONS,
});
} catch (err) {
if (err instanceof TelegramApiError && err.errorCode === 400) {
@@ -1788,7 +1784,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
...target,
...replyParams,
text: markdownChunk || '…',
- link_preview_options: { is_disabled: true },
+ link_preview_options: LINK_PREVIEW_OPTIONS,
});
} else {
throw err;
@@ -1813,7 +1809,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
...target,
...replyParams,
text: chunk || '…',
- link_preview_options: { is_disabled: true },
+ link_preview_options: LINK_PREVIEW_OPTIONS,
});
if (!firstMessageId) {
this.commitReplyTarget(lease);
@@ -1836,7 +1832,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
message_id: Number(nativeMessageId),
text: html || '…',
parse_mode: 'HTML',
- link_preview_options: { is_disabled: true },
+ link_preview_options: LINK_PREVIEW_OPTIONS,
...(replyMarkup !== undefined ? { reply_markup: replyMarkup } : {}),
});
} catch (err) {
@@ -1847,7 +1843,7 @@ export class TelegramIM extends BaseIM implements ChannelIM {
chat_id: chatId,
message_id: Number(nativeMessageId),
text: stripTelegramHtmlTags(html) || '…',
- link_preview_options: { is_disabled: true },
+ link_preview_options: LINK_PREVIEW_OPTIONS,
// 同样要带上 reply_markup: 走到这条 fallback 时若省略, 清空键盘的意图会被丢掉。
...(replyMarkup !== undefined ? { reply_markup: replyMarkup } : {}),
}).catch((fallbackErr) => {
diff --git a/packages/lizi-im/src/telegram/presentationCapabilities.ts b/packages/lizi-im/src/telegram/presentationCapabilities.ts
new file mode 100644
index 0000000000..22685de8f5
--- /dev/null
+++ b/packages/lizi-im/src/telegram/presentationCapabilities.ts
@@ -0,0 +1,61 @@
+/**
+ * telegram/presentationCapabilities.ts — 个人 Telegram driver 的呈现能力契约(#1855 L1)。
+ * ---------------------------------------------------------------------------
+ * **单一真相源**:需要真正出站 / 渠道能力才能兑现的呈现策略与车道差异。合同要求
+ * "不能只留声明/TODO" —— 本模块的值由**同包 driver(index.ts)真正消费**:typing
+ * 续命间隔/上限、link preview 关闭都直接引用这里,不再各写字面量;desktop 侧
+ * `turnPresenter` 再从 `@cindy/im` re-export(依赖方向 desktop → @cindy/im,不成环),
+ * 作为 L1 呈现层的能力声明锚。
+ *
+ * **不含 replyQuote**:emoji / replyQuoteGroup / replyQuoteDm 三档继续由各车道的
+ * `TelegramBehaviorConfig` 三字段直接供给,不进入本能力契约、不带出厂默认
+ * (#1855 replyQuote 勘误)。
+ */
+export interface TelegramDriverCapabilities {
+ /**
+ * 进度消息静音:过程帧不触发推送。个人栈**由设计兑现**而非独立开关 ——
+ * 流式路径靠惰性占位 + editMessageText 覆盖(编辑不推送),没有单独带通知的
+ * 过程消息。true 表示"过程帧零推送"这一既有性质;driver 无需再设 disable_notification。
+ */
+ progressSilent: boolean;
+ /** typing 保活重发间隔(ms)。原生 typing 只持续 ~5s,按此值续命。driver 直接消费。 */
+ typingKeepaliveMs: number;
+ /**
+ * typing 保活总上限(ms):超过即停发,turn 异常悬挂时不无限打 API。driver 直接消费。
+ * 官方侧 10min + 设备在线门控是车道差异,跨服务端不在本仓兑现。
+ */
+ typingKeepaliveMaxMs: number;
+ /** link preview 关闭覆盖面:true = 全档关闭(个人现状)。driver 出站直接消费。 */
+ linkPreviewDisabled: boolean;
+ /**
+ * NO_REPLY 哨兵生效范围。'all-turns' = 任何轮次(ambient 与非 ambient)命中哨兵都
+ * 静默。个人栈**已是 all-turns**:`streamingText.finalize` 的 `isNoReply` 判定不带
+ * ambient 门控,任何轮次的整条 NO_REPLY 都撤占位、零出站(见 presentationCapabilities
+ * 契约测试与 streamingText 用例锚定)。官方仅 ambient 的差异是跨服务端 TODO。
+ */
+ noReplyScope: 'all-turns' | 'ambient-only';
+ /** 官方 DM 终稿特效(messageEffectId):官方装饰位,个人无。声明车道差异。 */
+ messageEffectIdSupported: boolean;
+ /**
+ * threadId 双语义:"投递位置"= 裸 thread_id;"归属"= is_topic_message 门控
+ * (见 parseCallbackQuery)。普通群 reply 链回流错桶靠 desktop 读取侧兜住。声明车道差异。
+ */
+ threadIdDualSemantics: boolean;
+ /** lane 模型:per-principal(官方) vs per-chat(个人)。声明车道差异。 */
+ laneModel: 'per-principal' | 'per-chat';
+}
+
+/**
+ * 个人 Telegram 车道当前能力基线。**不是官方默认**,不得跨服务端套用。
+ * 本常量的可兑现字段由 index.ts 直接消费(单源);声明字段由契约测试锚定。
+ */
+export const TELEGRAM_PERSONAL_CAPABILITIES: TelegramDriverCapabilities = {
+ progressSilent: true,
+ typingKeepaliveMs: 4_500,
+ typingKeepaliveMaxMs: 5 * 60_000,
+ linkPreviewDisabled: true,
+ noReplyScope: 'all-turns',
+ messageEffectIdSupported: false,
+ threadIdDualSemantics: true,
+ laneModel: 'per-chat',
+};
diff --git a/packages/lizi-im/src/telegram/reactionPool.ts b/packages/lizi-im/src/telegram/reactionPool.ts
new file mode 100644
index 0000000000..78fcc05992
--- /dev/null
+++ b/packages/lizi-im/src/telegram/reactionPool.ts
@@ -0,0 +1,33 @@
+/**
+ * telegram/reactionPool.ts — expressive 档 reaction 变体池(#1855 L1)。
+ * ---------------------------------------------------------------------------
+ * 生动档变体池的**单一客户端出处** — Telegram bot 可用标准 reaction 全集按语义
+ * 分池(Chris: 能用的都随便用)。正/负分开是底线: 成功不能随机出 💩/🤡。选中
+ * 表情在该群被限制时(available_reactions), setMessageReaction 会 400 — 调用方
+ * 回落基础款(👍/👎)重试一次。
+ *
+ * emoji 档本身继续由各车道的 TelegramBehaviorConfig.emojiReactions 三字段直接
+ * 供给, L1 不为其带默认(#1855 replyQuote 勘误同源纪律): 本模块只提供 expressive
+ * 命中时的**变体池数据 + 选取原语**, 不做策略判定。
+ */
+
+/** expressive 终态(成功)变体池 — 35 款正向表情。 */
+export const EXPRESSIVE_DONE_POOL = [
+ '👍', '❤', '🔥', '🥰', '👏', '😁', '🎉', '🤩', '🙏', '👌',
+ '😍', '❤‍🔥', '💯', '🤣', '⚡', '🏆', '🍾', '🤗', '🫡', '😇',
+ '🤝', '💅', '🆒', '💘', '😎', '🦄', '🕊', '🐳', '🍓', '💋',
+ '😘', '🎃', '👾', '🍌', '🌭',
+] as const;
+
+/** expressive 终态(失败)变体池 — 10 款负向表情。 */
+export const EXPRESSIVE_ERROR_POOL = [
+ '👎', '😱', '😢', '💔', '😨', '🤯', '🥴', '🙈', '😐', '🗿',
+] as const;
+
+/** 从池中等概率取一个变体。`random` 可注入以便测试确定化(缺省 Math.random)。 */
+export function pickExpressiveReaction(
+ pool: readonly string[],
+ random: () => number = Math.random,
+): string {
+ return pool[Math.floor(random() * pool.length)];
+}