Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(model-access): 先保存新凭据并延后刷新忙碌进程
liugaowei671653d91dd7
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex f556c5229e..fded9bdfe6 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -32,6 +32,7 @@ describe('maker:event hot path ordering', () => {const cleared = vi.fn();const deps = {pendingCredentialSwitchHolder: null, deferredCodexRestartHolder: null,+ gatewayCodexRestartHolder: { onSessionSettled: vi.fn() },agentInputCoordinatorHolder: null,refreshRemoteCodexMcpOnTurnSettledHolder: () => { throw new Error('App session is switching'); },gitSnapshotCoordinator: { onSessionClosed: vi.fn() },@@ -45,6 +46,7 @@ describe('maker:event hot path ordering', () => {};const cleanup = new Function(...Object.keys(deps), `${js}; return cleanupClosedSessionRuntime;`)(...Object.values(deps));expect(() => cleanup({ id: 'departing-task' })).not.toThrow();+ expect(deps.gatewayCodexRestartHolder.onSessionSettled).toHaveBeenCalledOnce();expect(cleared).toHaveBeenCalledWith('departing-task');expect(deps.clearSessionPersistState).toHaveBeenCalledWith('departing-task');expect(deps.handleAgentIslandSessionClosedAfterCleanup).toHaveBeenCalledWith('departing-task', 'process-closed');diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 7d6a76647d..34648f8d62 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -47,7 +47,6 @@ import {CodexAgent,configureDefaultImageResizer,type AgentKind,- type AgentCredentialMode,type InteractionRequest,type AutoReviewDelegate,type McpProvider,@@ -594,6 +593,53 @@ export function setBeforeLocalCodexSessionStartHook(hook: (() => Promise<void>)_beforeLocalCodexSessionStartHook = hook;}+/** IPC owns the existing idle retry and input queue wake lifecycle. */+let _scheduleCodexGatewayKeyRefresh: (() => void) | null = null;+export function setCodexGatewayKeyRefreshHook(hook: () => void): void {+ _scheduleCodexGatewayKeyRefresh = hook;+ // Credential sync can precede IPC registration while utility hosts already+ // exist. Reconcile those consumers once when the idle retry service attaches.+ hook();+}++export function scheduleCodexGatewayKeyRefresh(): void {+ _scheduleCodexGatewayKeyRefresh?.();+}++export function listCodexGatewayHostKeys(): string[] {+ return _codexAgent?.getLocalHostKeysForCredentialMode('gateway-key') ?? [];+}++/** Refresh one gateway consumer after persistence, without changing OAuth state or other hosts. */+export async function refreshCodexGatewayHost(+ targetHostKey: string,+ stillValid: () => Promise<boolean>,+): Promise<void> {+ if (_codexCredentialChangeGuard) throw new CodexCredentialModeSwitchBusyError([]);+ const maker = _maker;+ const agent = _codexAgent;+ if (!maker || !agent) return;+ const guard = await agent.beginLocalHostCredentialChange('Cindy AI key changed', {+ allLocalHosts: true,+ credentialMode: 'gateway-key',+ targetHostKey,+ busyError: () => new CodexCredentialModeSwitchBusyError([]),+ });+ try {+ if (!await stillValid() || _maker !== maker || _codexAgent !== agent) return;+ await prepareLocalCodexCredentialModeSwitch({+ maker,+ isSessionInTurn,+ hostKeys: guard.affectedHostKeys.filter(key => agent.getLocalHostKeysForCredentialMode('gateway-key').includes(key)),+ });+ if (_maker !== maker || _codexAgent !== agent) return;+ guard.assertIdle();+ await guard.finalize();+ } finally {+ guard.release();+ }+}+// Process-lifetime IPC binding: its reconciler reads the dynamic Maker facade and// clears owner-scoped bookkeeping by epoch. Keep it across resetMaker; IPC is not// registered again after an account switch. MCP factories bind before it is ready.@@ -3236,7 +3282,7 @@ export async function waitForInitialCustomMcpRefresh(): Promise<void> {** null-safe: getMaker() 还没构造过 codexAgent 时直接 no-op (此时也没进程要收)。*/-export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: boolean; credentialMode?: AgentCredentialMode } = {}): Promise<void> {+export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: boolean } = {}): Promise<void> {if (_codexCredentialChangeGuard) {throw new Error('Codex credential mode change is already in progress');}@@ -3255,7 +3301,6 @@ export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: bawait prepareLocalCodexCredentialModeSwitch({maker,isSessionInTurn,- ...(options.credentialMode ? { hostKeys: guard?.affectedHostKeys ?? [] } : {}),});} catch (e) {desktopMakerLogger.warn(@@ -3313,7 +3358,7 @@ export function cancelCodexAuthModeChange(): void {guard?.release();}-export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvironment?: boolean; refreshAuthState?: boolean } = {}): Promise<void> {+export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvironment?: boolean } = {}): Promise<void> {// 只 dispose 本地 app-server, 让下一次本地 send 按新模式重新 spawn。// 远端 Codex host 使用远端 daemon / 远端用户配置,不能被本地 key / OAuth 变化误关。const guard = _codexCredentialChangeGuard;@@ -3340,10 +3385,8 @@ export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvi} else {await agent?.disposeLocalHostForCredentialChange();}- if (options.refreshAuthState !== false) {- clearCodexProxyAuthInjection();- await broadcastCodexRuntimeRoute();- }+ clearCodexProxyAuthInjection();+ await broadcastCodexRuntimeRoute();} catch (e) {desktopMakerLogger.warn('restartCodexAfterAuthModeChange: dispose threw', {error: e instanceof Error ? e.message : String(e),@@ -3351,8 +3394,6 @@ export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvithrow e;}}- // Gateway key rotation leaves OAuth state and unaffected hosts unchanged.- if (options.refreshAuthState === false) return;// proxy 路线: proxy 始终保活(两种 spawn 形态都依赖它), 仅在 app quit(bootstrap-electron onQuit)dispose。// codex 登录态变化只需上面 dispose codex agent 重 spawn —— 重 spawn 时按最新 OAuth 登录态冻结// authInjection(oauth-bearer / env-key), routingTransform 据此 + per-session 选择出路由。diff --git a/apps/desktop/src/main/maker-ipc/__tests__/gatewayCodexRestart.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/gatewayCodexRestart.test.tsnew file mode 100644index 0000000000..2126b00ad1--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/gatewayCodexRestart.test.ts@@ -0,0 +1,130 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { GatewayCodexRestartService } from '../gatewayCodexRestart.js';+import { CodexCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch.js';++beforeEach(() => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }));+afterEach(() => vi.useRealTimers());++function harness() {+ const busy = new Set<string>();+ const unavailable = new Set<string>();+ const keys = ['gateway-a', 'gateway-b'];+ const applied: string[] = [];+ const wake = vi.fn();+ const restart = vi.fn(async (key: string, stillValid: () => Promise<boolean>) => {+ if (unavailable.has(key)) throw new CodexCredentialModeSwitchBusyError([]);+ if (await stillValid()) applied.push(key);+ });+ const service = new GatewayCodexRestartService({+ listHostKeys: () => keys,+ hasBusySession: key => busy.has(key),+ listSessionIds: key => [`session-${key}`],+ restartHost: restart,+ onQueueGateReleased: wake,+ });+ return { service, busy, unavailable, keys, applied, wake, restart };+}++describe('gateway Codex deferred restart', () => {+ it('refreshes an idle host without waiting for a busy sibling', async () => {+ const h = harness();+ h.busy.add('gateway-a');+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.applied).toEqual(['gateway-b']);+ expect(h.service.isSessionRestarting('session-gateway-a')).toBe(false);+ h.busy.clear();+ h.service.onSessionSettled();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.applied).toEqual(['gateway-b', 'gateway-a']);+ expect(h.wake.mock.calls.flat(2)).toEqual(['session-gateway-b', 'session-gateway-a']);+ expect(vi.getTimerCount()).toBe(0);+ h.service.clear();+ });++ it.each(['startup', 'another-credential-change'])('retries after %s without losing the refresh', async () => {+ const h = harness();+ h.unavailable.add('gateway-a');+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.applied).toEqual(['gateway-b']);+ h.unavailable.clear();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(h.applied).toEqual(['gateway-b', 'gateway-a']);+ expect(vi.getTimerCount()).toBe(0);+ h.service.clear();+ });++ it('coalesces rotations while busy and refreshes on the next local start', async () => {+ const h = harness();+ h.busy.add('gateway-a');+ h.keys.splice(1);+ h.service.schedule();+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.restart).not.toHaveBeenCalled();+ h.busy.clear();+ await h.service.flushBeforeLocalCodexSessionStart();+ expect(h.applied).toEqual(['gateway-a']);+ expect(h.restart).toHaveBeenCalledOnce();+ h.service.clear();+ });++ it('releases only affected queues after a failed restart and retries', async () => {+ const h = harness();+ let finish!: () => void;+ h.restart.mockImplementationOnce(async () => {+ await new Promise<void>(resolve => { finish = resolve; });+ throw new Error('retirement failed');+ });+ h.keys.splice(1);+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.service.isSessionRestarting('session-gateway-a')).toBe(true);+ expect(h.service.isSessionRestarting('session-oauth')).toBe(false);+ finish();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.service.isSessionRestarting('session-gateway-a')).toBe(false);+ expect(h.wake).toHaveBeenCalledWith(['session-gateway-a']);+ await vi.advanceTimersByTimeAsync(10_000);+ expect(h.applied).toEqual(['gateway-a']);+ h.service.clear();+ });++ it('discards a queued old-owner restart before closing any new-owner sessions', async () => {+ const h = harness();+ let finish!: () => void;+ h.restart.mockImplementationOnce(async (key, stillValid) => {+ await new Promise<void>(resolve => { finish = resolve; });+ if (await stillValid()) h.applied.push(key);+ });+ h.keys.splice(1);+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ h.service.clear();+ finish();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(h.applied).toEqual([]);+ expect(h.wake).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('preserves a rotation arriving while the previous restart is completing', async () => {+ const h = harness();+ let finish!: () => void;+ h.keys.splice(1);+ h.restart.mockImplementationOnce(async (key, stillValid) => {+ if (!await stillValid()) return;+ await new Promise<void>(resolve => { finish = resolve; });+ h.applied.push(key);+ });+ h.service.schedule();+ await vi.advanceTimersByTimeAsync(0);+ h.service.schedule();+ finish();+ await vi.advanceTimersByTimeAsync(10_000);+ expect(h.applied).toEqual(['gateway-a', 'gateway-a']);+ expect(vi.getTimerCount()).toBe(0);+ h.service.clear();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/gatewayCodexRestart.ts b/apps/desktop/src/main/maker-ipc/gatewayCodexRestart.tsnew file mode 100644index 0000000000..9d1501c5bc--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/gatewayCodexRestart.ts@@ -0,0 +1,57 @@+import { DeferredCodexRestartService, type DeferredCodexRestartDeps } from './deferredCodexRestart.js';++export interface GatewayCodexRestartDeps {+ listHostKeys(): string[];+ restartHost(hostKey: string, stillValid: () => Promise<boolean>): Promise<void>;+ hasBusySession(hostKey: string): boolean;+ listSessionIds(hostKey: string): string[];+ onQueueGateReleased: NonNullable<DeferredCodexRestartDeps['onQueueGateReleased']>;+ logger?: DeferredCodexRestartDeps['logger'];+}++/** Reuse idle retry per gateway host so one busy host cannot delay other consumers. */+export class GatewayCodexRestartService {+ private readonly hosts = new Map<string, DeferredCodexRestartService>();++ constructor(private readonly deps: GatewayCodexRestartDeps) {}++ schedule(): void {+ for (const [key, service] of this.hosts) {+ if (!service.isPending()) this.hosts.delete(key);+ }+ for (const key of this.deps.listHostKeys()) {+ let service = this.hosts.get(key);+ if (!service) {+ service = new DeferredCodexRestartService({+ restart: (stillValid) => this.deps.restartHost(key, stillValid),+ hasBusyLocalCodexSession: () => this.deps.hasBusySession(key),+ listLocalCodexSessionIds: () => this.deps.listSessionIds(key),+ onQueueGateReleased: this.deps.onQueueGateReleased,+ logger: this.deps.logger,+ });+ this.hosts.set(key, service);+ }+ service.schedule('Cindy AI key changed');+ }+ // Keep credential persistence independent of host coordination. The caller+ // commits the matching endpoint before the guarded asynchronous refresh.+ queueMicrotask(() => this.onSessionSettled());+ }++ onSessionSettled(): void {+ for (const service of this.hosts.values()) service.onSessionSettled();+ }++ async flushBeforeLocalCodexSessionStart(): Promise<void> {+ await Promise.all([...this.hosts.values()].map(service => service.flushBeforeLocalCodexSessionStart()));+ }++ isSessionRestarting(sessionId: string): boolean {+ return [...this.hosts.values()].some(service => service.isSessionRestarting(sessionId));+ }++ clear(): void {+ for (const service of this.hosts.values()) service.clear();+ this.hosts.clear();+ }+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 33f6588fc9..88b233f9b7 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -599,6 +599,9 @@ import {ensureCodexMcpBridgeStartedForRemote,finalizeCodexAfterAuthModeChange,getMaker,+ listCodexGatewayHostKeys,+ refreshCodexGatewayHost,+ setCodexGatewayKeyRefreshHook,listSshCodexProviders,disposeRemoteCodexHostAfterRestart,getMakerIfReady,@@ -1210,6 +1213,7 @@ import {runMemoryChangeWithCodexRestart,type MemoryChangeParts,} from './deferredCodexRestart.js';+import { GatewayCodexRestartService } from './gatewayCodexRestart.js';import {createDeferredRestartSettledWake,createDeferredRestartQueueGate,@@ -4034,6 +4038,7 @@ function settlePendingCredentialSwitch(sessionId: string, source: string): void// 路径经 holder 调用; 未注入时 no-op。let refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null = null;let deferredCodexRestartHolder: DeferredCodexRestartService | null = null;+let gatewayCodexRestartHolder: GatewayCodexRestartService | null = null;let pendingAgentSwitchApplyHolder:((sessionId: string,@@ -4267,6 +4272,7 @@ export function isSessionTurnPendingCompletion(sessionId: string): boolean {*/export function clearDeferredCodexRestartForOwnerBoundary(): void {deferredCodexRestartHolder?.clear();+ gatewayCodexRestartHolder?.clear();}/** Reuse the owner-scoped idle retry for settings whose persistence already succeeded. */@@ -5086,6 +5092,7 @@ async function settleSilentStopDone(settlePendingCredentialSwitch(sessionId, `silent-stop:${reason}`);settlePendingSessionRuntimeControlHolder?.(sessionId, `silent-stop:${reason}`);deferredCodexRestartHolder?.onSessionSettled();+ gatewayCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);fireSilentStopSettled(sessionId, reason);@@ -5410,6 +5417,7 @@ function cleanupClosedSessionRuntime(session: WiredSession): void {// 会话关闭:兑现延迟凭证切换(直接写 route),并唤醒被它挡住的等待者。pendingCredentialSwitchHolder?.onSessionClosed(session.id);deferredCodexRestartHolder?.onSessionSettled();+ gatewayCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);try {refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);@@ -5567,6 +5575,9 @@ const sessionEventDependencies: SessionEventDependencies = {get deferredCodexRestartHolder() {return deferredCodexRestartHolder;},+ get gatewayCodexRestartHolder() {+ return gatewayCodexRestartHolder;+ },get refreshRemoteCodexMcpOnTurnSettledHolder() {return refreshRemoteCodexMcpOnTurnSettledHolder;},@@ -16860,6 +16871,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);settlePendingSessionRuntimeControlHolder?.(sessionId, `reconcile:${source}`);deferredCodexRestartHolder?.onSessionSettled();+ gatewayCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);} catch (err) {@@ -16924,6 +16936,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);settlePendingSessionRuntimeControlHolder?.(sessionId, `reconcile:${source}`);deferredCodexRestartHolder?.onSessionSettled();+ gatewayCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);} catch (err) {@@ -17766,7 +17779,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)hasPendingCredentialSwitchEntry: (sessionId) =>pendingCredentialSwitchHolder?.has(sessionId) === true,isSessionRestarting: (sessionId) =>- deferredCodexRestartHolder?.isSessionRestarting(sessionId) === true,+ deferredCodexRestartHolder?.isSessionRestarting(sessionId) === true ||+ gatewayCodexRestartHolder?.isSessionRestarting(sessionId) === true,}),emitProjection: (projection) => {broadcastToAllWindows(MAKER_PUSH.INPUT_PROJECTION, projection);@@ -18146,11 +18160,28 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)logger: log,});deferredCodexRestartHolder = deferredCodexRestartService;+ const gatewayCodexRestartService = new GatewayCodexRestartService({+ listHostKeys: listCodexGatewayHostKeys,+ restartHost: refreshCodexGatewayHost,+ hasBusySession: (hostKey) => maker.listActiveSessions().some(session =>+ session.agentKind === 'codex' && !session.remoteHostId &&+ (session.codexHostKey ?? 'local') === hostKey && isLocalSessionBusy(session, isSessionInTurn)),+ listSessionIds: (hostKey) => maker.listActiveSessions().filter(session =>+ session.agentKind === 'codex' && !session.remoteHostId &&+ (session.codexHostKey ?? 'local') === hostKey).map(session => session.id),+ onQueueGateReleased: createDeferredRestartSettledWake({+ wakeSession: (sessionId, reason) => inputCoordinator.wakeSession(sessionId, reason),+ }),+ logger: log,+ });+ gatewayCodexRestartHolder = gatewayCodexRestartService;+ setCodexGatewayKeyRefreshHook(() => gatewayCodexRestartService.schedule());// 新本地 Codex 会话加入 shared host 前先尝试兑现 pending 的延迟重启,// 让它直接在新状态的 fresh host 上起跑(maker-host onBeforeStart 接线)。- setBeforeLocalCodexSessionStartHook(() =>- deferredCodexRestartService.flushBeforeLocalCodexSessionStart(),- );+ setBeforeLocalCodexSessionStartHook(async () => {+ await gatewayCodexRestartService.flushBeforeLocalCodexSessionStart();+ await deferredCodexRestartService.flushBeforeLocalCodexSessionStart();+ });const requireSessionId = (value: unknown): string => {if (typeof value !== 'string' || value.length === 0) {diff --git a/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts b/apps/desktop/src/main/maker-ipc/sessionEventDelivery.tsindex 41392094ee..4e6c09448d 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventDelivery.ts@@ -52,6 +52,7 @@ export interface DeliverSessionEventDeps {readonly settlePendingSessionRuntimeControlHolder:((sessionId: string, reason: string) => void) | null;readonly deferredCodexRestartHolder: Pick<DeferredCodexRestartService, 'onSessionSettled'> | null;+ readonly gatewayCodexRestartHolder?: Pick<DeferredCodexRestartService, 'onSessionSettled'> | null;readonly refreshRemoteCodexMcpOnTurnSettledHolder: ((sessionId: string) => void) | null;readonly markTurnEndedAfterPersistDrain: (sessionId: string) => void;readonly gitSnapshotCoordinator: Pick<GitSnapshotCoordinator, 'onTurnEnd' | 'onTurnAbort'> | null;@@ -161,6 +162,7 @@ export function deliverSessionEvent(deps.settlePendingCredentialSwitch(session.id, `event:${event.type}`);deps.settlePendingSessionRuntimeControlHolder?.(session.id, `event:${event.type}`);deps.deferredCodexRestartHolder?.onSessionSettled();+ deps.gatewayCodexRestartHolder?.onSessionSettled();deps.agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);deps.refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);} else if (shouldMarkTurnStatusIdleAfterBroadcast) {diff --git a/apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.tsindex 3425142198..445087fc34 100644--- a/apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts+++ b/apps/desktop/src/main/model-access/__tests__/gatewayKeyRotation.test.ts@@ -2,7 +2,12 @@ import { readFileSync } from 'node:fs';import path from 'node:path';import vm from 'node:vm';import ts from 'typescript';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { GatewayCodexRestartService } from '../../maker-ipc/gatewayCodexRestart.js';+import { CodexCredentialModeSwitchBusyError } from '../../maker-host/codex-credential-switch.js';++beforeEach(() => vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }));+afterEach(() => vi.useRealTimers());// Execute the production writer with boundary/IO fixtures, without initializing// Electron or the model catalog. No copied implementation or source assertions.@@ -10,50 +15,43 @@ const source = ts.createSourceFile('index.ts', readFileSync(path.resolve(__dirnaconst writer = source.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === 'writeXdKeyWithCodexSideEffect')!;const compiled = ts.transpileModule(writer.getText(source), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;-function harness() {+function harness(schedule = vi.fn(), beforeStore = () => {}) {const owner = { scope: 'cloud:account-a:1', pending: false };- const prepare = vi.fn(async () => {});- const cancel = vi.fn();- const finalize = vi.fn(async () => {});const write = vi.fn(() => true);const notify = vi.fn();const context = vm.createContext({activeOwnerScopeKey: () => owner.scope,isAppSessionBoundaryPending: () => owner.pending,- prepareCodexForAuthModeChange: prepare,- cancelCodexAuthModeChange: cancel,- finalizeCodexAfterAuthModeChange: finalize,- getProviderSecretStore: () => ({ set: write }),+ scheduleCodexGatewayKeyRefresh: schedule,+ getProviderSecretStore: () => { beforeStore(); return { set: write }; },notifyXdProviderKeyChanged: notify,log: { warn: vi.fn() },});const rotate = vm.runInContext(`${compiled}\nwriteXdKeyWithCodexSideEffect`, context) as (key: string) => Promise<boolean>;- return { owner, prepare, cancel, finalize, write, notify, rotate };+ return { owner, schedule, write, notify, rotate };}describe('gateway key rotation writer', () => {- it('coordinates every gateway host before writing and leaves OAuth state unchanged', async () => {+ it('saves the key synchronously before scheduling gateway host refresh', async () => {const h = harness();- h.prepare.mockImplementation(async () => { expect(h.write).not.toHaveBeenCalled(); });- expect(await h.rotate('invalid-test-key')).toBe(true);- expect(h.prepare).toHaveBeenCalledExactlyOnceWith({ allLocalHosts: true, credentialMode: 'gateway-key' });+ h.schedule.mockImplementation(() => { expect(h.write).toHaveBeenCalledOnce(); });+ const result = h.rotate('invalid-test-key');expect(h.write).toHaveBeenCalledExactlyOnceWith('xd', 'invalid-test-key');+ expect(await result).toBe(true);expect(h.notify).toHaveBeenCalledOnce();- expect(h.finalize).toHaveBeenCalledExactlyOnceWith({ refreshAuthState: false });- expect(h.cancel).not.toHaveBeenCalled();+ expect(h.schedule).toHaveBeenCalledOnce();});it('does not start a rotation during account handoff', async () => {const h = harness();h.owner.pending = true;expect(await h.rotate('invalid-test-key')).toBe(false);- expect(h.prepare).not.toHaveBeenCalled();+ expect(h.schedule).not.toHaveBeenCalled();expect(h.write).not.toHaveBeenCalled();});- it.each(['different-owner', 'same-owner-new-generation', 'handoff-pending'])('discards stale credentials after preparation: %s', async change => {- const h = harness();- h.prepare.mockImplementation(async () => {+ it.each(['different-owner', 'same-owner-new-generation', 'handoff-pending'])('does not write across an owner boundary: %s', async change => {+ const h = harness(vi.fn(), () => {if (change === 'different-owner') h.owner.scope = 'cloud:account-b:2';if (change === 'same-owner-new-generation') h.owner.scope = 'cloud:account-a:3';if (change === 'handoff-pending') h.owner.pending = true;@@ -61,24 +59,46 @@ describe('gateway key rotation writer', () => {expect(await h.rotate('invalid-account-a-key')).toBe(false);expect(h.write).not.toHaveBeenCalled();expect(h.notify).not.toHaveBeenCalled();- expect(h.finalize).not.toHaveBeenCalled();- expect(h.cancel).toHaveBeenCalledOnce();+ expect(h.schedule).not.toHaveBeenCalled();});- it('preserves the stored key when the target host is busy', async () => {- const h = harness();- h.prepare.mockRejectedValue(new Error('busy'));- expect(await h.rotate('invalid-test-key')).toBe(false);- expect(h.write).not.toHaveBeenCalled();- expect(h.finalize).not.toHaveBeenCalled();+ it.each(['busy', 'starting', 'credential change in progress'])('still saves the key when host refresh is deferred: %s', async reason => {+ let blocked = true;+ const restarted = vi.fn();+ const service = new GatewayCodexRestartService({+ listHostKeys: () => ['gateway'],+ hasBusySession: () => reason === 'busy' && blocked,+ listSessionIds: () => ['gateway-session'],+ restartHost: async (_key, stillValid) => {+ if (blocked) throw new CodexCredentialModeSwitchBusyError([]);+ if (await stillValid()) restarted();+ },+ onQueueGateReleased: vi.fn(),+ });+ const h = harness(vi.fn(() => service.schedule()));+ try {+ expect(await h.rotate('invalid-new-key')).toBe(true);+ expect(h.write).toHaveBeenCalledExactlyOnceWith('xd', 'invalid-new-key');+ await vi.advanceTimersByTimeAsync(10_000);+ expect(restarted).not.toHaveBeenCalled();+ blocked = false;+ service.onSessionSettled();+ await vi.advanceTimersByTimeAsync(0);+ expect(restarted).toHaveBeenCalledOnce();+ } finally { service.clear(); }+ });++ it('keeps the successful write result if restart scheduling fails', async () => {+ const h = harness(vi.fn(() => { throw new Error('host unavailable'); }));+ expect(await h.rotate('invalid-test-key')).toBe(true);+ expect(h.write).toHaveBeenCalledOnce();});- it('releases the guard when credential storage rejects the write', async () => {+ it('does not schedule a restart when credential storage rejects the write', async () => {const h = harness();h.write.mockReturnValue(false);expect(await h.rotate('invalid-test-key')).toBe(false);- expect(h.cancel).toHaveBeenCalledOnce();expect(h.notify).not.toHaveBeenCalled();- expect(h.finalize).not.toHaveBeenCalled();+ expect(h.schedule).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex 1aae0ab7ff..1e31991536 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -14,7 +14,7 @@ import { serverApiFetch, ServerApiError } from '../serverApiClient.js';import { getClientEndpoint } from '../clientEndpointsService.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';import {- prepareCodexForAuthModeChange,+ scheduleCodexGatewayKeyRefresh,prepareCodexForCustomProviderHostChange,finalizeCodexAfterAuthModeChange,cancelCodexAuthModeChange,@@ -68,9 +68,8 @@ const log = createLogger('modelAccess');* 自动触发同步,登出复位;* - serverApiFetch + 独立 base(clientEndpoints 'modelAccessApiBaseUrl'):* 自动带 Bearer access token + 401 refresh;- * - providerSecretStore('xd')写 key,值变化时复用 codex env-key 重启副作用- * (与 safe-storage IPC 层同一套 prepare/finalize,见 bootstrap-electron 注释)- * ——main 侧自动写 key 的副作用缺口在此补齐(providerSecretStore.ts 顶注预告过);+ * - providerSecretStore('xd')先写 key,再按 host 实际凭据登记 Codex 刷新;+ * 忙碌或启动中的 gateway host 通过既有空闲重试机制兑现,不阻塞凭据保存;* - 状态经 MODEL_ACCESS_STATUS_CHANNEL 推给所有窗口,IPC 提供* get-status / retry / rotate 三个通道(仅本机设置页使用,不进 device-link* allowlist)。@@ -101,35 +100,24 @@ function rotateCredentials(): Promise<CredentialsPayload> {/*** 写 XD key(main 侧自动下发路径),带 codex env-key 重启副作用:* env-key spawn 的 codex app-server 把 gateway key 冻在子进程 env 里,写盘后- * 必须重建才生效——与 renderer 手填走的 safe-storage IPC 同一套语义。- * 按 host 的实际凭据筛选,覆盖不登记共享 proxy 状态的独立 session。+ * 必须重建才生效。服务端可能已经撤销旧 key,不能因进程忙碌而拒绝保存新 key。+ * 写入同步完成,相关 host 的刷新独立登记,忙碌或启动中的 host 延后到空闲。*/async function writeXdKeyWithCodexSideEffect(key: string): Promise<boolean> {if (isAppSessionBoundaryPending()) return false;const ownerScope = activeOwnerScopeKey();- try {- await prepareCodexForAuthModeChange({ allLocalHosts: true, credentialMode: 'gateway-key' });- } catch (err) {- log.warn('prepare codex before auto key write failed', {- error: err instanceof Error ? err.message : String(err),- });- return false;- }+ const store = getProviderSecretStore();if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) {- cancelCodexAuthModeChange();- return false;- }- const ok = getProviderSecretStore().set('xd', key);- if (!ok) {- cancelCodexAuthModeChange();return false;}+ const ok = store.set('xd', key);+ if (!ok) return false;notifyXdProviderKeyChanged();try {- await finalizeCodexAfterAuthModeChange({ refreshAuthState: false });+ scheduleCodexGatewayKeyRefresh();} catch (err) {- // key 已写盘(新值有效);codex 重建失败只记日志,下次 spawn 自然用新 key。- log.warn('finalize codex after auto key write failed', {+ // 已保存的 key 供所有现读调用方使用,不能把进程刷新失败伪报为存储失败。+ log.warn('schedule codex refresh after auto key write failed', {error: err instanceof Error ? err.message : String(err),});}diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 4429147232..743c44adbd 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -1094,6 +1094,7 @@ describe('CodexAgent spawn configuration', () => {const session = await agent.startSession({ sessionId: 'gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });const original = createdTransports[0];expect(createdStdioOptions[0].env?.XDT_CODEX_API_KEY).toBe(key);+ key = 'test-new-gateway-key';const guard = await agent.beginLocalHostCredentialChange('gateway key rotation', {allLocalHosts: true, credentialMode: 'gateway-key',});@@ -1104,7 +1105,6 @@ describe('CodexAgent spawn configuration', () => {guard.assertIdle();await guard.retireActiveHost();expect(original.closed).toBe(true);- key = 'test-new-gateway-key';await guard.finalize();} finally { guard.release(); }const restored = await agent.startSession({ sessionId: 'gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo', resumeSessionId: session.id });@@ -1152,7 +1152,34 @@ describe('CodexAgent spawn configuration', () => {} finally { await agent.dispose(); }});- it('defers gateway key rotation while an isolated host is starting', async () => {+ it('retires only the selected gateway host while another gateway host remains active', async () => {+ const deps = createDeps({}, {+ resolveCodexLocalAuthPolicy: () => 'isolated',+ resolveCodexThreadContextWindow: () => 700_000,+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),+ });+ deps.auth.getState = async () => ({ authenticated: true, authSource: 'api-key' });+ const agent = new CodexAgent(deps);+ try {+ const first = await agent.startSession({ sessionId: 'first-gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });+ const second = await agent.startSession({ sessionId: 'second-gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });+ expect(agent.getLocalHostKeysForCredentialMode('gateway-key')).toEqual([first.codexHostKey, second.codexHostKey]);+ const guard = await agent.beginLocalHostCredentialChange('saved gateway key', {+ allLocalHosts: true, credentialMode: 'gateway-key', targetHostKey: first.codexHostKey,+ });+ try {+ expect(guard.affectedHostKeys).toEqual([first.codexHostKey]);+ await first.close();+ guard.assertIdle();+ await guard.finalize();+ expect(createdTransports[0].closed).toBe(true);+ expect(createdTransports[1].closed).toBe(false);+ } finally { guard.release(); }+ await second.close();+ } finally { await agent.dispose(); }+ });++ it('defers gateway host retirement while an isolated host is starting', async () => {const started = deferred<void>();const finish = deferred<void>();const agent = new CodexAgent(createDeps({}, {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 516f16895a..4a37f8aa67 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2327,9 +2327,24 @@ export class CodexAgent extends BaseAgent {}}+ /** Current local consumers, including unresolved startup which may freeze this credential. */+ getLocalHostKeysForCredentialMode(credentialMode?: AgentCredentialMode): string[] {+ return [...new Set([+ ...this.hosts.keys(), ...this.hostPromises.keys(),+ ...this.hostSessionBindingLeases.keys(), ...this.retiringHosts.keys(),+ ])].filter((candidate) => {+ if (candidate.startsWith('remote:')) return false;+ if (!credentialMode) return true;+ const mode = this.hostEffectiveCredentialModes.get(candidate)+ ?? this.hostCredentialModes.get(candidate)+ ?? this.hostPromises.get(candidate)?.credentialMode;+ return mode === undefined || mode === credentialMode;+ });+ }+async beginLocalHostCredentialChange(reason = 'CodexAgent local credential state changed',- options: { allLocalHosts?: boolean; credentialMode?: AgentCredentialMode; forceRetire?: boolean; busyError?: () => Error } = {},+ options: { allLocalHosts?: boolean; credentialMode?: AgentCredentialMode; targetHostKey?: string; forceRetire?: boolean; busyError?: () => Error } = {},): Promise<{affectedHostKeys: readonly string[];assertIdle(): void;@@ -2368,18 +2383,8 @@ export class CodexAgent extends BaseAgent {};const affectedKeys = (): string[] => options.allLocalHosts- ? [...new Set([- ...this.hosts.keys(), ...this.hostPromises.keys(),- ...this.hostSessionBindingLeases.keys(), ...this.retiringHosts.keys(),- ])].filter((candidate) => {- if (candidate.startsWith('remote:')) return false;- if (!options.credentialMode) return true;- const mode = this.hostEffectiveCredentialModes.get(candidate)- ?? this.hostCredentialModes.get(candidate)- ?? this.hostPromises.get(candidate)?.credentialMode;- // Unresolved startup may still freeze the credential being replaced.- return mode === undefined || mode === options.credentialMode;- })+ ? this.getLocalHostKeysForCredentialMode(options.credentialMode)+ .filter((candidate) => options.targetHostKey === undefined || candidate === options.targetHostKey): [key];const activeUseCount = (): number => affectedKeys().reduce((count, candidate) => {const host = this.hosts.get(candidate);