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): 退出时隔离待确认请求并收口失效卡片 (#4702)

FicoWangd9601396d5c9
diff --git a/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts b/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
index 62494aff71..28dd750717 100644
--- a/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
+++ b/apps/desktop/src/main/im/__tests__/connectionLifecycle.test.ts
@@ -37,6 +37,21 @@ describe('serialized IM connection lifecycle', () => {
expect(lifecycle.isStarted()).toBe(false);
});
+ it('still closes the transport after pre-stop cleanup fails', async () => {
+ const failure = new Error('cleanup failed');
+ const events: string[] = [];
+ const lifecycle = createSerializedConnectionLifecycle({
+ startConnection: async () => undefined,
+ beforeStopConnection: async () => { events.push('cleanup'); throw failure; },
+ stopConnection: async () => { events.push('stop'); },
+ onStartError: vi.fn(),
+ });
+ lifecycle.start();
+ await expect(lifecycle.stop('logout')).rejects.toBe(failure);
+ expect(events).toEqual(['cleanup', 'stop']);
+ expect(lifecycle.isStarted()).toBe(false);
+ });
+
it('is idempotent within one login and reconnects after logout', async () => {
const startConnection = vi.fn(async () => undefined);
const stopConnection = vi.fn(async () => undefined);
diff --git a/apps/desktop/src/main/im/connectionLifecycle.ts b/apps/desktop/src/main/im/connectionLifecycle.ts
index c5b4d1a709..097e8e1048 100644
--- a/apps/desktop/src/main/im/connectionLifecycle.ts
+++ b/apps/desktop/src/main/im/connectionLifecycle.ts
@@ -13,6 +13,8 @@ export interface SerializedConnectionLifecycle {
/** Dependencies are injected so lifecycle ordering stays unit-testable. */
export interface SerializedConnectionLifecycleDeps {
startConnection(): Promise<void>;
+ /** Ingress must already be fenced; keep outbound transports available here. */
+ beforeStopConnection?(): Promise<void>;
stopConnection(reason?: string): Promise<void>;
onStartError(error: unknown): void;
}
@@ -62,7 +64,11 @@ export function createSerializedConnectionLifecycle(
generation += 1;
await enqueue(async () => {
if (!shouldStopConnection) return;
- await deps.stopConnection(reason);
+ try {
+ await deps.beforeStopConnection?.();
+ } finally {
+ await deps.stopConnection(reason);
+ }
});
},
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index 16f81a6661..125b90513d 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -557,20 +557,28 @@ async function reconcileOwnerScopedImWorkingDirs(): Promise<void> {
const connectionLifecycle = createSerializedConnectionLifecycle({
startConnection: initializeImConnection,
+ beforeStopConnection: async () => {
+ // A start already in flight may have activated ingress after the initial
+ // synchronous stop gate. Re-close and drain it on the serialized boundary
+ // before retaining outbound clients for the bounded card expiry attempt.
+ const closingGeneration = captureImAccountGeneration();
+ deactivateImAccountBoundary();
+ if (closingGeneration !== null) {
+ await waitForImAccountGenerationIdle(closingGeneration);
+ }
+ await Promise.all(listImOrchestrators().map(async (orchestrator) => {
+ try {
+ await orchestrator.disposeAllSessions();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`disposeAllSessions channel=${orchestrator.channel} failed: ${msg}`);
+ }
+ }));
+ },
stopConnection: async (reason) => {
- // Transports stop first so no new message can enter while account-scoped
- // orchestrator and binding caches are being discarded.
try {
await im.dispose();
} finally {
- for (const orchestrator of listImOrchestrators()) {
- try {
- await orchestrator.disposeAllSessions();
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.warn(`disposeAllSessions channel=${orchestrator.channel} failed: ${msg}`);
- }
- }
bindingStore.resetRuntime();
// 普通退出、登出、换账号与模式切换都只清内存热缓存, 保留本地 DB 游标;
// 只有明确删除账号数据时才清持久表。Telegram bot 解绑由 hook-control 的
diff --git a/apps/desktop/src/main/im/shared/__tests__/pendingInteractions.test.ts b/apps/desktop/src/main/im/shared/__tests__/pendingInteractions.test.ts
index 3b468f5838..581c213341 100644
--- a/apps/desktop/src/main/im/shared/__tests__/pendingInteractions.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/pendingInteractions.test.ts
@@ -119,3 +119,41 @@ describe('rejectAllPending', () => {
expect(getPendingCount()).toBe(0);
});
});
+
+
+describe('runner-owned disposal', () => {
+ it('returns only the disposing runner cards and keeps other channels and legacy requests live', () => {
+ const owner = Symbol('runner');
+ const other = Symbol('runner');
+ const foreignReject = vi.fn();
+ const legacyReject = vi.fn();
+ const rejects = [vi.fn(), vi.fn(), vi.fn()];
+ for (const [i, kind] of (['permission', 'plan_review', 'ask_user_question'] as const).entries()) {
+ registerPendingExternal(`owned-${i}`, kind, `own-card-${i}`, vi.fn(), rejects[i]!, { owner });
+ }
+ registerPendingExternal('foreign', 'permission', 'same-id', vi.fn(), foreignReject, { owner: other });
+ registerPendingExternal('legacy', 'permission', 'same-id', vi.fn(), legacyReject);
+ expect(rejectAllPending('session_disposed', owner)).toEqual([
+ { requestId: 'owned-0', messageId: 'own-card-0' },
+ { requestId: 'owned-1', messageId: 'own-card-1' },
+ { requestId: 'owned-2', messageId: 'own-card-2' },
+ ]);
+ for (const reject of rejects) expect(reject).toHaveBeenCalledWith(new Error('session_disposed'));
+ expect(foreignReject).not.toHaveBeenCalled();
+ expect(legacyReject).not.toHaveBeenCalled();
+ expect(getPendingCount()).toBe(2);
+ expect(rejectAllPending('session_disposed', owner)).toEqual([]);
+ cancelPending('foreign', 'cleanup');
+ cancelPending('legacy', 'cleanup');
+ });
+
+ it('does not erase a new request registered by a rejection callback', () => {
+ const owner = Symbol('runner');
+ registerPendingExternal('old', 'permission', 'old-card', vi.fn(), () => {
+ registerPendingExternal('new', 'permission', 'new-card', vi.fn(), vi.fn(), { owner });
+ }, { owner });
+ expect(rejectAllPending('session_disposed', owner)).toEqual([{ requestId: 'old', messageId: 'old-card' }]);
+ expect(getPendingCount()).toBe(1);
+ expect(cancelPending('new', 'cleanup')).toEqual({ messageId: 'new-card' });
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
index e107dc7935..6784208083 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts
@@ -25,6 +25,8 @@ import type {
} from '@cindy/maker-core';
import type { ChannelIM } from '@cindy/im';
import { setMainLocale } from '../../../i18n';
+import { enqueueAskCardPatch } from '../askCardPatchQueue';
+import { createSerializedConnectionLifecycle } from '../../connectionLifecycle';
const mocks = vi.hoisted(() => ({
logger: {
@@ -69,7 +71,7 @@ const mocks = vi.hoisted(() => ({
takePendingInteractionsForSession: vi.fn(),
// 取消不到时返回 null(取消到了返回 { messageId }, 调用方据此收口卡片)。
cancelPending: vi.fn(() => null),
- rejectAllPending: vi.fn(),
+ rejectAllPending: vi.fn<(reason: string, owner?: symbol) => Array<{ requestId: string; messageId: string }>>(() => []),
registerPending: vi.fn(),
registerPendingExternal: vi.fn(),
buildPermissionCard: vi.fn(),
@@ -3368,6 +3370,106 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()
expect(mocks.persistUserMessage).toHaveBeenCalledTimes(1);
});
+ it('bounds disposal when an expiry fails and another channel update stalls', async () => {
+ const stalled = deferred<void>();
+ const update = vi.fn()
+ .mockRejectedValueOnce(new Error('channel closing'))
+ .mockImplementationOnce(() => stalled.promise);
+ const card = { body: 'expired', buttons: [] };
+ const localRunner = createTurnRunner({
+ ...fakeAdapter,
+ interactionExpiredNotice: 'expired',
+ output: { kind: 'rich-card', im: { ...mocks.feishuIm, updateInteractiveCard: update } as unknown as ChannelIM },
+ }, fakeRepo, { ...fakeCards, buildResolvedCard: vi.fn(() => card) } as unknown as ImCardBuilders);
+ mocks.rejectAllPending.mockReturnValueOnce([
+ { requestId: 'dispose-first', messageId: 'first' },
+ { requestId: 'dispose-second', messageId: 'second' },
+ ]);
+ await localRunner.disposeAllSessions();
+ await flushMicrotasks();
+ expect(mocks.rejectAllPending).toHaveBeenLastCalledWith('session_disposed', expect.any(Symbol));
+ expect(update).toHaveBeenNthCalledWith(1, 'first', card);
+ expect(update).toHaveBeenNthCalledWith(2, 'second', card);
+ expect(mocks.logger.warn).toHaveBeenCalledWith(expect.stringContaining('channel closing'));
+ stalled.resolve(undefined);
+ await flushMicrotasks();
+ });
+
+ it('finishes expiry before stopping the transport and allowing a reconnect', async () => {
+ const updating = deferred<void>();
+ let connected = false;
+ const events: string[] = [];
+ const update = vi.fn(async () => {
+ expect(connected).toBe(true);
+ events.push('expiry:start');
+ await updating.promise;
+ expect(connected).toBe(true);
+ events.push('expiry:end');
+ });
+ const localRunner = createTurnRunner({
+ ...fakeAdapter,
+ interactionExpiredNotice: 'expired',
+ output: { kind: 'rich-card', im: { ...mocks.feishuIm, updateInteractiveCard: update } as unknown as ChannelIM },
+ }, fakeRepo, fakeCards);
+ const lifecycle = createSerializedConnectionLifecycle({
+ startConnection: async () => { connected = true; events.push('connect'); },
+ beforeStopConnection: () => localRunner.disposeAllSessions(),
+ stopConnection: async () => { connected = false; events.push('disconnect'); },
+ onStartError: vi.fn(),
+ });
+ lifecycle.start();
+ await flushMicrotasks();
+ mocks.rejectAllPending.mockReturnValueOnce([{ requestId: 'order-expiry', messageId: 'old-card' }]);
+ const stopping = lifecycle.stop('logout');
+ lifecycle.start();
+ await waitForAssertion(() => expect(events).toEqual(['connect', 'expiry:start']));
+ updating.resolve(undefined);
+ await stopping;
+ await waitForAssertion(() => expect(events).toEqual(['connect', 'expiry:start', 'expiry:end', 'disconnect', 'connect']));
+ await lifecycle.stop();
+ });
+
+ it('skips an expiry still queued behind a patch when disposal times out', async () => {
+ vi.useFakeTimers();
+ const toggle = deferred<void>();
+ const previous = enqueueAskCardPatch('queued-expiry', () => toggle.promise);
+ const update = vi.fn(async () => undefined);
+ const localRunner = createTurnRunner({
+ ...fakeAdapter,
+ interactionExpiredNotice: 'expired',
+ output: { kind: 'rich-card', im: { ...mocks.feishuIm, updateInteractiveCard: update } as unknown as ChannelIM },
+ }, fakeRepo, fakeCards);
+ try {
+ mocks.rejectAllPending.mockReturnValueOnce([{ requestId: 'queued-expiry', messageId: 'old-card' }]);
+ let disposed = false;
+ const disposing = localRunner.disposeAllSessions().then(() => { disposed = true; });
+ await vi.advanceTimersByTimeAsync(999);
+ expect(disposed).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+ await disposing;
+ expect(disposed).toBe(true);
+ toggle.resolve(undefined);
+ await previous;
+ await flushMicrotasks();
+ expect(update).not.toHaveBeenCalled();
+ } finally {
+ toggle.resolve(undefined);
+ vi.useRealTimers();
+ }
+ });
+
+ it('retains optional expiry capability and distinct runner identities', async () => {
+ const first = createTurnRunner(fakeAdapter, fakeRepo, fakeCards);
+ const second = createTurnRunner(fakeAdapter, fakeRepo, fakeCards);
+ mocks.rejectAllPending.mockReturnValueOnce([{ requestId: 'no-expiry', messageId: 'legacy' }]);
+ await first.disposeAllSessions();
+ await second.disposeAllSessions();
+ await flushMicrotasks();
+ const calls = mocks.rejectAllPending.mock.calls;
+ expect(calls.at(-2)?.[1]).not.toBe(calls.at(-1)?.[1]);
+ expect(mocks.feishuIm.updateInteractiveCard).not.toHaveBeenCalled();
+ });
+
it('disposeAllSessions aborts and awaits an IM-owned in-flight turn', async () => {
const h = setupSession(async () => ({ accepted: true }));
const abortGate = deferred<void>();
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
index 6a3d19331a..1db3b6310a 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -41,7 +41,7 @@ const mocks = vi.hoisted(() => ({
noteSilentStopUserSend: vi.fn(),
noteSilentStopSessionReset: vi.fn(),
onSilentStopSettled: vi.fn(() => vi.fn()),
- rejectAllPending: vi.fn(),
+ rejectAllPending: vi.fn<(reason: string, owner?: symbol) => Array<{ requestId: string; messageId: string }>>(() => []),
registerPending: vi.fn(),
registerPendingExternal: vi.fn(),
checkDestructiveToolCall: vi.fn(() => ({ destructive: false })),
diff --git a/apps/desktop/src/main/im/shared/pendingInteractions.ts b/apps/desktop/src/main/im/shared/pendingInteractions.ts
index 898c50574f..72741c4ab8 100644
--- a/apps/desktop/src/main/im/shared/pendingInteractions.ts
+++ b/apps/desktop/src/main/im/shared/pendingInteractions.ts
@@ -19,6 +19,8 @@ import {
} from './interactionCardModel';
interface PendingEntry {
+ /** Runtime runner identity; never shared across channels or reconnect instances. */
+ owner?: symbol;
resolve: (decision: InteractionDecision) => void;
reject: (err: Error) => void;
/** Card messageId we sent — orchestrator can patch it after resolve. */
@@ -59,6 +61,7 @@ export function registerPending(
kind: InteractionDecision['kind'],
messageId: string,
extras?: {
+ owner?: symbol;
toolName?: string;
permissionCard?: { title: string; body: string };
askQuestions?: AskUserQuestionItem[];
@@ -89,6 +92,7 @@ export function registerPendingExternal(
resolve: (decision: InteractionDecision) => void,
reject: (err: Error) => void,
extras?: {
+ owner?: symbol;
toolName?: string;
permissionCard?: { title: string; body: string };
askQuestions?: AskUserQuestionItem[];
@@ -103,6 +107,7 @@ export function registerPendingExternal(
reject,
messageId,
kind,
+ owner: extras?.owner,
toolName: extras?.toolName,
permissionCard: extras?.permissionCard,
askQuestions: extras?.askQuestions,
@@ -149,11 +154,15 @@ export function cancelPending(requestId: string, reason: string): { messageId: s
}
/** Reject all pending interactions (used on session close / error). */
-export function rejectAllPending(reason: string): void {
- for (const [, entry] of pending) {
- entry.reject(new Error(reason));
- }
- pending.clear();
+export function rejectAllPending(
+ reason: string,
+ owner?: symbol,
+): Array<{ requestId: string; messageId: string }> {
+ const entries = [...pending].filter(([, entry]) => owner === undefined || entry.owner === owner);
+ // Remove the selected entries before callbacks can register another request.
+ for (const [requestId] of entries) pending.delete(requestId);
+ for (const [, entry] of entries) entry.reject(new Error(reason));
+ return entries.map(([requestId, entry]) => ({ requestId, messageId: entry.messageId }));
}
export function getPendingCount(): number {
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index f53b27c0ed..21eab687d6 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -562,6 +562,8 @@ export function createTurnRunner(
deps: ImTurnRunnerDeps = {},
): ImTurnRunner {
const { im, output, ui, channel } = adapter;
+ const pendingOwner = Symbol('im-runner-pending');
+ const cardExpirations = new Set<{ done: Promise<void>; cancel(): void }>();
const richIm = output.kind === 'rich-card' ? output.im : null;
function sendTextClaimingOpener(
@@ -1913,12 +1915,12 @@ export function createTurnRunner(
: { kind, behavior: 'deny', reason: err.message },
);
},
- req.kind === 'permission'
- ? {
- toolName: req.toolName,
- permissionCard: { title: spec.title ?? '', body: spec.body },
- }
- : askMultiExtras(req),
+ {
+ owner: pendingOwner,
+ ...(req.kind === 'permission'
+ ? { toolName: req.toolName, permissionCard: { title: spec.title ?? '', body: spec.body } }
+ : askMultiExtras(req)),
+ },
);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
@@ -2600,11 +2602,19 @@ export function createTurnRunner(
// 返回值是 router 的契约: true = 渠道侧已收口这次交互, router 不再自行 cancel。
// 丢掉它会让同一个 requestId 被取消两次(第二次落到 SDK 的默认拒绝路径)。
if (!cancelled) return false;
+ expireInteractionCard(requestId, cancelled.messageId);
+ return true;
+ }
+
+ function expireInteractionCard(requestId: string, messageId: string): void {
const notice = adapter.interactionExpiredNotice;
- if (!notice || !richIm) return true;
- const messageId = cancelled.messageId;
+ if (!notice || !richIm) return;
const im = richIm;
- void enqueueAskCardPatch(requestId, async () => {
+ let cancelled = false;
+ const done = enqueueAskCardPatch(requestId, async () => {
+ // A queued patch must not first reach a transport after logout timed out
+ // and a later account has reconnected the shared adapter.
+ if (cancelled) return;
try {
await im.updateInteractiveCard(messageId, cards.buildResolvedCard(notice));
} catch (err: unknown) {
@@ -2612,7 +2622,32 @@ export function createTurnRunner(
log.warn(`dropped interaction card cleanup failed (non-fatal): ${msg}`);
}
});
- return true;
+ const expiration = { done, cancel: () => { cancelled = true; } };
+ cardExpirations.add(expiration);
+ void done.then(() => cardExpirations.delete(expiration));
+ }
+
+ async function drainCardExpirations(): Promise<void> {
+ const pending = [...cardExpirations];
+ if (pending.length === 0) return;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ Promise.all(pending.map(({ done }) => done)),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(() => {
+ log.warn('interaction card cleanup timed out (non-fatal)');
+ resolve();
+ }, 1000);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ for (const expiration of pending) {
+ expiration.cancel();
+ cardExpirations.delete(expiration);
+ }
+ }
}
function settleTurnTerminal(turn: TurnState): void {
@@ -3385,12 +3420,12 @@ export function createTurnRunner(
// Stash toolName for permission requests so cardActionHandler can
// build permissionUpdates when the user picks 'allow:always'.
// permissionCard 留着收口时恢复原始正文(工具名 + 参数预览)。
- req.kind === 'permission'
- ? {
- toolName: req.toolName,
- permissionCard: { title: spec.title ?? '', body: spec.body },
- }
- : askMultiExtras(req),
+ {
+ owner: pendingOwner,
+ ...(req.kind === 'permission'
+ ? { toolName: req.toolName, permissionCard: { title: spec.title ?? '', body: spec.body } }
+ : askMultiExtras(req)),
+ },
);
return decision;
} catch (err) {
@@ -3539,8 +3574,10 @@ export function createTurnRunner(
// Denial reasons are classified by exact/prefix match. Keep this a stable
// system code so Auto-review fallback confirmations are not presented as
// a user click when logout / disconnect disposes the IM runner.
- rejectAllPending('session_disposed');
- return Promise.all(aborts).then(() => undefined);
+ for (const card of rejectAllPending('session_disposed', pendingOwner)) {
+ expireInteractionCard(card.requestId, card.messageId);
+ }
+ return Promise.all([...aborts, drainCardExpirations()]).then(() => undefined);
}
function getMakerSessionById(sessionId: string): MakerSession | null {