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(wechat): serialize companion binding with profile deletion

Chris671e4962fb29
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index 1dd3680b50..6a530d8adb 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -64,7 +64,7 @@ import {
captureSessionRuntimeControlOwnerEpoch,
sessionRuntimeControlOwnerEpochMatches,
} from '../maker-ipc/sessionRuntimeControl.js';
-import { botProfiles, sessions } from '../localDb/schema';
+import { sessions } from '../localDb/schema';
import {
im,
feishuIm,
@@ -92,6 +92,7 @@ import { resetChannelGroupContextCursors } from './shared/channelGroupWindow';
import { getImOrchestrator, listImOrchestrators } from './shared/orchestrator';
import {
configureBotImConnectionRuntime,
+ setWechatCompanionBinding,
registerBotImConnectionIpc as registerBotImConnectionRuntimeIpc,
startBotImConnections,
stopBotImConnections,
@@ -127,7 +128,6 @@ import {
readWechatChannelSettings,
resetWechatWorkingDir,
writeWechatWorkingDir,
- writeWechatCompanionBinding,
} from './wechat/channelSettings';
/** 伙伴「消息平台」的 IPC: 连接增删 / 群聊 / 隐藏任务, 以及把个人 bot 移给伙伴。 */
@@ -421,21 +421,16 @@ export function startImOrchestrators(): void {
return connectionLifecycle.runWhileStarted(async () => {
const generation = captureImAccountGeneration();
if (generation === null) throwIpcError('PRECONDITION_FAILED', 'Account unavailable');
- if (botId) {
- const [profile] = await getDbClient().drizzle.select({ status: botProfiles.status })
- .from(botProfiles).where(eq(botProfiles.id, botId as string)).limit(1);
- if (profile?.status !== 'active') throwIpcError('PRECONDITION_FAILED', 'BOT_INACTIVE');
- const current = readWechatChannelSettings().companionBotId;
- if (current && current !== botId) throwIpcError('PRECONDITION_FAILED', 'WECHAT_COMPANION_IN_USE');
- }
try {
- await wechatIm.updateCompanionBinding(() => {
+ await setWechatCompanionBinding(botId as string | null, (commit) => wechatIm.updateCompanionBinding(() => {
if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');
- writeWechatCompanionBinding(botId as string | null);
- });
+ commit();
+ }));
} catch (error) {
- throwIpcError('PRECONDITION_FAILED', error instanceof Error && error.message === 'WECHAT_CONNECTION_BUSY'
- ? 'WECHAT_CONNECTION_BUSY' : 'WECHAT_COMPANION_UPDATE_FAILED');
+ const code = error instanceof Error ? error.message : '';
+ throwIpcError('PRECONDITION_FAILED',
+ ['WECHAT_CONNECTION_BUSY', 'BOT_INACTIVE', 'WECHAT_COMPANION_IN_USE'].includes(code)
+ ? code : 'WECHAT_COMPANION_UPDATE_FAILED');
}
BrowserWindow.getAllWindows().forEach((window) => {
if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', readWechatChannelSettings());
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 e538cd9ef0..c82a936976 100644
--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts
@@ -83,6 +83,7 @@ vi.mock('../../../security/trustedAppRenderer', () => ({ assertTrustedAppRendere
import {
addBotImConnection,
configureBotImConnectionRuntime,
+ setWechatCompanionBinding,
getBotFeishuTransport,
listBotImConnectionGroups,
removeBotImConnection,
@@ -93,6 +94,7 @@ import {
__testing,
} from '../botImConnectionRuntime';
import { addBotImConnectionRecord, listBotImConnections, secretKeyPrefixFor } from '../botImConnectionStore';
+import { withBotProfileLocks } from '../../../maker-ipc/botProfileLock';
import { readWechatChannelSettings, writeWechatCompanionBinding, writeWechatWorkingDir } from '../../wechat/channelSettings';
import {
adoptPersonalBot,
@@ -485,6 +487,39 @@ describe('bot im connection runtime', () => {
expect(removed.connections).toEqual([]);
});
+ // #6492 r4318509719, unit: existing cleanup tests miss an initially unbound
+ // teammate being deleted during transport drain. Use the real binding/store
+ // entry and the same profile lock as botLifecycleService, with controlled gates.
+ it('does not resurrect a deleted teammate when its first WeChat binding is draining', async () => {
+ let release!: () => void;
+ let entered!: () => void;
+ const draining = new Promise<void>((resolve) => { entered = resolve; });
+ const drained = new Promise<void>((resolve) => { release = resolve; });
+ const binding = setWechatCompanionBinding('bot-mia', async (commit) => {
+ entered();
+ await drained;
+ commit();
+ });
+ await draining;
+ const deletion = withBotProfileLocks(['bot-mia'], async () => {
+ h.botStatus = 'deleting';
+ await removeBotImConnectionsForBot('bot-mia');
+ h.botStatus = null;
+ });
+ // Run until deletion either completes or waits on the binding's profile lock.
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ release();
+ await Promise.all([binding, deletion]);
+ expect(readWechatChannelSettings().companionBotId).toBeUndefined();
+ const apply = vi.fn(async (commit: () => void) => { commit(); });
+ await expect(setWechatCompanionBinding('bot-mia', apply)).rejects.toThrow('BOT_INACTIVE');
+ expect(apply).not.toHaveBeenCalled();
+ // A different active teammate can claim the shared connection afterwards.
+ h.botStatus = 'active';
+ await setWechatCompanionBinding('bot-other', apply);
+ expect(readWechatChannelSettings().companionBotId).toBe('bot-other');
+ });
+
// Regression #6492: a WeChat-only teammate has no connection-store records.
// unit tier: real deletion cleanup and settings store; keep shared auth and unrelated owners.
it('clears only the deleted teammate’s WeChat assignment and broadcasts without removing authorization', async () => {
diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
index 501b63f978..fe9c5b19e9 100644
--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts
@@ -23,6 +23,7 @@ import { createLogger } from '../../logger';
import { getDbClient } from '../../localDb/client/current';
import { archiveBotChannelLanes } from '../../localDb/ipc/bots';
import { botProfiles } from '../../localDb/schema';
+import { withBotProfileLocks } from '../../maker-ipc/botProfileLock';
import { assertTrustedAppRendererEvent } from '../../security/trustedAppRenderer';
import { throwIpcError } from '../../utils/ipcValidate';
import { ownerScopedImSecrets } from '../ownerScopedStorage';
@@ -652,6 +653,23 @@ export async function removeBotImConnection(id: string): Promise<BotImConnection
return { ...buildBotImConnectionListPayload(), archivedSessionIds };
}
+/** Keep profile validation and deferred WeChat persistence in one lifecycle operation. */
+export async function setWechatCompanionBinding(
+ botId: string | null,
+ apply: (commit: () => void) => Promise<void>,
+): Promise<void> {
+ const run = async () => {
+ if (botId) {
+ if (await readBotProfileStatus(botId) !== 'active') throw new Error('BOT_INACTIVE');
+ const current = readWechatChannelSettings().companionBotId;
+ if (current && current !== botId) throw new Error('WECHAT_COMPANION_IN_USE');
+ }
+ await apply(() => { writeWechatCompanionBinding(botId); });
+ };
+ // Match deletion lock order: profile first, then the WeChat transport lifecycle.
+ await withBotProfileLocks(botId ? [botId] : [], run);
+}
+
/** 伙伴被删除 / 归档时带走它的全部连接。 */
export async function removeBotImConnectionsForBot(botId: string): Promise<void> {
// WeChat shares the personal transport: remove only the teammate assignment,