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(codex): 修复 MCP 刷新与任务启动并发导致工具断连 (#4658)

Dash53aa8aa0b8f9
diff --git a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
index 72c567e73c..f45ac71bf1 100644
--- a/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/computerUsePluginIpc.test.ts
@@ -10,8 +10,10 @@ describe('computer use plugin IPC invariants', () => {
await expect(
refreshCodexMcpEnvironment({
- restartCodex: vi.fn(async () => {
+ restartCodex: vi.fn(async (refresh) => {
calls.push('restart-codex');
+ await refresh();
+ calls.push('release-startups');
}),
shutdownCodexEnvironment: vi.fn(async () => {
calls.push('shutdown-bridge');
@@ -19,7 +21,7 @@ describe('computer use plugin IPC invariants', () => {
}),
).resolves.toEqual({ codexMcpRefreshed: true });
- expect(calls).toEqual(['restart-codex', 'shutdown-bridge']);
+ expect(calls).toEqual(['restart-codex', 'shutdown-bridge', 'release-startups']);
});
it('keeps the existing bridge alive and reports deferred when Codex is busy', async () => {
@@ -48,7 +50,7 @@ describe('computer use plugin IPC invariants', () => {
await expect(
refreshCodexMcpEnvironment({
- restartCodex: vi.fn(async () => undefined),
+ restartCodex: vi.fn(async (refresh) => refresh()),
shutdownCodexEnvironment: vi.fn(async () => {
throw new Error('bridge shutdown failed');
}),
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index d215746e80..a7ec8979f0 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -312,7 +312,7 @@ import {
} from './rsb-browser-bridge/native-popup-surfaces.js';
import { disposeAndroidAdb } from './mcp-integrations/android.js';
import { shutdownCodexEnvironment } from './mcp-integrations/codexEnvironment.js';
-import { shutdownPiEnvironment } from './mcp-integrations/piEnvironment.js';
+import { invalidatePiEnvironment, shutdownPiEnvironment } from './mcp-integrations/piEnvironment.js';
import { fetchRemoteMediaImageBytes } from './device-link/remoteMediaProtocol';
import * as imageCacheStore from './imageCacheStore';
import {
@@ -726,6 +726,7 @@ import {
anySessionInTurn,
applyCodexSpawnConfigChangeWithRestart,
clearDeferredCodexRestartForOwnerBoundary,
+ scheduleDeferredCodexRestart,
clearWorkingDirectoryRecoveryForOwnerBoundary,
collectAgentInputQueueScanTexts,
createAutomationUserTurnGitBaselineHooks,
@@ -4953,7 +4954,12 @@ const registerIpcHandlers = () => {
});
// 智能通讯录 IPC —— 设置开关 + 数据 CRUD(设置页管理 UI 通道), 提前注册。
- registerContactsIpc();
+ registerContactsIpc({
+ restartCodexAfterAuthModeChange,
+ shutdownCodexEnvironment,
+ scheduleDeferredCodexRestart,
+ invalidatePiEnvironment,
+ });
// 聊天嵌入开关 IPC —— 与 compat-mode 同理提前注册:
// renderer 启动 bootstrap 同步 localStorage 镜像, 远早于 splash 完成。
diff --git a/apps/desktop/src/main/hook-control/ipc.ts b/apps/desktop/src/main/hook-control/ipc.ts
index 1e6dbacdc4..bcdf641b8b 100644
--- a/apps/desktop/src/main/hook-control/ipc.ts
+++ b/apps/desktop/src/main/hook-control/ipc.ts
@@ -194,8 +194,7 @@ async function drainCodexMcpRefreshForSlackAvailability(): Promise<void> {
while (codexMcpRefreshPending) {
codexMcpRefreshPending = false;
try {
- await restartCodexAfterAuthModeChange();
- await shutdownCodexEnvironment();
+ await restartCodexAfterAuthModeChange(shutdownCodexEnvironment);
log.info('Codex MCP environment refreshed after Slack provider availability changed', {
enabled: latestSlackToolProviderEnabled,
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
index d5c1b085cf..1435a678ff 100644
--- a/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/accountProviderModelRefresh.test.ts
@@ -20,8 +20,9 @@ describe('resetAccountProviderRuntimes', () => {
let allow = true;
await resetAccountProviderRuntimes(
{
- restartCodex: async () => {
+ restartCodex: async (refresh) => {
allow = false;
+ expect(await refresh()).toBe(false);
},
shutdownCodexEnvironment,
log: { warn: vi.fn() },
@@ -37,8 +38,9 @@ describe('resetAccountProviderRuntimes', () => {
let boundaryPending = false;
await resetAccountProviderRuntimes(
{
- restartCodex: async () => {
+ restartCodex: async (refresh) => {
boundaryPending = true;
+ await refresh();
},
shutdownCodexEnvironment,
log: { warn: vi.fn() },
@@ -75,8 +77,9 @@ describe('refreshProviderModelsAfterAccountReady', () => {
const backgroundRefresh = deferred();
const events: string[] = [];
const operation = refreshProviderModelsAfterAccountReady({
- restartCodex: async () => {
+ restartCodex: async (refresh) => {
events.push('restart');
+ await refresh();
},
shutdownCodexEnvironment: async () => {
events.push('shutdown');
@@ -145,7 +148,7 @@ describe('refreshProviderModelsAfterAccountReady', () => {
const warn = vi.fn();
await expect(
refreshProviderModelsAfterAccountReady({
- restartCodex: vi.fn(async () => {}),
+ restartCodex: vi.fn(async (refresh) => { await refresh(); }),
shutdownCodexEnvironment: vi.fn(async () => {}),
loadXaiLkg: vi.fn(async () => false),
refreshProviderModels: async () => {
@@ -167,7 +170,7 @@ describe('refreshProviderModelsAfterAccountReady', () => {
const releaseLkg = deferred();
const events: string[] = [];
const operation = refreshProviderModelsAfterAccountReady({
- restartCodex: async () => {},
+ restartCodex: async (refresh) => { await refresh(); },
shutdownCodexEnvironment: async () => {},
loadXaiLkg: async () => {
events.push('lkg:start');
diff --git a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
index 366d80f3ff..ba2fb56837 100644
--- a/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
+++ b/apps/desktop/src/main/maker-host/account-provider-model-refresh.ts
@@ -8,7 +8,7 @@ interface AccountProviderModelRefreshLogger {
}
export interface AccountProviderModelRefreshDeps {
- restartCodex(): Promise<void>;
+ restartCodex(refreshEnvironment: () => Promise<void | boolean>): Promise<void>;
shutdownCodexEnvironment(): Promise<void>;
loadXaiLkg(): Promise<boolean>;
refreshProviderModels(
@@ -35,21 +35,13 @@ export async function resetAccountProviderRuntimes(
shouldContinue: () => boolean = () => true,
): Promise<void> {
if (!shouldContinue()) return;
- let codexRestarted = false;
try {
- await deps.restartCodex();
- codexRestarted = true;
- } catch (error) {
- deps.log.warn('restartCodexAfterAuthModeChange on account switch failed', {
- error: error instanceof Error ? error.message : String(error),
+ await deps.restartCodex(async () => {
+ if (!shouldContinue()) return false;
+ await deps.shutdownCodexEnvironment();
});
- }
-
- if (!shouldContinue() || !codexRestarted) return;
- try {
- await deps.shutdownCodexEnvironment();
} catch (error) {
- deps.log.warn('shutdownCodexEnvironment on account switch failed', {
+ deps.log.warn('restartCodexAfterAuthModeChange on account switch failed', {
error: error instanceof Error ? error.message : String(error),
});
}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index db2fb9df0c..3e9676630f 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -341,7 +341,7 @@ import {
getSessionProvider,
hydrateSessionProvider,
} from './session-provider-store.js';
-import { prepareLocalCodexCredentialModeSwitch } from './codex-credential-switch.js';
+import { CodexCredentialModeSwitchBusyError, prepareLocalCodexCredentialModeSwitch } from './codex-credential-switch.js';
import { createDesktopOrcaTeamStoreAdapter } from './orcaTeamStoreAdapter.js';
import { broadcastOrcaWorkerChanged } from './orcaWorkerBroadcast.js';
import {
@@ -2921,12 +2921,15 @@ export async function waitForInitialCustomMcpRefresh(): Promise<void> {
*
* null-safe: getMaker() 还没构造过 codexAgent 时直接 no-op (此时也没进程要收)。
*/
-export async function prepareCodexForAuthModeChange(): Promise<void> {
+export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: boolean } = {}): Promise<void> {
if (_codexCredentialChangeGuard) {
throw new Error('Codex credential mode change is already in progress');
}
const guard = _codexAgent
- ? await _codexAgent.beginLocalHostCredentialChange('Codex desktop auth mode changed')
+ ? await _codexAgent.beginLocalHostCredentialChange('Codex desktop auth mode changed', {
+ ...options,
+ busyError: () => new CodexCredentialModeSwitchBusyError([]),
+ })
: null;
let prepared = false;
// 软重启存活的本地 codex 会话。busy session 直接 fail closed,调用方据此避免先改持久化状态。
@@ -2949,6 +2952,9 @@ export async function prepareCodexForAuthModeChange(): Promise<void> {
}
}
guard?.assertIdle();
+ // MCP invalidation can run before finalize (settings applyRuntime). Keep
+ // the reservation held, but retire every old bridge consumer first.
+ if (options.allLocalHosts) await guard?.retireActiveHost();
_codexCredentialChangeGuard = guard;
prepared = true;
} finally {
@@ -2990,12 +2996,26 @@ export function cancelCodexAuthModeChange(): void {
guard?.release();
}
-export async function finalizeCodexAfterAuthModeChange(): Promise<void> {
+export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvironment?: boolean } = {}): Promise<void> {
// 只 dispose 本地 app-server, 让下一次本地 send 按新模式重新 spawn。
// 远端 Codex host 使用远端 daemon / 远端用户配置,不能被本地 key / OAuth 变化误关。
const guard = _codexCredentialChangeGuard;
- _codexCredentialChangeGuard = null;
const agent = _codexAgent;
+ try {
+ if (options.prepareMcpEnvironment && _mcpProviders.codex) {
+ // Bridge preparation does not acquire a host; model backfill below does.
+ await getCodexExtraSpawnConfig({ mcpProviders: _mcpProviders.codex, logger: desktopMakerLogger });
+ }
+ } catch (error) {
+ if (_codexCredentialChangeGuard === guard) _codexCredentialChangeGuard = null;
+ guard?.release();
+ throw error;
+ }
+ if (_codexCredentialChangeGuard !== guard || _codexAgent !== agent) {
+ guard?.release();
+ return;
+ }
+ _codexCredentialChangeGuard = null;
if (guard || agent) {
try {
if (guard) {
@@ -3028,9 +3048,20 @@ export async function finalizeCodexAfterAuthModeChange(): Promise<void> {
await broadcastCodexAuthStateChanged();
}
-export async function restartCodexAfterAuthModeChange(): Promise<void> {
- await prepareCodexForAuthModeChange();
- await finalizeCodexAfterAuthModeChange();
+export async function restartCodexAfterAuthModeChange(
+ refreshEnvironment?: () => Promise<void | boolean>,
+): Promise<void> {
+ await prepareCodexForAuthModeChange({ allLocalHosts: !!refreshEnvironment });
+ const ownedGuard = _codexCredentialChangeGuard;
+ try {
+ if (refreshEnvironment) {
+ if (await refreshEnvironment() === false) return;
+ }
+ if (_codexCredentialChangeGuard !== ownedGuard) return;
+ await finalizeCodexAfterAuthModeChange({ prepareMcpEnvironment: !!refreshEnvironment });
+ } finally {
+ if (_codexCredentialChangeGuard === ownedGuard) cancelCodexAuthModeChange();
+ }
}
/**
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contactsIpc.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contactsIpc.test.ts
index f12e8a6596..28f2e3b03d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contactsIpc.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contactsIpc.test.ts
@@ -14,7 +14,7 @@ import { MakerContactsManager } from '@cindy/maker-core';
// handler 工厂本身不用它们, mock 空壳即可。
vi.mock('electron', () => ({
app: { getPath: () => '/tmp/unused', on: () => undefined },
- ipcMain: { handle: () => undefined },
+ ipcMain: { handle: vi.fn() },
BrowserWindow: { getAllWindows: () => [] },
}));
@@ -25,9 +25,27 @@ vi.mock('../../contacts-sync/driver.js', () => ({
setContactsDeviceSyncEnabled: vi.fn(),
}));
-import { createContactsIpcHandlers } from '../contacts-ipc.js';
+vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn() }));
+vi.mock('../../maker-host/contacts-settings-store.js', () => ({
+ readContactsSettingsState: () => ({ value: { enabled: false }, isCustomized: false }),
+ writeContactsEnabled: vi.fn(),
+}));
+
+import { ipcMain } from 'electron';
+import * as appSessionState from '../../appSessionState.js';
+import { writeContactsEnabled } from '../../maker-host/contacts-settings-store.js';
+import { createContactsIpcHandlers, registerContactsIpc } from '../contacts-ipc.js';
import { MAKER_INVOKE } from '../channels.js';
+const runtime = {
+ restartCodexAfterAuthModeChange: vi.fn<(refresh: () => Promise<void>) => Promise<void>>(
+ async () => { throw new Error('control RPC busy'); },
+ ),
+ shutdownCodexEnvironment: vi.fn(async () => {}),
+ scheduleDeferredCodexRestart: vi.fn(),
+ invalidatePiEnvironment: vi.fn(),
+};
+
function noopLogger() {
const noop = () => {};
const l = {
@@ -71,6 +89,8 @@ describe('contacts-ipc handlers', () => {
});
afterEach(() => {
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
manager.dispose();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -87,6 +107,103 @@ describe('contacts-ipc handlers', () => {
);
});
+ it('production wiring retains the bridge and schedules idle retry after a persisted toggle meets busy RPC', async () => {
+ registerContactsIpc(runtime);
+ const handler = vi.mocked(ipcMain.handle).mock.calls.find(
+ ([channel]) => channel === MAKER_INVOKE.CONTACTS_SETTINGS_SET,
+ )![1];
+ await expect(handler({} as Electron.IpcMainInvokeEvent, true)).resolves.toEqual({
+ enabled: true, codexMcpRefreshed: false,
+ });
+ expect(writeContactsEnabled).toHaveBeenCalledWith(true);
+ expect(runtime.shutdownCodexEnvironment).not.toHaveBeenCalled();
+ expect(runtime.scheduleDeferredCodexRestart).toHaveBeenCalledWith('Contacts MCP configuration changed');
+ expect(runtime.invalidatePiEnvironment).toHaveBeenCalledTimes(1);
+ });
+
+ it('invalidates Pi after persistence and refreshes the Codex bridge under its guard', async () => {
+ const order: string[] = [];
+ runtime.restartCodexAfterAuthModeChange.mockImplementationOnce(async (refresh) => {
+ order.push('guard');
+ await refresh();
+ order.push('release');
+ });
+ runtime.shutdownCodexEnvironment.mockImplementationOnce(async () => { order.push('bridge'); });
+ runtime.invalidatePiEnvironment.mockImplementationOnce(() => {
+ expect(writeContactsEnabled).toHaveBeenCalledWith(true);
+ order.push('pi');
+ });
+ registerContactsIpc(runtime);
+ const handler = vi.mocked(ipcMain.handle).mock.calls.find(
+ ([channel]) => channel === MAKER_INVOKE.CONTACTS_SETTINGS_SET,
+ )![1];
+ await expect(handler({} as Electron.IpcMainInvokeEvent, true)).resolves.toEqual({
+ enabled: true, codexMcpRefreshed: true,
+ });
+ expect(order).toEqual(['pi', 'guard', 'bridge', 'release']);
+ expect(runtime.scheduleDeferredCodexRestart).not.toHaveBeenCalled();
+ });
+
+ it.each(['resolve', 'reject'] as const)('invalidates Pi without waiting for a Codex restart to %s', async (outcome) => {
+ let settle!: () => void;
+ const restart = new Promise<void>((resolve, reject) => {
+ settle = outcome === 'resolve' ? resolve : () => reject(new Error('bridge failed'));
+ });
+ runtime.restartCodexAfterAuthModeChange.mockReturnValueOnce(restart);
+ registerContactsIpc(runtime);
+ const handler = vi.mocked(ipcMain.handle).mock.calls.find(
+ ([channel]) => channel === MAKER_INVOKE.CONTACTS_SETTINGS_SET,
+ )![1];
+ const result = handler({} as Electron.IpcMainInvokeEvent, true);
+ await vi.waitFor(() => expect(runtime.restartCodexAfterAuthModeChange).toHaveBeenCalledTimes(1));
+ try {
+ expect(runtime.invalidatePiEnvironment).toHaveBeenCalledTimes(1);
+ expect(runtime.scheduleDeferredCodexRestart).not.toHaveBeenCalled();
+ } finally {
+ settle();
+ await result;
+ }
+ expect(await result).toEqual({ enabled: true, codexMcpRefreshed: outcome === 'resolve' });
+ expect(runtime.invalidatePiEnvironment).toHaveBeenCalledTimes(1);
+ expect(runtime.scheduleDeferredCodexRestart).toHaveBeenCalledTimes(outcome === 'reject' ? 1 : 0);
+ });
+
+ it.each(['pending', 'changed'] as const)('does not re-register a late refresh after owner boundary is %s', async (boundary) => {
+ const scope = vi.spyOn(appSessionState, 'activeOwnerScopeKey').mockReturnValue('owner-a');
+ const pending = vi.spyOn(appSessionState, 'isAppSessionBoundaryPending').mockReturnValue(false);
+ const piScopes: string[] = [];
+ runtime.invalidatePiEnvironment.mockImplementationOnce(() => {
+ piScopes.push(appSessionState.activeOwnerScopeKey());
+ });
+ runtime.restartCodexAfterAuthModeChange.mockImplementationOnce(async () => {
+ if (boundary === 'pending') pending.mockReturnValue(true);
+ else scope.mockReturnValue('owner-b');
+ throw new Error('old owner refresh failed');
+ });
+ registerContactsIpc(runtime);
+ const handler = vi.mocked(ipcMain.handle).mock.calls.find(
+ ([channel]) => channel === MAKER_INVOKE.CONTACTS_SETTINGS_SET,
+ )![1];
+ await expect(handler({} as Electron.IpcMainInvokeEvent, true)).resolves.toEqual({
+ enabled: true, codexMcpRefreshed: false,
+ });
+ expect(runtime.scheduleDeferredCodexRestart).not.toHaveBeenCalled();
+ expect(runtime.invalidatePiEnvironment).toHaveBeenCalledTimes(1);
+ expect(piScopes).toEqual(['owner-a']);
+ });
+
+ it('does not invalidate either runtime when persisting the toggle fails', async () => {
+ vi.mocked(writeContactsEnabled).mockImplementationOnce(() => { throw new Error('write failed'); });
+ registerContactsIpc(runtime);
+ const handler = vi.mocked(ipcMain.handle).mock.calls.find(
+ ([channel]) => channel === MAKER_INVOKE.CONTACTS_SETTINGS_SET,
+ )![1];
+ await expect(handler({} as Electron.IpcMainInvokeEvent, true)).rejects.toThrow('write failed');
+ expect(runtime.invalidatePiEnvironment).not.toHaveBeenCalled();
+ expect(runtime.restartCodexAfterAuthModeChange).not.toHaveBeenCalled();
+ expect(runtime.scheduleDeferredCodexRestart).not.toHaveBeenCalled();
+ });
+
it('开关落盘失败按 [CODE] 协议上抛, 不漏裸 Error(规则 13)', async () => {
handlers = createContactsIpcHandlers({
getManager: () => manager,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
index 3651ae2742..7300821990 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/deferredCodexRestart.test.ts
@@ -30,7 +30,9 @@ describe('DeferredCodexRestartService', () => {
}) {
const restart = overrides?.restart ?? vi.fn(async () => {});
const service = new DeferredCodexRestartService({
- restart,
+ restart: async (applyRuntime) => {
+ if (await applyRuntime()) await restart();
+ },
hasBusyLocalCodexSession: overrides?.hasBusyLocalCodexSession ?? (() => false),
listLocalCodexSessionIds: overrides?.listLocalCodexSessionIds ?? (() => []),
onApplied: overrides?.onApplied,
@@ -58,6 +60,29 @@ describe('DeferredCodexRestartService', () => {
expect(restart).toHaveBeenCalledTimes(1);
});
+ it('preserves pending bridge work when a concurrent startup prevents guarded preparation', async () => {
+ const applyRuntime = vi.fn(async () => {});
+ let starting = true;
+ const service = new DeferredCodexRestartService({
+ restart: async (apply) => {
+ if (starting) throw new CodexCredentialModeSwitchBusyError(['starting-account']);
+ await apply();
+ },
+ hasBusyLocalCodexSession: () => false,
+ listLocalCodexSessionIds: () => [],
+ logger,
+ });
+ service.schedule('bridge-refresh', applyRuntime);
+ await service.flushBeforeLocalCodexSessionStart();
+ expect(applyRuntime).not.toHaveBeenCalled();
+ expect(service.isPending()).toBe(true);
+ starting = false;
+ await service.flushBeforeLocalCodexSessionStart();
+ expect(applyRuntime).toHaveBeenCalledOnce();
+ expect(service.isPending()).toBe(false);
+ service.clear();
+ });
+
it('无 pending 时 settle 不触发重启', async () => {
const restart = vi.fn(async () => {});
const { service } = createService({ restart });
@@ -336,7 +361,7 @@ describe('DeferredCodexRestartService', () => {
expect(service.isPending()).toBe(true);
});
- it('旧 runtime await 期间新 schedule: 循环接着应用新闭包, 不被旧闭包收口误清', async () => {
+ it.each(['runtime', 'mcp'] as const)('consumes %s work arriving before the bridge snapshot in the same restart', async (kind) => {
const order: string[] = [];
let resolveFirst: () => void = () => {};
const restart = vi.fn(async () => {
@@ -354,20 +379,24 @@ describe('DeferredCodexRestartService', () => {
service.onSessionSettled();
await Promise.resolve();
// 旧 runtime 还挂着时用户再次变更(busy 路径)覆盖登记
- service.schedule('memory-change', async () => {
+ service.schedule('settings-change', kind === 'mcp' ? undefined : async () => {
order.push('second');
});
resolveFirst();
await vi.runOnlyPendingTimersAsync();
- expect(order).toEqual(['first:start', 'second', 'restart']);
+ expect(order).toEqual(kind === 'mcp' ? ['first:start', 'restart'] : ['first:start', 'second', 'restart']);
expect(service.isPending()).toBe(false);
});
- it('restart await 期间新 schedule: 本轮不收口, 下一边界应用新 runtime 后再重启', async () => {
+ it.each(['runtime', 'mcp', 'mixed'] as const)('retains %s changes made after the active restart snapshots config', async (kind) => {
const runtimes: string[] = [];
+ let persistedRevision = 1;
+ const snapshots: number[] = [];
+ const onApplied = vi.fn();
let resolveRestart: () => void = () => {};
let restartCalls = 0;
const restart = vi.fn(() => {
+ snapshots.push(persistedRevision);
restartCalls += 1;
if (restartCalls === 1) {
return new Promise<void>((resolve) => {
@@ -376,7 +405,7 @@ describe('DeferredCodexRestartService', () => {
}
return Promise.resolve();
});
- const { service } = createService({ restart });
+ const { service } = createService({ restart, onApplied });
service.schedule('memory-change', async () => {
runtimes.push('first');
});
@@ -384,23 +413,69 @@ describe('DeferredCodexRestartService', () => {
await Promise.resolve();
await Promise.resolve();
// 第一次 restart 还挂着时又来一次变更登记
- service.schedule('memory-change', async () => {
- runtimes.push('second');
- });
+ if (kind !== 'mcp') {
+ service.schedule('memory-change', async () => {
+ runtimes.push('second');
+ });
+ }
+ persistedRevision = 2;
+ if (kind !== 'runtime') service.schedule('custom-mcp-change');
+ persistedRevision = 3;
+ if (kind !== 'runtime') service.schedule('contacts-change');
resolveRestart();
await Promise.resolve();
await Promise.resolve();
// 本轮不收口:pending 保持, second 尚未应用
expect(service.isPending()).toBe(true);
expect(runtimes).toEqual(['first']);
+ expect(snapshots).toEqual([1]);
+ expect(onApplied).not.toHaveBeenCalled();
service.onSessionSettled();
await vi.runOnlyPendingTimersAsync();
- expect(runtimes).toEqual(['first', 'second']);
+ expect(runtimes).toEqual(kind === 'mcp' ? ['first'] : ['first', 'second']);
+ expect(snapshots).toEqual([1, 3]);
+ expect(onApplied).toHaveBeenCalledOnce();
expect(restart).toHaveBeenCalledTimes(2);
expect(service.isPending()).toBe(false);
});
+ it('retains the pre-close snapshot if an immediate takeover also fails', async () => {
+ let liveIds = ['closed-by-immediate-prepare'];
+ const onApplied = vi.fn();
+ const { service } = createService({ listLocalCodexSessionIds: () => liveIds, onApplied });
+ service.schedule('memory-change');
+ expect(service.listGatedSessionIds()).toEqual(liveIds);
+ liveIds = [];
+ service.schedule('subagent-spawn-config-change');
+ await service.flushBeforeLocalCodexSessionStart();
+ expect(onApplied).toHaveBeenCalledExactlyOnceWith(['closed-by-immediate-prepare']);
+ });
+
+ it('retains closed IDs for immediate takeover but clears them across owner changes', async () => {
+ let liveIds = ['old-owner'];
+ let fail = true;
+ const onApplied = vi.fn();
+ const { service } = createService({
+ listLocalCodexSessionIds: () => liveIds,
+ onApplied,
+ restart: async () => {
+ liveIds = [];
+ if (fail) throw new CodexCredentialModeSwitchBusyError([]);
+ },
+ });
+ service.schedule('memory-change');
+ await service.flushBeforeLocalCodexSessionStart();
+ expect(service.listGatedSessionIds()).toEqual(['old-owner']);
+ service.clear();
+ expect(service.listGatedSessionIds()).toEqual([]);
+ liveIds = ['new-owner'];
+ fail = false;
+ service.schedule('memory-change');
+ await service.flushBeforeLocalCodexSessionStart();
+ expect(onApplied).toHaveBeenCalledExactlyOnceWith(['new-owner']);
+ });
+
it('listGatedSessionIds: pending 时返回 live 会话名单, 无 pending / deps 抛错时为空', () => {
const { service } = createService({
listLocalCodexSessionIds: () => ['s1', 's2'],
@@ -431,6 +506,34 @@ describe('runMemoryChangeWithCodexRestart', () => {
};
}
+ it.each(['memory-change', 'subagent-spawn-config-change'])(
+ 'defers %s for a real auxiliary-host lease and applies after it settles', async (reason) => {
+ const { CodexAgent } = await import('../../../../../../packages/maker-core/src/agents/codex/index.js');
+ const agent = new CodexAgent({ auth: {}, runtimeConfig: {}, binaryPath: process.execPath, logger } as any);
+ const release = (agent as any).acquireHostSessionBindingLease('local-control:oauth-bearer');
+ let guard: Awaited<ReturnType<InstanceType<typeof CodexAgent>['beginLocalHostCredentialChange']>> | undefined;
+ const deps = createDeps();
+ deps.prepare.mockImplementation(async () => {
+ guard = await agent.beginLocalHostCredentialChange('settings refresh', {
+ allLocalHosts: true,
+ busyError: () => new CodexCredentialModeSwitchBusyError([]),
+ });
+ try { guard.assertIdle(); } catch (error) { guard.release(); throw error; }
+ });
+ deps.finalize.mockImplementation(async () => { await guard?.finalize(); });
+ const persist = vi.fn(async () => ({ value: true }));
+ const applyRuntime = reason === 'memory-change' ? vi.fn(async () => {}) : undefined;
+ const parts = { persist, applyRuntime, reason };
+ await expect(runMemoryChangeWithCodexRestart(deps, parts)).resolves.toEqual({ value: true, codexRestartDeferred: true });
+ expect(persist).toHaveBeenCalledOnce();
+ if (applyRuntime) expect(applyRuntime).not.toHaveBeenCalled();
+ expect(deps.scheduleDeferredRestart).toHaveBeenCalledWith(reason, applyRuntime);
+ release();
+ await expect(runMemoryChangeWithCodexRestart(deps, parts)).resolves.toEqual({ value: true, codexRestartDeferred: false });
+ if (applyRuntime) expect(applyRuntime).toHaveBeenCalledOnce();
+ },
+ );
+
it('prepare 成功: persist → applyRuntime → finalize, 不登记延迟重启, 清掉旧登记', async () => {
const deps = createDeps();
const order: string[] = [];
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
index a7354ac2af..79ebbc4acb 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/deferredRestartQueueDrain.test.ts
@@ -26,6 +26,7 @@ import type {
AgentInputSendResult,
} from '../agent-input-coordinator.js';
import { DeferredCodexRestartService } from '../deferredCodexRestart.js';
+import { CodexCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch.js';
import {
createDeferredRestartAppliedWake,
createDeferredRestartQueueGate,
@@ -150,6 +151,7 @@ function sendSuccess(source = 'test'): AgentInputSendResult {
*/
function createRestartHarness() {
let running = false;
+ let live = true;
let busyOtherSession = false;
const projections: AgentInputProjection[] = [];
let loadQueueSnapshot: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null = null;
@@ -168,11 +170,12 @@ function createRestartHarness() {
let coordinator: AgentInputCoordinator;
const service = new DeferredCodexRestartService({
- restart: async () => {
+ restart: async (applyRuntime) => {
+ if (!await applyRuntime()) return;
await restartImpl();
},
hasBusyLocalCodexSession: () => busyOtherSession,
- listLocalCodexSessionIds: () => [SID],
+ listLocalCodexSessionIds: () => live ? [SID] : [],
onApplied: createDeferredRestartAppliedWake({
wakeSession: (sessionId, reason) => coordinator.wakeSession(sessionId, reason),
}),
@@ -201,7 +204,7 @@ function createRestartHarness() {
hasPendingCredentialSwitch: createDeferredRestartQueueGate({
hasPendingCredentialSwitchEntry: () => false,
isDeferredRestartPending: () => service.isPending(),
- listActiveSessions: () => [{ id: SID, agentKind: 'codex', remoteHostId: null }],
+ listActiveSessions: () => live ? [{ id: SID, agentKind: 'codex', remoteHostId: null }] : [],
}),
emitProjection: (projection) => {
projections.push(projection);
@@ -222,6 +225,9 @@ function createRestartHarness() {
setRunning(value: boolean) {
running = value;
},
+ setLive(value: boolean) {
+ live = value;
+ },
setBusyOtherSession(value: boolean) {
busyOtherSession = value;
},
@@ -299,6 +305,37 @@ describe('deferred Codex restart × input queue drain (#2506)', () => {
expect(latestProjection(h.projections).pendingQueue).toEqual([]);
});
+ it.each(['busy', 'bridge-failure', 'new-runtime', 'new-mcp-config'])(
+ 'wakes a preserved queue after a closed session disappears during %s retry', async (failure) => {
+ const h = createRestartHarness();
+ await h.coordinator.ensureQueueRestored(h.SID);
+ h.service.schedule('memory-change');
+ h.coordinator.enqueue(h.SID, makeItem('retry-message', 'resume after retry'));
+ await flush();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ let first = true;
+ h.setRestartImpl(async () => {
+ h.coordinator.onSessionClosed(h.SID);
+ h.setLive(false);
+ if (!first) return;
+ first = false;
+ if (failure === 'busy') throw new CodexCredentialModeSwitchBusyError([]);
+ if (failure === 'bridge-failure') throw new Error('bridge preparation failed');
+ h.service.schedule(failure, failure === 'new-runtime' ? async () => {} : undefined);
+ });
+ await h.service.flushBeforeLocalCodexSessionStart();
+ expect(h.service.isPending()).toBe(true);
+ expect(h.service.listGatedSessionIds()).toEqual([h.SID]);
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ await h.service.flushBeforeLocalCodexSessionStart();
+ await flush();
+ expect(h.service.isPending()).toBe(false);
+ expect(h.sendToAgent).toHaveBeenCalledOnce();
+ expect(mocks.createMessage).toHaveBeenCalledOnce();
+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);
+ },
+ );
+
it('竞态 a:wake 在队列恢复读取期间到达 → 被 gate 挡下并留痕;安静恢复进入暂停态同样可诊断', async () => {
const h = createRestartHarness();
const restore = deferred<AgentInputQueuedMessage[]>();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
index 4d4ce2f9bd..e79a46dc89 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/mcpHandlers.test.ts
@@ -21,6 +21,9 @@ import {
import type { CustomMcpConfig } from '../../../shared/customMcp.js';
import { MAKER_INVOKE } from '../channels.js';
import { registerMcpHandlers, type McpHandlerDeps } from '../mcpHandlers.js';
+import { refreshCodexMcpEnvironment } from '../codexMcpRefresh.js';
+import { DeferredCodexRestartService } from '../deferredCodexRestart.js';
+import { CodexCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch.js';
import { IpcHarness } from './helpers/ipcHarness.js';
vi.mock('../../secrets/providerSecretStore.js', () => ({ readCustomMcpToken: () => null }));
@@ -226,6 +229,52 @@ describe('mcp:custom:* CRUD handlers', () => {
expect(deps.invalidateCodex).toHaveBeenCalledOnce();
});
+ it('retains persisted MCP edits during a control RPC and refreshes the latest config before next start', async () => {
+ mountDb();
+ let rpcBusy = true;
+ let bridgeConfig: CustomMcpConfig[] = [];
+ const shutdown = vi.fn(async () => { bridgeConfig = await listCustomMcpServers(); });
+ const restart = async (refresh: () => Promise<void>) => {
+ if (rpcBusy) throw new CodexCredentialModeSwitchBusyError([]);
+ await refresh();
+ };
+ const deferred = new DeferredCodexRestartService({
+ hasBusyLocalCodexSession: () => false,
+ listLocalCodexSessionIds: () => [],
+ restart: (applyRuntime) => restart(async () => {
+ if (await applyRuntime()) await shutdown();
+ }),
+ });
+ const harness = new IpcHarness();
+ registerMcpHandlers(harness, makeDeps({
+ invalidateCodex: async () => {
+ await refreshCodexMcpEnvironment({
+ restartCodex: restart,
+ shutdownCodexEnvironment: shutdown,
+ onDeferred: () => deferred.schedule('Custom MCP configuration changed'),
+ });
+ },
+ }));
+ try {
+ await harness.invoke(MAKER_INVOKE.MCP_CUSTOM_CREATE, validConfig);
+ const updated = { ...validConfig, url: 'https://updated.example.com/mcp' };
+ await harness.invoke(MAKER_INVOKE.MCP_CUSTOM_UPDATE, updated);
+ expect(await listCustomMcpServers()).toEqual([expect.objectContaining(updated)]);
+ await deferred.flushBeforeLocalCodexSessionStart();
+ expect(deferred.isPending()).toBe(true);
+ expect(shutdown).not.toHaveBeenCalled();
+ expect(bridgeConfig).toEqual([]);
+
+ rpcBusy = false;
+ await deferred.flushBeforeLocalCodexSessionStart();
+ expect(deferred.isPending()).toBe(false);
+ expect(shutdown).toHaveBeenCalledOnce();
+ expect(bridgeConfig).toEqual([expect.objectContaining(updated)]);
+ } finally {
+ deferred.clear();
+ }
+ });
+
it('rejects invalid config (bad url) with INVALID_PARAMS and does not write', async () => {
mountDb();
const harness = new IpcHarness();
diff --git a/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts b/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts
index 6fa3068ae9..f8842a503a 100644
--- a/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts
+++ b/apps/desktop/src/main/maker-ipc/codexMcpRefresh.ts
@@ -6,7 +6,8 @@
* intact; callers can then report that the persisted setting is deferred.
*/
export async function refreshCodexMcpEnvironment(deps: {
- restartCodex: () => Promise<void>;
+ /** Hold all local host startup reservations through the supplied refresh. */
+ restartCodex: (refreshEnvironment: () => Promise<void>) => Promise<void>;
shutdownCodexEnvironment: () => Promise<void>;
/** Schedule the same refresh for the next idle boundary when the host is busy. */
onDeferred?: () => void;
@@ -14,20 +15,16 @@ export async function refreshCodexMcpEnvironment(deps: {
warn: (message: string, meta?: Record<string, unknown>) => void;
};
}): Promise<{ codexMcpRefreshed: boolean }> {
+ let refreshingBridge = false;
try {
- await deps.restartCodex();
- } catch (err) {
- deps.logger?.warn('Codex MCP refresh deferred because the shared host could not restart', {
- error: err instanceof Error ? err.message : String(err),
+ await deps.restartCodex(async () => {
+ refreshingBridge = true;
+ await deps.shutdownCodexEnvironment();
});
- deps.onDeferred?.();
- return { codexMcpRefreshed: false };
- }
-
- try {
- await deps.shutdownCodexEnvironment();
} catch (err) {
- deps.logger?.warn('Codex MCP refresh deferred because the old bridge could not shut down', {
+ deps.logger?.warn(refreshingBridge
+ ? 'Codex MCP refresh deferred because the old bridge could not shut down'
+ : 'Codex MCP refresh deferred because the shared host could not restart', {
error: err instanceof Error ? err.message : String(err),
});
deps.onDeferred?.();
diff --git a/apps/desktop/src/main/maker-ipc/contacts-ipc.ts b/apps/desktop/src/main/maker-ipc/contacts-ipc.ts
index df71360922..ae1657e698 100644
--- a/apps/desktop/src/main/maker-ipc/contacts-ipc.ts
+++ b/apps/desktop/src/main/maker-ipc/contacts-ipc.ts
@@ -18,6 +18,7 @@
import { BrowserWindow, ipcMain } from 'electron';
import { createLogger } from '../logger.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
import {
broadcastContactsNow,
getContactsDeviceSyncStatus,
@@ -337,8 +338,13 @@ function broadcastContactsSyncStatus(status: unknown): void {
}
}
-/** bootstrap-electron 启动期调一次: 组装 desktop deps + ipcMain.handle 接线 */
-export function registerContactsIpc(): void {
+/** Bootstrap supplies static runtime dependencies, avoiding a contacts → Maker import cycle. */
+export function registerContactsIpc(runtime: {
+ restartCodexAfterAuthModeChange(refreshEnvironment: () => Promise<void>): Promise<void>;
+ shutdownCodexEnvironment(): Promise<void>;
+ scheduleDeferredCodexRestart(reason: string): void;
+ invalidatePiEnvironment(): void;
+}): void {
const handlers = createContactsIpcHandlers({
getManager: getDesktopContactsManager,
readSettingsState: readContactsSettingsState,
@@ -354,36 +360,28 @@ export function registerContactsIpc(): void {
// 与 register.ts 自定义 MCP CRUD 的 invalidateCodex 同款语义与顺序: 先 dispose
// app-server(含 busy 检查), 成功后再关 bridge/清 cache —— 若先关 bridge 而 dispose
// 失败(busy), running 会话的 mcp_servers URL 会指向已停的 bridge。
- // 动态 import 破环: contacts-ipc 被 mcp-providers 静态引用, 而 maker-host/index
- // 又引 mcp-providers, 这里静态 import maker-host/index 会成环(同 mcp-providers
- // 内 remote-ssh 的先例)。
// 契约: 任一步失败都 rethrow(见 ContactsIpcDeps.invalidateCodexMcp 注释),
// handler 把失败折成 codexMcpRefreshed:false 由 renderer 提示延迟生效。
invalidateCodexMcp: async () => {
+ const ownerScopeKey = activeOwnerScopeKey();
+ // Pi 的 generation lease 保留活动会话;落盘后立即让新会话读取新配置,
+ // 不等待 Codex 的 busy 检查或 bridge 重建,也不在迟到回调中给新 owner 换代。
try {
- const { restartCodexAfterAuthModeChange } = await import('../maker-host/index.js');
- await restartCodexAfterAuthModeChange();
+ runtime.invalidatePiEnvironment();
} catch (err) {
- log.warn(
- 'restartCodexAfterAuthModeChange on contacts toggle failed — codex keeps stale MCP config until app restart or re-toggle',
- {
- error: err instanceof Error ? err.message : String(err),
- },
- );
+ log.warn('Pi MCP environment invalidation on contacts toggle failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
throw err;
}
try {
- // Codex 与 Pi 各自的 MCP bridge 都在首个会话冻结 server 集合;contacts 开关变更后
- // 两者都要 invalidate,否则新会话仍暴露已禁用的 contacts server(Pi 侧 codex review P1)。
- const [{ shutdownCodexEnvironment }, { invalidatePiEnvironment }] = await Promise.all([
- import('../mcp-integrations/codexEnvironment.js'),
- import('../mcp-integrations/piEnvironment.js'),
- ]);
- await shutdownCodexEnvironment();
- invalidatePiEnvironment();
+ await runtime.restartCodexAfterAuthModeChange(runtime.shutdownCodexEnvironment);
} catch (err) {
+ if (!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey) {
+ runtime.scheduleDeferredCodexRestart('Contacts MCP configuration changed');
+ }
log.warn(
- 'shutdown agent MCP environments on contacts toggle failed — cached spawn config still stale',
+ 'restartCodexAfterAuthModeChange on contacts toggle failed — idle retry if owner is still current',
{
error: err instanceof Error ? err.message : String(err),
},
diff --git a/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts b/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
index 91e9849ba4..5eef44457b 100644
--- a/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
+++ b/apps/desktop/src/main/maker-ipc/deferredCodexRestart.ts
@@ -14,9 +14,8 @@ import { isCredentialModeSwitchBusyError } from '../maker-host/codex-credential-
* 兑现路径(与 PendingCredentialSwitchService 同款结构):
* turn done/error / 会话关闭(register.ts 接线)→ onSessionSettled:
* 仍有本地 Codex 会话在 turn 内 → 静默保留 pending,等下一个边界;
- * 全部空闲 → 先执行登记的 applyRuntime(native setMemory 热推,此刻无
- * in-flight turn 可打扰),再 restartCodexAfterAuthModeChange(关会话 +
- * dispose host,下一次发送按新设置重建),最后 onApplied 唤醒被 pending 门
+ * 全部空闲 → restart 先持有全部本地 host 的启动守卫并软关闭会话,再在
+ * 守卫内执行 applyRuntime、替换 bridge,最后 onApplied 唤醒被 pending 门
* 挡住的输入队列。
* 排队门:pending 期间本地 Codex live 会话的输入队列被 coordinator 的
* hasPendingCredentialSwitch 谓词(register.ts 扩展)挡住 —— 否则排队消息
@@ -36,7 +35,8 @@ const DEFERRED_RESTART_RETRY_DELAY_MS = 10_000;
export interface DeferredCodexRestartDeps {
/** 实际执行软重启(maker-host restartCodexAfterAuthModeChange)。busy 时抛 CredentialModeSwitchBusyError。 */
- restart: () => Promise<void>;
+ /** Run applyRuntime under the all-local startup guard; false cancels a stale owner generation. */
+ restart: (applyRuntime: () => Promise<boolean>) => Promise<void>;
/**
* 兑现前置探测:仍有本地 Codex 会话在 turn 内时跳过本轮,避免注定失败的
* close 尝试刷 warn 日志。探测与真正兑现之间存在竞态窗口 —— restart 内部的
@@ -60,6 +60,8 @@ export interface DeferredCodexRestartDeps {
export class DeferredCodexRestartService {
private pending = false;
+ /** Sessions closed by any attempt still need a wake when this pending restart settles. */
+ private readonly pendingSessionIds = new Set<string>();
/** 兑现时机才执行的 runtime 变更(native setMemory 热推);最后一次登记生效。 */
private pendingApplyRuntime: (() => Promise<void>) | null = null;
/** 兑现串行化:turn done/error 双事件可能背靠背触发。 */
@@ -93,6 +95,11 @@ export class DeferredCodexRestartService {
// review 第 2 轮)。同域覆盖(memory-over-memory 传入新回调)仍是 last-write-wins。
if (applyRuntime !== undefined) {
this.pendingApplyRuntime = applyRuntime;
+ } else if (this.applying && !this.pendingApplyRuntime) {
+ // Even a persist-only edit must leave work for the active attempt to
+ // consume: its bridge may already have snapshotted the previous config.
+ // Reuse the existing work slot without replacing a queued Memory update.
+ this.pendingApplyRuntime = async () => {};
}
if (!alreadyPending) {
this.scheduleRetry();
@@ -143,21 +150,25 @@ export class DeferredCodexRestartService {
this.clearRetry();
this.pending = false;
this.pendingApplyRuntime = null;
+ this.pendingSessionIds.clear();
}
/**
- * 当前被 pending 门挡住派发的本地 Codex live 会话名单。立即路径覆盖 pending
+ * 当前被 pending 门挡住及此前重试已关闭的本地 Codex 会话名单。立即路径覆盖 pending
* 登记时,调用方在 prepare 关会话**前**采集,clear 后逐个补唤醒 —— 门谓词变
* false 不会自己触发 drain,漏唤 = 队列停到下一次无关唤醒(review P1
- * 2026-07-23)。无 pending 时为空;facade 边界窗口抛错按空处理。
+ * 2026-07-23)。无 pending 时为空;facade 暂不可读时保留已采集名单,owner clear 会清空。
*/
listGatedSessionIds(): string[] {
if (!this.pending) return [];
try {
- return this.deps.listLocalCodexSessionIds();
+ // Immediate takeover can itself fail after closing sessions. Its pre-close
+ // snapshot belongs to this pending work until success or owner clear too.
+ for (const id of this.deps.listLocalCodexSessionIds()) this.pendingSessionIds.add(id);
} catch {
- return [];
+ // Keep the previously captured IDs while the facade is unavailable.
}
+ return [...this.pendingSessionIds];
}
private async tryApply(): Promise<void> {
@@ -168,26 +179,28 @@ export class DeferredCodexRestartService {
// deps 走 dynamic Maker facade,owner 边界期间会抛 —— 整段兜住,
// 靠兜底定时器(或边界时的 clear())收口,不产生 unhandled rejection。
if (this.deps.hasBusyLocalCodexSession()) return;
- // claim-before-await 循环:await 期间新 schedule 覆盖登记时,下一轮取到
- // 最新闭包接着应用(last-write-wins),旧闭包收口不会误清新登记(review
- // P1 2026-07-23)。
- for (;;) {
- const applyRuntime = this.pendingApplyRuntime;
- if (!applyRuntime) break;
- this.pendingApplyRuntime = null;
- try {
- await applyRuntime();
- } catch (err) {
- // runtime 热推失败不阻塞重启:agent 级 memoryOverride 已在 setMemory
- // 内先行落位,restart 后新 host ensure 时会补推,重启本身是最终收敛。
- this.deps.logger?.warn('deferred memory runtime apply failed; proceeding with restart', {
- error: err instanceof Error ? err.message : String(err),
- });
+ for (const id of this.deps.listLocalCodexSessionIds()) this.pendingSessionIds.add(id);
+ await this.deps.restart(async () => {
+ if (gen !== this.generation) return false;
+ // Claim inside the startup guard: a runtime callback can close the
+ // shared bridge. Claim-before-await preserves last-write-wins updates.
+ for (;;) {
+ const applyRuntime = this.pendingApplyRuntime;
+ if (!applyRuntime) break;
+ this.pendingApplyRuntime = null;
+ try {
+ await applyRuntime();
+ } catch (err) {
+ // The in-memory override is set before native push; new hosts
+ // apply it after restart even if the old native push failed.
+ this.deps.logger?.warn('deferred memory runtime apply failed; proceeding with restart', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ if (gen !== this.generation) return false;
}
- if (gen !== this.generation) return;
- }
- const sessionIds = this.deps.listLocalCodexSessionIds();
- await this.deps.restart();
+ return true;
+ });
if (gen !== this.generation) {
// clear 与 restart 的 await 竞态:restart 副作用已发生(TOCTOU 无法避免,
// owner 边界窗口内 facade 会抛、真正跨 owner 的 restart 到不了这里),
@@ -195,11 +208,12 @@ export class DeferredCodexRestartService {
return;
}
if (this.pendingApplyRuntime) {
- // restart await 期间又有新登记:重启已带最新 persist 值,但新登记的
- // runtime 尚未应用 —— 本轮不收口(pending 保持,兜底定时器仍在),
- // 下一边界把新 runtime 应用后再重启一次收口。
+ // Work arrived after the guarded apply loop. The bridge may have frozen
+ // an older persisted config too; keep pending until the next restart.
return;
}
+ const sessionIds = [...this.pendingSessionIds];
+ this.pendingSessionIds.clear();
this.pending = false;
this.clearRetry();
this.deps.logger?.info('deferred codex restart applied', {
diff --git a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
index d356397085..793a02f14d 100644
--- a/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/mcpHandlers.ts
@@ -45,7 +45,7 @@ export interface McpHandlerDeps {
* 但 Codex 的 extraArgs/extraEnv 在 codexEnvironment 的模块级 `cached` 里被冻住,后续会话复用旧
* spawn 配置——不失效则新增 server 不出现、删除 / 换 token 仍残留,直到重启 app。生产实现清
* codexEnvironment 缓存 + dispose app-server(与 slack 变更同款,best-effort,busy 会话软重启失败
- * 只告警不阻塞 CRUD)。测试可省略。
+ * 登记空闲重试而不阻塞 CRUD)。测试可省略。
*/
invalidateCodex?(): Promise<void>;
/**
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 9d43a558c1..c94a52723a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1605,14 +1605,14 @@ async function applyMemoryChangeWithCodexRestart<T extends object>(
{
prepare: async () => {
try {
- await prepareCodexForAuthModeChange();
+ await prepareCodexForAuthModeChange({ allLocalHosts: true });
} catch (err) {
// busy 原样透传 —— 执行体靠它分流延迟路径;其余是真实故障,编码后上抛。
if (isCredentialModeSwitchBusyError(err)) throw err;
throwIpcError('INTERNAL', err instanceof Error ? err.message : String(err));
}
},
- finalize: finalizeCodexAfterAuthModeChange,
+ finalize: () => finalizeCodexAfterAuthModeChange({ prepareMcpEnvironment: true }),
cancel: cancelCodexAuthModeChange,
scheduleDeferredRestart: (reason, applyRuntime) => {
deferredCodexRestartHolder?.schedule(reason, applyRuntime);
@@ -3480,6 +3480,11 @@ export function clearDeferredCodexRestartForOwnerBoundary(): void {
deferredCodexRestartHolder?.clear();
}
+/** Reuse the owner-scoped idle retry for settings whose persistence already succeeded. */
+export function scheduleDeferredCodexRestart(reason: string): void {
+ deferredCodexRestartHolder?.schedule(reason);
+}
+
export function clearWorkingDirectoryRecoveryForOwnerBoundary(): void {
workingDirectoryRecovery.clear();
}
@@ -5815,29 +5820,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 内置 server 名对自定义 MCP 是保留名:撞名会在装配层顶替内置 server 并继承
// 它在 MCP 审批策略里的信任,所以 CRUD 阶段就拒收。
getReservedMcpIds: () => getBuiltinMcpServerNames(),
- // Codex 的 MCP flags 冻在 codexEnvironment 的 cached spawn 配置里,清缓存 + dispose app-server,
- // 让下个 codex 会话按新 MCP 配置重 spawn(与 slack 变更同款 best-effort;busy 会话软重启失败只告警)。
- // 顺序:先 dispose app-server(含 busy 检查),成功后再关 bridge/cache。
- // 若先关 bridge、后 dispose 失败(busy),running 会话的 mcp_servers URL 会指向已停的 bridge。
+ // Persisted MCP changes must eventually replace the frozen spawn config;
+ // busy hosts keep their bridge until the existing idle retry can refresh it.
invalidateCodex: async () => {
- let codexRestarted = false;
- try {
- await restartCodexAfterAuthModeChange();
- codexRestarted = true;
- } catch (err) {
- log.warn('restartCodexAfterAuthModeChange on custom mcp change failed', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
- if (codexRestarted) {
- try {
- await shutdownCodexEnvironment();
- } catch (err) {
- log.warn('shutdownCodexEnvironment on custom mcp change failed', {
- error: err instanceof Error ? err.message : String(err),
- });
- }
- }
+ const ownerScopeKey = activeOwnerScopeKey();
+ await refreshCodexMcpEnvironment({
+ restartCodex: restartCodexAfterAuthModeChange,
+ shutdownCodexEnvironment,
+ onDeferred: () => {
+ if (!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScopeKey) {
+ scheduleDeferredCodexRestart('Custom MCP configuration changed');
+ }
+ },
+ logger: log,
+ });
// Pi 的 MCP bridge 同样按首个会话冻结 server 集合:自定义 MCP 增删改后必须 invalidate,
// 否则新 Pi 会话仍暴露已删/已禁用的工具、拿不到新启用的工具(codex review P1)。
// 与 codex 分支独立(不依赖 codexRestarted),下一次 startSession lazy 重建。
@@ -14247,7 +14243,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 期间本地 Codex live 会话的排队派发被上方 coordinator 的 hasPendingCredentialSwitch
// 谓词挡住,兑现后由 onApplied 逐个唤醒。
const deferredCodexRestartService = new DeferredCodexRestartService({
- restart: restartCodexAfterAuthModeChange,
+ restart: (applyRuntime) => restartCodexAfterAuthModeChange(async () => {
+ if (await applyRuntime() === false) return false;
+ await shutdownCodexEnvironment();
+ }),
hasBusyLocalCodexSession: () =>
maker
.listActiveSessions()
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index da8f55b89e..c6b8f9945e 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -360,6 +360,183 @@ function createDeps(
}
describe('CodexAgent spawn configuration', () => {
+ it('holds account session recovery until the MCP bridge replacement is ready', async () => {
+ let endpoint = 'http://127.0.0.1:51359/mcp/cindy_scheduler';
+ const prepare = vi.fn(async () => {
+ const frozenEndpoint = endpoint;
+ return { extraArgs: [], extraEnv: {},
+ buildSessionMcpConfig: () => ({ 'mcp_servers.cindy_scheduler.url': frozenEndpoint }) };
+ });
+ const agent = new CodexAgent(createDeps({}, {
+ isolateCodexAccountSessions: true,
+ prepareCodexExtraSpawnConfig: prepare,
+ }));
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', { allLocalHosts: true });
+ guard.assertIdle();
+ const recovery = agent.startSession({ sessionId: 'recover-account', sessionInstanceId: 'recover-instance', model: 'gpt-5.4',
+ workingDir: '/repo', resumeSessionId: '11111111-1111-1111-1111-111111111111' });
+ await new Promise(resolve => setTimeout(resolve, 10));
+ expect(prepare).not.toHaveBeenCalled();
+ await guard.retireActiveHost();
+ endpoint = 'http://127.0.0.1:51409/mcp/cindy_scheduler';
+ await guard.finalize();
+ const handle = await recovery;
+ const resume = createdTransports[0].lines.map(line => JSON.parse(line))
+ .find(message => message.method === Method.ThreadResume);
+ expect(resume.params.config['mcp_servers.cindy_scheduler.url']).toBe(endpoint);
+ await handle.close();
+ await agent.dispose();
+ });
+
+ it('defers MCP refresh while an account session is recovering before registration', async () => {
+ const started = deferred<void>();
+ const finish = deferred<void>();
+ MockCodexTransport.beforeThreadStartResponse = async () => {
+ started.resolve();
+ await finish.promise;
+ };
+ const agent = new CodexAgent(createDeps({}, { isolateCodexAccountSessions: true }));
+ const startup = agent.startSession({ sessionId: 'starting-account', model: 'gpt-5.4', workingDir: '/repo' });
+ await started.promise;
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', { allLocalHosts: true });
+ expect(() => guard.assertIdle()).toThrow(/active Codex session/);
+ expect(createdTransports[0].closed).toBe(false);
+ guard.release();
+ finish.resolve();
+ const handle = await startup;
+ await handle.close();
+ await agent.dispose();
+ });
+
+ it('defers MCP refresh during asynchronous control-plane host preparation', async () => {
+ const started = deferred<void>();
+ const finish = deferred<void>();
+ const agent = new CodexAgent(createDeps({}, { prepareCodexExtraSpawnConfig: async () => {
+ started.resolve();
+ await finish.promise;
+ return { extraArgs: [], extraEnv: {} };
+ } }));
+ const models = agent.refreshLocalModels({ credentialMode: 'oauth-bearer' });
+ await started.promise;
+ const busy = new Error('deferrable startup');
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', { allLocalHosts: true, busyError: () => busy });
+ expect(() => guard.assertIdle()).toThrow(busy);
+ guard.release();
+ finish.resolve();
+ await models;
+ await agent.dispose();
+ });
+
+ it.each([Method.ModelList, Method.ThreadFork, Method.AccountRateLimitsRead, Method.SkillsList, Method.ConfigRead, Method.MemoryReset])(
+ 'keeps %s leased until the control-plane operation settles', async (method) => {
+ const started = deferred<void>();
+ const finish = deferred<void>();
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, async (requested) => {
+ if (requested !== method) return undefined;
+ started.resolve();
+ await finish.promise;
+ if (method === Method.ModelList) return { data: [], nextCursor: null };
+ if (method === Method.AccountRateLimitsRead || method === Method.MemoryReset) return {};
+ return undefined;
+ });
+ const operation = method === Method.ModelList ? agent.refreshLocalModels({ credentialMode: 'oauth-bearer' })
+ : method === Method.ThreadFork ? agent.forkSdkSession({ sourceSdkSessionId: 'source', upToMessageId: 'message', workingDir: '/repo' })
+ : method === Method.AccountRateLimitsRead ? agent.readAccountRateLimits()
+ : method === Method.SkillsList ? agent.listAgentSkills({ workingDir: '/repo' })
+ : method === Method.ConfigRead ? agent.getMemoryStatus()
+ : agent.resetMemory();
+ await started.promise;
+ const busy = new Error('defer auxiliary operation');
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', {
+ allLocalHosts: true, busyError: () => busy,
+ });
+ expect(() => guard.assertIdle()).toThrow(busy);
+ await expect(guard.retireActiveHost()).rejects.toThrow(/active Codex session/);
+ expect(host.retire).not.toHaveBeenCalled();
+ guard.release();
+ finish.resolve();
+ await operation;
+ const after = await agent.beginLocalHostCredentialChange('after operation', { allLocalHosts: true });
+ after.assertIdle();
+ await after.finalize();
+ },
+ );
+
+ it('releases the control-plane lease when its RPC rejects', async () => {
+ const agent = new CodexAgent(createDeps());
+ installFakeHost(agent, (method) => {
+ if (method === Method.ModelList) throw new Error('model failure');
+ });
+ await expect(agent.refreshLocalModels({ credentialMode: 'oauth-bearer' })).rejects.toThrow('model failure');
+ const guard = await agent.beginLocalHostCredentialChange('after failure', { allLocalHosts: true });
+ guard.assertIdle();
+ await guard.finalize();
+ });
+
+ it('defers memory push while refresh owns admission and new RPCs use the replacement host', async () => {
+ const agent = new CodexAgent(createDeps());
+ await agent.refreshLocalModels();
+ const old = createdTransports[0];
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', { allLocalHosts: true });
+ const before = old.lines.length;
+ expect(await agent.setMemory(true)).toEqual({ effective: 'next-session' });
+ const models = agent.refreshLocalModels();
+ await Promise.resolve();
+ expect(old.lines).toHaveLength(before);
+ guard.assertIdle();
+ await guard.retireActiveHost();
+ await guard.finalize();
+ await models;
+ expect(old.closed).toBe(true);
+ expect(createdTransports).toHaveLength(2);
+ await agent.dispose();
+ });
+
+ it('serializes overlapping MCP refresh reservations and releases after failure', async () => {
+ const prepare = vi.fn(async () => ({ extraArgs: [], extraEnv: {} }));
+ const agent = new CodexAgent(createDeps({}, { prepareCodexExtraSpawnConfig: prepare }));
+ const first = await agent.beginLocalHostCredentialChange('first refresh', { allLocalHosts: true });
+ let acquired = false;
+ const secondPromise = agent.beginLocalHostCredentialChange('second refresh', { allLocalHosts: true })
+ .then(guard => { acquired = true; return guard; });
+ await Promise.resolve();
+ expect(acquired).toBe(false);
+ // A bridge replacement failure must release its reservation without
+ // releasing a later refresh that has already acquired admission.
+ first.release();
+ const second = await secondPromise;
+ first.release();
+ const startup = agent.startSession({ sessionId: 'after-failed-refresh', model: 'gpt-5.4', workingDir: '/repo' });
+ await Promise.resolve();
+ expect(prepare).not.toHaveBeenCalled();
+ second.release();
+ const handle = await startup;
+ expect(prepare).toHaveBeenCalledOnce();
+ await handle.close();
+ await agent.dispose();
+ });
+
+ it('retires all local MCP consumers without blocking or retiring remote sessions', async () => {
+ const agent = new CodexAgent(createDeps({}, { getRemoteCodexTransport: () => {
+ const transport = new MockCodexTransport();
+ createdTransports.push(transport);
+ return transport;
+ } }));
+ await agent.refreshLocalModels({ credentialMode: 'oauth-bearer' });
+ const localTransport = createdTransports[0];
+ const guard = await agent.beginLocalHostCredentialChange('MCP refresh', { allLocalHosts: true });
+ const remote = await agent.startSession({ sessionId: 'remote-during-refresh', model: 'gpt-5.4',
+ workingDir: '/repo', remoteHostId: 'remote-1' });
+ guard.assertIdle();
+ await guard.retireActiveHost();
+ expect(localTransport.closed).toBe(true);
+ expect(createdTransports[1].closed).toBe(false);
+ await guard.finalize();
+ await remote.close();
+ await agent.dispose();
+ });
+
it.each(['oauth-bearer', 'gateway-key'] as const)('separates canonical history from target credentials (%s)', async mode => {
const credentialHome = path.resolve(os.tmpdir(), 'target-account-fixture');
const historyHome = path.resolve(os.tmpdir(), 'original-history-fixture');
@@ -570,6 +747,7 @@ describe('CodexAgent oneShot dispatch guard', () => {
});
const subscribeThread = vi.fn(() => ({ release: vi.fn() }));
const host = { ensureStarted, request, subscribeThread };
+ (agent as any).hosts.set('test-utility-host', host);
Object.defineProperty(agent, 'getUtilityHost', {
value: vi.fn(async () => ({ key: 'test-utility-host', host })),
configurable: true,
@@ -602,6 +780,7 @@ describe('CodexAgent oneShot dispatch guard', () => {
request,
subscribeThread,
};
+ (agent as any).hosts.set('test-utility-host', host);
Object.defineProperty(agent, 'getUtilityHost', {
value: vi.fn(async () => ({ key: 'test-utility-host', host })),
configurable: true,
@@ -819,6 +998,9 @@ function installFakeHost(
);
const getOpenAiWebSocketsEnabled = vi.fn(() => opts.openAiWebSocketsEnabled !== false);
const host = {
+ activeSubscriptions: 0,
+ retire: vi.fn(async () => {}),
+ notifySubscribersOfForcedRetire: vi.fn(),
ensureStarted,
// startSession 的 initialize 直调走限时变体 (codex R13 P1): fake 里
// 直接委托 ensureStarted (超时语义由 host.test.ts 的真 transport 覆盖)。
@@ -850,7 +1032,11 @@ function installFakeHost(
discardPendingDescendantLineage: vi.fn(),
};
- const getHost = vi.fn(async () => host);
+ const getHost = vi.fn(async (remoteHostId?: string, _mode?: string, options?: { keyOverride?: string }) => {
+ const key = options?.keyOverride ?? (remoteHostId ? `remote:${remoteHostId}` : 'local');
+ (agent as any).hosts.set(key, host);
+ return host;
+ });
Object.defineProperty(agent, 'getHost', {
value: getHost,
});
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index f048160386..359be917f1 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -470,6 +470,8 @@ export function hostKey(remoteHostId?: string | null): string {
}
const LOCAL_CONTROL_PLANE_HOST_PREFIX = 'local-control:';
+// One bridge is shared by every local host, including account and utility hosts.
+const LOCAL_MCP_REFRESH_KEY = 'local-mcp-refresh';
const CODEX_MODEL_LIST_RPC_TIMEOUT_MS = 20_000;
const CODEX_MODEL_REFRESH_DEADLINE_MS = 20_000;
@@ -2001,10 +2003,10 @@ export class CodexAgent extends BaseAgent {
forceReload: boolean,
remoteHostId?: string,
): Promise<{ skills: SkillMetadata[]; errors: Array<{ path?: string; message: string }> }> {
- const host = remoteHostId
- ? await this.getHost(remoteHostId)
- : (await this.getUtilityHost()).host;
- return await this.listSkillsForHost(host, workingDir, forceReload);
+ return this.withHostOperation(async () => remoteHostId
+ ? { key: hostKey(remoteHostId), host: await this.getHost(remoteHostId) }
+ : this.getUtilityHost(),
+ host => this.listSkillsForHost(host, workingDir, forceReload));
}
private async listSkillsForHost(
@@ -2175,7 +2177,8 @@ export class CodexAgent extends BaseAgent {
private async waitForHostCredentialModeSwitch(key: string): Promise<void> {
while (true) {
- const switching = this.hostCredentialModeSwitches.get(key);
+ const switching = this.hostCredentialModeSwitches.get(LOCAL_MCP_REFRESH_KEY)
+ ?? this.hostCredentialModeSwitches.get(key);
if (!switching) return;
await switching.catch(() => undefined);
}
@@ -2183,14 +2186,24 @@ export class CodexAgent extends BaseAgent {
async beginLocalHostCredentialChange(
reason = 'CodexAgent local credential state changed',
+ options: { allLocalHosts?: boolean; busyError?: () => Error } = {},
): Promise<{
assertIdle(): void;
retireActiveHost(): Promise<void>;
finalize(): Promise<void>;
release(): void;
}> {
- const key = hostKey();
- await this.waitForHostCredentialModeSwitch(key);
+ const key = options.allLocalHosts ? LOCAL_MCP_REFRESH_KEY : hostKey();
+ // Check and reserve in the same synchronous segment. An await-only gate
+ // allows two callers to pass before either has installed its reservation.
+ while (true) {
+ const pending = options.allLocalHosts
+ ? [...this.hostCredentialModeSwitches.values()]
+ : [this.hostCredentialModeSwitches.get(LOCAL_MCP_REFRESH_KEY), this.hostCredentialModeSwitches.get(key)]
+ .filter((value): value is Promise<void> => value !== undefined);
+ if (pending.length === 0) break;
+ await Promise.allSettled(pending);
+ }
let releaseSwitch!: () => void;
const switchPromise = new Promise<void>((resolve) => {
@@ -2209,36 +2222,53 @@ export class CodexAgent extends BaseAgent {
releaseSwitch();
};
- const activeUseCount = (): number => {
- const host = this.hosts.get(key);
- return host
- ? this.hostActiveUseCount(key, host)
- : (this.hostSessionBindingLeases.get(key) ?? 0);
+ const affectedKeys = (): string[] => options.allLocalHosts
+ ? [...new Set([
+ ...this.hosts.keys(), ...this.hostPromises.keys(),
+ ...this.hostSessionBindingLeases.keys(), ...this.retiringHosts.keys(),
+ ])].filter((candidate) => !candidate.startsWith('remote:'))
+ : [key];
+ const activeUseCount = (): number => affectedKeys().reduce((count, candidate) => {
+ const host = this.hosts.get(candidate);
+ return count + (host
+ ? this.hostActiveUseCount(candidate, host)
+ : (this.hostSessionBindingLeases.get(candidate) ?? 0))
+ + (options.allLocalHosts && this.hostPromises.has(candidate) ? 1 : 0);
+ }, 0);
+ const retire = async (): Promise<void> => {
+ for (const candidate of affectedKeys()) {
+ await this.retireHostKey(candidate, reason, {
+ failIfActive: options.allLocalHosts === true,
+ logPrefix: 'codex local credential hard cut',
+ throwOnShutdownFailure: true,
+ });
+ }
};
return {
assertIdle: () => {
const count = activeUseCount();
if (count > 0) {
- throw new Error(
+ throw options.busyError?.() ?? new Error(
`Cannot restart local Codex host while ${count} active Codex session(s) are attached`,
);
}
},
retireActiveHost: async () => {
if (released || hostRetired) return;
- await this.retireHostKey(key, reason, {
- failIfActive: false,
- logPrefix: 'codex local credential hard cut',
- throwOnShutdownFailure: true,
- });
+ await retire();
hostRetired = true;
},
finalize: async () => {
if (released) return;
try {
if (!hostRetired) {
- await this.disposeLocalHostForCredentialChangeUnlocked(key, reason);
+ if (options.allLocalHosts) {
+ if (activeUseCount() > 0) throw options.busyError?.() ?? new Error('Cannot refresh MCP while local Codex hosts are active or starting');
+ await retire();
+ } else {
+ await this.disposeLocalHostForCredentialChangeUnlocked(key, reason);
+ }
}
} finally {
cleanup();
@@ -2404,7 +2434,8 @@ export class CodexAgent extends BaseAgent {
|| (subagentRoutingProfileCompatible
&& await canReuseRegistered(existing, currentMode, currentEffective))
) {
- if (this.hosts.get(key) !== existing || this.retiringHosts.has(key)) continue;
+ if (this.hosts.get(key) !== existing || this.retiringHosts.has(key)
+ || (!remoteHostId && this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY))) continue;
return existing;
}
await this.shutdownHostForCredentialModeChange(
@@ -2467,7 +2498,8 @@ export class CodexAgent extends BaseAgent {
)
&& await canReuseRegistered(inflightHost, registeredRaw, registeredEffective)
) {
- if (this.hosts.get(key) !== inflightHost || this.retiringHosts.has(key)) continue;
+ if (this.hosts.get(key) !== inflightHost || this.retiringHosts.has(key)
+ || this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)) continue;
return inflightHost;
}
continue;
@@ -2504,6 +2536,7 @@ export class CodexAgent extends BaseAgent {
}
if (this.retiringHosts.has(key) || this.hosts.has(key) || this.hostPromises.has(key)) continue;
+ if (!remoteHostId && this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)) continue;
const generation = this.bumpHostGeneration(key);
// 超集归一化发生在 createHost 内(gateway-key → oauth-bearer);通过回调同步
// in-flight 登记,让并发的 oauth-bearer 诉求命中复用而不是 supersede 重建。
@@ -2543,15 +2576,52 @@ export class CodexAgent extends BaseAgent {
};
this.hostPromises.set(key, inflightEntry);
const host = await promise;
- if (this.hosts.get(key) !== host || this.retiringHosts.has(key)) continue;
+ if (this.hosts.get(key) !== host || this.retiringHosts.has(key)
+ || (!remoteHostId && this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY))) continue;
return host;
}
}
+ /** Reserve the returned host before handing it to a non-thread operation. */
+ private async acquireHostOperation(
+ getHost: () => Promise<{ key: string; host: AppServerHost }>,
+ ): Promise<{ key: string; host: AppServerHost; release: () => void }> {
+ while (true) {
+ const { key, host } = await getHost();
+ if (key.startsWith('remote:')) return { key, host, release: () => {} };
+ // No await between validation and reservation, including after getHost resolves.
+ if (this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)
+ || this.hostCredentialModeSwitches.has(key)
+ || this.retiringHosts.has(key)
+ || this.hosts.get(key) !== host) {
+ await this.waitForHostCredentialModeSwitch(key);
+ continue;
+ }
+ const generation = this.hostGenerations.get(key);
+ const release = this.acquireHostSessionBindingLease(key);
+ return { key, host, release: () => {
+ if (this.hostGenerations.get(key) === generation) release();
+ } };
+ }
+ }
+
+ private async withHostOperation<T>(
+ getHost: () => Promise<{ key: string; host: AppServerHost }>,
+ operation: (host: AppServerHost, key: string) => Promise<T>,
+ ): Promise<T> {
+ const { key, host, release } = await this.acquireHostOperation(getHost);
+ try {
+ return await operation(host, key);
+ } finally {
+ release();
+ }
+ }
+
private async getUtilityHost(): Promise<{ key: string; host: AppServerHost }> {
const key = hostKey();
while (true) {
await this.waitForHostCredentialModeSwitch(key);
+ if (this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)) continue;
const retiring = this.retiringHosts.get(key);
if (retiring) {
await this.beginHostRetirement(key, retiring.host, 'recheck retirement before utility use');
@@ -2568,18 +2638,19 @@ export class CodexAgent extends BaseAgent {
}
/** Start the local OAuth host used by non-model account control-plane RPCs. */
- private async getStartedAccountHost(providerId?: string, startupTimeoutMs?: number): Promise<AppServerHost> {
+ private async withStartedAccountHost<T>(providerId: string | undefined, operation: (host: AppServerHost) => Promise<T>, startupTimeoutMs?: number): Promise<T> {
const credentialMode = 'oauth-bearer';
- const host = await this.getHost(undefined, credentialMode, {
- providerId,
- keyOverride: providerId ? `local-account:${providerId}:control-plane` : localControlPlaneHostKey(credentialMode),
- hostPurpose: 'control-plane',
+ const key = providerId ? `local-account:${providerId}:control-plane` : localControlPlaneHostKey(credentialMode);
+ return this.withHostOperation(async () => ({
+ key,
+ host: await this.getHost(undefined, credentialMode, { providerId, keyOverride: key, hostPurpose: 'control-plane' }),
+ }), async (host) => {
+ const init = startupTimeoutMs
+ ? await host.ensureStartedWithTimeout(startupTimeoutMs, 'account token refresh')
+ : await host.ensureStarted();
+ if (init.codexHome && !providerId) this.codexHome = init.codexHome;
+ return operation(host);
});
- const init = startupTimeoutMs
- ? await host.ensureStartedWithTimeout(startupTimeoutMs, 'account token refresh')
- : await host.ensureStarted();
- if (init.codexHome && !providerId) this.codexHome = init.codexHome;
- return host;
}
/**
@@ -2627,56 +2698,60 @@ export class CodexAgent extends BaseAgent {
const key = options?.providerId ? `local-account:${options.providerId}:models` : credentialMode
? localControlPlaneHostKey(credentialMode)
: hostKey();
- const host = credentialMode
- ? await this.getHost(undefined, credentialMode, {
- providerId: options?.providerId,
- keyOverride: key,
- hostPurpose: 'control-plane',
- })
- : (await this.getUtilityHost()).host;
- const init = await host.ensureStarted();
- if (init.codexHome && !options?.providerId) this.codexHome = init.codexHome;
-
- const models: CodexModelListResponse['data'] = [];
- const seenCursors = new Set<string>();
- let cursor: string | null = null;
- try {
- do {
- const page: CodexModelListResponse = await host.request<CodexModelListResponse>(
- Method.ModelList,
- {
- cursor,
- limit: 100,
- includeHidden: false,
- },
- { timeoutMs: CODEX_MODEL_LIST_RPC_TIMEOUT_MS },
- );
- models.push(...(Array.isArray(page.data) ? page.data : []));
- const next: string | null = typeof page.nextCursor === 'string' && page.nextCursor.length > 0
- ? page.nextCursor
- : null;
- if (next && seenCursors.has(next)) {
- throw new Error(`Codex app-server model/list repeated cursor: ${next}`);
+ return this.withHostOperation(async () => ({
+ key: credentialMode ? key : hostKey(),
+ host: credentialMode
+ ? await this.getHost(undefined, credentialMode, {
+ providerId: options?.providerId,
+ keyOverride: key,
+ hostPurpose: 'control-plane',
+ })
+ : (await this.getUtilityHost()).host,
+ }), async (host) => {
+ const init = await host.ensureStarted();
+ if (init.codexHome && !options?.providerId) this.codexHome = init.codexHome;
+
+ const models: CodexModelListResponse['data'] = [];
+ const seenCursors = new Set<string>();
+ let cursor: string | null = null;
+ try {
+ do {
+ const page: CodexModelListResponse = await host.request<CodexModelListResponse>(
+ Method.ModelList,
+ {
+ cursor,
+ limit: 100,
+ includeHidden: false,
+ },
+ { timeoutMs: CODEX_MODEL_LIST_RPC_TIMEOUT_MS },
+ );
+ models.push(...(Array.isArray(page.data) ? page.data : []));
+ const next: string | null = typeof page.nextCursor === 'string' && page.nextCursor.length > 0
+ ? page.nextCursor
+ : null;
+ if (next && seenCursors.has(next)) {
+ throw new Error(`Codex app-server model/list repeated cursor: ${next}`);
+ }
+ if (next) seenCursors.add(next);
+ cursor = next;
+ } while (cursor !== null);
+ } catch (error) {
+ if (credentialMode && error instanceof AppServerRequestTimeoutError) {
+ await this.retireHostKey(key, 'Codex control-plane model/list timed out', {
+ failIfActive: false,
+ logPrefix: 'codex model list refresh',
+ });
}
- if (next) seenCursors.add(next);
- cursor = next;
- } while (cursor !== null);
- } catch (error) {
- if (credentialMode && error instanceof AppServerRequestTimeoutError) {
- await this.retireHostKey(key, 'Codex control-plane model/list timed out', {
- failIfActive: false,
- logPrefix: 'codex model list refresh',
- });
+ throw error;
}
- throw error;
- }
- // Auth 切换 / logout 可能在分页请求期间 retire 旧 host。旧账号的迟到响应绝不能
- // 覆盖新账号目录;只有仍登记为当前 local host 的结果才允许交给宿主。
- if (this.hosts.get(key) !== host || !this.deps.onCodexLocalModelsListed) return false;
- if (options?.providerId) await this.deps.onCodexLocalModelsListed(models, options.providerId);
- else await this.deps.onCodexLocalModelsListed(models);
- return true;
+ // Auth 切换 / logout 可能在分页请求期间 retire 旧 host。旧账号的迟到响应绝不能
+ // 覆盖新账号目录;只有仍登记为当前 local host 的结果才允许交给宿主。
+ if (this.hosts.get(key) !== host || !this.deps.onCodexLocalModelsListed) return false;
+ if (options?.providerId) await this.deps.onCodexLocalModelsListed(models, options.providerId);
+ else await this.deps.onCodexLocalModelsListed(models);
+ return true;
+ });
}
/** Read ChatGPT subscription windows and banked reset credits via app-server RPC. */
@@ -2684,8 +2759,8 @@ export class CodexAgent extends BaseAgent {
// This RPC is credential-specific, unlike model/list or memory utilities. Requiring
// oauth-bearer prevents a gateway/provider host from reading or mutating the wrong
// account context; getHost refuses to replace a differently-authenticated active host.
- const host = await this.getStartedAccountHost(providerId);
- return await host.request<AccountRateLimitsResponse>(Method.AccountRateLimitsRead, undefined);
+ return this.withStartedAccountHost(providerId,
+ host => host.request<AccountRateLimitsResponse>(Method.AccountRateLimitsRead, undefined));
}
/** Consume one reset credit on the non-model app-server control plane. */
@@ -2693,11 +2768,8 @@ export class CodexAgent extends BaseAgent {
params: ConsumeAccountRateLimitResetCreditParams,
providerId?: string,
): Promise<ConsumeAccountRateLimitResetCreditResponse> {
- const host = await this.getStartedAccountHost(providerId);
- return await host.request<ConsumeAccountRateLimitResetCreditResponse>(
- Method.AccountRateLimitResetCreditConsume,
- params,
- );
+ return this.withStartedAccountHost(providerId,
+ host => host.request<ConsumeAccountRateLimitResetCreditResponse>(Method.AccountRateLimitResetCreditConsume, params));
}
private async createHost(
@@ -2954,9 +3026,10 @@ export class CodexAgent extends BaseAgent {
let tokens = await readAccountTokens();
assertCurrentGeneration('external authentication scope');
if (refresh && tokens.accessToken === staleAccessToken) {
- const accountHost = await this.getStartedAccountHost(providerId, 8_000);
- assertCurrentGeneration('account token refresh');
- await accountHost.request('account/read', { refreshToken: true }, { timeoutMs: 8_000 });
+ await this.withStartedAccountHost(providerId, async (accountHost) => {
+ assertCurrentGeneration('account token refresh');
+ await accountHost.request('account/read', { refreshToken: true }, { timeoutMs: 8_000 });
+ }, 8_000);
tokens = await readAccountTokens();
}
assertCurrentGeneration('external authentication result');
@@ -3117,9 +3190,12 @@ export class CodexAgent extends BaseAgent {
if (opts?.maxTokens !== undefined) {
log.warn(`maxTokens=${opts.maxTokens} ignored — Codex host protocol does not expose max_tokens`);
}
+ let releaseHost: (() => void) | undefined;
let subscription: ThreadSubscription | null = null;
try {
- const { host } = await this.getUtilityHost();
+ const leased = await this.acquireHostOperation(() => this.getUtilityHost());
+ releaseHost = leased.release;
+ const { host } = leased;
await host.ensureStarted();
// Host startup can await credential discovery and process readiness. The
@@ -3249,6 +3325,7 @@ export class CodexAgent extends BaseAgent {
throw new OneShotError('network', err instanceof Error ? err.message : String(err));
} finally {
try { await subscription?.release(); } catch { /* no-op */ }
+ releaseHost?.();
}
}
@@ -4705,7 +4782,10 @@ export class CodexAgent extends BaseAgent {
if (opts.remoteHostId) return await this.getHost(opts.remoteHostId, credentialMode);
// 本地会话先等已有 credential switch 完成,再占用 startup reservation。否则
// session 已拿到旧 host、但尚未 thread/start 订阅时,credential 切换看不到它。
- await this.waitForHostCredentialModeSwitch(currentHostKey);
+ do {
+ await this.waitForHostCredentialModeSwitch(currentHostKey);
+ } while (this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)
+ || this.hostCredentialModeSwitches.has(currentHostKey));
acquireHostBindingLeaseIfNeeded();
return await this.getHost(opts.remoteHostId, credentialMode, {
...(accountProviderId ? { providerId: accountProviderId } : {}),
@@ -14108,6 +14188,7 @@ export class CodexAgent extends BaseAgent {
// session 全部同时报错。fork 是离线控制面操作(不跑 turn、无订阅者),改用
// 唯一 key 的一次性 app-server:超限只让 fork 自己失败,不波及活跃任务。
const forkHostKey = forkAccountId ? `local-account:${forkAccountId}:${localForkHostKey()}` : localForkHostKey();
+ let releaseForkLease: (() => void) | undefined;
let forkHost: AppServerHost | undefined;
let forkHostRetired = false;
let stage: CodexForkStage = 'source-prepare';
@@ -14170,20 +14251,25 @@ export class CodexAgent extends BaseAgent {
const forkStorage = await this.deps.resolveCodexThreadStorage?.(opts.sourceSdkSessionId);
const forkSqliteHome = forkStorage?.sqliteHome;
stage = 'host-create';
- const host = await this.getHost(undefined, forkCredentialMode, {
- keyOverride: forkHostKey,
- ...(forkAccountId ? { providerId: forkAccountId } : {}),
- ...(forkSqliteHome ? { sqliteHome: forkSqliteHome } : {}),
- ...(forkStorage ? { historyHome: forkStorage.historyHome } : {}),
- hostPurpose: 'control-plane',
- }).catch((error) => {
- // This is the outgoing source's offline fork host, not a target send.
- // Missing old credentials must not trap a task on the provider it is leaving.
- if (opts.stripEncryptedReasoning && error instanceof AgentNotAuthenticatedError) {
- throw new CodexHistoryRecoveryRequiredError();
- }
- throw error;
+ const leased = await this.acquireHostOperation(async () => {
+ const host = await this.getHost(undefined, forkCredentialMode, {
+ keyOverride: forkHostKey,
+ ...(forkAccountId ? { providerId: forkAccountId } : {}),
+ ...(forkSqliteHome ? { sqliteHome: forkSqliteHome } : {}),
+ ...(forkStorage ? { historyHome: forkStorage.historyHome } : {}),
+ hostPurpose: 'control-plane',
+ }).catch((error) => {
+ // This is the outgoing source's offline fork host, not a target send.
+ // Missing old credentials must not trap a task on the provider it is leaving.
+ if (opts.stripEncryptedReasoning && error instanceof AgentNotAuthenticatedError) {
+ throw new CodexHistoryRecoveryRequiredError();
+ }
+ throw error;
+ });
+ return { key: forkHostKey, host };
});
+ const { host } = leased;
+ releaseForkLease = leased.release;
forkHost = host;
stage = 'host-start';
const initResp = await host.ensureStarted();
@@ -14306,17 +14392,21 @@ export class CodexAgent extends BaseAgent {
} finally {
// 一次性 host 用完即收,无论成败。key 唯一、无 session 绑定,
// retire 不会波及任何共享 host 或活跃会话。
- if (forkHost && !forkHostRetired) {
- // Unsubscribe is not a writer-release barrier. Never publish a
- // successful fork unless physical shutdown has been confirmed.
- await retireForkHost(true).catch((err) => {
- if (!operationFailed) throw new CodexForkError('host-retire', err);
- if (forkFailure) forkFailure.cleanupFailed = true;
- log.warn('fork host retire failed', {
- forkHostKey,
- err: err instanceof Error ? err.message : String(err),
+ try {
+ if (forkHost && !forkHostRetired) {
+ // Unsubscribe is not a writer-release barrier. Never publish a
+ // successful fork unless physical shutdown has been confirmed.
+ await retireForkHost(true).catch((err) => {
+ if (!operationFailed) throw new CodexForkError('host-retire', err);
+ if (forkFailure) forkFailure.cleanupFailed = true;
+ log.warn('fork host retire failed', {
+ forkHostKey,
+ err: err instanceof Error ? err.message : String(err),
+ });
});
- });
+ }
+ } finally {
+ releaseForkLease?.();
}
}
}
@@ -14583,25 +14673,26 @@ export class CodexAgent extends BaseAgent {
// config/read 返回的 effective config 已经把 in-memory enablement 合并进去了
// (config_processor.rs:99-110), 所以 setMemory 后立刻 read 也能看到新值
try {
- const { key, host } = await this.getUtilityHost();
- // app-server 重启后 in-memory enablement 会丢, server 端回到 config.toml 默认值 (memories=false);
- // 读之前先把 maker 端持久化的 memoryOverride 同步过去, 否则 Settings 界面显示的是 server 默认值,
- // 不是用户上次保存的设置。ensureMemoryOverridePushed 内部用 memoryOverridePushed 去重, 已 push 是 no-op。
- await host.ensureStarted();
- await this.ensureMemoryOverridePushed(host, key).catch((e) => {
- this.deps.logger.warn('codex.getMemoryStatus: ensureMemoryOverridePushed failed', {
- error: e instanceof Error ? e.message : String(e),
+ return await this.withHostOperation(() => this.getUtilityHost(), async (host, key) => {
+ // app-server 重启后 in-memory enablement 会丢, server 端回到 config.toml 默认值 (memories=false);
+ // 读之前先把 maker 端持久化的 memoryOverride 同步过去, 否则 Settings 界面显示的是 server 默认值,
+ // 不是用户上次保存的设置。ensureMemoryOverridePushed 内部用 memoryOverridePushed 去重, 已 push 是 no-op。
+ await host.ensureStarted();
+ await this.ensureMemoryOverridePushed(host, key).catch((e) => {
+ this.deps.logger.warn('codex.getMemoryStatus: ensureMemoryOverridePushed failed', {
+ error: e instanceof Error ? e.message : String(e),
+ });
});
+ type ConfigReadResp = { config?: { features?: { memories?: boolean } } };
+ const resp = await host.request<ConfigReadResp>(Method.ConfigRead, { includeLayers: false });
+ const enabled = resp.config?.features?.memories ?? false;
+ return {
+ enabled,
+ // memoryOverride 没设过时 enabled 来自 config.toml + server 默认, 算 'user-config';
+ // host 显式覆盖过算 'host-runtime'
+ source: this.memoryOverride === undefined ? 'user-config' : 'host-runtime',
+ };
});
- type ConfigReadResp = { config?: { features?: { memories?: boolean } } };
- const resp = await host.request<ConfigReadResp>(Method.ConfigRead, { includeLayers: false });
- const enabled = resp.config?.features?.memories ?? false;
- return {
- enabled,
- // memoryOverride 没设过时 enabled 来自 config.toml + server 默认, 算 'user-config';
- // host 显式覆盖过算 'host-runtime'
- source: this.memoryOverride === undefined ? 'user-config' : 'host-runtime',
- };
} catch (err) {
if (err instanceof AgentNotAuthenticatedError) {
// 未授权 → host 起不来, 报推断值 (codex 默认 false)
@@ -14618,6 +14709,8 @@ export class CodexAgent extends BaseAgent {
const log = this.deps.logger.child('codex/setMemory');
log.info('setMemory ▶', { from: this.memoryOverride, to: enabled });
this.memoryOverride = enabled;
+ // A refresh already owns admission; the replacement host will read this override.
+ if (this.hostCredentialModeSwitches.has(LOCAL_MCP_REFRESH_KEY)) return { effective: 'next-session' };
// 立即 push, 让所有 live thread 通过 server 端 reload_user_config 拿到新值
try {
const localSessionHosts = Array.from(this.hosts.entries()).filter(
@@ -14634,11 +14727,17 @@ export class CodexAgent extends BaseAgent {
await Promise.all(localSessionHosts.map(async ([key, host]) => {
// Only thread-serving local hosts receive Maker Memory. Remote hosts own
// their native setting; model-list control-plane hosts have no live threads.
- await host.request(Method.ExperimentalFeatureEnablementSet, {
- enablement: { memories: enabled },
- });
- this.memoryOverridePushedByHost.set(key, enabled);
- return key;
+ const generation = this.hostGenerations.get(key);
+ const release = this.acquireHostSessionBindingLease(key);
+ try {
+ await host.request(Method.ExperimentalFeatureEnablementSet, {
+ enablement: { memories: enabled },
+ });
+ this.memoryOverridePushedByHost.set(key, enabled);
+ return key;
+ } finally {
+ if (this.hostGenerations.get(key) === generation) release();
+ }
}));
log.info('setMemory ◀ pushed to app-server, hot-reloaded all live threads');
return { effective: 'immediate' };
@@ -14658,13 +14757,14 @@ export class CodexAgent extends BaseAgent {
async resetMemory(): Promise<MemoryResetResult> {
const log = this.deps.logger.child('codex/resetMemory');
log.info('resetMemory ▶');
- const { host } = await this.getUtilityHost();
- // server 端清 <CODEX_HOME>/memories/ 目录 + state_*.sqlite 的 memory stage 数据;
- // 不影响各 thread 的 memory_mode (用户随后改 thread/memoryMode/set 才动那个)
- await host.request(Method.MemoryReset, {});
- log.info('resetMemory ◀ ok');
- // server 不返回数量统计, removedEntries / removedBytes 留 undefined
- return {};
+ return this.withHostOperation(() => this.getUtilityHost(), async (host) => {
+ // server 端清 <CODEX_HOME>/memories/ 目录 + state_*.sqlite 的 memory stage 数据;
+ // 不影响各 thread 的 memory_mode (用户随后改 thread/memoryMode/set 才动那个)
+ await host.request(Method.MemoryReset, {});
+ log.info('resetMemory ◀ ok');
+ // server 不返回数量统计, removedEntries / removedBytes 留 undefined
+ return {};
+ });
}
/**