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(feishu): await companion routing and skip unavailable connections

Chris8d9933ca491d
diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
index b444c1b88b..8b44142749 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
@@ -82,6 +82,7 @@ vi.mock('../../../security/trustedAppRenderer', () => ({ assertTrustedAppRendere
import {
addBotImConnection,
configureBotImConnectionRuntime,
+ getBotFeishuTransport,
listBotImConnectionGroups,
removeBotImConnection,
setBotImConnectionGroupMode,
@@ -90,7 +91,7 @@ import {
stopBotImConnections,
__testing,
} from '../botImConnectionRuntime';
-import { listBotImConnections, secretKeyPrefixFor } from '../botImConnectionStore';
+import { addBotImConnectionRecord, listBotImConnections, secretKeyPrefixFor } from '../botImConnectionStore';
import {
adoptPersonalBot,
configureBotImPersonalAdoption,
@@ -321,6 +322,47 @@ describe('bot im connection runtime', () => {
});
});
+ // #6439: persisted connections can fail init and remain in instances. Exercise
+ // the real store/start/select lifecycle (unit) instead of a selector replica.
+ it('skips failed and ownerless Feishu connections without changing the resolved recipient', async () => {
+ const states = [
+ { kind: 'error', owner: 'ou_failed' },
+ { kind: 'connected', owner: null },
+ { kind: 'connected', owner: 'ou_target' },
+ { kind: 'connected', owner: 'ou_other' },
+ ];
+ const records: BotImConnectionRecord[] = [];
+ for (let index = 0; index < states.length; index += 1) {
+ records.push(await addBotImConnectionRecord({ botId: 'bot-mia', channel: 'feishu' }, { now: () => index }));
+ }
+ configureBotImConnectionRuntime({
+ create: (record) => {
+ const state = states[records.findIndex((candidate) => candidate.id === record.id)]!;
+ return {
+ kind: 'feishu',
+ im: {
+ init: async () => { if (state.kind === 'error') throw new Error('startup failed'); },
+ dispose: async () => undefined,
+ onStatusChange: () => () => undefined,
+ getStatus: () => ({ kind: state.kind }),
+ getOwnerOpenId: () => state.owner,
+ } as never,
+ orchestrator: fakeOrchestrator() as never,
+ };
+ },
+ settingsIdentity: () => ({ telegramToken: null, feishuAppId: null, wecomBotId: null, dingtalkAppKey: null, discordToken: null }),
+ listKnownGroups: async () => [],
+ });
+ await startBotImConnections();
+ expect(getBotFeishuTransport('bot-mia')?.getOwnerOpenId()).toBe('ou_target');
+ states[2]!.kind = 'error';
+ // A later tool phase must not retry a resolved target through another owner.
+ expect(getBotFeishuTransport('bot-mia', 'ou_target')).toBeNull();
+ expect(getBotFeishuTransport('unrelated-bot')).toBeNull();
+ await stopBotImConnections();
+ expect(getBotFeishuTransport('bot-mia')).toBeNull();
+ });
+
it('lists known groups with their per-connection activation and toggles it live', async () => {
const added = await addBotImConnection({
botId: 'bot-mia',
diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
index f68e5c53e8..9165493e08 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
@@ -283,11 +283,18 @@ export function getBotImConnectionOrchestrator(id: string): ImOrchestrator | und
* 不能回落到设置页那份可能已被清空的个人 bot —— 否则 `getOwnerOpenId()` 为 null 时
* `send_message_to_user` / `send_file_to_user` 会误报 NO_CHAT_CONTEXT。
*/
-export function getBotFeishuTransport(botId: string): FeishuIM | null {
+export function getBotFeishuTransport(botId: string, ownerOpenId?: string): FeishuIM | null {
for (const record of listBotImConnectionsForBot(botId)) {
if (record.channel !== 'feishu') continue;
const live = instances.get(record.id);
- if (live?.transport.kind === 'feishu') return live.transport.im;
+ if (live?.transport.kind !== 'feishu' || live.record.botId !== botId) continue;
+ const im = live.transport.im;
+ const owner = im.getOwnerOpenId();
+ if (im.getStatus().kind !== 'connected' || !owner) continue;
+ // open_id belongs to this app. Never send a previously resolved recipient
+ // through a different owner's connection after a disconnect/reconfiguration.
+ if (ownerOpenId && owner !== ownerOpenId) continue;
+ return im;
}
return null;
}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
index cd956e943c..ba8f1a3512 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,11 @@ const mockState = vi.hoisted(() => ({
_sessionInstanceId: string | undefined,
) => ({ ok: true as const })),
capturedProvidersConfig: null as null | Record<string, unknown>,
+ companionFeishu: {
+ getOwnerOpenId: () => 'ou_companion',
+ sendMarkdownText: vi.fn(async () => ({ messageId: 'om_companion_text' })),
+ sendFile: vi.fn(async () => ({ ok: true, messageId: 'om_companion_file' })),
+ },
}));
vi.mock('electron', () => ({
@@ -72,10 +77,15 @@ vi.mock('../../scheduler-host/index.js', () => ({
vi.mock('../../im/index.js', () => ({
feishuIm: {
+ getOwnerOpenId: () => null,
sendFile: vi.fn(),
},
}));
+vi.mock('../../im/shared/botImConnectionRuntime', () => ({
+ getBotFeishuTransport: (botId: string) => botId === 'bot-feishu' ? mockState.companionFeishu : null,
+}));
+
vi.mock('../cindyProxyMedia.js', () => ({
getCindyProxyMediaService: () => ({ mcp: {} }),
}));
@@ -116,6 +126,9 @@ import {
resolveCollabDispatchResult,
} from '../../maker-ipc/collabSendOutcome.js';
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';
const botCapabilities = {
list: vi.fn(async () => ({ ok: true as const, capabilities: [] })),
@@ -206,6 +219,39 @@ describe('collab send outcome semantics', () => {
});
+ // #6439: real Desktop host callbacks + worker DB, only the external IM service
+ // is replaced. Covers missing awaits at host call sites, beyond resolver tests.
+ 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 {
+ 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')");
+ await client.exec("INSERT INTO bot_session_links VALUES ('background-receipt', 'bot-feishu', 'canonical')");
+ setCurrentDbClient(client, 'feishu-test-owner');
+ createDesktopMcpProviders({
+ botCapabilities,
+ getMakerMemoryManager: vi.fn(),
+ lspPool: {} as never,
+ pluginRegistry: { isEnabled: () => true, getPlugins: () => [] } as never,
+ invokeRemote: vi.fn(),
+ });
+ const feishu = mockState.capturedProvidersConfig!.feishuBot as FeishuBotMcpHostDeps;
+ const session = { sessionId: 'background-receipt', sessionInstanceId: 'runtime' };
+ const owner = await feishu.getOwnerOpenId(session);
+ expect(owner).toBe('ou_companion');
+ expect(await feishu.sendMessage(owner!, 'task complete', session.sessionId, session))
+ .toMatchObject({ ok: true, messageId: 'om_companion_text' });
+ expect(await feishu.sendFile(owner!, '/tmp/report.txt', 'report.txt', session))
+ .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');
+ } finally {
+ clearCurrentDbClient(client);
+ await client.dispose();
+ }
+ });
+
it('rejects start_skill_learning after the built-in Learn Skill is disabled', async () => {
mockState.learnEnabled = false;
createDesktopMcpProviders({
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts
index a54738f20f..36613dc84e 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/feishuTransportRouting.test.ts
@@ -1,35 +1,75 @@
-import { describe, expect, it } from 'vitest';
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
-import { selectFeishuTransport } from '../feishuTransportRouting';
+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';
-const personal = { id: 'personal' };
-const companion = { id: 'companion' };
-const lane = { id: 'lane' };
+// #6439: exercise the production resolver through DbClient -> Drizzle proxy ->
+// worker_threads -> SQLite. The former pure selector never queried the DB.
+// Minimal failure: one canonical link, no inbound lease; unit, one in-memory worker.
+let client: DbClient;
+const personal = { getOwnerOpenId: () => 'ou_personal' } as FeishuToolTransport;
+const companion = { getOwnerOpenId: () => 'ou_companion' } as FeishuToolTransport;
+const lane = { getOwnerOpenId: () => 'ou_lane' } as FeishuToolTransport;
+const readTurnScope = vi.fn<() => { im: FeishuToolTransport } | null>(() => null);
+const getCompanionTransport = vi.fn((): FeishuToolTransport | null => companion);
+const resolve = createFeishuTransportResolver({ readTurnScope, getCompanionTransport, personalIm: personal });
-interface Transport { id: string }
+beforeAll(async () => {
+ client = await createDbClient({ transport: 'worker-thread', useInlineWorker: true });
+ 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 ('canonical', 'bot'), ('desktop', 'desktop'), ('late', 'bot')");
+ await client.exec("INSERT INTO bot_session_links VALUES ('canonical', 'bot-a', 'canonical')");
+});
+beforeEach(() => {
+ setCurrentDbClient(client, 'account-a');
+ readTurnScope.mockReturnValue(null);
+ getCompanionTransport.mockReturnValue(companion);
+});
+afterAll(async () => {
+ 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' });
+ 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);
+ clearCurrentDbClient(client);
+ readTurnScope.mockReturnValue({ im: lane });
+ expect(await resolve({ sessionId: 'canonical' })).toBe(lane);
+ });
-function pick(input: Partial<Parameters<typeof selectFeishuTransport<Transport>>[0]>) {
- return selectFeishuTransport<Transport>({
- turnScopeIm: null,
- companionBotId: null,
- companionIm: null,
- personalIm: personal,
- ...input,
- }).id;
-}
+ it('sees canonical ownership established after an earlier lookup', async () => {
+ expect(await resolve({ sessionId: 'late' })).toBe(personal);
+ await client.exec("INSERT INTO bot_session_links VALUES ('late', 'bot-a', 'canonical')");
+ expect(await resolve({ sessionId: 'late' })).toBe(companion);
+ });
-describe('cindy_feishu_bot transport routing', () => {
- it('uses the connection that triggered this Feishu turn', () => {
- expect(pick({ turnScopeIm: lane, companionBotId: 'bot', companionIm: companion })).toBe('lane');
+ it('never falls back to personal credentials when a companion is unavailable', async () => {
+ getCompanionTransport.mockReturnValue(null);
+ await expect(resolve({ sessionId: 'canonical' })).rejects.toThrow('Companion Feishu connection unavailable');
});
- it('keeps a companion session on its own connection without a turn scope', () => {
- // 后台任务回执 / 心跳 / 桌面输入触发的轮次没有逐轮作用域; 不能回落到设置页那份。
- expect(pick({ companionBotId: 'bot', companionIm: companion })).toBe('companion');
+ it('rejects a lookup that completes across an account switch', async () => {
+ const pending = resolve({ sessionId: 'canonical' });
+ setCurrentDbClient(client, 'account-b');
+ await expect(pending).rejects.toThrow('Feishu account changed');
});
- it('falls back to the personal bot for non-companion sessions', () => {
- expect(pick({})).toBe('personal');
- expect(pick({ companionBotId: 'bot', companionIm: null })).toBe('personal');
+ 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 {
+ await expect(resolve({ sessionId: 'canonical' })).rejects.toThrow();
+ } finally {
+ await client.exec('ALTER TABLE unavailable_links RENAME TO bot_session_links');
+ }
+ expect(await resolve({ sessionId: 'canonical' })).toBe(companion);
});
});
diff --git a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
index b854a635a2..0af703cd11 100644
--- a/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
+++ b/apps/desktop/src/main/mcp-integrations/feishuTransportRouting.ts
@@ -1,23 +1,41 @@
-/**
- * cindy_feishu_bot 出站选哪条飞书连接。
- *
- * 顺序:
- * 1. 本轮飞书逐轮作用域(由飞书入站消息触发的轮次);
- * 2. 会话所属伙伴自己的飞书连接(伙伴主任务的后台任务回执 / 心跳 / 桌面输入轮次);
- * 3. 设置页那份个人 bot(hook 会话、桌面任务的「飞书通知我」)。
- *
- * 第 2 步不能省: 伙伴主任务不带专线的 `feishuChatId`, 个人 bot 移交给伙伴后那份又被清空,
- * 少了这一步就会拿设置页的空 owner 去出站, 误报 NO_CHAT_CONTEXT。
+import { and, eq } from 'drizzle-orm';
+
+import { getCurrentDbClientSnapshot } 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;
+
+/** Resolve each notification against the current account and live connection.
+ * No negative cache: a session can acquire its canonical link after creation.
*/
-export function selectFeishuTransport<T>(
- input: {
- turnScopeIm: T | null;
- companionBotId: string | null;
- companionIm: T | null;
- personalIm: T;
- },
-): T {
- if (input.turnScopeIm) return input.turnScopeIm;
- if (input.companionBotId && input.companionIm) return input.companionIm;
- return input.personalIm;
+export function createFeishuTransportResolver(deps: {
+ readTurnScope: (session: Caller) => { im: FeishuToolTransport } | null;
+ getCompanionTransport: (botId: string, ownerOpenId?: string) => FeishuToolTransport | null;
+ personalIm: FeishuToolTransport;
+}) {
+ return async (session: Caller, ownerOpenId?: string): Promise<FeishuToolTransport> => {
+ const scope = deps.readTurnScope(session);
+ if (scope) return scope.im;
+ if (!session?.sessionId) return deps.personalIm;
+
+ const snapshot = getCurrentDbClientSnapshot();
+ if (!snapshot) throw new Error('DbClient not ready');
+ const row = await snapshot.client.drizzle
+ .select({ botId: botSessionLinks.botId })
+ .from(botSessionLinks)
+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
+ .where(and(
+ eq(botSessionLinks.sessionId, session.sessionId),
+ eq(sessions.source, 'bot'),
+ eq(botSessionLinks.role, 'canonical'),
+ ))
+ .limit(1)
+ .get();
+ if (getCurrentDbClientSnapshot() !== snapshot) throw new Error('Feishu account changed');
+ if (!row?.botId) return deps.personalIm;
+ const im = deps.getCompanionTransport(row.botId, ownerOpenId);
+ if (!im) throw new Error('Companion Feishu connection unavailable');
+ return im;
+ };
}
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index aaa4cd2e26..fb9f20cce4 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -44,8 +44,8 @@ import { getBrowserMcpDeps } from './browser.js';
import { getComputerMcpDeps } from './computer.js';
import { feishuIm, wechatIm } from '../im';
import { getBotFeishuTransport } from '../im/shared/botImConnectionRuntime';
-import { selectFeishuTransport } from './feishuTransportRouting';
-import { readChannelToolScope, type FeishuToolTransport } from '../im/shared/channelToolScope';
+import { createFeishuTransportResolver } from './feishuTransportRouting';
+import { readChannelToolScope } from '../im/shared/channelToolScope';
import { hasImChannelVendorOptions } from '../../shared/botImConnection.js';
import { sendFeishuSessionNotification } from '../im/feishu/notificationOrigin';
import { getSlackToolBridge } from '../hook-control/slackToolBridge.js';
@@ -170,9 +170,6 @@ export interface DesktopMcpProvidersDeps {
* 当前 tool-call 所属的飞书逐轮作用域(个人 bot 或伙伴自有连接), 没有就是 null。
* 用 sessionId + sessionInstanceId 查租约: 旧实例借不到新实例的权限。
*/
-/** 会话 → 伙伴主任务归属(tool-call 高频路径); 换账号 / 换连接时整表清空。 */
-const companionBotIdBySession = new Map<string, { dbClient: object; botId: string | null }>();
-
function readFeishuTurnScope(
session: { sessionId?: string; sessionInstanceId?: string } | undefined,
) {
@@ -183,59 +180,11 @@ function readFeishuTurnScope(
return scope?.channel === 'feishu' ? scope : null;
}
-/**
- * 这个 tool-call 所属的会话是哪位伙伴(没有 ≡ 不是伙伴会话)。
- *
- * 伙伴主任务(role='canonical')与桌面共用、不带专线的 `feishuChatId`, 所以后台任务回执 /
- * 心跳 / scheduler / 对话输入触发的轮次没有逐轮作用域。出站仍必须走伙伴自己的连接。
- */
-function companionBotIdForSession(sessionId: string | undefined): string | null {
- if (!sessionId) return null;
- const dbClient = tryGetDbClient();
- if (!dbClient) return null;
- const cached = companionBotIdBySession.get(sessionId);
- if (cached && cached.dbClient === dbClient) return cached.botId;
- let botId: string | null = null;
- try {
- const row = dbClient.drizzle
- .select({ botId: botSessionLinks.botId })
- .from(botSessionLinks)
- .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
- .where(and(
- eq(botSessionLinks.sessionId, sessionId),
- eq(sessions.source, 'bot'),
- eq(botSessionLinks.role, 'canonical'),
- ))
- .limit(1)
- .get();
- botId = row?.botId ?? null;
- } catch {
- return null;
- }
- if (companionBotIdBySession.size > 512) companionBotIdBySession.clear();
- companionBotIdBySession.set(sessionId, { dbClient, botId });
- return botId;
-}
-
-/**
- * cindy_feishu_bot 出站走哪个 bot: 飞书入站轮次走触发本轮的那条连接; 伙伴主任务
- * (后台任务回执 / 心跳 / 桌面输入轮次)走该伙伴自己的连接; 其余(hook 会话 / 桌面
- * 任务的「飞书通知我」)才走设置页那份。
- *
- * 不能把伙伴会话回落到设置页那份: 个人 bot 移交给伙伴后那份已被清空, owner 为空,
- * `getChatId()` 会直接给 NO_CHAT_CONTEXT —— 用户明明已经私聊过机器人。
- */
-function feishuTransportFor(
- session: { sessionId?: string; sessionInstanceId?: string } | undefined,
-): FeishuToolTransport {
- const companionBotId = companionBotIdForSession(session?.sessionId);
- return selectFeishuTransport({
- turnScopeIm: readFeishuTurnScope(session)?.im ?? null,
- companionBotId,
- companionIm: companionBotId ? getBotFeishuTransport(companionBotId) : null,
- personalIm: feishuIm,
- });
-}
+const feishuTransportFor = createFeishuTransportResolver({
+ readTurnScope: readFeishuTurnScope,
+ getCompanionTransport: getBotFeishuTransport,
+ personalIm: feishuIm,
+});
export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcpProvider[] {
setSessionPathAuthorizer((request) =>
@@ -420,10 +369,10 @@ 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: (session) => feishuTransportFor(session).getOwnerOpenId(),
+ getOwnerOpenId: async (session) => (await feishuTransportFor(session)).getOwnerOpenId(),
sendFile: async (chatId: string, absPath: string, displayName?: string, session?) => {
try {
- return await feishuTransportFor(session).sendFile(chatId, absPath, displayName);
+ return await (await feishuTransportFor(session, chatId)).sendFile(chatId, absPath, displayName);
} catch (err) {
createLogger('mcp/cindy_feishu_bot').warn(
'sendFile failed target=...%s detail=%s',
@@ -440,9 +389,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 = feishuTransportFor(session);
- // 通知主人并挂回原任务: 只有个人 bot 有这条路(伙伴连接的轮次本来就带飞书 chatId,
- // 不会走到 notificationSessionId 分支)。
+ const im = await feishuTransportFor(session, chatId);
+ // 只有个人 bot 维护通知到普通任务的回复关联; 伙伴连接已有自己的主任务。
if (im === feishuIm && notificationSessionId && chatId === feishuIm.getOwnerOpenId()) {
const { messageId, sessionLinked } = await sendFeishuSessionNotification(
feishuIm, notificationSessionId, markdown,
diff --git a/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts b/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts
index 3577981b87..d36d1a8b50 100644
--- a/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts
+++ b/packages/lizi-mcps/src/__tests__/providersFeishuRouting.test.ts
@@ -1,11 +1,13 @@
import { describe, expect, it, vi } from 'vitest';
import { createLiziMcpProviders } from '../providers.js';
import { runWithLiziMcpSessionContext } from '../session-context.js';
+import type { FeishuBotMcpHostDeps } from '../types.js';
-function setup() {
+function setup(getOwnerOpenId: FeishuBotMcpHostDeps['getOwnerOpenId'] = async () => 'ou_owner') {
const sendMessage = vi.fn(async () => ({ ok: true, messageId: 'om_notification' }));
+ const sendFile = vi.fn(async () => ({ ok: true, messageId: 'om_file' }));
const provider = createLiziMcpProviders({
- feishuBot: { getOwnerOpenId: () => 'ou_owner', sendFile: vi.fn(), sendMessage },
+ feishuBot: { getOwnerOpenId, sendFile, sendMessage },
}).find((candidate) => candidate.name === 'cindy_feishu_bot')!;
const config = provider.toClaudeSdkConfig({ agentKind: 'codex', workingDir: '' }) as {
instance: { _registeredTools: Record<string, { handler: (args: unknown) => Promise<unknown> }> };
@@ -13,10 +15,20 @@ function setup() {
const call = () => config.instance._registeredTools.call_tool.handler({
name: 'send_message_to_user', args: { text: 'hello' },
});
- return { sendMessage, call };
+ const callFile = () => config.instance._registeredTools.call_tool.handler({
+ name: 'send_file_to_user', args: { absPath: '/tmp/report.txt' },
+ });
+ return { sendMessage, sendFile, call, callFile };
}
describe('Feishu notification session attribution', () => {
+ // #6439: worker DB owner lookup is asynchronous. The real MCP handler must
+ // pass a resolved recipient to both send paths, never a Promise (unit tier).
+ it('awaits the owner before sending a file', async () => {
+ const { sendFile, callFile } = setup();
+ await callFile();
+ expect(sendFile).toHaveBeenCalledWith('ou_owner', '/tmp/report.txt', undefined, expect.any(Object));
+ });
it('resolves each caller at tool-call time on the shared bridge', async () => {
const { sendMessage, call } = setup();
await Promise.all(['session-a', 'session-b'].map((sessionId) => runWithLiziMcpSessionContext(
@@ -37,8 +49,17 @@ describe('Feishu notification session attribution', () => {
});
it('leaves messages unattributed when no trusted caller is available', async () => {
- const { sendMessage, call } = setup();
+ const { sendMessage, call } = setup(() => 'ou_owner');
await call();
expect(sendMessage).toHaveBeenCalledWith('ou_owner', 'hello', undefined, expect.objectContaining({ agentKind: 'codex' }));
});
+
+ it('does not send or suggest rebinding when the asynchronous owner lookup fails', async () => {
+ const { sendMessage, sendFile, call, callFile } = setup(async () => { throw new Error('DbClient not ready'); });
+ for (const invoke of [call, callFile]) {
+ await expect(invoke()).rejects.toThrow('DbClient not ready');
+ }
+ expect(sendMessage).not.toHaveBeenCalled();
+ expect(sendFile).not.toHaveBeenCalled();
+ });
});
diff --git a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
index cb96357f07..6d14bacbf3 100644
--- a/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
+++ b/packages/lizi-mcps/src/cindy_feishuBotMcpServer.ts
@@ -116,7 +116,7 @@ export type FeishuBotMcpDeps = Omit<FeishuBotMcpHostDeps, 'getOwnerOpenId' | 're
* (typically: user has never DM'd the bot). Tools translate null into
* NO_CHAT_CONTEXT with guidance.
*/
- getChatId: () => string | null | undefined;
+ getChatId: () => string | null | undefined | Promise<string | null | undefined>;
/**
* 会话来源(ctx.vendorOptions.source,session 构建期确定)。Cindy hook 来源给
* 本 server 全部工具描述追加渠道路由提示——若通道选择交给模型自由判断会
@@ -163,7 +163,7 @@ function registerSendFileToUser(
.describe('发送给用户看到的文件名,默认用 basename(absPath)'),
},
handler: async ({ absPath, displayName }) => {
- const chatId = deps.getChatId();
+ const chatId = await deps.getChatId();
if (!chatId) {
return buildJsonResult(
{
@@ -230,7 +230,7 @@ function registerSendMessageToUser(
),
},
handler: async ({ text }) => {
- const chatId = deps.getChatId();
+ const chatId = await deps.getChatId();
if (!chatId) {
return buildJsonResult(
{
diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.ts
index 153af8c6d9..8e16d57cd6 100644
--- a/packages/lizi-mcps/src/providers.ts
+++ b/packages/lizi-mcps/src/providers.ts
@@ -251,9 +251,9 @@ export function createLiziMcpProviders(
instance: createFeishuBotMcpServer({
// 每个 host dep 都带上当前 tool-call 的 session:宿主据此选出这一轮真正要
// 出站的 bot(个人设置页那份,或触发本轮的伙伴自有连接)。
- getChatId: () => {
+ getChatId: async () => {
const current = resolveLiziMcpSessionContext(ctx);
- return readFeishuChatId(current) ?? opts.feishuBot!.getOwnerOpenId(current) ?? null;
+ return readFeishuChatId(current) ?? await opts.feishuBot!.getOwnerOpenId(current) ?? null;
},
sendFile: (chatId, absPath, displayName) =>
opts.feishuBot!.sendFile(chatId, absPath, displayName, resolveLiziMcpSessionContext(ctx)),
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 4ff93041e7..edafdcef55 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -203,7 +203,7 @@ export interface FeishuBotMcpHostDeps {
* Returns null when no owner has been bound yet — user must DM the bot once
* first (same precondition as scheduler feishu-completion notifications).
*/
- getOwnerOpenId(session?: FeishuBotHostSession): string | null;
+ getOwnerOpenId(session?: FeishuBotHostSession): string | null | Promise<string | null>;
logger?: LiziMcpLogger;
}