Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(feishu): fence companion sends across owner transitions
Chris8741c2b88b67
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.tsindex ba8f1a3512..5b3b02757e 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts@@ -21,6 +21,7 @@ const mockState = vi.hoisted(() => ({_sessionInstanceId: string | undefined,) => ({ ok: true as const })),capturedProvidersConfig: null as null | Record<string, unknown>,+ afterSelectCompanion: null as null | (() => void),companionFeishu: {getOwnerOpenId: () => 'ou_companion',sendMarkdownText: vi.fn(async () => ({ messageId: 'om_companion_text' })),@@ -83,7 +84,10 @@ vi.mock('../../im/index.js', () => ({}));vi.mock('../../im/shared/botImConnectionRuntime', () => ({- getBotFeishuTransport: (botId: string) => botId === 'bot-feishu' ? mockState.companionFeishu : null,+ getBotFeishuTransport: (botId: string) => {+ if (mockState.afterSelectCompanion) queueMicrotask(mockState.afterSelectCompanion);+ return botId === 'bot-feishu' ? mockState.companionFeishu : null;+ },}));vi.mock('../cindyProxyMedia.js', () => ({@@ -129,6 +133,7 @@ import { createDesktopMcpProviders } from '../mcp-providers.js';import { createDbClient } from '../../localDb/client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';import type { FeishuBotMcpHostDeps } from '@cindy/mcps';+import { beginAppSessionBoundary, commitVolatileAppSession } from '../../appSessionState.js';const botCapabilities = {list: vi.fn(async () => ({ ok: true as const, capabilities: [] })),@@ -224,6 +229,7 @@ describe('collab send outcome semantics', () => {it('sends canonical background text and files through companion host callbacks with a worker DB', async () => {const client = await createDbClient({ transport: 'worker-thread', useInlineWorker: true });try {+ commitVolatileAppSession('cloud', 'feishu-test-owner');await client.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT)');await client.exec('CREATE TABLE bot_session_links (session_id TEXT, bot_id TEXT, role TEXT)');await client.exec("INSERT INTO sessions VALUES ('background-receipt', 'bot')");@@ -246,7 +252,33 @@ describe('collab send outcome semantics', () => {.toMatchObject({ ok: true, messageId: 'om_companion_file' });expect(mockState.companionFeishu.sendMarkdownText).toHaveBeenCalledWith('ou_companion', 'task complete');expect(mockState.companionFeishu.sendFile).toHaveBeenCalledWith('ou_companion', '/tmp/report.txt', 'report.txt');++ // A boundary may start after the resolver fulfills but before its caller+ // resumes. Both production send callbacks must recheck before dispatch.+ for (const transition of ['pending', 'generation'] as const) {+ for (const send of [+ () => feishu.sendMessage(owner!, 'must not send', session.sessionId, session),+ () => feishu.sendFile(owner!, '/tmp/report.txt', 'report.txt', session),+ ]) {+ let release: (() => void) | undefined;+ mockState.companionFeishu.sendMarkdownText.mockClear();+ mockState.companionFeishu.sendFile.mockClear();+ mockState.afterSelectCompanion = () => {+ if (transition === 'pending') release = beginAppSessionBoundary();+ else commitVolatileAppSession('cloud', 'feishu-test-owner', true);+ };+ try {+ expect(await send()).toMatchObject({ ok: false, reason: 'SEND_FAIL' });+ expect(mockState.companionFeishu.sendMarkdownText).not.toHaveBeenCalled();+ expect(mockState.companionFeishu.sendFile).not.toHaveBeenCalled();+ } finally {+ mockState.afterSelectCompanion = null;+ release?.();+ }+ }+ }} finally {+ commitVolatileAppSession('signed-out');clearCurrentDbClient(client);await client.dispose();}diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.tsindex 36613dc84e..4bdec5d6c2 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts@@ -4,6 +4,12 @@ import { createDbClient, type DbClient } from '../../localDb/client/DbClient.js'import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';import type { FeishuToolTransport } from '../../im/shared/channelToolScope.js';import { createFeishuTransportResolver } from '../feishuTransportRouting.js';+import { beginAppSessionBoundary, commitVolatileAppSession } from '../../appSessionState.js';++vi.mock('../../logger.js', () => ({ createLogger: () => ({ info: vi.fn() }) }));+vi.mock('../../maker-host/override-settings-file.js', () => ({+ createOverrideSettingsFile: () => ({ read: () => ({ activeMode: 'signed-out' }) }),+}));// #6439: exercise the production resolver through DbClient -> Drizzle proxy ->// worker_threads -> SQLite. The former pure selector never queried the DB.@@ -24,32 +30,34 @@ beforeAll(async () => {await client.exec("INSERT INTO bot_session_links VALUES ('canonical', 'bot-a', 'canonical')");});beforeEach(() => {+ commitVolatileAppSession('cloud', 'account-a');setCurrentDbClient(client, 'account-a');readTurnScope.mockReturnValue(null);getCompanionTransport.mockReturnValue(companion);});afterAll(async () => {+ commitVolatileAppSession('signed-out');clearCurrentDbClient(client);await client.dispose();});describe('Feishu transport with worker database', () => {it('resolves a canonical companion without an inbound scope', async () => {- const im = await resolve({ sessionId: 'canonical' });+ const { im } = await resolve({ sessionId: 'canonical' });expect(im.getOwnerOpenId()).toBe('ou_companion');});it('keeps inbound scope ahead of DB lookup and ordinary desktop notifications on personal bot', async () => {- expect(await resolve({ sessionId: 'desktop' })).toBe(personal);+ expect((await resolve({ sessionId: 'desktop' })).im).toBe(personal);clearCurrentDbClient(client);readTurnScope.mockReturnValue({ im: lane });- expect(await resolve({ sessionId: 'canonical' })).toBe(lane);+ expect((await resolve({ sessionId: 'canonical' })).im).toBe(lane);});it('sees canonical ownership established after an earlier lookup', async () => {- expect(await resolve({ sessionId: 'late' })).toBe(personal);+ expect((await resolve({ sessionId: 'late' })).im).toBe(personal);await client.exec("INSERT INTO bot_session_links VALUES ('late', 'bot-a', 'canonical')");- expect(await resolve({ sessionId: 'late' })).toBe(companion);+ expect((await resolve({ sessionId: 'late' })).im).toBe(companion);});it('never falls back to personal credentials when a companion is unavailable', async () => {@@ -63,6 +71,25 @@ describe('Feishu transport with worker database', () => {await expect(pending).rejects.toThrow('Feishu account changed');});+ // PR #6443: teardown marks a boundary pending before replacing the worker DB.+ // Existing snapshot-switch coverage misses this reachable window (unit tier).+ it('rejects notifications while teardown is pending, including an in-flight worker lookup', async () => {+ const pending = resolve({ sessionId: 'canonical' });+ const release = beginAppSessionBoundary();+ try {+ await expect(pending).rejects.toThrow('Feishu account changed');+ await expect(resolve({ sessionId: 'canonical' })).rejects.toThrow('Feishu account changed');+ } finally {+ release();+ }+ });++ it('rejects an owner generation change even while the DB snapshot remains unchanged', async () => {+ const pending = resolve({ sessionId: 'canonical' });+ commitVolatileAppSession('cloud', 'account-a', true);+ await expect(pending).rejects.toThrow('Feishu account changed');+ });+it('propagates asynchronous database failure instead of caching a missing owner', async () => {await client.exec('ALTER TABLE bot_session_links RENAME TO unavailable_links');try {@@ -70,6 +97,6 @@ describe('Feishu transport with worker database', () => {} finally {await client.exec('ALTER TABLE unavailable_links RENAME TO bot_session_links');}- expect(await resolve({ sessionId: 'canonical' })).toBe(companion);+ expect((await resolve({ sessionId: 'canonical' })).im).toBe(companion);});});diff --git a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.tsindex 0af703cd11..aa153fed3a 100644--- a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts+++ b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts@@ -1,10 +1,12 @@import { and, eq } from 'drizzle-orm';-import { getCurrentDbClientSnapshot } from '../localDb/client/current.js';+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';+import { getCurrentDbClientSnapshot, type CurrentDbClientSnapshot } from '../localDb/client/current.js';import { botSessionLinks, sessions } from '../localDb/schema.js';import type { FeishuToolTransport } from '../im/shared/channelToolScope.js';type Caller = { sessionId?: string; sessionInstanceId?: string } | undefined;+type ResolvedTransport = { im: FeishuToolTransport; assertCurrent: () => void };/** Resolve each notification against the current account and live connection.* No negative cache: a session can acquire its canonical link after creation.@@ -14,12 +16,23 @@ export function createFeishuTransportResolver(deps: {getCompanionTransport: (botId: string, ownerOpenId?: string) => FeishuToolTransport | null;personalIm: FeishuToolTransport;}) {- return async (session: Caller, ownerOpenId?: string): Promise<FeishuToolTransport> => {+ return async (session: Caller, ownerOpenId?: string): Promise<ResolvedTransport> => {+ const ownerScope = activeOwnerScopeKey();+ let snapshot: CurrentDbClientSnapshot | null = null;+ // Teardown marks the boundary pending before replacing the DB or stopping IM.+ // Callers must also check after awaiting this resolver, immediately before use.+ const assertCurrent = () => {+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope ||+ (snapshot && getCurrentDbClientSnapshot() !== snapshot)) {+ throw new Error('Feishu account changed');+ }+ };+ assertCurrent();const scope = deps.readTurnScope(session);- if (scope) return scope.im;- if (!session?.sessionId) return deps.personalIm;+ if (scope) return { im: scope.im, assertCurrent };+ if (!session?.sessionId) return { im: deps.personalIm, assertCurrent };- const snapshot = getCurrentDbClientSnapshot();+ snapshot = getCurrentDbClientSnapshot();if (!snapshot) throw new Error('DbClient not ready');const row = await snapshot.client.drizzle.select({ botId: botSessionLinks.botId })@@ -32,10 +45,10 @@ export function createFeishuTransportResolver(deps: {)).limit(1).get();- if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('Feishu account changed');- if (!row?.botId) return deps.personalIm;+ assertCurrent();+ if (!row?.botId) return { im: deps.personalIm, assertCurrent };const im = deps.getCompanionTransport(row.botId, ownerOpenId);if (!im) throw new Error('Companion Feishu connection unavailable');- return im;+ return { im, assertCurrent };};}diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex fb9f20cce4..0a1c6c68aa 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -369,10 +369,16 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// the current session isn't a feishu one — semantically "notify the// bot's human owner". Same TOFU accessor scheduler completion// notifications use; returns null before the user has DM'd the bot.- getOwnerOpenId: async (session) => (await feishuTransportFor(session)).getOwnerOpenId(),+ getOwnerOpenId: async (session) => {+ const { im, assertCurrent } = await feishuTransportFor(session);+ assertCurrent();+ return im.getOwnerOpenId();+ },sendFile: async (chatId: string, absPath: string, displayName?: string, session?) => {try {- return await (await feishuTransportFor(session, chatId)).sendFile(chatId, absPath, displayName);+ const { im, assertCurrent } = await feishuTransportFor(session, chatId);+ assertCurrent();+ return await im.sendFile(chatId, absPath, displayName);} catch (err) {createLogger('mcp/cindy_feishu_bot').warn('sendFile failed target=...%s detail=%s',@@ -389,7 +395,8 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc// into `reason` for logging without leaking axios internals to the tool.sendMessage: async (chatId, markdown, notificationSessionId, session) => {try {- const im = await feishuTransportFor(session, chatId);+ const { im, assertCurrent } = await feishuTransportFor(session, chatId);+ assertCurrent();// 只有个人 bot 维护通知到普通任务的回复关联; 伙伴连接已有自己的主任务。if (im === feishuIm && notificationSessionId && chatId === feishuIm.getOwnerOpenId()) {const { messageId, sessionLinked } = await sendFeishuSessionNotification(diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.mdindex f5f4d9e738..1d910954ce 100644--- a/docs/dev-rules/im-turn-flow.md+++ b/docs/dev-rules/im-turn-flow.md@@ -65,7 +65,8 @@ Telegram / Slack / X)是同一件事的两套实现:把渠道里的一条消主任务的后台回报、心跳或桌面轮次中可主动通知主人。无飞书逐轮作用域时,宿主异步查询当前账号的`bot_session_links`(`role='canonical'`,关联 `sessions.source='bot'`),选择该伙伴已连接且已绑定主人的飞书连接;发送时校验连接的 owner 与已解析收件人一致。已识别伙伴但没有匹配的可用连接、-数据库查询失败或查询期间切换账号,均拒绝发送,不回落个人 bot。没有 canonical 伙伴归属的普通+数据库查询失败、账号边界处于 pending 或 owner 代次变化,均拒绝发送,不回落个人 bot;查询前后+及实际调用发送前都复核账号边界、owner 代次与所用 DB 快照。没有 canonical 伙伴归属的普通任务仍保留设置页个人 bot 的主人通知能力。此路径不向主任务持久写入 `feishuChatId`,也不生成租约或授予轮次内原生 API 权限;`cindyBotImChannels` 只控制工具挂载,不作为归属或授权依据。实现见 [`feishuTransportRouting.ts`](../../apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts)