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(im): suppress Feishu presence notices from passive shared instances

xuzini-xzne06d51621371
diff --git a/apps/desktop/src/main/im/__tests__/feishuLifecycleAnnouncements.test.ts b/apps/desktop/src/main/im/__tests__/feishuLifecycleAnnouncements.test.ts
new file mode 100644
index 0000000000..c49e45e1e2
--- /dev/null
+++ b/apps/desktop/src/main/im/__tests__/feishuLifecycleAnnouncements.test.ts
@@ -0,0 +1,38 @@
+/**
+ * Regression: a shared-profile preview must not announce global bot presence.
+ * Calls the runtime predicate used by both Desktop Feishu factories; existing
+ * transport tests do not know Electron's resolved profile. Minimal input is
+ * dev + XDT_PASSIVE_SHARED_USER_DATA=1. Unit tier, no external resources;
+ * standalone wall time: 274ms.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { shouldAnnounceFeishuLifecycle } from '../feishu/lifecycleAnnouncements';
+
+const electron = vi.hoisted(() => ({ app: { isPackaged: false } }));
+vi.mock('electron', () => electron);
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ electron.app.isPackaged = false;
+});
+
+describe('Desktop Feishu lifecycle notice ownership', () => {
+ it.each([
+ [true, '1', true],
+ [false, '1', false],
+ [false, undefined, true],
+ [false, '0', true],
+ ])('packaged=%s shared-passive=%s allows notices=%s', (packaged, sharedPassive, expected) => {
+ electron.app.isPackaged = packaged;
+ vi.stubEnv('XDT_PASSIVE_SHARED_USER_DATA', sharedPassive);
+ expect(shouldAnnounceFeishuLifecycle()).toBe(expected);
+ });
+
+ it('checks the resolved profile at send time, keeping isolated passive sandboxes eligible', () => {
+ vi.stubEnv('XDT_PASSIVE_SHARED_USER_DATA', undefined);
+ vi.stubEnv('XDT_SCHEDULER_PASSIVE', '1');
+ expect(shouldAnnounceFeishuLifecycle()).toBe(true);
+ vi.stubEnv('XDT_PASSIVE_SHARED_USER_DATA', '1');
+ expect(shouldAnnounceFeishuLifecycle()).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/im/feishu/lifecycleAnnouncements.ts b/apps/desktop/src/main/im/feishu/lifecycleAnnouncements.ts
new file mode 100644
index 0000000000..8c1d7741f2
--- /dev/null
+++ b/apps/desktop/src/main/im/feishu/lifecycleAnnouncements.ts
@@ -0,0 +1,8 @@
+import { app } from 'electron';
+
+/** Shared-profile previews do not own the bot's process-wide presence notices. */
+export function shouldAnnounceFeishuLifecycle(): boolean {
+ // Read at send time: host modules can load before bootstrap resolves the profile.
+ // A genuinely isolated sandbox still owns its own configured bot connection.
+ return app.isPackaged || process.env.XDT_PASSIVE_SHARED_USER_DATA !== '1';
+}
diff --git a/apps/desktop/src/main/im/host.ts b/apps/desktop/src/main/im/host.ts
index c980732970..f3e27911ca 100644
--- a/apps/desktop/src/main/im/host.ts
+++ b/apps/desktop/src/main/im/host.ts
@@ -65,6 +65,7 @@ import {
} from './wechat/compatibilityPolicy';
import { fetchPublicImageBytes } from './publicImageFetch';
import { buildPersonalBotCommandMenu } from './shared/botCommands';
+import { shouldAnnounceFeishuLifecycle } from './feishu/lifecycleAnnouncements';
const log = createLogger('im/host');
@@ -190,13 +191,20 @@ const host: IMHost = {
createLogger,
};
-export const feishuIm = createFeishuIM(host);
+export const feishuIm = createFeishuIM(host, {
+ shouldAnnounceLifecycle: shouldAnnounceFeishuLifecycle,
+});
/**
* 伙伴自有飞书 / Lark 连接的传输层实例: 凭证与 TOFU 主人按连接前缀隔离、不注册设置卡
* IPC、对外开放(非主人的私聊与群 @ 带非主人标记进业务层)。
*/
export function createBotFeishuIM(secretKeyPrefix: string): FeishuIM {
- return createFeishuIM(host, { secretKeyPrefix, ipc: false, guests: true });
+ return createFeishuIM(host, {
+ secretKeyPrefix,
+ ipc: false,
+ guests: true,
+ shouldAnnounceLifecycle: shouldAnnounceFeishuLifecycle,
+ });
}
export const discordIm = createDiscordIM(host, {
resolveImageUrl: resolveManagedImageAbsPath,
diff --git a/packages/lizi-im/src/feishu/__tests__/lifecycleAnnouncements.test.ts b/packages/lizi-im/src/feishu/__tests__/lifecycleAnnouncements.test.ts
new file mode 100644
index 0000000000..663fea79e9
--- /dev/null
+++ b/packages/lizi-im/src/feishu/__tests__/lifecycleAnnouncements.test.ts
@@ -0,0 +1,155 @@
+/**
+ * Regression: a secondary socket shutting down falsely reports the shared bot
+ * offline. Exercises real FeishuIM init/dispose/inbound/reply with an SDK fake;
+ * existing conflict tests use one scope and cannot observe two instances.
+ * Minimal input: two scopes with the same bot credentials, then secondary exit.
+ * Unit tier, no network or disk; standalone wall time: 407ms.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { IMHost } from '../../types.js';
+import { createFeishuIM, type FeishuIM } from '../index.js';
+import { messages } from '../messages.js';
+
+type Handlers = Record<string, (data: unknown) => Promise<unknown>>;
+
+const sdk = vi.hoisted(() => ({
+ sockets: [] as Array<{ handlers: Handlers; close: ReturnType<typeof vi.fn> }>,
+ create: vi.fn<(request: { data: { content: string } }) => Promise<{ data: { message_id: string } }>>(async () => ({
+ data: { message_id: 'om_sent' },
+ })),
+}));
+
+vi.mock('@larksuiteoapi/node-sdk', () => ({
+ Domain: { Feishu: 'feishu', Lark: 'lark' },
+ LoggerLevel: { info: 'info' },
+ Client: class {
+ im = { v1: { message: { create: sdk.create } } };
+ },
+ EventDispatcher: class {
+ handlers: Handlers = {};
+ register(handlers: Handlers) {
+ this.handlers = handlers;
+ return this;
+ }
+ },
+ WSClient: class {
+ close = vi.fn();
+ constructor(private options: { onReady(): void }) {}
+ getConnectionStatus() {
+ return { state: 'connected' };
+ }
+ async start({ eventDispatcher }: { eventDispatcher: { handlers: Handlers } }) {
+ sdk.sockets.push({ handlers: eventDispatcher.handlers, close: this.close });
+ this.options.onReady();
+ }
+ },
+}));
+
+const instances: FeishuIM[] = [];
+
+function makeHost(prefix: string, enabled = true): IMHost {
+ const values = new Map([
+ [prefix + 'feishu_bot_app_id', 'cli_shared_bot'],
+ [prefix + 'feishu_bot_app_secret', 'test-secret'],
+ [prefix + 'feishu_bot_owner_open_id', 'ou_owner'],
+ [prefix + 'feishu_bot_lifecycle_announcement', String(enabled)],
+ ]);
+ return {
+ secrets: {
+ read: (key) => values.get(key) ?? null,
+ write: vi.fn((key, value) => {
+ values.set(key, value);
+ return true;
+ }),
+ remove: vi.fn(),
+ isAvailable: () => true,
+ },
+ ipc: {
+ handle: vi.fn(),
+ broadcast: vi.fn(),
+ throwIpcError: () => { throw new Error('invalid'); },
+ },
+ paths: { feishuMediaDir: '' },
+ httpPostForm: vi.fn(async () => { throw new Error('Unexpected host HTTP request'); }),
+ createLogger: () => ({
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(),
+ warn: vi.fn(), error: vi.fn(), fatal: vi.fn(),
+ }),
+ };
+}
+
+async function connect(host: IMHost, options: Parameters<typeof createFeishuIM>[1]) {
+ const im = createFeishuIM(host, options);
+ instances.push(im);
+ await im.init();
+ expect(im.getStatus().kind).toBe('connected');
+ return im;
+}
+
+function sentTexts() {
+ return sdk.create.mock.calls.map(([request]) => JSON.parse(request.data.content).text);
+}
+
+async function receive(socket: number, messageId: string) {
+ await sdk.sockets[socket].handlers['im.message.receive_v1']({
+ sender: { sender_id: { open_id: 'ou_owner' } },
+ message: {
+ message_id: messageId,
+ chat_id: 'oc_dm',
+ chat_type: 'p2p',
+ message_type: 'text',
+ content: JSON.stringify({ text: 'hihi' }),
+ },
+ });
+}
+
+afterEach(async () => {
+ for (const im of instances.splice(0)) await im.dispose();
+ sdk.sockets.length = 0;
+ sdk.create.mockClear();
+});
+
+describe('Feishu lifecycle announcements across shared-profile instances', () => {
+ it.each(['', 'companion:'])('secondary exit keeps primary online without a false notice (prefix=%s)', async (secretKeyPrefix) => {
+ const host = makeHost(secretKeyPrefix);
+ const options = { secretKeyPrefix, ipc: false };
+ const primary = await connect(host, options);
+ const secondary = await connect(host, { ...options, shouldAnnounceLifecycle: () => false });
+ await secondary.dispose();
+ expect(sdk.sockets[1].close).toHaveBeenCalledOnce();
+ expect(primary.getStatus().kind).toBe('connected');
+ expect(sentTexts()).toEqual([messages.lifecycle.online]);
+
+ const onMessage = vi.fn();
+ primary.onMessage(onMessage);
+ await receive(0, 'om_after_secondary_exit');
+ expect(onMessage).toHaveBeenCalledWith(expect.objectContaining({ text: 'hihi' }));
+ await primary.sendText('ou_owner', 'reply');
+ await primary.dispose();
+ expect(sentTexts()).toEqual([messages.lifecycle.online, 'reply', messages.lifecycle.offline]);
+ expect(host.secrets.write).not.toHaveBeenCalled();
+ });
+
+ it('secondary still receives and replies, including after reconnect, without an offline-history warning', async () => {
+ const host = makeHost('');
+ const secondary = await connect(host, { ipc: false, shouldAnnounceLifecycle: () => false });
+ const onMessage = vi.fn();
+ secondary.onMessage(onMessage);
+ await receive(0, 'om_secondary');
+ await secondary.sendText('ou_owner', 'secondary reply');
+ await secondary.reconnect();
+ await receive(1, 'om_secondary_reconnected');
+ expect(onMessage).toHaveBeenCalledTimes(2);
+ await secondary.dispose();
+ expect(sentTexts()).toEqual(['secondary reply']);
+ expect(host.secrets.write).not.toHaveBeenCalled();
+ });
+
+ it('primary still respects a saved disabled announcement preference', async () => {
+ const host = makeHost('', false);
+ const primary = await connect(host, { ipc: false, shouldAnnounceLifecycle: () => true });
+ await primary.dispose();
+ expect(sentTexts()).toEqual([]);
+ expect(host.secrets.write).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/lizi-im/src/feishu/index.ts b/packages/lizi-im/src/feishu/index.ts
index 3e0738f69b..4e0d910545 100644
--- a/packages/lizi-im/src/feishu/index.ts
+++ b/packages/lizi-im/src/feishu/index.ts
@@ -63,6 +63,8 @@ export interface FeishuIMOptions {
ipc?: boolean;
/** 对外开放: 非主人的私聊与群 @ 进业务层(带非主人标记), 命令仍只认主人。 */
guests?: boolean;
+ /** Process-local notice ownership; secondary hosts may chat without announcing global presence. */
+ shouldAnnounceLifecycle?: () => boolean;
}
export class FeishuIM extends BaseIM implements ChannelIM {
@@ -102,6 +104,7 @@ export class FeishuIM extends BaseIM implements ChannelIM {
secretKeyPrefix: options.secretKeyPrefix ?? '',
ipc: options.ipc !== false,
guests: options.guests === true,
+ shouldAnnounceLifecycle: options.shouldAnnounceLifecycle,
});
// 设置页那份(无前缀、带 IPC)就是默认作用域: 单测直接调模块函数、Electron IPC 进来
// 没有作用域时都落在它上面。
diff --git a/packages/lizi-im/src/feishu/moduleScope.ts b/packages/lizi-im/src/feishu/moduleScope.ts
index 5239f5c257..9d1b8fc39a 100644
--- a/packages/lizi-im/src/feishu/moduleScope.ts
+++ b/packages/lizi-im/src/feishu/moduleScope.ts
@@ -32,6 +32,8 @@ export interface FeishuScopeOptions {
ipc?: boolean;
/** 对外开放: 非主人的私聊与群 @ 进业务层(带非主人标记), 命令仍只认主人。 */
guests?: boolean;
+ /** Runtime ownership is independent of the owner's saved announcement preference. */
+ shouldAnnounceLifecycle?: () => boolean;
}
export interface FeishuScope {
@@ -40,6 +42,7 @@ export interface FeishuScope {
readonly secretKeyPrefix: string;
readonly ipc: boolean;
readonly guests: boolean;
+ readonly shouldAnnounceLifecycle?: () => boolean;
readonly events: FeishuEventBus;
/** 各模块的实例状态(scopeSlot 按 symbol 懒建)。 */
readonly slots: Map<symbol, unknown>;
@@ -55,6 +58,7 @@ export function createFeishuScope(options: FeishuScopeOptions): FeishuScope {
secretKeyPrefix: options.secretKeyPrefix ?? '',
ipc: options.ipc !== false,
guests: options.guests === true,
+ shouldAnnounceLifecycle: options.shouldAnnounceLifecycle,
events: new FeishuEventBus(),
slots: new Map(),
};
diff --git a/packages/lizi-im/src/feishu/wsClient.ts b/packages/lizi-im/src/feishu/wsClient.ts
index 2de77e8df3..c9565e397a 100644
--- a/packages/lizi-im/src/feishu/wsClient.ts
+++ b/packages/lizi-im/src/feishu/wsClient.ts
@@ -682,6 +682,15 @@ async function stopCurrentClient(opts: StopOptions): Promise<void> {
async function announceLifecycle(phase: 'online' | 'offline'): Promise<void> {
const log = getLog();
+ // A shared-profile preview owns only its local socket, not the bot's presence.
+ // Do not create an offline-history warning or persist a user preference here.
+ if (getScope().shouldAnnounceLifecycle?.() === false) {
+ log.info(
+ `[feishu/wsClient] announceLifecycle ${phase}: suppressed for secondary instance`,
+ );
+ return;
+ }
+
const owner = ownerGuard.firstAllowed();
if (!owner) {
log.info(`[feishu/wsClient] announceLifecycle ${phase}: no owner whitelisted, skip`);