Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 从接管绑定恢复后台结果监听
Dashe6f47a27e02a
diff --git a/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.tsnew file mode 100644index 0000000000..aaf6e8825b--- /dev/null+++ b/apps/desktop/src/main/im/shared/__tests__/orchestratorOutput.test.ts@@ -0,0 +1,103 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { Session } from '@cindy/maker-core';+import type { IdentityKey } from '@cindy/im';+import type { ImChannelAdapter } from '../types';++const mocks = vi.hoisted(() => ({+ limit: vi.fn(),+ capture: vi.fn(),+ current: vi.fn(),+ binding: vi.fn<() => IdentityKey | null>(),+ status: vi.fn(),+ attach: vi.fn(),+}));+vi.mock('../../../logger', () => ({ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }) }));+vi.mock('../../../localDb/client/current', () => ({+ getDbClient: () => ({ drizzle: { select: () => ({ from: () => ({ where: () => ({ limit: mocks.limit }) }) }) } }),+}));+vi.mock('../../accountBoundary', () => ({+ captureImAccountGeneration: mocks.capture, isImAccountGenerationCurrent: mocks.current,+}));+vi.mock('../../binding', () => ({ bindingStore: { findByTarget: mocks.binding } }));+vi.mock('../../../maker-ipc/register', () => ({+ acquirePendingAgentSwitchForDirectSend: vi.fn(),+ acquirePendingAgentSwitchForImSend: vi.fn(),+ registerSwitchedSessionVendorOptionsResolver: vi.fn(),+}));+vi.mock('../channelDefaultRouteSync', () => ({ createImChannelDefaultRouteSync: () => ({}) }));+vi.mock('../sessionRepo', () => ({ createImSessionRepo: () => ({}) }));+vi.mock('../cardBuilders', () => ({ createCardBuilders: () => ({}) }));+vi.mock('../turnRunner', () => ({ createTurnRunner: () => ({ attachSessionOutput: mocks.attach }) }));+vi.mock('../slashCommands', () => ({ createSlashHandlers: () => ({}) }));+vi.mock('../messageHandler', () => ({ createMessageHandler: () => vi.fn() }));+vi.mock('../cardActionHandler', () => ({ createCardActionHandler: () => vi.fn() }));++import { createImOrchestrator } from '../orchestrator';+import { publishChannelTurn } from '../../../maker-ipc/channelTurnSignal';++for (const channel of ['telegram', 'feishu'] as const) {+ createImOrchestrator({+ channel, im: { getStatus: mocks.status }, sessions: { source: channel },+ output: { kind: 'chunked-text' },+ } as unknown as ImChannelAdapter);+}+const session = { id: 'desktop-task' } as Session;+const binding: IdentityKey = {+ channel: 'telegram', botContextId: 'bot', userId: 'group-user', scopeKey: 'topic',+};+const nativeRow = {+ source: 'feishu', status: 'active', feishuBotAppId: 'bot', feishuOpenId: 'native-user',+};++beforeEach(() => {+ vi.clearAllMocks();+ mocks.capture.mockReturnValue(1);+ mocks.current.mockReturnValue(true);+ mocks.status.mockReturnValue({ kind: 'connected', appId: 'bot' });+ mocks.binding.mockReturnValue(null);+ mocks.limit.mockResolvedValue([nativeRow]);+});++describe('background output route recovery', () => {+ it.each(['desktop', 'feishu'])('prefers takeover identity over %s source', async (source) => {+ mocks.limit.mockResolvedValue([{ ...nativeRow, source }]);+ mocks.binding.mockReturnValue(binding);+ await publishChannelTurn(session, 'starting');+ expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'group-user', { attached: true, scopeKey: 'topic' });+ });++ it.each(['feishu', 'telegram'])('falls back to native %s identity without a binding', async (source) => {+ mocks.limit.mockResolvedValue([{ ...nativeRow, source, imBotContextId: 'bot', imUserId: 'native-user' }]);+ await publishChannelTurn(session, 'starting');+ expect(mocks.attach).toHaveBeenCalledExactlyOnceWith(session, 'native-user', { attached: false, scopeKey: undefined });+ });++ it.each(['deleted', 'archived', 'missing', 'disconnected', 'wrong-bot', 'wrong-account', 'unbound-desktop', 'unsupported-binding'])(+ 'does not attach for %s', async (state) => {+ mocks.binding.mockReturnValue(binding);+ if (state === 'deleted' || state === 'archived') mocks.limit.mockResolvedValue([{ ...nativeRow, status: state }]);+ if (state === 'missing') mocks.limit.mockResolvedValue([]);+ if (state === 'disconnected') mocks.status.mockReturnValue({ kind: 'disconnected' });+ if (state === 'wrong-bot') mocks.status.mockReturnValue({ kind: 'connected', appId: 'other-bot' });+ if (state === 'wrong-account') mocks.current.mockReturnValue(false);+ if (state === 'unbound-desktop') {+ mocks.binding.mockReturnValue(null);+ mocks.limit.mockResolvedValue([{ ...nativeRow, source: 'desktop' }]);+ }+ if (state === 'unsupported-binding') mocks.binding.mockReturnValue({ ...binding, channel: 'unknown' });+ await publishChannelTurn(session, 'starting');+ expect(mocks.attach).not.toHaveBeenCalled();+ },+ );++ it('reads the current binding after the async row query, not a detached identity', async () => {+ let finish!: (rows: unknown[]) => void;+ mocks.limit.mockReturnValue(new Promise((resolve) => { finish = resolve; }));+ mocks.binding.mockReturnValue(binding);+ const restoring = publishChannelTurn(session, 'starting');+ mocks.binding.mockReturnValue(null);+ finish([{ source: 'desktop', status: 'active' }]);+ await restoring;+ expect(mocks.attach).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex 8054afadc5..f88f705512 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -769,6 +769,36 @@ describe('turnRunner 渠道任务后台结果回传', () => {expect(mocks.getMaker().createSession).not.toHaveBeenCalled();});+ it.each([false, true])('cold takeover restores scheduler-only topic output (replace runtime: %s)', async (replace) => {+ const old = makeSessionHarness('cold-takeover');+ const route = { attached: true, scopeKey: '300.3' };+ runner.attachSessionOutput(old.session, 'U1', route);+ const h = replace ? makeSessionHarness(old.session.id) : old;+ runner.attachSessionOutput(h.session, 'U1', route);+ if (replace) expect(old.unsubscribe).toHaveBeenCalledTimes(1);+ const stub = streamingHandleStub();+ mocks.slackIm.startStreamingText.mockResolvedValue(stub);+ old.emit({ type: 'text', data: { text: 'desktop input' } });+ old.emit({ type: 'done', data: {} });+ h.emit({ type: 'text', data: { text: 'cross-session input' } });+ h.emit({ type: 'done', data: {} });+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ const turnOrigin = { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'daily' };+ h.emit({ type: 'text', turnOrigin, data: { text: 'scheduled result', isFinal: true } });+ h.emit({ type: 'done', turnOrigin, data: {} });+ await vi.waitFor(() => expect(stub.finalize).toHaveBeenCalledTimes(1));+ expect(stub.finalize).toHaveBeenCalledWith(expect.stringContaining('scheduled result'));+ expect(mocks.slackIm.startStreamingText).toHaveBeenCalledExactlyOnceWith('U1', undefined, { threadTs: '300.3' });+ expect(mocks.getMaker().createSession).not.toHaveBeenCalled();+ expect(h.session.setInteractionListener).not.toHaveBeenCalled();+ runner.detachFromSession(h.session.id);+ mocks.slackIm.startStreamingText.mockClear();+ h.emit({ type: 'text', turnOrigin, data: { text: 'after detach' } });+ h.emit({ type: 'done', turnOrigin, data: {} });+ expect(mocks.slackIm.startStreamingText).not.toHaveBeenCalled();+ expect(h.unsubscribe).toHaveBeenCalledTimes(1);+ });+async function channelAndIdle(): Promise<SessionHarness> {await runTurn('100.1');const h = harnesses.get(sessionIdFor('T1', 'U1', '100.1'))!;diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.tsindex 0c2ac50019..33663605ae 100644--- a/apps/desktop/src/main/im/shared/orchestrator.ts+++ b/apps/desktop/src/main/im/shared/orchestrator.ts@@ -16,6 +16,7 @@ import { getDbClient } from '../../localDb/client/current';import { sessions } from '../../localDb/schema';import { onChannelTurn } from '../../maker-ipc/channelTurnSignal';import { captureImAccountGeneration, isImAccountGenerationCurrent } from '../accountBoundary';+import { bindingStore } from '../binding';import {acquirePendingAgentSwitchForDirectSend,acquirePendingAgentSwitchForImSend,@@ -56,13 +57,17 @@ onChannelTurn(async (session, phase) => {const [row] = await getDbClient().drizzle.select().from(sessions).where(eq(sessions.id, session.id)).limit(1);if (!row || row.status === 'deleted' || row.status === 'archived' || !isImAccountGenerationCurrent(generation)) return;- const orchestrator = registry.get(row.source as ImChannelName);+ const binding = bindingStore.findByTarget(session.id);+ const orchestrator = registry.get((binding?.channel ?? row.source) as ImChannelName);if (!orchestrator) return;const status = orchestrator.adapter.im.getStatus();- const botId = row.source === 'feishu' ? row.feishuBotAppId : row.imBotContextId;+ const botId = binding?.botContextId ?? (row.source === 'feishu' ? row.feishuBotAppId : row.imBotContextId);if (status.kind !== 'connected' || status.appId !== botId) return;- const userId = row.source === 'feishu' ? row.feishuOpenId : row.imUserId;- if (userId) orchestrator.turnRunner.attachSessionOutput(session, userId);+ const userId = binding?.userId ?? (row.source === 'feishu' ? row.feishuOpenId : row.imUserId);+ if (userId) orchestrator.turnRunner.attachSessionOutput(session, userId, {+ attached: binding !== null,+ scopeKey: binding?.scopeKey,+ });});/**diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex d2a35d4f2f..289eacca1c 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -513,7 +513,7 @@ export type ImTurnDispatch =/** createTurnRunner 返回的编排实例 — per channel 一个。 */export interface ImTurnRunner {- attachSessionOutput(session: MakerSession, userId: string): void;+ attachSessionOutput(session: MakerSession, userId: string, route?: { attached: boolean; scopeKey?: string }): void;runAgentTurn(args: ImRunAgentTurnArgs): Promise<void>;/*** 把渠道用户消息**提前**写进本地 messages 表 —— 只给「dispatch 之前还有重活」@@ -4084,18 +4084,25 @@ export function createTurnRunner(}return {- attachSessionOutput: (session, userId) => {+ attachSessionOutput: (session, userId, route) => {const existing = sessionStates.get(session.id);- if (existing?.makerSession === session) return;if (existing) {- rebindSessionOutput(existing, session, userId);+ const userChanged = existing.userId !== userId;+ if (route?.attached) {+ existing.attached = true;+ existing.preserveSessionConfig = true;+ existing.userId = userId;+ existing.scopeKey = route.scopeKey;+ }+ if (existing.makerSession !== session || userChanged) rebindSessionOutput(existing, session, userId);return;}ensureMakerCloseSubscription(getMaker());const state: SessionState = {makerSession: session,- preserveSessionConfig: false,+ preserveSessionConfig: route?.attached === true,userId,+ scopeKey: route?.scopeKey,workingDir: session.workDir,queue: [],sendQueue: [],@@ -4103,7 +4110,7 @@ export function createTurnRunner(unsubscribers: [],detachDrainPromise: null,resolveDetachDrain: null,- attached: false,+ attached: route?.attached === true,scheduledTranspond: null,pendingTranspondFinals: 0,};diff --git a/docs/product-rules/telegram-bot-parity.md b/docs/product-rules/telegram-bot-parity.mdindex 1f1c988a54..3a7ddf2386 100644--- a/docs/product-rules/telegram-bot-parity.md+++ b/docs/product-rules/telegram-bot-parity.md@@ -256,6 +256,8 @@ SSH 任务不把远端路径或托管媒体引用当作本地文件上传;个临时回复通知不建立普通任务的持续转播;`/ctr` 接管任务仍只转播 scheduler 输出。每轮执行前从当前账号库恢复输出监听,核对 bot 身份和任务状态,因此重启后无需先从 IM 发一条消息。+恢复路由优先读取持久化接管绑定的渠道、bot、用户和话题,无接管绑定时才使用渠道原生任务的来源;+接管监听保留 scheduler-only 判据,解除接管沿用原清理入口。飞书/Lark 话题缺少内存锚点时,从原话题查询合法消息恢复;查询失败不降级到群主流。切换执行实例仅换绑事件监听,保留该任务已排队的 IM 消息。个人 IM 的排队入站消息在已有后台结果的发送尝试结束后再派发;发送失败同样释放队列,