Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(wechat): settle queued work before deleting companion binding
Chrisf40ec3d20729
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.tsindex 8221ea2d0d..1dd3680b50 100644--- a/apps/desktop/src/main/im/index.ts+++ b/apps/desktop/src/main/im/index.ts@@ -266,6 +266,17 @@ export function startImOrchestrators(): void {// 伙伴自有 IM 连接: 每条记录一份传输层 + 编排器, 与上面设置页那份并存。// 实例在 initializeImConnection 里按记录起, 这里只注入装配方式。configureBotImConnectionRuntime({+ removeWechatCompanionBinding: (update, isCurrent) => {+ const generation = captureImAccountGeneration();+ if (generation === null) return Promise.reject(new Error('ACCOUNT_CHANGED'));+ return wechatIm.updateCompanionBinding(() => {+ if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');+ update();+ }, { cancelPendingIf: () => {+ if (!isImAccountGenerationCurrent(generation)) throw new Error('ACCOUNT_CHANGED');+ return isCurrent();+ } });+ },create: (record) => {const prefix = secretKeyPrefixFor(record.id);if (record.channel === 'telegram') {diff --git a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.tsindex 1e1089f60d..b463987415 100644--- a/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/botImConnectionRuntime.test.ts@@ -18,6 +18,7 @@ const h = vi.hoisted(() => ({archiveCalls: [] as unknown[],sent: [] as Array<{ channel: string; payload: unknown }>,ownerKey: 'owner-a',+ drainWechat: vi.fn(async (update: () => void, isCurrent: () => boolean) => { if (isCurrent()) update(); }),/** 每次 Telegram setConfig 落盘前调用(测并发添加 / 建连期间切账号)。 */beforeTelegramSetConfig: null as (() => Promise<void> | void) | null,}));@@ -293,7 +294,9 @@ describe('bot im connection runtime', () => {connectOutcome = true;telegramConflictAfterConnect = false;adoptionTesting.reset();+ h.drainWechat.mockClear();configureBotImConnectionRuntime({+ removeWechatCompanionBinding: h.drainWechat,create: (record) => {const prefix = secretKeyPrefixFor(record.id);const orchestrator = fakeOrchestrator();@@ -452,7 +455,12 @@ describe('bot im connection runtime', () => {expect(readWechatChannelSettings()).toEqual(before);expect(h.sent).toEqual([]);+ h.drainWechat.mockRejectedValueOnce(new Error('DRAIN_FAILED'));+ await expect(removeBotImConnectionsForBot('bot-mia')).rejects.toThrow('DRAIN_FAILED');+ expect(readWechatChannelSettings()).toEqual(before);+ expect(h.sent).toEqual([]);await removeBotImConnectionsForBot('bot-mia');+ expect(h.drainWechat).toHaveBeenCalledTimes(2);expect(readWechatChannelSettings()).toEqual({ version: 1, workingDir: before.workingDir, workingDirAvailable: true });expect(h.secrets).toEqual(secrets);expect(h.sent).toEqual([{ channel: 'wechatBot:channel-settings-changed', payload: readWechatChannelSettings() }]);diff --git a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts b/apps/desktop/src/main/im/shared/botImConnectionRuntime.tsindex 41c93cad48..c13af6d0c3 100644--- a/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts+++ b/apps/desktop/src/main/im/shared/botImConnectionRuntime.ts@@ -74,6 +74,8 @@ export interface BotImSettingsIdentity {}export interface BotImConnectionRuntimeDeps {+ /** Drain the shared WeChat transport and cancel queued work before clearing its owner. */+ removeWechatCompanionBinding(update: () => void, isCurrent: () => boolean): Promise<void>;/** 为一条记录装配传输层 + 编排器(不 init)。渠道尚未支持时抛错。 */create(record: BotImConnectionRecord): BotImTransportInstance;/** 设置页那份个人 bot 当前用的平台身份(用于拒绝同一个 bot 两处同时用)。 */@@ -631,10 +633,13 @@ export async function removeBotImConnectionsForBot(botId: string): Promise<void>// WeChat shares the personal transport: remove only the teammate assignment,// even when there are no dedicated connections. Keep its authorization intact.if (readWechatChannelSettings().companionBotId === botId) {- const settings = writeWechatCompanionBinding(null);- for (const window of BrowserWindow.getAllWindows()) {- if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', settings);- }+ await requireDeps().removeWechatCompanionBinding(() => {+ if (readWechatChannelSettings().companionBotId !== botId) return;+ const settings = writeWechatCompanionBinding(null);+ for (const window of BrowserWindow.getAllWindows()) {+ if (!window.isDestroyed()) window.webContents.send('wechatBot:channel-settings-changed', settings);+ }+ }, () => readWechatChannelSettings().companionBotId === botId);}for (const record of listBotImConnectionsForBot(botId)) {try {diff --git a/apps/desktop/src/main/im/wechat/WechatIM.ts b/apps/desktop/src/main/im/wechat/WechatIM.tsindex c3dc0451dc..87b5f7e03b 100644--- a/apps/desktop/src/main/im/wechat/WechatIM.ts+++ b/apps/desktop/src/main/im/wechat/WechatIM.ts@@ -197,27 +197,42 @@ export class WechatIM extends BaseIM implements RichChannelIM {return !!this.#epoch && this.#epoch.credentials.userId === userId;}- /** Change routing only between messages; credentials and the authorization epoch stay intact. */- updateCompanionBinding(update: () => void): Promise<void> {+ /** Change routing between messages, or cancel pending input when its companion is deleted. */+ updateCompanionBinding(update: () => void, options: { cancelPendingIf?: () => boolean } = {}): Promise<void> {return this.#queueLifecycle(async () => {- if (this.#authorizationAbort || this.#activeTasks.size || this.#pendingInteractions.size) {+ const cancelPending = options.cancelPendingIf?.() ?? false;+ if (options.cancelPendingIf && !cancelPending) return;+ if (this.#authorizationAbort || (!cancelPending && (this.#activeTasks.size || this.#pendingInteractions.size))) {throw new Error('WECHAT_CONNECTION_BUSY');}const epoch = this.#epoch;- if (epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {+ if (!cancelPending && epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {throw new Error('WECHAT_CONNECTION_BUSY');}- if (this.#activeTasks.size) throw new Error('WECHAT_CONNECTION_BUSY');+ if (!cancelPending && this.#activeTasks.size) throw new Error('WECHAT_CONNECTION_BUSY');const revision = this.#compatibilityRevision;+ const db = cancelPending ? this.#deps.getDbClient() : null;await this.#stopEpoch();+ let updated = false;try {+ if (cancelPending && db) {+ if (!options.cancelPendingIf?.()) throw new Error('WECHAT_BINDING_CHANGED');+ // Deletion must also settle a disabled/offline connection's durable inbox.+ const binding = epoch?.binding ?? await this.#readActiveBindingWithoutKey(db);+ if (binding) await db.tx('wechatStopAll', {+ bindingEpoch: binding.bindingEpoch, now: this.#now(),+ errorCode: 'COMPANION_DELETED', cancelPending: true,+ });+ }// A poll already in flight may have persisted a message while we drained it.- if (epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {+ if (!cancelPending && epoch && await this.#requireStore().countQueuedTasks(epoch.binding.bindingEpoch)) {throw new Error('WECHAT_CONNECTION_BUSY');}update();+ updated = true;} finally {- if (epoch && this.#isCompatibilityRevisionAllowed(revision)) {+ // A failed deletion cleanup must not resume work against an archived teammate.+ if ((!cancelPending || updated) && epoch && this.#isCompatibilityRevisionAllowed(revision)) {const binding = await this.#requireStore().getActiveBinding();if (binding) await this.#startEpoch(binding, epoch.credentials, revision);}@@ -1041,10 +1056,15 @@ export class WechatIM extends BaseIM implements RichChannelIM {): Promise<void> {while (!signal.aborted && this.#isGenerationCurrent(generation)) {await this.#pollBarrier;+ if (signal.aborted) break;const task = await this.#requireStore().leaseNextTask({bindingEpoch: binding.bindingEpoch,now: this.#now(),});+ if (signal.aborted) {+ if (task) await this.#requireStore().releaseDispatch(task.bindingEpoch, task.id);+ break;+ }if (!task) {await delay(IDLE_PUMP_DELAY_MS, signal);continue;@@ -1105,6 +1125,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {const turnInput = prepareWechatTaskTurn(payload);const botContextId = this.#epoch?.credentials.ilinkBotId ?? '';+ const signal = this.#epoch?.abort.signal;const companion = runtime.runner.companionBotIdFor?.(botContextId);const requesterIsOwner = this.isOwner(task.peerId);const active: ActiveTask = { task, terminalCommitted: false };@@ -1112,6 +1133,7 @@ export class WechatIM extends BaseIM implements RichChannelIM {const stopTyping = await this.#startTyping(task);let dispatch;try {+ if (!signal || signal.aborted) throw new Error('WECHAT_CONNECTION_STOPPED');dispatch = await runtime.runner.dispatchAgentTurn({botContextId,userId: task.peerId,@@ -1140,8 +1162,10 @@ export class WechatIM extends BaseIM implements RichChannelIM {attachments: payload.attachments,queueMode: 'external',beforeProviderStart: async () => {+ if (signal.aborted) throw new Error('WECHAT_CONNECTION_STOPPED');const accepted = await this.#requireStore().markAccepted(task.bindingEpoch, task.id);if (!accepted) throw new Error('WECHAT_ACCEPT_CAS_REJECTED');+ if (signal.aborted) throw new Error('WECHAT_CONNECTION_STOPPED');},onRouteResolved: (sessionId) => {if (this.#activeTasks.get(task.peerId) === active) {@@ -1679,8 +1703,8 @@ export class WechatIM extends BaseIM implements RichChannelIM {};}- async #readActiveBindingWithoutKey(): Promise<WechatActiveBinding | null> {- const row = await this.#deps.getDbClient().queryOne<{+ async #readActiveBindingWithoutKey(db = this.#deps.getDbClient()): Promise<WechatActiveBinding | null> {+ const row = await db.queryOne<{bindingEpoch: string;cursor: string;}>(diff --git a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.tsindex f656149017..d8ccbf86d9 100644--- a/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts+++ b/apps/desktop/src/main/im/wechat/__tests__/WechatIM.test.ts@@ -597,6 +597,57 @@ describe('WechatIM host boundary', () => {} finally { await im.dispose(); }});+ // #6492 unit regression: deletion must include the late poll batch in its+ // cancellation, preserve authorization, and never restart after settlement failure.+ it.each([false, true])('settles deletion after poll drain (failure=%s)', async (fail) => {+ const { im, transport, db, testHost } = restoredConnection(() => 1);+ const order: string[] = [];+ im.attachTurnRuntime({ runner: { companionBotIdFor: () => 'cindy',+ resolveRouteTarget: async () => ({ row: { id: 'companion-owner' } }) },+ repo: {}, config: {}, resetSessionToDefaults: vi.fn() } as never);+ vi.mocked(transport.poll).mockImplementationOnce((_cursor, signal) => new Promise((resolve) => {+ signal.addEventListener('abort', () => resolve({ cursor: 'next', messages: [{+ senderId: 'owner', messageId: 'late-owner', text: 'hello', contextToken: 'context', media: [],+ }] }), { once: true });+ }));+ vi.mocked(db.tx).mockImplementation(async (name, args) => {+ if (name === 'wechatCommitPollBatch') {+ order.push('batch');+ return { committed: true, insertedTaskIds: [], duplicateTaskIds: [], rejectedTaskIds: [] };+ }+ if (name === 'wechatStopAll' && (args as { cancelPending?: boolean }).cancelPending) {+ order.push('cancel');+ if (fail) throw new Error('DRAIN_FAILED');+ }+ return null;+ });+ await im.init();+ try {+ const update = vi.fn(() => { order.push('update'); });+ const changing = im.updateCompanionBinding(update, { cancelPendingIf: () => true });+ if (fail) await expect(changing).rejects.toThrow('DRAIN_FAILED');+ else await changing;+ expect(order).toEqual(fail ? ['batch', 'cancel'] : ['batch', 'cancel', 'update']);+ expect(transport.notifyStart).toHaveBeenCalledTimes(fail ? 1 : 2);+ expect(testHost.secrets.write).not.toHaveBeenCalled();+ expect(testHost.secrets.remove).not.toHaveBeenCalled();+ } finally { await im.dispose(); }+ });++ it('settles a stored inbox without starting an offline transport and skips a changed owner', async () => {+ const { im, transport, db } = restoredConnection(() => 1);+ const update = vi.fn();+ await im.updateCompanionBinding(update, { cancelPendingIf: () => false });+ expect(db.tx).not.toHaveBeenCalled();+ expect(update).not.toHaveBeenCalled();+ await im.updateCompanionBinding(update, { cancelPendingIf: () => true });+ expect(db.tx).toHaveBeenCalledWith('wechatStopAll', expect.objectContaining({+ bindingEpoch: 'epoch', cancelPending: true, errorCode: 'COMPANION_DELETED',+ }));+ expect(update).toHaveBeenCalledOnce();+ expect(transport.notifyStart).not.toHaveBeenCalled();+ });+// Regression: the durable inbox used to claim a personal session even for companion messages.// tier: unit; feed transport ingress and inspect the real task-store transaction boundary.it('persists companion ingress against the resolved task before dispatch', async () => {diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 51628e2bdd..aabc127c8a 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -1252,10 +1252,13 @@ export interface WechatStopAllArgs {bindingEpoch: string;now: number;errorCode: string;+ /** Permanent companion deletion cancels pre-accepted work instead of replaying it. */+ cancelPending?: boolean;}export interface WechatStopAllResult {requeued: number;+ cancelled: number;interrupted: number;expired: number;repaired: number;diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.tsindex a69b95adfc..064e8122f7 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/__tests__/wechatTx.test.ts@@ -392,6 +392,44 @@ describe('WeChat reliable worker transactions', () => {);});+ // #6492 unit regression through the real worker transaction: deleting a+ // companion cancels pending/dispatching input and releases staged attachments.+ // Restart recovery is covered separately and must continue requeuing input.+ it('cancels deleted companion work without closing authorization or removing final replies', () => {+ const db = createDb();+ activate(db, 'epoch-1', null);+ for (const id of ['pending', 'dispatching', 'accepted', 'reply']) {+ db.prepare('INSERT INTO sessions (id) VALUES (?)').run(`session-${id}`);+ }+ commitBatch(db, {+ messages: ['pending', 'dispatching', 'accepted', 'reply'].map((id) => message(id, id, `session-${id}`)),+ mediaBlobs: [{ hash: HASH, ext: '.png', mimeType: 'image/png', bytes: 4,+ isCache: false, createdAt: 100, lastAccessAt: 100 }],+ mediaRefs: [{ id: 'pending-media', hash: HASH, taskId: 'pending', label: 'image', createdAt: 100 }],+ fileAttachments: [{ id: 'pending-file', taskId: 'pending', sessionId: 'session-pending',+ absPath: '/tmp/wechat-delete-fixture.pdf', originalName: 'fixture.pdf', mimeType: 'application/pdf',+ bytes: 4, createdAt: 100 }],+ });+ db.prepare("UPDATE wechat_inbox SET status = 'dispatching' WHERE id = 'dispatching'").run();+ db.prepare("UPDATE wechat_inbox SET status = 'accepted_running' WHERE id IN ('accepted', 'reply')").run();+ runTx(db, 'wechatCommitTerminal', { bindingEpoch: 'epoch-1', taskId: 'reply', now: 200,+ outbox: [outbox('reply-outbox', 'reply-client', 0, 'already finished')] });+ expect(runTx(db, 'wechatStopAll', { bindingEpoch: 'epoch-1', now: 201,+ errorCode: 'COMPANION_DELETED', cancelPending: true,+ })).toMatchObject({ requeued: 0, cancelled: 2, interrupted: 1 });+ expect(readTaskStatus(db, 'pending')).toBe('cancelled');+ expect(readTaskStatus(db, 'dispatching')).toBe('cancelled');+ expect(readTaskStatus(db, 'accepted')).toBe('interrupted');+ expect(readTaskStatus(db, 'reply')).toBe('delivery_pending');+ expect(count(db, 'media_refs')).toBe(0);+ expect(db.prepare('SELECT status FROM wechat_file_attachments').pluck().get()).toBe('released');+ expect(count(db, 'wechat_outbox')).toBe(1);+ expect(db.prepare('SELECT is_active FROM wechat_sync_state').pluck().get()).toBe(1);+ runTx(db, 'wechatStopAll', { bindingEpoch: 'epoch-1', now: 202, errorCode: 'PROCESS_RESTARTED' });+ expect(lease(db, 'epoch-1', 203)).toBeNull();+ expect(readTaskStatus(db, 'pending')).toBe('cancelled');+ });+it('replays only pre-accepted work and interrupts accepted work after recovery', () => {const db = createDb();activate(db, 'epoch-1', null);diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.tsindex 5e891fb2b6..77df0d9028 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/wechatTx.ts@@ -704,6 +704,7 @@ export function wechatStopAll(db: Database.Database, args: unknown): WechatStopAconst bindingEpoch = expectId(payload.bindingEpoch, 'bindingEpoch');const now = expectTimestamp(payload.now, 'now');const errorCode = expectMachineCode(payload.errorCode, 'errorCode');+ const cancelPending = payload.cancelPending === undefined ? false : expectBoolean(payload.cancelPending, 'cancelPending');return db.transaction(() => {db.prepare(@@ -713,6 +714,10 @@ export function wechatStopAll(db: Database.Database, args: unknown): WechatStopA).run(now, bindingEpoch);repairAcceptedTaskAttachments(db, bindingEpoch, now);const expired = expirePendingTasks(db, bindingEpoch, now);+ const cancelled = cancelPending ? db.prepare(+ `UPDATE wechat_inbox SET status = 'cancelled', lease_until = NULL, last_error_code = ?+ WHERE binding_epoch = ? AND status IN ('pending', 'dispatching')`,+ ).run(errorCode, bindingEpoch).changes : 0;const requeued = db.prepare(`UPDATE wechat_inbox@@ -741,7 +746,7 @@ export function wechatStopAll(db: Database.Database, args: unknown): WechatStopA).run(bindingEpoch).changes;releaseTerminalMediaRefs(db, bindingEpoch);- return { requeued, interrupted, expired, repaired };+ return { requeued, cancelled, interrupted, expired, repaired };})();}