Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 保留后台回传的话题锚点、队列与图片
Dash1874ab2040e4
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex 96dff9f76b..6c40034315 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -9,6 +9,7 @@* 5. binding(identity+scopeKey)命中 → attached 路由到 desktop session*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import path from 'node:path';import type { AgentEvent, Session, SessionSendResult } from '@cindy/maker-core';import type { ChannelIM } from '@cindy/im';@@ -20,6 +21,7 @@ const mocks = vi.hoisted(() => ({removeMessageReaction: vi.fn(),sendText: vi.fn(),sendMarkdownText: vi.fn(),+ sendFile: vi.fn(async () => ({ ok: true, messageId: 'file' })),startStreamingText: vi.fn(),patchMarkdownCard: vi.fn(),sendInteractiveCard: vi.fn(),@@ -134,6 +136,7 @@ function makeSessionHarness(sessionId: string): SessionHarness {);const session = {id: sessionId,+ workDir: '/tmp/slack-wd',agentKind: 'claude-code',abort: vi.fn(async () => undefined),send,@@ -243,6 +246,7 @@ function streamingHandleStub() {append: vi.fn(),replace: vi.fn(),finalize: vi.fn(async () => undefined),+ addExtraImageAbsPath: vi.fn(),close: vi.fn(),};}@@ -554,6 +558,62 @@ describe('turnRunner thread = session 路由(slack threadScoped)', () => {});describe('turnRunner 渠道任务后台结果回传', () => {+ it('换执行实例只换绑监听,保留同话题已经排队的消息', async () => {+ const old = await channelAndIdle();+ vi.mocked(old.session.isTurnRunning).mockReturnValue(true);+ await runTurn('100.1', 'queued after background');+ const next = makeSessionHarness(old.session.id);+ harnesses.set(old.session.id, next);+ runner.attachSessionOutput(next.session, 'U1');+ expect(old.unsubscribe).toHaveBeenCalledTimes(1);+ old.emit({ type: 'text', data: { text: 'stale result' } });+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ next.emit({ type: 'done', data: {} });+ await vi.waitFor(() => expect(next.send).toHaveBeenCalledTimes(1));+ expect(next.send.mock.calls[0]![0]).toEqual(expect.objectContaining({+ content: expect.stringContaining('queued after background'),+ }));+ next.emit({ type: 'done', data: {} });+ });++ it.each(['rich-card', 'chunked-text'] as const)('%s 回传纯工具图片并去重,不依赖最终正文', async (kind) => {+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ if (kind === 'chunked-text') {+ runner = createTurnRunner({ ...fakeAdapter, output: {+ kind, im: fakeAdapter.im, commitFinal: vi.fn(async () => undefined),+ } }, fakeRepo, fakeCards);+ }+ const h = makeSessionHarness('image-background');+ runner.attachSessionOutput(h.session, 'U1');+ const absPath = path.resolve('generated.png');+ mocks.resolveXdtImageUrl.mockReturnValue({ absPath });+ const event: AgentEvent = { type: 'tool_result_full', data: {+ fullText: JSON.stringify({ xdt_image_url: 'xdt-image://generated' }),+ } };+ h.emit(event);+ h.emit(event);+ h.emit({ type: 'done', data: {} });+ if (kind === 'rich-card') {+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledWith(''));+ expect(stub.addExtraImageAbsPath).toHaveBeenCalledExactlyOnceWith(absPath);+ expect(stub.addExtraImageAbsPath.mock.invocationCallOrder[0]).toBeLessThan(stub.finalize.mock.invocationCallOrder[0]!);+ } else {+ await vi.waitFor(() => expect(mocks.slackIm.sendFile).toHaveBeenCalledExactlyOnceWith('U1', absPath, undefined, { threadTs: undefined }));+ expect(mocks.slackIm.sendMarkdownText).not.toHaveBeenCalled();+ }+ });++ it('远端后台轮次不把媒体路径作为本地文件发送', async () => {+ const h = makeSessionHarness('remote-background');+ Object.assign(h.session, { remoteHostId: 'ssh-host' });+ runner.attachSessionOutput(h.session, 'U1');+ h.emit({ type: 'tool_result_full', data: { fullText: '{"xdt_image_url":"xdt-image://remote"}' } });+ h.emit({ type: 'done', data: {} });+ expect(mocks.resolveXdtImageUrl).not.toHaveBeenCalled();+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ });+it('重启后仅恢复输出监听,不新建会话;重复恢复不会重复回复', async () => {const h = makeSessionHarness('cold-session');const stub = streamingHandleStub();diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex a6f700f6ed..9662fde23d 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -379,6 +379,7 @@ interface ScheduledTranspond {activityTicker: ReturnType<typeof setInterval> | null;/** 自动任务这一轮 agent 的回复文本累加。 */buffer: string;+ mediaAbsPaths: string[];streamingHandle: StreamingTextHandle | null;streamingHandlePromise: Promise<StreamingTextHandle> | null;}@@ -1669,6 +1670,12 @@ export function createTurnRunner(}if (current === previous) return;+ rebindSessionOutput(state, current, userId);+ wireSessionToIpcExternal(current);+ }++ /** Rebind observation without discarding accepted or queued IM messages. */+ function rebindSessionOutput(state: SessionState, current: MakerSession, userId: string): void {for (const unsubscribe of state.unsubscribers) {try {unsubscribe();@@ -1678,9 +1685,8 @@ export function createTurnRunner(}state.unsubscribers = [];state.makerSession = current;- wireSessionToIpcExternal(current);- state.unsubscribers.push(current.onEvent(handleEventFor(sessionId, userId)));- sessionStates.set(sessionId, state);+ state.workingDir = current.workDir;+ state.unsubscribers.push(current.onEvent(handleEventFor(current.id, userId)));}/**@@ -2532,32 +2538,34 @@ export function createTurnRunner(*/function handleToolResultFullEvent(turn: TurnState, event: AgentEvent): void {if (turn.allowedFileRoots.length === 0) return;+ const extraAbsPaths = collectToolResultImages(turn.mediaAbsPaths, event);+ if (extraAbsPaths.length === 0) return;+ void ensureStreamingHandle(turn).then((handle) => {+ for (const absPath of extraAbsPaths) handle?.addExtraImageAbsPath?.(absPath);+ });+ }++ /** Both inbound and background turns resolve and deduplicate the same media ledger. */+ function collectToolResultImages(mediaAbsPaths: string[], event: AgentEvent): string[] {const data = event.data as { fullText?: unknown } | null;- if (!data || typeof data.fullText !== 'string') return;+ if (!data || typeof data.fullText !== 'string') return [];const urls = extractRenderableXdtImageUrls(data.fullText);- if (urls.length === 0) return;const extraAbsPaths: string[] = [];for (const url of urls) {try {const { absPath } = url.startsWith('cindy-media://')? resolveCindyMediaUrl(url): resolveXdtImageUrl(url);- extraAbsPaths.push(absPath);- if (!turn.mediaAbsPaths.includes(absPath)) turn.mediaAbsPaths.push(absPath);+ if (!mediaAbsPaths.includes(absPath)) {+ mediaAbsPaths.push(absPath);+ extraAbsPaths.push(absPath);+ }} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.warn(`[${channel}/turn] resolve managed image failed for ${url}: ${msg}`);}}- if (extraAbsPaths.length === 0) return;- // streamingHandle 可能还没 spawn (e.g. 工具调用先于任何 text delta) — 触发- // 一下 ensureStreamingHandle 让 card 先建出来, 再投递。投递接口本身是- // O(1) 同步 push, 不阻塞事件循环。终态群主流镜像读 turn.mediaAbsPaths,- // 所以 extra 图必须同步记到 turn 上, 不能只挂在句柄里。- void ensureStreamingHandle(turn).then((handle) => {- if (!handle?.addExtraImageAbsPath) return; // patchedCardHandle 不实现这个能力 / 创建失败(null)- for (const absPath of extraAbsPaths) handle.addExtraImageAbsPath(absPath);- });+ return extraAbsPaths;}/**@@ -2686,7 +2694,7 @@ export function createTurnRunner(// create or close a projection card.if (event.type === 'status') return;if (event.type === 'done' && isTurnContinuationBoundaryEvent(event)) return;- if (!['text', 'tool_use', 'done', 'error'].includes(event.type)) return;+ if (!['text', 'tool_use', 'tool_result_full', 'done', 'error'].includes(event.type)) return;// 首条事件惰性建转播态(避免给空 turn 开卡)。if (!state.scheduledTranspond) {const origin = event.turnOrigin;@@ -2697,12 +2705,24 @@ export function createTurnRunner(activity: createTurnActivity(Date.now()),activityTicker: null,buffer: '',+ mediaAbsPaths: [],streamingHandle: null,streamingHandlePromise: null,};}const t = state.scheduledTranspond;switch (event.type) {+ case 'tool_result_full': {+ if (state.makerSession.remoteHostId) return;+ const paths = collectToolResultImages(t.mediaAbsPaths, event);+ if (paths.length && richIm) {+ void ensureTranspondHandle(state, t).then((handle) => {+ if (sessionStates.get(state.makerSession.id) !== state) return;+ for (const absPath of paths) handle.addExtraImageAbsPath?.(absPath);+ }).catch((err) => log.warn('transpond media failed (non-fatal)', err));+ }+ return;+ }case 'text': {const data = event.data as { text?: string; isFinal?: boolean } | null;if (!data || typeof data.text !== 'string') return;@@ -2773,16 +2793,31 @@ export function createTurnRunner(// 它不置 turn.done, composeStreamingView 会把 activity 一起写进正文。setActivityNotice(t.activity, null);// 没产出任何内容(无文本无步骤)且无错 → 不留空卡。- if (!t.streamingHandle && t.buffer.length === 0 && t.activity.totalSteps === 0 && !errMsg) {+ if (!t.streamingHandle && t.buffer.length === 0 && t.mediaAbsPaths.length === 0 && t.activity.totalSteps === 0 && !errMsg) {return;}try {+ if (output.kind === 'chunked-text' && !state.makerSession.remoteHostId && t.buffer.includes('![')) {+ const materialized = await materializeLocalMarkdownImages({+ text: t.buffer, workingDir: state.workingDir, sessionId: state.makerSession.id,+ maxImages: 4, existingAbsPaths: t.mediaAbsPaths,+ });+ t.buffer = materialized.text;+ for (const absPath of materialized.absPaths) {+ if (!t.mediaAbsPaths.includes(absPath)) t.mediaAbsPaths.push(absPath);+ }+ }+ if (sessionStates.get(state.makerSession.id) !== state) return;const base = composeTranspondView(t, true);const body = errMsg ? [base, ui.agent.runtimeError(errMsg)].filter(Boolean).join('\n\n') : base;if (output.kind === 'chunked-text') {// 微信等文本渠道由适配器解析当前账号下该聊天最近的有效回复上下文。// 不伪造入站 taskId,也不占用另一次用户消息的 durable final。if (body) await im.sendMarkdownText(state.userId, body, { threadTs: state.scopeKey });+ for (const absPath of t.mediaAbsPaths.slice(0, 4)) {+ if (sessionStates.get(state.makerSession.id) !== state) return;+ await im.sendFile(state.userId, absPath, undefined, { threadTs: state.scopeKey });+ }return;}const handle = await ensureTranspondHandle(state, t);@@ -4017,7 +4052,10 @@ export function createTurnRunner(attachSessionOutput: (session, userId) => {const existing = sessionStates.get(session.id);if (existing?.makerSession === session) return;- if (existing) cleanupSessionState(existing);+ if (existing) {+ rebindSessionOutput(existing, session, userId);+ return;+ }ensureMakerCloseSubscription(getMaker());const state: SessionState = {makerSession: session,diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex da513958ce..62808dea4b 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -250,9 +250,13 @@ hook 侧既有的逐轮 `[渠道说明]`,两者措辞不同但都向模型说包括自动任务、其它任务发送消息触发的回复;无需先 `/ctr` 接管。自动任务保留任务名,其它来源直接显示回复正文,目的地沿用该任务原聊天和话题。正常 IM 入站轮次仍只发送一次;子代理和旧轮次的后台事件不转播。纯文本渠道通过适配器使用现有有效聊天上下文发送最终结果。+工具结果中的托管图片沿用正常 IM 轮次的解析与去重规则,即使最终正文没有重复引用也会回传;+SSH 任务不把远端路径当作本地文件上传。临时回复通知不建立普通任务的持续转播;`/ctr` 接管任务仍只转播 scheduler 输出。每轮执行前从当前账号库恢复输出监听,核对 bot 身份和任务状态,因此重启后无需先从 IM 发一条消息。+飞书/Lark 话题缺少内存锚点时,从原话题查询合法消息恢复;查询失败不降级到群主流。+切换执行实例仅换绑事件监听,保留该任务已排队的 IM 消息。官方 Telegram、Slack 复用已有 hook binding、轮次观察和附件收集;双方宣告 `session-result-v1`后用 `turn.end(background: true)` 发送结果,服务端在原私聊或话题新发消息。普通 IM 轮次和diff --git a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.tsindex f330064c1a..ac583916e8 100644--- a/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts+++ b/packages/lizi-im/src/feishu/__tests__/outboundLane.test.ts@@ -4,6 +4,9 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const larkMocks = vi.hoisted(() => {+ const list = vi.fn<() => Promise<{ code: number; data: { items: Array<{+ message_id: string; thread_id: string; chat_id: string; deleted?: boolean;+ }> } }>>(async () => ({ code: 0, data: { items: [] } }));const create = vi.fn(async (payload: { params: unknown; data: { content: string } }) => {void payload;return { data: { message_id: 'om_created' } };@@ -60,7 +63,7 @@ const larkMocks = vi.hoisted(() => {return Promise.resolve({ data: { items: [] } });},);- return { create, reply, deleteMessage, getMessage, patch, replyOwners, getOwners, deleteOwners };+ return { list, create, reply, deleteMessage, getMessage, patch, replyOwners, getOwners, deleteOwners };});vi.mock('@larksuiteoapi/node-sdk', () => ({@@ -68,6 +71,7 @@ vi.mock('@larksuiteoapi/node-sdk', () => ({im = {v1: {message: {+ list: larkMocks.list,create: larkMocks.create,reply: larkMocks.reply,delete: larkMocks.deleteMessage,@@ -158,6 +162,50 @@ describe('feishu outbound lane routing', () => {expect(larkMocks.create).not.toHaveBeenCalled();});+ it('restores a cold topic anchor before streaming a background result', async () => {+ larkMocks.list.mockResolvedValueOnce({ code: 0, data: { items: [+ { message_id: 'om_deleted', thread_id: 'omt_t1', chat_id: 'oc_group1', deleted: true },+ { message_id: 'om_other', thread_id: 'omt_other', chat_id: 'oc_group1' },+ { message_id: 'om_saved', thread_id: 'omt_t1', chat_id: 'oc_group1' },+ ] } });+ await outbound.sendCardRaw('g/oc_group1/omt_t1', { body: 'background result' });+ await outbound.sendText('g/oc_group1/omt_t1', 'next result');+ expect(larkMocks.list).toHaveBeenCalledTimes(1);+ expect(larkMocks.list).toHaveBeenCalledWith({ params: {+ container_id_type: 'thread', container_id: 'omt_t1',+ sort_type: 'ByCreateTimeDesc', page_size: 50,+ } });+ expect(larkMocks.reply).toHaveBeenCalledTimes(2);+ expect(larkMocks.reply).toHaveBeenLastCalledWith(expect.objectContaining({ path: { message_id: 'om_saved' } }));+ expect(larkMocks.create).not.toHaveBeenCalled();+ });++ it('keeps a newer inbound anchor when history lookup finishes', async () => {+ larkMocks.list.mockImplementationOnce(async () => {+ outbound.pushReplyAnchor('g/oc_group1/omt_t1', 'om_live');+ return { code: 0, data: { items: [{ message_id: 'om_old', thread_id: 'omt_t1', chat_id: 'oc_group1' }] } };+ });+ await outbound.sendCardRaw('g/oc_group1/omt_t1', {});+ expect(larkMocks.reply).toHaveBeenCalledWith(expect.objectContaining({ path: { message_id: 'om_live' } }));+ });++ it('rejects anchor lookup completion after account replacement', async () => {+ larkMocks.list.mockImplementationOnce(async () => {+ rebindFresh(otherCreds);+ return { code: 0, data: { items: [{ message_id: 'om_old', thread_id: 'omt_t1', chat_id: 'oc_group1' }] } };+ });+ await expect(outbound.sendCardRaw('g/oc_group1/omt_t1', {})).rejects.toThrow(/account replaced/);+ expect(larkMocks.reply).not.toHaveBeenCalled();+ expect(larkMocks.create).not.toHaveBeenCalled();+ });++ it('does not send an already resolved target through a replacement account', async () => {+ const sending = outbound.sendText('ou_someone', 'old account output');+ rebindFresh(otherCreds);+ await expect(sending).rejects.toThrow(/account was replaced/);+ expect(larkMocks.create).not.toHaveBeenCalled();+ });+it('sendCardRaw advances to the next queued anchor per round', async () => {outbound.pushReplyAnchor('g/oc_g', 'om_q1');outbound.pushReplyAnchor('g/oc_g', 'om_q2');diff --git a/packages/lizi-im/src/feishu/outbound.ts b/packages/lizi-im/src/feishu/outbound.tsindex e14e1cd052..b3f7f337e4 100644--- a/packages/lizi-im/src/feishu/outbound.ts+++ b/packages/lizi-im/src/feishu/outbound.ts@@ -692,8 +692,30 @@ export async function sendNotification(userId: string, markdown: string): Promisreturn createMessage({ kind: 'open_id', id: userId }, 'interactive', JSON.stringify(buildInteractiveCardV1({ body: markdown, buttons: [] })));}-function requireSendTarget(userId: string, opts?: { advanceRound?: boolean; threadTs?: string }): SendTarget {- const target = resolveSendTarget(userId, opts);+async function requireSendTarget(userId: string, opts?: { advanceRound?: boolean; threadTs?: string }): Promise<SendTarget> {+ let target = resolveSendTarget(userId, opts);+ const lane = decodeLaneUserId(userId);+ if (!target && lane?.threadId) {+ // A persisted topic lane survives restart, unlike its in-memory reply anchor.+ // Recover from that exact thread; never fall back to the group main timeline.+ const epoch = accountEpoch;+ const res = await ensureClient().im.v1.message.list({+ params: { container_id_type: 'thread', container_id: lane.threadId,+ sort_type: 'ByCreateTimeDesc', page_size: 50 },+ });+ if (epoch !== accountEpoch) throw new Error('Feishu account replaced during anchor recovery');+ ensureClient();+ if (res.code !== 0) throw new Error(`Feishu topic anchor lookup failed: ${res.code}`);+ const anchor = res.data?.items?.find((item) =>+ !item.deleted && item.message_id?.startsWith('om_') &&+ item.thread_id === lane.threadId && item.chat_id === lane.chatId);+ // Inbound may have supplied an anchor while the lookup was in flight.+ target = resolveSendTarget(userId, opts);+ if (!target && anchor?.message_id) {+ pushReplyAnchor(userId, anchor.message_id);+ target = resolveSendTarget(userId, opts);+ }+ }if (!target) {throw new Error(`[feishu/outbound] no reply anchor for topic lane ...${userId.slice(-8)} — message dropped`,@@ -702,6 +724,19 @@ function requireSendTarget(userId: string, opts?: { advanceRound?: boolean; threreturn target;}+/** Keep lookup and delivery on the same account across their async boundary. */+async function withSendTarget<T>(+ userId: string,+ opts: { advanceRound?: boolean; threadTs?: string } | undefined,+ send: (target: SendTarget) => Promise<T>,+): Promise<T> {+ return runWithPinnedAccount({ client: ensureClient(), epoch: accountEpoch }, async () => {+ const target = await requireSendTarget(userId, opts);+ ensureClient();+ return send(target);+ });+}+export function getBoundClient(): Lark.Client | null {return client;}@@ -750,7 +785,7 @@ function ensureClient(): Lark.Client {// ── basic text ────────────────────────────────────────────────────────────────export async function sendText(userId: string, text: string, opts?: { threadTs?: string }): Promise<{ messageId: string }> {- return createMessage(requireSendTarget(userId, opts), 'text', JSON.stringify({ text }));+ return withSendTarget(userId, opts, (target) => createMessage(target, 'text', JSON.stringify({ text })));}/** 直接回复某条消息(非 owner 群 @ 的礼貌回应等 — 不走 lane 锚点)。 */@@ -1137,11 +1172,11 @@ export async function sendInteractive(return createMessage({ kind: 'open_id', id: owner }, 'interactive', JSON.stringify(card));}const card = buildInteractiveCardV1(spec);- const result = await createMessage(- requireSendTarget(userId, opts),+ const result = await withSendTarget(userId, opts, (target) => createMessage(+ target,'interactive',JSON.stringify(card),- );+ ));registerCardLane(userId, result.messageId);return result;}@@ -1183,11 +1218,11 @@ export async function sendCardRaw(cardJson: unknown,opts?: { threadTs?: string },): Promise<{ messageId: string }> {- return createMessage(- requireSendTarget(userId, { advanceRound: true, ...opts }),+ return withSendTarget(userId, { advanceRound: true, ...opts }, (target) => createMessage(+ target,'interactive',JSON.stringify(cardJson),- );+ ));}/** Send a terminal-output mirror directly to a parent group main timeline. */@@ -1255,12 +1290,12 @@ export async function sendFile(displayName?: string,opts?: { threadTs?: string },): Promise<FeishuSendFileResult> {- const target = resolveSendTarget(userId, opts);- if (!target) {- getLog().error(`[feishu/outbound] sendFile: no reply anchor for topic lane ...${userId.slice(-8)}`);+ try {+ return await withSendTarget(userId, opts, (target) => sendFileToTarget(target, absPath, displayName));+ } catch {+ getLog().error('[feishu/outbound] sendFile: target or delivery unavailable');return { ok: false, reason: 'SEND_FAIL' };}- return sendFileToTarget(target, absPath, displayName);}/** Re-send an already uploaded terminal-output file to a parent group main timeline. */