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。

fix(desktop): hook turn 多消息文本不再丢失, Telegram 群进度带过程时间线 (#848)

Chris Zhang252073135781
diff --git a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
index d379d1696a..df5beee0ea 100644
--- a/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/dispatcher.test.ts
@@ -247,6 +247,26 @@ describe('normalizeTaskSource', () => {
expect(fr.calls[0]?.source?.userText).toHaveLength(20_000);
fr.finish();
});
+
+ it('laneKind 派生: telegram group/topic externalKey → group, DM 与 Slack → dm', async () => {
+ const fr = fakeRunner();
+ const { d } = makeDispatcher({ runner: fr.runner });
+ const c = collector();
+
+ const keys = [
+ 'telegram:group:bot:-900:42:9:g0',
+ 'telegram:topic:bot:-900:77:9:g0',
+ 'telegram:dm:bot:user:g0',
+ 'team-slack:C1:1.1',
+ ];
+ for (const [i, externalKey] of keys.entries()) {
+ d.handleDispatch('conn-1', dispatch({ requestId: `req-lane-${i}`, externalKey }), c.send);
+ await tick();
+ fr.finish();
+ await tick();
+ }
+ expect(fr.calls.map((call) => call.laneKind)).toEqual(['group', 'group', 'dm', 'dm']);
+ });
});
describe('dispatcher 核心语义', () => {
diff --git a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
index 61b5f291aa..1ddad15759 100644
--- a/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
+++ b/apps/desktop/src/main/hook-control/__tests__/session-runner.test.ts
@@ -53,7 +53,15 @@ const h = vi.hoisted(() => {
readImDefaultSettings: vi.fn(),
useActualDefaults: false,
/** 每个 fake session 的事件监听回调(emit done 用)。 */
- eventCbs: new Map<string, (ev: { type: string; data: unknown }) => void>(),
+ eventCbs: new Map<
+ string,
+ (ev: {
+ type: string;
+ data: unknown;
+ source?: string;
+ agentMeta?: Record<string, unknown>;
+ }) => void
+ >(),
/** 每个 fake session 被装上的 interaction listener(交互测试驱动用)。 */
interactionListeners: new Map<string, (req: unknown) => Promise<unknown>>(),
headlessDuringSend: [] as boolean[],
@@ -663,7 +671,14 @@ describe('进度快照(turn.progress 链路)', () => {
return {
id,
workDir: 'D:/repo',
- onEvent(cb: (ev: { type: string; data: unknown }) => void) {
+ onEvent(
+ cb: (ev: {
+ type: string;
+ data: unknown;
+ source?: string;
+ agentMeta?: Record<string, unknown>;
+ }) => void,
+ ) {
h.eventCbs.set(id, cb);
return () => {
h.eventCbs.delete(id);
@@ -690,6 +705,194 @@ describe('进度快照(turn.progress 链路)', () => {
for (let i = 0; i < times; i++) await Promise.resolve();
}
+ it('多消息 turn: isFinal 逐条追加不整体替换, 先答一句再思考再终答两段都保留', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(baseReq({}));
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ // 消息 1 流式 + 完成(codex translator: 每条 agent_message completed
+ // 都发 isFinal=true 携带该条全文)
+ cb({ type: 'text', data: { text: '我正在追溯, 稍等。', isFinal: false } });
+ cb({ type: 'text', data: { text: '我正在追溯, 稍等。', isFinal: true } });
+ // 思考 + 工具
+ cb({ type: 'thinking', data: { stage: 'final', blockId: 't1', text: '检查提交记录' } });
+ // 消息 2(最终答案)流式 + 完成
+ cb({ type: 'text', data: { text: '查到了: 是 PR #527 引入的。', isFinal: false } });
+ cb({ type: 'text', data: { text: '查到了: 是 PR #527 引入的。', isFinal: true } });
+ cb({ type: 'done', data: null });
+
+ const outcome = await p;
+ expect(outcome.status).toBe('ok');
+ // 两段都在, 且以定稿顺序拼接 —— 整体替换语义会丢掉其中一段。
+ expect(outcome.finalText).toContain('我正在追溯');
+ expect(outcome.finalText).toContain('PR #527');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('续尾补推(claude result 兜底): isFinal 只含缺失尾段时与已流增量原样接上', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(baseReq({}));
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ // 消息 1 正常定稿。
+ cb({ type: 'text', data: { text: '旁白说明。', isFinal: true } });
+ // 消息 2 流到一半被截断, translator 用 result 兜底只补 UI 缺的尾段
+ // (fallbackTail): 该 isFinal 不含已流出的前缀。
+ cb({ type: 'text', data: { text: '最终答案是 4', isFinal: false } });
+ cb({ type: 'text', data: { text: '2。', isFinal: true } });
+ cb({ type: 'done', data: null });
+
+ const outcome = await p;
+ // 前缀不丢、正文中间不插段落分隔。
+ expect(outcome.finalText).toContain('最终答案是 42。');
+ expect(outcome.finalText).toContain('旁白说明。');
+ expect(outcome.finalText).not.toContain('4\n\n2');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('claude 同一条消息的相邻文本块按原文连拼, 不同消息之间空行分隔', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(baseReq({}));
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ // 消息 m1 含两个相邻文本块(translator 逐块发 isFinal, 同 uuid)。
+ cb({
+ type: 'text',
+ data: { text: '前半', isFinal: true },
+ source: 'claude-code',
+ agentMeta: { uuid: 'm1' },
+ });
+ cb({
+ type: 'text',
+ data: { text: '后半。', isFinal: true },
+ source: 'claude-code',
+ agentMeta: { uuid: 'm1' },
+ });
+ // 消息 m2 是另一条 assistant 消息。
+ cb({
+ type: 'text',
+ data: { text: '第二条。', isFinal: true },
+ source: 'claude-code',
+ agentMeta: { uuid: 'm2' },
+ });
+ cb({ type: 'done', data: null });
+
+ const outcome = await p;
+ expect(outcome.finalText).toBe('前半后半。\n\n第二条。');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('claude 续尾与已流增量重复前缀时不误判为全文(ha→haha 不丢后半段)', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(baseReq({}));
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ // 流式增量 "ha" 后流被截断, result 兜底补的尾段恰好也是 "ha"
+ // (全文 "haha")。fallbackTail 契约: 不带 agentMeta。
+ cb({ type: 'text', data: { text: 'ha', isFinal: false }, source: 'claude-code' });
+ cb({ type: 'text', data: { text: 'ha', isFinal: true }, source: 'claude-code' });
+ cb({ type: 'done', data: null });
+
+ const outcome = await p;
+ expect(outcome.finalText).toBe('haha');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('未定稿流式尾巴保留首行缩进与换行(markdown 代码块不被 trim 破坏)', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(baseReq({}));
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ cb({ type: 'text', data: { text: ' indented code\nline2', isFinal: false } });
+ cb({ type: 'done', data: null });
+
+ const outcome = await p;
+ expect(outcome.finalText).toContain(' indented code\nline2');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('Telegram 群 lane: 进度带过程时间线(时间线在上正文在下), 无正文时也有时间线', async () => {
+ vi.useFakeTimers();
+ try {
+ fakeMaker.createSession.mockImplementationOnce(async (opts: { id?: string }) =>
+ makeManualSession(opts.id ?? 'sess-x'),
+ );
+ const emitted: string[] = [];
+ const runner = createMakerHookSessionRunner({ log });
+ const p = runner.run(
+ baseReq({
+ source: { im: 'telegram', userText: 'hi' },
+ laneKind: 'group',
+ onProgress: (text: string) => emitted.push(text),
+ }),
+ );
+ await flush();
+ const cb = h.eventCbs.get('sess-new')!;
+
+ // 与 DM(answer-only)不同: 群 lane 只有工具活动、还没有正文时,
+ // 也要发时间线, 群成员能看到"正在干什么"。
+ cb({
+ type: 'tool_use',
+ data: { toolUseId: 'read-1', toolName: 'Read', input: { file_path: '/repo/a.ts' } },
+ });
+ await vi.advanceTimersByTimeAsync(1_500);
+ expect(emitted.length).toBeGreaterThan(0);
+ expect(emitted.at(-1)).toContain('▸');
+
+ cb({ type: 'text', data: { text: '结论是 42。', isFinal: false } });
+ await vi.advanceTimersByTimeAsync(1_500);
+ const last = emitted.at(-1)!;
+ expect(last).toContain('结论是 42。');
+ // 合成规则与 Slack 过程卡同款: 时间线在上, 正文在下。
+ expect(last.indexOf('▸')).toBeLessThan(last.indexOf('结论是 42。'));
+
+ cb({ type: 'done', data: null });
+ await p;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('thinking/tool_use/text 驱动友好快照,过程文字持续保留;done 后停止', async () => {
vi.useFakeTimers();
try {
@@ -825,7 +1028,14 @@ describe('交互卡链路(interaction listener 覆盖)', () => {
return {
id,
workDir: 'D:/repo',
- onEvent(cb: (ev: { type: string; data: unknown }) => void) {
+ onEvent(
+ cb: (ev: {
+ type: string;
+ data: unknown;
+ source?: string;
+ agentMeta?: Record<string, unknown>;
+ }) => void,
+ ) {
h.eventCbs.set(id, cb);
return () => {
h.eventCbs.delete(id);
diff --git a/apps/desktop/src/main/hook-control/dispatcher.ts b/apps/desktop/src/main/hook-control/dispatcher.ts
index ee0dd6e9c3..c87d86cb10 100644
--- a/apps/desktop/src/main/hook-control/dispatcher.ts
+++ b/apps/desktop/src/main/hook-control/dispatcher.ts
@@ -69,6 +69,12 @@ export interface HookSessionRunner {
export interface HookRunRequest {
sessionId: string;
+ /**
+ * IM lane 形态(externalKey 派生): 'group' = 群/topic, 'dm' = 私聊。
+ * runner 据此决定进度快照是否携带过程时间线(群内可编辑消息适合过程卡,
+ * DM 的 Rich draft 动画不适合反复重排)。缺省按 'dm' 保守处理。
+ */
+ laneKind?: 'dm' | 'group';
/** true = 新建 session(workingDir/title 生效); false = 复用/接管已有。 */
isNew: boolean;
workingDir: string;
@@ -674,6 +680,8 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
/** 旧绑定作废、本次不得不新建会话时, 随 turn.end 回给渠道的说明。 */
let recreatedNotice: string | null = null;
+ const laneKind: 'dm' | 'group' =
+ /^telegram:(group|topic):/.test(payload.externalKey) ? 'group' : 'dm';
// 接管路径: server 显式指定已有 session(对话会话同样可接管)
if (payload.sessionId !== null) {
const info = await runner.inspect(payload.sessionId);
@@ -689,6 +697,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
run: {
sessionId: payload.sessionId,
isNew: false,
+ laneKind,
workingDir: info.workingDir as string,
agentKind,
model,
@@ -768,6 +777,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
run: {
sessionId: bound,
isNew: false,
+ laneKind,
// 尚未落库, 没有 meta 可查 —— 用建它时那个刚重新过完映射校验的目录
workingDir: pendingDir!,
agentKind,
@@ -807,6 +817,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
run: {
sessionId: bound,
isNew: false,
+ laneKind,
workingDir,
agentKind,
model,
@@ -888,6 +899,7 @@ export function createHookDispatcher(deps: HookDispatcherDeps): HookDispatcher {
run: {
sessionId,
isNew: true,
+ laneKind,
workingDir: runDir,
agentKind,
model,
diff --git a/apps/desktop/src/main/hook-control/session-runner.ts b/apps/desktop/src/main/hook-control/session-runner.ts
index f0d710154a..4f8aeb8821 100644
--- a/apps/desktop/src/main/hook-control/session-runner.ts
+++ b/apps/desktop/src/main/hook-control/session-runner.ts
@@ -660,10 +660,29 @@ export function createMakerHookSessionRunner(deps: {
}
}
- // turn 收口监听 —— 语义与 scheduler runner 第 5 步同源:
- // text isFinal 替换 / delta 追加; done 时若有在途后台任务则延迟定格,
- // 事件静默超时兜底; terminal error 即失败。
+ // turn 收口监听 —— done 时若有在途后台任务则延迟定格, 事件静默超时
+ // 兜底; terminal error 即失败。
+ //
+ // 文本累积语义(2026-07-28 修订): translator 的 isFinal 是**逐条**
+ // agent_message 的完成信号(每条完成都携带该条全文), 不是整个 turn 的
+ // 终稿 —— 用它整体替换累积文本, 会让"先回一句 → 思考 → 终答"的多消息
+ // turn 只剩最后被替换的那条(实踩: Telegram 群里最终答案丢失)。
+ // 正确姿势: isFinal 把该条追加进已定稿段, 流式增量走尾部缓冲。
+ let finalizedText = '';
+ let streamTail = '';
let assistantText = '';
+ /** 最近一次定稿段所属的 claude 消息 uuid(同消息相邻块连拼用)。 */
+ let lastFinalUuid: string | undefined;
+ const recomputeAssistantText = (): void => {
+ // trim 只用于判空(纯空白尾巴不该拼出悬空分隔), 拼接用原文 ——
+ // 首行缩进/换行是内容(markdown 代码块等), 不得被裁掉。
+ const hasTail = streamTail.trim().length > 0;
+ assistantText = hasTail
+ ? finalizedText
+ ? `${finalizedText}\n\n${streamTail}`
+ : streamTail
+ : finalizedText;
+ };
// tool_result 旁路收集的出站图片 absPath(收口时随 turn.end 附件外发)
const extraImageAbsPaths: string[] = [];
// 进度快照(turn.progress 链路): 过程区时间线与 IM 流式卡同一套纯逻辑
@@ -671,14 +690,14 @@ export function createMakerHookSessionRunner(deps: {
// 上正文在下, done/error 后 stop, 不再发射。
const activity = createTurnActivity(Date.now());
const isTelegram = req.source?.im === 'telegram';
+ // Telegram DM 的 Rich draft 是"部分终稿"动画, 过程时间线反复重排会导致
+ // 整段清空重播 —— DM 保持只流正文。群/topic 的进度载体是可编辑消息
+ // (无 draft 动画), 与 Slack 过程卡同款: 时间线在上正文在下, 让群成员
+ // 看到"正在干什么"而不是盯着一句旧话干等(2026-07-28 实踩)。
+ const answerOnlyProgress = isTelegram && req.laneKind !== 'group';
const progress = req.onProgress
? createProgressEmitter(req.onProgress, () => {
- // Telegram Rich Message drafts are the partial final answer, not
- // an editable process card. turnActivity can reorder/fold as
- // thinking and tool events arrive, which makes Telegram animate
- // repeated full clears. Keep Slack's established process card,
- // while Telegram streams only the monotonically growing answer.
- if (isTelegram) return assistantText;
+ if (answerOnlyProgress) return assistantText;
const act = renderActivity(activity, Date.now());
if (!act) return assistantText;
return assistantText ? `${act}\n\n${assistantText}` : act;
@@ -726,8 +745,40 @@ export function createMakerHookSessionRunner(deps: {
if (ev.type === 'text') {
const data = ev.data as { text?: string; isFinal?: boolean } | null;
if (data && typeof data.text === 'string') {
- if (data.isFinal) assistantText = data.text;
- else assistantText += data.text;
+ if (data.isFinal) {
+ // isFinal 形态按 translator 契约区分, 不做内容猜测(前缀
+ // 启发式在"尾段恰好以已流增量开头"时会误判丢正文):
+ // ① claude 块终稿(带 agentMeta): data.text 是该块全文, 覆盖
+ // 已流增量; 同一条消息(同 uuid)的相邻文本块按原文连拼
+ // (renderer 同款 raw concat), 不同消息之间空行分隔。
+ // ② claude result 兜底 fallbackTail(刻意不带 agentMeta):
+ // 只含 UI 缺的尾段, 与已流增量原样接上。
+ // ③ codex item.completed: 该条全文, 覆盖已流增量。
+ // ④ 未知 source: 保守用前缀启发式。
+ const src = (ev as { source?: string }).source;
+ const meta = (ev as { agentMeta?: { uuid?: unknown } }).agentMeta;
+ const claudeTail = src === 'claude-code' && meta === undefined;
+ const segment = claudeTail
+ ? streamTail + data.text
+ : src === 'claude-code' || src === 'codex'
+ ? data.text
+ : data.text.startsWith(streamTail)
+ ? data.text
+ : streamTail + data.text;
+ const uuid =
+ src === 'claude-code' && typeof meta?.uuid === 'string'
+ ? meta.uuid
+ : undefined;
+ const sameMessage = uuid !== undefined && uuid === lastFinalUuid;
+ finalizedText = finalizedText
+ ? `${finalizedText}${sameMessage ? '' : '\n\n'}${segment}`
+ : segment;
+ lastFinalUuid = uuid;
+ streamTail = '';
+ } else {
+ streamTail += data.text;
+ }
+ recomputeAssistantText();
markActivityWriting(activity);
progress?.schedule();
}