Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(im): 保留运行实例重建期间的排队消息 (#4522)
GaoWei Liu95b14e8a2739
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.tsindex 12272ebf9a..a937e54b7a 100644--- a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts@@ -703,7 +703,7 @@ describe('model:pick 持久化失败', () => {await pressModelPick(im, 'provider-b');- expect(closeSession).toHaveBeenCalledWith('sess-target');+ expect(closeSession).toHaveBeenCalledWith('sess-target', 'runtime-refresh');expect(live.setModel).not.toHaveBeenCalled();expect(mocks.setSessionProvider).toHaveBeenCalledWith('sess-target', 'provider-b');expect(im.updateInteractiveCard).toHaveBeenCalledWith(diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex d92cfa8189..e107dc7935 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -341,6 +341,7 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {function createMakerHarness(session: Session) {return {+ getSession: vi.fn(() => session),createSession: vi.fn(async () => session),on: vi.fn((listener: (event: MakerEvent) => void) => {makerEventListeners.push(listener);@@ -1210,7 +1211,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()}});- it('applies a deferred switch and sends the first queued IM message through the refreshed session', async () => {+ it.each(['agent-switch', 'runtime-refresh'] as const)('preserves queued IM input across a %s close during send', async (reason) => {const order: string[] = [];const turnPermissionPolicy: TurnPermissionPolicy = {origin: { kind: 'im', channel: 'wechat' },@@ -1257,7 +1258,7 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()type: 'session:closed',sessionId: 'feishu-session',session: oldSession.session,- reason: 'agent-switch',+ reason,});return releaseAgentSwitchLock;});@@ -1642,6 +1643,267 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()}});+ it.each([+ { reason: 'runtime-refresh', precedingRefresh: false },+ { reason: 'requested', precedingRefresh: false },+ { reason: 'unexpected', precedingRefresh: false },+ { reason: 'runtime-refresh', precedingRefresh: true },+ { reason: 'requested', precedingRefresh: true },+ { reason: 'unexpected', precedingRefresh: true },+ ] as const)(+ 'handles $reason outside switch acquisition with precedingRefresh=$precedingRefresh',+ async ({ reason, precedingRefresh }) => {+ vi.useFakeTimers();+ const oldSession = createSessionHarness(async () => ({ accepted: true }));+ const replacement = createSessionHarness(async () => ({ accepted: true }));+ oldSession.isTurnRunning.mockReturnValue(true);+ let live: Session | undefined = oldSession.session;+ const maker = {+ createSession: vi.fn(async () => oldSession.session),+ getSession: vi.fn(() => live),+ on: vi.fn((listener: (event: MakerEvent) => void) => {+ makerEventListeners.push(listener);+ return () => {+ makerEventListeners = makerEventListeners.filter((candidate) => candidate !== listener);+ };+ }),+ };+ mocks.getMaker.mockReturnValue(maker);+ const acquirePendingAgentSwitch = vi.fn(async () => vi.fn());+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {+ acquirePendingAgentSwitch,+ });+ const firstComplete = vi.fn();+ const secondComplete = vi.fn();+ try {+ for (const [index, onTurnComplete] of [firstComplete, secondComplete].entries()) {+ await localRunner.runAgentTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ userMessageId: `queued-${index}`, text: `message-${index}`, attachments: [],+ onTurnComplete,+ });+ }+ expect(acquirePendingAgentSwitch).not.toHaveBeenCalled();+ oldSession.isTurnRunning.mockReturnValue(false);+ const intermediate = createSessionHarness(async () => ({ accepted: true }));+ if (precedingRefresh) {+ live = undefined;+ emitMakerEvent({+ type: 'session:closed', sessionId: 'feishu-session',+ session: oldSession.session, reason: 'runtime-refresh',+ });+ live = intermediate.session;+ expect(localRunner.getMakerSessionById('feishu-session')).toBe(intermediate.session);+ }+ live = undefined;+ emitMakerEvent({+ type: 'session:closed', sessionId: 'feishu-session',+ session: precedingRefresh ? intermediate.session : oldSession.session, reason,+ });+ // Model-card effort/permission actions must not target the retired runtime.+ expect(localRunner.getMakerSessionById('feishu-session')).toBeNull();+ live = replacement.session;+ expect(localRunner.getMakerSessionById('feishu-session')).toBe(+ reason === 'runtime-refresh' ? replacement.session : null,+ );+ await vi.advanceTimersByTimeAsync(600);+ expect(oldSession.send).not.toHaveBeenCalled();+ expect(intermediate.send).not.toHaveBeenCalled();+ if (reason !== 'runtime-refresh') {+ expect(replacement.send).not.toHaveBeenCalled();+ expect(localRunner.getMakerSessionById('feishu-session')).toBeNull();+ expect(mocks.persistUserMessage).not.toHaveBeenCalled();+ expect(mocks.feishuIm.removeMessageReaction).toHaveBeenCalledTimes(2);+ return;+ }+ expect(replacement.send).toHaveBeenCalledTimes(1);+ expect(firstComplete).not.toHaveBeenCalled();+ expect(secondComplete).not.toHaveBeenCalled();+ expect(localRunner.getMakerSessionById('feishu-session')).toBe(replacement.session);+ // An old instance's late close cannot cancel the replacement or queued input.+ emitMakerEvent({+ type: 'session:closed', sessionId: 'feishu-session',+ session: oldSession.session, reason: 'unexpected',+ });+ replacement.emit({ type: 'done', data: {} });+ await vi.advanceTimersByTimeAsync(600);+ expect(replacement.send).toHaveBeenCalledTimes(2);+ expect(firstComplete).toHaveBeenCalledOnce();+ expect(secondComplete).not.toHaveBeenCalled();+ expect(replacement.send.mock.calls.map(([message]) => message)).toEqual([+ expect.objectContaining({ content: 'message-0' }),+ expect.objectContaining({ content: 'message-1' }),+ ]);+ replacement.emit({ type: 'done', data: {} });+ await vi.advanceTimersByTimeAsync(600);+ expect(secondComplete).toHaveBeenCalledOnce();+ } finally {+ localRunner.disposeAllSessions();+ vi.useRealTimers();+ }+ },+ );++ it.each([+ { operation: 'stop', queued: true },+ { operation: 'stop', queued: false },+ { operation: 'dispose', queued: true },+ { operation: 'dispose', queued: false },+ ] as const)(+ '$operation targets the current runtime after refresh with queued=$queued',+ async ({ operation, queued }) => {+ vi.useFakeTimers();+ const oldSession = createSessionHarness(async () => ({ accepted: true }));+ const replacement = createSessionHarness(async () => ({ accepted: true }));+ oldSession.isTurnRunning.mockReturnValue(queued);+ replacement.isTurnRunning.mockReturnValue(true);+ let live: Session | undefined = oldSession.session;+ mocks.getMaker.mockReturnValue({+ createSession: vi.fn(async () => oldSession.session),+ getSession: vi.fn(() => live),+ on: vi.fn((listener: (event: MakerEvent) => void) => {+ makerEventListeners.push(listener);+ return () => {+ makerEventListeners = makerEventListeners.filter((candidate) => candidate !== listener);+ };+ }),+ });+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {+ acquirePendingAgentSwitch: vi.fn(async () => vi.fn()),+ });+ try {+ await localRunner.runAgentTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ userMessageId: 'queued-control', text: 'queued input', attachments: [],+ });+ if (!queued) {+ oldSession.emit({ type: 'done', data: {} });+ await vi.advanceTimersByTimeAsync(600);+ oldSession.send.mockClear();+ }+ oldSession.isTurnRunning.mockReturnValue(false);+ live = undefined;+ emitMakerEvent({+ type: 'session:closed', sessionId: 'feishu-session',+ session: oldSession.session, reason: 'runtime-refresh',+ });+ live = replacement.session;+ if (operation === 'stop') {+ expect(await localRunner.stopActiveTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ })).toEqual({ stopped: true, droppedQueued: queued ? 1 : 0 });+ expect(replacement.abort).toHaveBeenCalledOnce();+ } else {+ await localRunner.disposeOneSession('feishu-session');+ expect(replacement.session.close).toHaveBeenCalledOnce();+ expect(localRunner.getMakerSessionById('feishu-session')).toBeNull();+ }+ expect(oldSession.abort).not.toHaveBeenCalled();+ expect(oldSession.session.close).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(600);+ expect(oldSession.send).not.toHaveBeenCalled();+ expect(replacement.send).not.toHaveBeenCalled();+ } finally {+ await localRunner.disposeAllSessions();+ vi.useRealTimers();+ }+ },+ );++ it.each(['rich-card', 'chunked-text', 'chunked-final-error'] as const)(+ 'cancels stopped input waiting for the send lock with %s output', async (outputKind) => {+ const previousOutput = fakeAdapter.output;+ const beginReply = vi.fn(async () => undefined);+ const commitFinal = vi.fn(async () => undefined);+ if (outputKind !== 'rich-card') {+ fakeAdapter.output = {+ kind: 'chunked-text', im: mocks.feishuIm as unknown as ChannelIM, beginReply, commitFinal,+ };+ if (outputKind === 'chunked-final-error') commitFinal.mockRejectedValueOnce(new Error('disconnected'));+ }+ const oldSession = createSessionHarness(async () => ({ accepted: true }));+ const replacement = createSessionHarness(async () => ({ accepted: true }));+ let live: Session | undefined = oldSession.session;+ const lockEntered = deferred<void>();+ const releaseRefresh = deferred<void>();+ const releaseLock = vi.fn();+ mocks.getMaker.mockReturnValue({+ createSession: vi.fn(async () => oldSession.session),+ getSession: vi.fn(() => live),+ on: vi.fn((listener: (event: MakerEvent) => void) => {+ makerEventListeners.push(listener);+ return () => {+ makerEventListeners = makerEventListeners.filter((candidate) => candidate !== listener);+ };+ }),+ });+ const acquirePendingAgentSwitch = vi.fn(async () => releaseLock);+ acquirePendingAgentSwitch.mockImplementationOnce(async () => {+ live = undefined;+ emitMakerEvent({+ type: 'session:closed', sessionId: 'feishu-session',+ session: oldSession.session, reason: 'runtime-refresh',+ });+ lockEntered.resolve(undefined);+ await releaseRefresh.promise;+ return releaseLock;+ });+ const localRunner = createTurnRunner(fakeAdapter, fakeRepo, fakeCards, {+ acquirePendingAgentSwitch,+ });+ const complete = vi.fn();+ try {+ const first = localRunner.runAgentTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ userMessageId: 'stop-before-send', text: 'cancel me', attachments: [],+ onTurnComplete: complete,+ });+ await lockEntered.promise;+ expect(await localRunner.stopActiveTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ })).toEqual({ stopped: true, droppedQueued: 0 });+ live = replacement.session;+ releaseRefresh.resolve(undefined);+ await first;+ expect(oldSession.send).not.toHaveBeenCalled();+ expect(replacement.send).not.toHaveBeenCalled();+ expect(mocks.persistUserMessage).not.toHaveBeenCalled();+ expect(complete).toHaveBeenCalledOnce();+ expect(releaseLock).toHaveBeenCalledOnce();+ if (outputKind !== 'rich-card') {+ expect(beginReply).toHaveBeenCalledOnce();+ expect(commitFinal).toHaveBeenCalledExactlyOnceWith({+ userId: 'ou_user', text: fakeAdapter.ui.agent.stopDone(0),+ terminal: 'aborted', threadTs: undefined,+ });+ } else {+ expect(commitFinal).not.toHaveBeenCalled();+ }+ await localRunner.runAgentTurn({+ botContextId: 'cli_test_bot', userId: 'ou_user',+ userMessageId: 'after-stop', text: 'fresh input', attachments: [],+ });+ expect(replacement.send).toHaveBeenCalledOnce();+ expect(replacement.send).toHaveBeenCalledWith(+ expect.objectContaining({ content: 'fresh input' }), expect.anything(),+ );+ if (outputKind !== 'rich-card') {+ expect(beginReply).toHaveBeenCalledTimes(2);+ expect(commitFinal.mock.invocationCallOrder[0]).toBeLessThan(beginReply.mock.invocationCallOrder[1]!);+ replacement.emit({ type: 'text', data: { text: 'fresh response', isFinal: true } });+ replacement.emit({ type: 'done', data: {} });+ await waitForAssertion(() => expect(commitFinal).toHaveBeenCalledTimes(2));+ expect(commitFinal).toHaveBeenLastCalledWith(expect.objectContaining({+ text: 'fresh response', terminal: 'done',+ }));+ }+ } finally {+ fakeAdapter.output = previousOutput;+ releaseRefresh.resolve(undefined);+ await localRunner.disposeAllSessions();+ }+ });+it('does not suppress a concurrent close of the replacement session', async () => {const oldSession = createSessionHarness(async () => ({ accepted: true }));const switchedSession = createSessionHarness(async () => ({ accepted: true }));diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.tsindex abedb798ed..6a3d19331a 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts@@ -274,6 +274,7 @@ beforeEach(() => {mocks.takePendingInteractionsForSession.mockReturnValue([]);// maker.createSession: 按 id 返回独立 harness(多 session 并行的关键)mocks.getMaker.mockReturnValue({+ getSession: vi.fn((id: string) => harnesses.get(id)?.session),on: vi.fn(() => () => undefined),createSession: vi.fn(async (args: { id?: string }) => {const id = args.id ?? 'anon';diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex bc7abc8db6..f53b27c0ed 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -612,6 +612,18 @@ export function createTurnRunner(subscribedMaker = maker;unsubscribeMakerEvents = maker.on((event) => {if (event.type !== 'session:closed') return;+ const state = sessionStates.get(event.sessionId);+ // A retired instance must not clear a replacement already wired to this task.+ if (+ state && state.makerSession !== event.session &&+ maker.getSession(event.sessionId) === state.makerSession+ ) return;+ // Runtime refresh preserves the task and its queued input, including refreshes+ // applied repeatedly before dispatch rebinds the cached runtime under the send lock.+ if (+ state && event.reason === 'runtime-refresh' &&+ deps.acquirePendingAgentSwitch+ ) return;const suppression = agentSwitchCloseSuppressed.get(event.sessionId);if (suppression?.expectedSession === event.session && event.reason === 'agent-switch') return;forgetClosedSession(event.sessionId, 'maker session closed');@@ -1125,6 +1137,29 @@ export function createTurnRunner(// resolveEffectiveTurnPolicy。不挂时走与 DM 轮次相同的无策略路径。const effectiveTurnPolicy = await resolveEffectiveTurnPolicy(item);+ // Stop can arrive while this turn waits for the switch/send lock, before+ // Maker owns it. Its abort cannot cancel that pre-dispatch input for us.+ if (item.turn.terminalKind === 'aborted') {+ const index = state.queue.indexOf(item.turn);+ if (index >= 0) state.queue.splice(index, 1);+ if (output.kind === 'chunked-text' && item.turn.chunkedReplyBegun) {+ try {+ await output.commitFinal({+ userId,+ text: ui.agent.stopDone(0),+ terminal: 'aborted',+ threadTs: item.turn.scopeKey,+ });+ } catch (err) {+ log.warn(`cancelled reply finalization failed: ${err instanceof Error ? err.message : String(err)}`);+ }+ }+ await completeTurnCallbackAfterAck(item.turn);+ settleTurnTerminal(item.turn);+ if (!finishDeferredDetachIfIdle(state)) armDispatchRetry(state, userId);+ return { kind: 'rejected', reason: 'aborted' };+ }+const sendResult = await state.makerSession.send(outgoingMessage as typeof item.userMessage, {planMode: false,// The channel adapter and routing state live in Main. A symbol-keyed@@ -3509,7 +3544,10 @@ export function createTurnRunner(}function getMakerSessionById(sessionId: string): MakerSession | null {- return sessionStates.get(sessionId)?.makerSession ?? null;+ // The queue can retain a retired instance until the next dispatch rebinds it.+ // Model/effort/permission actions must only operate on Maker's current runtime.+ if (!sessionStates.has(sessionId)) return null;+ return getMaker().getSession(sessionId) ?? null;}/**@@ -3574,6 +3612,7 @@ export function createTurnRunner(: await resolveExistingRouteTarget(botContextId, userId, scopeKey);const state = target ? sessionStates.get(target.row.id) : undefined;if (!state) return { stopped: false, droppedQueued: 0 };+ const current = getMaker().getSession(state.makerSession.id);if (args.notificationSessionId) {const matches = (turn: TurnState) => turn.userId === userId && turn.scopeKey === scopeKey;const removed = state.sendQueue.filter((item) => matches(item.turn));@@ -3586,11 +3625,11 @@ export function createTurnRunner(if (!active || !matches(active)) return { stopped: removed.length > 0, droppedQueued: removed.length };noteSilentStopSessionReset(state.makerSession.id);active.terminalKind = 'aborted';- await state.makerSession.abort();+ await current?.abort();return { stopped: true, droppedQueued: removed.length };}const running =- state.queue.length > 0 || state.sendQueue.length > 0 || state.makerSession.isTurnRunning();+ state.queue.length > 0 || state.sendQueue.length > 0 || current?.isTurnRunning();if (!running) return { stopped: false, droppedQueued: 0 };const droppedQueued = state.sendQueue.length;// 先清排队再 abort — abort 触发的 done/error 会走 maybeDispatchNextQueued,@@ -3602,7 +3641,7 @@ export function createTurnRunner(// 重置后守卫判 superseded → settle('skip') → 挂起 turn 经现有订阅按 done 收口。noteSilentStopSessionReset(state.makerSession.id);if (state.queue[0]) state.queue[0].terminalKind = 'aborted';- await state.makerSession.abort();+ await current?.abort();log.info(`!stop aborted turn for session=...${state.makerSession.id.slice(-8)} droppedQueued=${droppedQueued}`,);@@ -3621,7 +3660,7 @@ export function createTurnRunner(cleanupSessionState(state);settleDetachDrain(state, 'cancelled');try {- await state.makerSession.close();+ await getMaker().getSession(sessionId)?.close();} catch (err) {const msg = err instanceof Error ? err.message : String(err);log.warn(`disposeOneSession close failed (non-fatal): ${msg}`);diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.tsindex 1dcb7bee5e..332757d27a 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts@@ -407,7 +407,7 @@ describe('prepareLocalSessionCredentialModeSwitch', () => {expect(result).toEqual({ closedSessionIds: ['target-claude'] });expect(closeSession).toHaveBeenCalledTimes(1);- expect(closeSession).toHaveBeenCalledWith('target-claude');+ expect(closeSession).toHaveBeenCalledWith('target-claude', 'runtime-refresh');expect(sideEffect).not.toHaveBeenCalled();});@@ -489,7 +489,7 @@ describe('prepareLocalCodexCredentialModeSwitch', () => {expect(result).toEqual({ closedSessionIds: ['local-codex-1'] });expect(closeSession).toHaveBeenCalledTimes(1);- expect(closeSession).toHaveBeenCalledWith('local-codex-1');+ expect(closeSession).toHaveBeenCalledWith('local-codex-1', 'runtime-refresh');expect(sideEffect).not.toHaveBeenCalled();});diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.tsindex 0458bc8b5e..c46f9c6af1 100644--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts@@ -74,7 +74,7 @@ interface LocalAgentSession {interface LocalCredentialModeSwitchMaker {listActiveSessions: () => LocalAgentSession[];- closeSession: (sessionId: string) => Promise<void>;+ closeSession: (sessionId: string, reason?: 'runtime-refresh') => Promise<void>;}export interface PrepareLocalCodexCredentialModeSwitchInput {@@ -388,7 +388,7 @@ export async function prepareLocalSessionCredentialModeSwitch(await withRehydrateCloseSuppressed(session.id, async () => {throwIfCredentialSwitchAborted(input.signal);- await input.maker.closeSession(session.id);+ await input.maker.closeSession(session.id, 'runtime-refresh');});return { closedSessionIds: [session.id] };}@@ -423,7 +423,7 @@ export async function prepareLocalCodexCredentialModeSwitch(throwIfCredentialSwitchAborted(input.signal);await withRehydrateCloseSuppressed(session.id, async () => {throwIfCredentialSwitchAborted(input.signal);- await input.maker.closeSession(session.id);+ await input.maker.closeSession(session.id, 'runtime-refresh');});closedSessionIds.push(session.id);}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.tsindex fef6fe517a..9e2b96f885 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/pendingCredentialSwitch.test.ts@@ -105,7 +105,7 @@ describe('PendingCredentialSwitchService', () => {await h.service.onTurnSettled(sessionId);expect(h.service.has(sessionId)).toBe(false);- expect(h.closeSession).toHaveBeenCalledWith(sessionId);+ expect(h.closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(getSessionProvider(sessionId)).toBe('xd');expect(h.broadcastApplied).toHaveBeenCalledWith({sessionId,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.tsindex c1ff05f99e..18f92bcd69 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts@@ -234,7 +234,7 @@ describe('applyRuntimeSetModelChange', () => {});expect(requiresModelSwitchRebuild).not.toHaveBeenCalled();- expect(result.closeSession).toHaveBeenCalledWith(result.sessionId);+ expect(result.closeSession).toHaveBeenCalledWith(result.sessionId, 'runtime-refresh');expect(result.setModel).not.toHaveBeenCalled();});@@ -254,7 +254,7 @@ describe('applyRuntimeSetModelChange', () => {expect(requiresModelSwitchRebuild).toHaveBeenCalledWith('a-alt-model', {providerId: routeA.providerId,});- expect(result.closeSession).toHaveBeenCalledWith(result.sessionId);+ expect(result.closeSession).toHaveBeenCalledWith(result.sessionId, 'runtime-refresh');expect(result.setModel).not.toHaveBeenCalled();});@@ -290,7 +290,7 @@ describe('applyRuntimeSetModelChange', () => {nextModel: testCase.targetModel,});- expect(result.closeSession).toHaveBeenCalledWith(result.sessionId);+ expect(result.closeSession).toHaveBeenCalledWith(result.sessionId, 'runtime-refresh');expect(result.setModel).not.toHaveBeenCalled();expect(getSessionProvider(result.sessionId)).toBe(testCase.targetProvider);});@@ -534,7 +534,7 @@ describe('applyRuntimeSetModelChange', () => {providerId: 'xd',});- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('xd');});@@ -606,7 +606,7 @@ describe('applyRuntimeSetModelChange', () => {providerId: 'xai',});- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('xai');});@@ -715,7 +715,7 @@ describe('applyRuntimeSetModelChange', () => {expect(result).toEqual({ status: 'applied' });expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('xd');});@@ -751,7 +751,7 @@ describe('applyRuntimeSetModelChange', () => {});expect(result).toEqual({ status: 'applied' });- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('deepseek');});@@ -922,7 +922,7 @@ describe('applyRuntimeSetModelChange', () => {codexAuthInjection: 'oauth-bearer',});- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('xai');});@@ -958,7 +958,7 @@ describe('applyRuntimeSetModelChange', () => {expect(result).toEqual({ status: 'applied' });expect(closeSession).toHaveBeenCalledTimes(1);- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(getSessionProvider(sessionId)).toBe('xd');});@@ -1263,7 +1263,7 @@ describe('applyRuntimeSetModelChange', () => {wakeSessionInputQueue: vi.fn(),})).resolves.toEqual({ status: 'applied' });- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe(toProvider);},@@ -1358,7 +1358,7 @@ describe('applyRuntimeSetModelChange', () => {expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, { model: 'same-model', providerId: 'xd', forceSessionRebuild: true });busy = false;await expect(applyRuntimeSetModelChange(input)).resolves.toEqual({ status: 'applied' });- expect(closeSession).toHaveBeenCalledExactlyOnceWith(sessionId);+ expect(closeSession).toHaveBeenCalledExactlyOnceWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(getSessionProvider(sessionId)).toBe('xd');expect(cleanup).not.toHaveBeenCalled();@@ -1393,7 +1393,7 @@ describe('applyRuntimeSetModelChange', () => {clearPendingCredentialSwitch: vi.fn(),})).resolves.toEqual({ status: 'applied' });- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();});@@ -1428,7 +1428,7 @@ describe('applyRuntimeSetModelChange', () => {expect(requiresModelSwitchRebuild).toHaveBeenCalledWith('gpt-5.6-sol', {providerId: 'mygpt',});- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();});@@ -1663,7 +1663,7 @@ describe('context configuration refresh across live routes', () => {hasPendingSelection: () => false, withSessionLock: withSendToSessionLock,inferProviderId: () => 'xd', assertCurrent: () => {},});- expect(closeSession.mock.calls).toEqual([[sessions[0]!.id], [sessions[1]!.id]]);+ expect(closeSession.mock.calls).toEqual([[sessions[0]!.id, 'runtime-refresh'], [sessions[1]!.id, 'runtime-refresh']]);expect(registerPendingCredentialSwitch).toHaveBeenCalledExactlyOnceWith(sessions[0]!.id, {model: 'model', providerId: null, forceSessionRebuild: true,});@@ -1750,7 +1750,7 @@ describe('Claude native account switching', () => {expect(result.status).toBe('applied');}expect(getSessionProvider(sessionId)).toBe(to);- expect(closeSession).toHaveBeenLastCalledWith(sessionId);+ expect(closeSession).toHaveBeenLastCalledWith(sessionId, 'runtime-refresh');expect(setModel).not.toHaveBeenCalled();expect(cleanup).not.toHaveBeenCalled();} finally { pending.clear(sessionId); }diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.tsindex ab72af436c..2d19f3f330 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts@@ -250,7 +250,7 @@ describe.each(routeCases)('Codex route: $sourceModel → $targetModel', (route)expect(clearPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, { wake: false });expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, oldPending);- expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(closeSession).toHaveBeenCalledWith(sessionId, 'runtime-refresh');expect(relinkCodexThread).toHaveBeenCalledOnce();expect(getSessionProvider(sessionId)).toBe(sourceProvider);expect(wakeSessionInputQueue).not.toHaveBeenCalled();diff --git a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.tsindex 751b421dc4..3839269fac 100644--- a/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts+++ b/apps/desktop/src/main/maker-ipc/pendingCredentialSwitch.ts@@ -63,7 +63,7 @@ interface PendingSwitchSession {export interface PendingCredentialSwitchDeps {maker: {listActiveSessions: () => PendingSwitchSession[];- closeSession: (sessionId: string) => Promise<void>;+ closeSession: (sessionId: string, reason?: 'runtime-refresh') => Promise<void>;};isSessionInTurn?: (sessionId: string) => boolean;/** 生效后广播给 renderer(清「任务结束后生效」标记 / 会话内 toast)。 */@@ -181,7 +181,7 @@ export class PendingCredentialSwitchService {if (session) {try {if (session.remoteHostId && target.forceSessionRebuild) {- await withRehydrateCloseSuppressed(sessionId, () => this.deps.maker.closeSession(sessionId));+ await withRehydrateCloseSuppressed(sessionId, () => this.deps.maker.closeSession(sessionId, 'runtime-refresh'));} else {await prepareLocalSessionCredentialModeSwitch({maker: this.deps.maker,diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex bbf8866bdb..52307bb86f 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12407,7 +12407,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const live = getMaker().getSession(sessionId);// busy ≠ failed:外层已守卫 turn-running;这里若仍撞上,中止而不是升级成 rebuild。if (live?.isTurnRunning()) return 'busy';- if (live) await getMaker().closeSession(sessionId);+ if (live) await getMaker().closeSession(sessionId, 'runtime-refresh');const forked = await getMaker().forkSdkSession('codex', {sourceSdkSessionId: threadId,model: model ?? undefined,@@ -12500,7 +12500,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)findLatestRebuildMeta: findLatestContextRebuildMeta,getLiveSession: (sessionId) => maker.getSession(sessionId),rehydrateColdPiRuntimeForWindowVerification,- closeSession: (sessionId) => maker.closeSession(sessionId),+ closeSession: (sessionId) => maker.closeSession(sessionId, 'runtime-refresh'),drainPersistQueue,commitRebuild: async (sessionId, handoff, meta, signal) => {// Read projection metadata before the transaction: after a successfuldiff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.tsindex 1b8e4fcad8..279d756e60 100644--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts@@ -44,7 +44,7 @@ interface RuntimeSetModelActiveSession {export interface RuntimeSetModelMaker {getSession: (sessionId: string) => RuntimeSetModelSession | undefined;listActiveSessions: () => RuntimeSetModelActiveSession[];- closeSession: (sessionId: string) => Promise<void>;+ closeSession: (sessionId: string, reason?: 'runtime-refresh') => Promise<void>;}interface RuntimeSetModelLogger {@@ -302,7 +302,7 @@ export async function applyRuntimeSetModelChange(// A configuration reload targets this task's remote handle only. The// local-only credential helper deliberately does not close SSH handles.if (isSelfBusy()) throw new CredentialModeSwitchBusyError([sessionId]);- await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId, 'runtime-refresh'));} else {await prepareLocalSessionCredentialModeSwitch({maker,diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex 560dcc7169..12ea5d253b 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@ -702,7 +702,7 @@ describe('MakerScheduleRunner model selection', () => {expect(requiresModelSwitchRebuild).toHaveBeenCalledWith('gpt-5.6-sol', {providerId: 'mygpt',});- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0],);@@ -1368,7 +1368,7 @@ describe('MakerScheduleRunner model selection', () => {}),);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0],);@@ -1470,7 +1470,7 @@ describe('MakerScheduleRunner model selection', () => {}),);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0],);@@ -1561,7 +1561,7 @@ describe('MakerScheduleRunner model selection', () => {);expect(harness.closeSession).toHaveBeenCalledTimes(1);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({ providerId: routeB!.providerId, model: 'shared-model' }),);@@ -1599,7 +1599,7 @@ describe('MakerScheduleRunner model selection', () => {}),);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.createSession).toHaveBeenCalledWith(expect.objectContaining({ providerId: routeA.providerId, model: 'chat-model' }),);@@ -1646,7 +1646,7 @@ describe('MakerScheduleRunner model selection', () => {);expect(harness.closeSession).toHaveBeenCalledTimes(1);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.closeSession).not.toHaveBeenCalledWith('unrelated-busy-codex');expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0],@@ -1718,7 +1718,7 @@ describe('MakerScheduleRunner model selection', () => {}),);- expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session');+ expect(harness.closeSession).toHaveBeenCalledWith('scheduler-session', 'runtime-refresh');expect(harness.closeSession.mock.invocationCallOrder[0]).toBeLessThan(harness.createSession.mock.invocationCallOrder[0],);