Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): safely rebuild Codex thread across credential providers (#3586)
Chris Zhang2a1dd0849d0b
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsindex 003983d72e..ab3934b9e6 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@ -300,6 +300,70 @@ describe('session runtime control wiring', () => {expect(setModel).toContain('return withSendToSessionLock(sessionId, applyLocked);');});+ it('maps every Codex relink failure to the structured IPC error protocol', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const relinkBoundary = setModel.slice(+ setModel.indexOf('const relinkCodexThread ='),+ setModel.indexOf('const rebuildLiveOrcaWorker'),+ );+ expect(relinkBoundary).toContain(+ "throwIpcError(\n 'PRECONDITION_FAILED'",+ );+ expect(relinkBoundary).toContain('.catch((error) => {');+ expect(relinkBoundary).toContain('reserveCodexForkCleanup(');+ expect(relinkBoundary).toContain('...(cleanup ? { cleanup } : {})');+ expect(relinkBoundary).toContain('if (isIpcError(error)) throw error;');+ expect(relinkBoundary).toContain(+ "throwIpcError('INTERNAL', 'Failed to rebuild Codex provider thread')",+ );+ expect(relinkBoundary).not.toContain('throw new Error');+ });++ it('relinks legacy provider selections with the persisted effort and Fast axes', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const targetRoute = setModel.slice(+ setModel.indexOf('const targetCodexRoute:'),+ setModel.indexOf('const relinkCodexThread ='),+ );+ expect(targetRoute).toContain('requiresCodexThreadRelink');+ expect(targetRoute).toContain('? {');+ expect(targetRoute).toContain(+ 'effort: atomicSelection ? atomicSelection.effort : runtimeStatus.effort',+ );+ expect(targetRoute).toContain(+ 'fastMode: atomicSelection ? atomicSelection.fastMode : runtimeStatus.fastMode',+ );+ expect(targetRoute).not.toContain('requiresCodexThreadRelink && atomicSelection');+ });++ it('derives the Codex relink boundary from effective credential identities', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const relinkGate = setModel.slice(+ setModel.indexOf('const hasPersistedLocalCodexThread ='),+ setModel.indexOf('const targetCodexRoute:'),+ );+ expect(relinkGate).toContain('decideCodexProviderThreadRelink(');+ expect(relinkGate).toContain(+ '{ model: runtimeStatus.model, providerId: runtimeStatus.providerId }',+ );+ expect(relinkGate).toContain('{ model, providerId: targetProviderId }');+ expect(relinkGate).toContain("relinkDecision === 'unresolved'");+ expect(relinkGate).toContain("relinkDecision === 'relink'");+ expect(relinkGate).toContain("throwIpcError(\n 'PRECONDITION_FAILED'");+ });+it('rejects terminal tasks before effort or Fast mutations recreate runtime state', () => {const effort = handlerBody(registerSource,diff --git a/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts b/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.tsindex 5ce16f6c51..dd00088f6c 100644--- a/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/importSharedCodexThread.test.ts@@ -21,6 +21,7 @@ vi.mock('../../logger.js', () => ({import {importSharedCodexThread,removeSharedCodexThread,+ reserveCodexForkCleanup,} from '../codex-local-sessions';const THREAD_ID = '019dcd5a-6e54-7960-95e0-aa68117a28f1';@@ -254,4 +255,31 @@ describe('importSharedCodexThread', () => {expect(db.prepare('SELECT COUNT(*) AS n FROM thread_dynamic_tools').get()).toEqual({ n: 0 });db.close();});++ it('removes only the exact reserved fork rollout and state rows', async () => {+ const sourceThreadId = '019dcd5a-6e54-7960-95e0-aa68117a28f2';+ const rolloutPath = path.join(+ codexHome,+ 'sessions',+ '2026',+ '08',+ '29',+ `rollout-2026-08-29T00-00-00-${THREAD_ID}.jsonl`,+ );+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });+ fs.writeFileSync(rolloutPath, '{"type":"session_meta"}\n');+ const db = new Database(stateDbPath);+ db.prepare('INSERT INTO threads (id, rollout_path) VALUES (?, ?)').run(THREAD_ID, rolloutPath);+ db.prepare('INSERT INTO thread_dynamic_tools (thread_id, tool_name) VALUES (?, ?)')+ .run(THREAD_ID, 'browser');+ db.close();++ const reservation = reserveCodexForkCleanup(THREAD_ID, sourceThreadId);+ expect(reservation).not.toBeNull();+ await reservation!();++ expect(fs.existsSync(rolloutPath)).toBe(false);+ expect(desktopThreadExists(THREAD_ID)).toBe(false);+ expect(reserveCodexForkCleanup(sourceThreadId, sourceThreadId)).toBeNull();+ });});diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.tsindex eef63dcde0..02eb637716 100644--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts@@ -1564,6 +1564,68 @@ export async function dumpCodexThreadStateRows(threadId: string): Promise<CodexTreturn dump;}+/** Capture only a newly forked thread's exact private DB row and rollout identity. */+export function reserveCodexForkCleanup(+ threadId: string,+ sourceThreadId: string,+): (() => Promise<void>) | null {+ if (!isLikelyThreadId(threadId) || threadId === sourceThreadId) return null;+ const home = getDesktopCodexHome();+ const stateDbPath = findLatestStateDb(home);+ if (!stateDbPath || !isPathInside(home, stateDbPath)) return null;+ const row = readRawThreadRow(stateDbPath, threadId);+ const rolloutPath = stringValue(row?.rollout_path);+ if (+ !rolloutPath ||+ !isPathInside(home, rolloutPath) ||+ threadIdFromRolloutPath(rolloutPath) !== threadId+ ) return null;+ try {+ const stateDb = fs.lstatSync(stateDbPath);+ const rollout = fs.lstatSync(rolloutPath);+ if (!stateDb.isFile() || !rollout.isFile()) return null;+ return async () => {+ let db: Database.Database | null = null;+ try {+ const currentDb = fs.lstatSync(stateDbPath);+ const currentRollout = fs.lstatSync(rolloutPath);+ if (+ !currentDb.isFile() || currentDb.dev !== stateDb.dev || currentDb.ino !== stateDb.ino ||+ !currentRollout.isFile() || currentRollout.dev !== rollout.dev || currentRollout.ino !== rollout.ino+ ) return;+ db = createBetterSqliteDatabase(stateDbPath);+ db.pragma(`busy_timeout = ${SQLITE_BUSY_TIMEOUT_MS}`);+ const targetDb = db;+ let stateRemoved = false;+ targetDb.transaction(() => {+ const current = targetDb.prepare('SELECT rollout_path FROM threads WHERE id = ? LIMIT 1')+ .get(threadId) as { rollout_path?: string } | undefined;+ if (current?.rollout_path !== rolloutPath) return;+ if (tableExists(targetDb, 'thread_dynamic_tools')) {+ targetDb.prepare('DELETE FROM thread_dynamic_tools WHERE thread_id = ?').run(threadId);+ }+ if (tableExists(targetDb, 'thread_spawn_edges')) {+ targetDb.prepare('DELETE FROM thread_spawn_edges WHERE parent_thread_id = ?').run(threadId);+ }+ stateRemoved = targetDb.prepare('DELETE FROM threads WHERE id = ? AND rollout_path = ?')+ .run(threadId, rolloutPath).changes > 0;+ })();+ if (stateRemoved) await fsp.rm(rolloutPath, { force: true });+ } catch (error) {+ log.warn('forked Codex thread cleanup failed', {+ threadId,+ error: error instanceof Error ? error.message : String(error),+ });+ throw error;+ } finally {+ closeDbQuietly(db);+ }+ };+ } catch {+ return null;+ }+}+/** 只读取一个 state DB 里该 thread 的三表行并转成 JSON 可序列化形态。 */function readThreadStateRows(dbPath: string,diff --git a/apps/desktop/src/main/maker-ipc/__tests__/codexProviderThreadRelink.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/codexProviderThreadRelink.test.tsnew file mode 100644index 0000000000..85c81ad3eb--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/codexProviderThreadRelink.test.ts@@ -0,0 +1,174 @@+import { describe, expect, it, vi } from 'vitest';++import {+ decideCodexProviderThreadRelink,+ isXdOpenAiCodexProviderTransition,+ relinkCodexProviderThread,+} from '../codexProviderThreadRelink.js';++const source = {+ sdkSessionId: 'thread-xd',+ workingDir: '/work',+ model: 'codex/gpt-5.6-sol',+ providerId: 'xd',+ effort: 'xhigh',+ fastMode: true,+};++const target = {+ model: 'gpt-5.6-sol',+ providerId: 'openai',+ effort: 'high',+ fastMode: false,+};++describe('isXdOpenAiCodexProviderTransition', () => {+ it('accepts only the two intended credential-family directions', () => {+ expect(isXdOpenAiCodexProviderTransition('xd', 'openai')).toBe(true);+ expect(isXdOpenAiCodexProviderTransition('openai', 'xd')).toBe(true);+ expect(isXdOpenAiCodexProviderTransition('xd', 'xai')).toBe(false);+ expect(isXdOpenAiCodexProviderTransition(null, 'openai')).toBe(false);+ expect(isXdOpenAiCodexProviderTransition('openai', 'openai')).toBe(false);+ });++ it('recognizes implicit XD Codex routes after credential identity resolution', () => {+ const implicitXd = { providerId: null, model: 'codex/gpt-5.6-sol' };+ const subscription = { providerId: 'openai', model: 'gpt-5.6-sol' };++ expect(decideCodexProviderThreadRelink(implicitXd, subscription)).toBe('relink');+ expect(decideCodexProviderThreadRelink(subscription, implicitXd)).toBe('relink');+ expect(+ decideCodexProviderThreadRelink({ providerId: null, model: 'ambiguous-model' }, subscription),+ ).toBe('unresolved');+ });+});++describe('relinkCodexProviderThread', () => {+ it.each([+ {+ name: 'implicit XD to OpenAI',+ source: { ...source, providerId: null, model: 'codex/gpt-5.6-sol' },+ target,+ },+ {+ name: 'OpenAI to implicit XD fixed-effort model',+ source: {+ ...source,+ sdkSessionId: 'thread-openai',+ providerId: 'openai',+ model: 'gpt-5.6-sol',+ },+ target: {+ model: 'codex/gpt-5.6-sol',+ providerId: null,+ effort: null,+ fastMode: true,+ },+ },+ ])('forks and CAS-commits the complete route for $name', async ({ source, target }) => {+ const cleanup = vi.fn(async () => {});+ const fork = vi.fn(async () => ({ newSdkSessionId: 'thread-replacement', cleanup }));+ const commit = vi.fn(async () => true);++ expect(decideCodexProviderThreadRelink(source, target)).toBe('relink');+ await expect(+ relinkCodexProviderThread(+ { readSource: vi.fn(async () => source), fork, commit },+ { sessionId: 'session-implicit-provider', target },+ ),+ ).resolves.toEqual({+ previousSdkSessionId: source.sdkSessionId,+ newSdkSessionId: 'thread-replacement',+ });++ expect(fork).toHaveBeenCalledWith({+ sourceSdkSessionId: source.sdkSessionId,+ sourceModel: source.model,+ sourceProviderId: source.providerId,+ workingDir: source.workingDir,+ });+ expect(commit).toHaveBeenCalledWith({+ sessionId: 'session-implicit-provider',+ source,+ newSdkSessionId: 'thread-replacement',+ target,+ });+ expect(cleanup).not.toHaveBeenCalled();+ });++ it('forks with source credentials and CAS-commits the full target route', async () => {+ const fork = vi.fn(async () => ({ newSdkSessionId: 'thread-openai' }));+ const commit = vi.fn(async () => true);++ await expect(+ relinkCodexProviderThread(+ { readSource: vi.fn(async () => source), fork, commit },+ { sessionId: 'session-1', target },+ ),+ ).resolves.toEqual({+ previousSdkSessionId: 'thread-xd',+ newSdkSessionId: 'thread-openai',+ });++ expect(fork).toHaveBeenCalledWith({+ sourceSdkSessionId: 'thread-xd',+ sourceModel: 'codex/gpt-5.6-sol',+ sourceProviderId: 'xd',+ workingDir: '/work',+ });+ expect(commit).toHaveBeenCalledWith({+ sessionId: 'session-1',+ source,+ newSdkSessionId: 'thread-openai',+ target,+ });+ });++ it('does not fork when the task has no persisted native thread', async () => {+ const fork = vi.fn();+ const commit = vi.fn();+ await expect(+ relinkCodexProviderThread(+ { readSource: vi.fn(async () => ({ ...source, sdkSessionId: null })), fork, commit },+ { sessionId: 'session-1', target },+ ),+ ).resolves.toBeNull();+ expect(fork).not.toHaveBeenCalled();+ expect(commit).not.toHaveBeenCalled();+ });++ it('fails closed when the source tuple is superseded before CAS commit', async () => {+ const cleanup = vi.fn(async () => {});+ await expect(+ relinkCodexProviderThread(+ {+ readSource: vi.fn(async () => source),+ fork: vi.fn(async () => ({ newSdkSessionId: 'thread-openai', cleanup })),+ commit: vi.fn(async () => false),+ },+ { sessionId: 'session-1', target },+ ),+ ).rejects.toThrow(/superseded/);+ expect(cleanup).toHaveBeenCalledOnce();+ });++ it('preserves the database error when replacement cleanup also fails', async () => {+ const databaseError = new Error('route CAS failed');+ const cleanup = vi.fn(async () => {+ throw new Error('replacement cleanup failed');+ });+ await expect(+ relinkCodexProviderThread(+ {+ readSource: vi.fn(async () => source),+ fork: vi.fn(async () => ({ newSdkSessionId: 'thread-openai', cleanup })),+ commit: vi.fn(async () => {+ throw databaseError;+ }),+ },+ { sessionId: 'session-1', target },+ ),+ ).rejects.toBe(databaseError);+ expect(cleanup).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.tsnew file mode 100644index 0000000000..c41f85ad5e--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModelCodexRelink.test.ts@@ -0,0 +1,194 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ clearSessionProvider,+ getSessionProvider,+ setSessionProvider,+} from '../../maker-host/session-provider-store.js';+import { applyRuntimeSetModelChange, type RuntimeSetModelMaker } from '../runtimeSetModel.js';++const sessionProviderWriteObserver = vi.hoisted(() => ({+ current: null as ((sessionId: string, providerId: string | null) => void) | null,+}));++vi.mock('../../maker-host/session-provider-store.js', async (importOriginal) => {+ const actual =+ await importOriginal<typeof import('../../maker-host/session-provider-store.js')>();+ return {+ ...actual,+ setSessionProvider: (sessionId: string, providerId: string | null) => {+ actual.setSessionProvider(sessionId, providerId);+ sessionProviderWriteObserver.current?.(sessionId, providerId);+ },+ };+});++const touchedSessions = new Set<string>();++afterEach(() => {+ sessionProviderWriteObserver.current = null;+ for (const sessionId of touchedSessions) clearSessionProvider(sessionId);+ touchedSessions.clear();+});++function rememberSession(sessionId: string): string {+ touchedSessions.add(sessionId);+ return sessionId;+}++describe('applyRuntimeSetModelChange Codex provider thread relink', () => {+ it('closes, relinks, then publishes an idle XD-to-subscription route', async () => {+ const sessionId = rememberSession('runtime-set-model-atomic-relink');+ setSessionProvider(sessionId, 'xd');+ const order: string[] = [];+ const closeSession = vi.fn(async () => {+ order.push('close');+ });+ const relinkCodexThread = vi.fn(async () => {+ order.push('relink');+ });+ const wakeSessionInputQueue = vi.fn(() => {+ order.push('wake');+ });+ sessionProviderWriteObserver.current = (writtenSessionId, providerId) => {+ if (writtenSessionId === sessionId && providerId === 'openai') order.push('route');+ };+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'codex',+ remoteHostId: null,+ model: 'codex/gpt-5.6-sol',+ setModel: vi.fn(async () => {}),+ }),+ listActiveSessions: () => [+ { id: sessionId, agentKind: 'codex', remoteHostId: null, isTurnRunning: () => false },+ ],+ closeSession,+ };++ await expect(+ applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.6-sol',+ providerId: 'openai',+ requiresCodexThreadRelink: true,+ relinkCodexThread,+ clearPendingCredentialSwitch: vi.fn(),+ wakeSessionInputQueue,+ }),+ ).resolves.toEqual({ status: 'applied', persistedRoute: true });++ expect(order).toEqual(['close', 'relink', 'route', 'wake']);+ expect(getSessionProvider(sessionId)).toBe('openai');+ });++ it('fails closed instead of registering pending work while the task is busy', async () => {+ const sessionId = rememberSession('runtime-set-model-busy-relink');+ setSessionProvider(sessionId, 'xd');+ const registerPendingCredentialSwitch = vi.fn();+ const relinkCodexThread = vi.fn(async () => {});+ const closeSession = vi.fn(async () => {});+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'codex',+ remoteHostId: null,+ model: 'codex/gpt-5.6-sol',+ setModel: vi.fn(async () => {}),+ }),+ listActiveSessions: () => [+ { id: sessionId, agentKind: 'codex', remoteHostId: null, isTurnRunning: () => true },+ ],+ closeSession,+ };++ await expect(+ applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.6-sol',+ providerId: 'openai',+ requiresCodexThreadRelink: true,+ relinkCodexThread,+ registerPendingCredentialSwitch,+ }),+ ).rejects.toThrow(/busy/);++ expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();+ expect(relinkCodexThread).not.toHaveBeenCalled();+ expect(closeSession).not.toHaveBeenCalled();+ expect(getSessionProvider(sessionId)).toBe('xd');+ });++ it('still fails closed when the task becomes busy during the close preflight', async () => {+ const sessionId = rememberSession('runtime-set-model-busy-race-relink');+ setSessionProvider(sessionId, 'xd');+ let busyCheck = 0;+ const registerPendingCredentialSwitch = vi.fn();+ const relinkCodexThread = vi.fn(async () => {});+ const closeSession = vi.fn(async () => {});+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'codex',+ remoteHostId: null,+ model: 'codex/gpt-5.6-sol',+ setModel: vi.fn(async () => {}),+ }),+ listActiveSessions: () => [+ {+ id: sessionId,+ agentKind: 'codex',+ remoteHostId: null,+ isTurnRunning: () => ++busyCheck > 1,+ },+ ],+ closeSession,+ };++ await expect(+ applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.6-sol',+ providerId: 'openai',+ requiresCodexThreadRelink: true,+ relinkCodexThread,+ registerPendingCredentialSwitch,+ clearPendingCredentialSwitch: vi.fn(),+ }),+ ).rejects.toThrow(/busy/);++ expect(registerPendingCredentialSwitch).not.toHaveBeenCalled();+ expect(relinkCodexThread).not.toHaveBeenCalled();+ expect(closeSession).not.toHaveBeenCalled();+ expect(getSessionProvider(sessionId)).toBe('xd');+ });++ it('relinks a persisted thread even without a live Session handle', async () => {+ const sessionId = rememberSession('runtime-set-model-cold-relink');+ setSessionProvider(sessionId, 'xd');+ const relinkCodexThread = vi.fn(async () => {});+ const wakeSessionInputQueue = vi.fn();+ const maker: RuntimeSetModelMaker = {+ getSession: () => undefined,+ listActiveSessions: () => [],+ closeSession: vi.fn(async () => {}),+ };++ await expect(+ applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.6-sol',+ providerId: 'openai',+ requiresCodexThreadRelink: true,+ relinkCodexThread,+ wakeSessionInputQueue,+ }),+ ).resolves.toEqual({ status: 'applied', persistedRoute: true });++ expect(relinkCodexThread).toHaveBeenCalledOnce();+ expect(wakeSessionInputQueue).toHaveBeenCalledWith(sessionId);+ expect(getSessionProvider(sessionId)).toBe('openai');+ });+});diff --git a/apps/desktop/src/main/maker-ipc/codexProviderThreadRelink.ts b/apps/desktop/src/main/maker-ipc/codexProviderThreadRelink.tsnew file mode 100644index 0000000000..52b20f81f1--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/codexProviderThreadRelink.ts@@ -0,0 +1,106 @@+/**+ * Rebuild a local Codex native thread before crossing the XD/OpenAI credential boundary.+ *+ * Fork authentication belongs to the source thread. The replacement thread id and the+ * complete target runtime route are then committed by one caller-provided CAS.+ */++import { resolveAgentCredentialMode } from '@cindy/maker-core';++export interface CodexProviderThreadRoute {+ model: string;+ providerId: string | null;+ effort: string | null;+ fastMode: boolean;+}++export interface CodexProviderThreadRelinkSource extends CodexProviderThreadRoute {+ sdkSessionId: string | null;+ workingDir: string | null;+}++export interface CodexProviderThreadRelinkDeps {+ readSource(sessionId: string): Promise<CodexProviderThreadRelinkSource | null>;+ fork(input: {+ sourceSdkSessionId: string;+ sourceModel: string;+ sourceProviderId: string | null;+ workingDir?: string;+ }): Promise<{ newSdkSessionId: string; cleanup?: () => Promise<void> }>;+ commit(input: {+ sessionId: string;+ source: CodexProviderThreadRelinkSource & { sdkSessionId: string };+ newSdkSessionId: string;+ target: CodexProviderThreadRoute;+ }): Promise<boolean>;+}++export function isXdOpenAiCodexProviderTransition(+ sourceProviderId: string | null | undefined,+ targetProviderId: string | null | undefined,+): boolean {+ const source = sourceProviderId?.trim() || null;+ const target = targetProviderId?.trim() || null;+ return (source === 'xd' && target === 'openai') || (source === 'openai' && target === 'xd');+}++export type CodexProviderThreadRelinkDecision = 'relink' | 'not-applicable' | 'unresolved';++export function decideCodexProviderThreadRelink(+ source: Pick<CodexProviderThreadRoute, 'model' | 'providerId'>,+ target: Pick<CodexProviderThreadRoute, 'model' | 'providerId'>,+): CodexProviderThreadRelinkDecision {+ const sourceMode = resolveAgentCredentialMode({ agentKind: 'codex', ...source });+ const targetMode = resolveAgentCredentialMode({ agentKind: 'codex', ...target });+ const toProviderIdentity = (mode: typeof sourceMode): 'xd' | 'openai' | null => {+ if (mode === 'gateway-key') return 'xd';+ if (mode === 'oauth-bearer') return 'openai';+ return null;+ };+ const involvesXdOpenAiBoundary = [sourceMode, targetMode].some(+ (mode) => mode === 'gateway-key' || mode === 'oauth-bearer',+ );+ if (involvesXdOpenAiBoundary && (sourceMode === undefined || targetMode === undefined)) {+ return 'unresolved';+ }+ return isXdOpenAiCodexProviderTransition(+ toProviderIdentity(sourceMode),+ toProviderIdentity(targetMode),+ )+ ? 'relink'+ : 'not-applicable';+}++export async function relinkCodexProviderThread(+ deps: CodexProviderThreadRelinkDeps,+ input: { sessionId: string; target: CodexProviderThreadRoute },+): Promise<{ previousSdkSessionId: string; newSdkSessionId: string } | null> {+ const source = await deps.readSource(input.sessionId);+ if (!source?.sdkSessionId) return null;++ const sourceWithThread = { ...source, sdkSessionId: source.sdkSessionId };+ const forked = await deps.fork({+ sourceSdkSessionId: sourceWithThread.sdkSessionId,+ sourceModel: sourceWithThread.model,+ sourceProviderId: sourceWithThread.providerId,+ ...(sourceWithThread.workingDir ? { workingDir: sourceWithThread.workingDir } : {}),+ });+ try {+ const committed = await deps.commit({+ sessionId: input.sessionId,+ source: sourceWithThread,+ newSdkSessionId: forked.newSdkSessionId,+ target: input.target,+ });+ if (!committed) {+ throw new Error(`Codex provider thread relink was superseded for session ${input.sessionId}`);+ }+ } catch (error) {+ await forked.cleanup?.().catch(() => undefined);+ throw error;+ }+ return {+ previousSdkSessionId: sourceWithThread.sdkSessionId,+ newSdkSessionId: forked.newSdkSessionId,+ };+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 3ead89481b..ec7f815382 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -762,7 +762,10 @@ import {persistedUserContentToWireMessage,shouldRebuildPiNativeSession,} from './contextOverflowRollover.js';-import { classifyCodexHistoryOversized } from '../maker-host/codex-local-sessions.js';+import {+ classifyCodexHistoryOversized,+ reserveCodexForkCleanup,+} from '../maker-host/codex-local-sessions.js';import { hydrateQueuedAgentReferences } from './agentInputReferences.js';import { agentHandoffPending } from './agentHandoffPendingSingleton.js';import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';@@ -896,6 +899,11 @@ import {applyRuntimeSetModelChange,isRemoteModelSwitchRouteChangeError,} from './runtimeSetModel.js';+import {+ decideCodexProviderThreadRelink,+ relinkCodexProviderThread,+ type CodexProviderThreadRoute,+} from './codexProviderThreadRelink.js';import {applyRuntimeSelectionAxesWithRecovery,commitRuntimeAxisAfterPersistence,@@ -15086,7 +15094,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 状态可封住两种次序:本请求先拿锁时终态写等待并在之后清理 override;终态// 先拿锁时旧请求看到非 active,不能在 cleanup 后重新建立 pending/override。const [runtimeStatus] = await getDbClient()- .drizzle.select({ status: sessions.status, orcaRole: sessions.orcaRole })+ .drizzle.select({+ status: sessions.status,+ orcaRole: sessions.orcaRole,+ agentKind: sessions.agentKind,+ remoteHostId: sessions.remoteHostId,+ sdkSessionId: sessions.sdkSessionId,+ model: sessions.model,+ providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,+ workingDir: sessions.workingDir,+ }).from(sessions).where(eq(sessions.id, sessionId)).limit(1);@@ -15299,6 +15318,162 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)effectiveProviderId === undefined? currentProviderId: (normalizeSessionProviderId(effectiveProviderId) ?? null);+ const hasPersistedLocalCodexThread =+ internalOptions.source === 'user' &&+ !isDeviceLinkInvoke() &&+ runtimeStatus.agentKind === 'codex' &&+ !runtimeStatus.remoteHostId &&+ !!runtimeStatus.sdkSessionId;+ const relinkDecision = hasPersistedLocalCodexThread+ ? decideCodexProviderThreadRelink(+ { model: runtimeStatus.model, providerId: runtimeStatus.providerId },+ { model, providerId: targetProviderId },+ )+ : 'not-applicable';+ if (relinkDecision === 'unresolved') {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Codex provider credential identity could not be resolved; retry with an explicit provider',+ );+ }+ const requiresCodexThreadRelink = relinkDecision === 'relink';+ const targetCodexRoute: CodexProviderThreadRoute | undefined = requiresCodexThreadRelink+ ? {+ model,+ providerId: targetProviderId,+ effort: atomicSelection ? atomicSelection.effort : runtimeStatus.effort,+ fastMode: atomicSelection ? atomicSelection.fastMode : runtimeStatus.fastMode,+ }+ : undefined;+ const relinkCodexThread = targetCodexRoute+ ? async (): Promise<void> => {+ const ownerScope = captureDataOwnerBroadcastScope();+ const dbSnapshot = getCurrentDbClientSnapshot();+ if (!dbSnapshot) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Codex provider thread relink requires an active Profile database',+ );+ }+ const relinked = await relinkCodexProviderThread(+ {+ readSource: async (targetSessionId) => {+ const [row] = await dbSnapshot.client.drizzle+ .select({+ sdkSessionId: sessions.sdkSessionId,+ workingDir: sessions.workingDir,+ model: sessions.model,+ providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,+ })+ .from(sessions)+ .where(eq(sessions.id, targetSessionId))+ .limit(1);+ return row ?? null;+ },+ fork: async ({ sourceSdkSessionId, sourceModel, sourceProviderId, workingDir }) => {+ const forked = await maker.forkSdkSession('codex', {+ sourceSdkSessionId,+ model: sourceModel,+ providerId: sourceProviderId,+ upToMessageId: undefined,+ ...(workingDir ? { workingDir } : {}),+ stripEncryptedReasoning: true,+ remoteHostId: null,+ });+ if (forked.newSdkSessionId === sourceSdkSessionId) {+ throwIpcError('INTERNAL', 'Codex fork returned an invalid replacement thread');+ }+ const cleanup = reserveCodexForkCleanup(+ forked.newSdkSessionId,+ sourceSdkSessionId,+ );+ return {+ newSdkSessionId: forked.newSdkSessionId,+ ...(cleanup ? { cleanup } : {}),+ };+ },+ commit: async ({ sessionId: targetSessionId, source, newSdkSessionId, target }) => {+ if (+ !isDataOwnerBroadcastScopeCurrent(ownerScope) ||+ getCurrentDbClientSnapshot()?.clientEpoch !== dbSnapshot.clientEpoch+ ) {+ return false;+ }+ const now = Date.now();+ const sourceRouteConditions = [+ eq(sessions.id, targetSessionId),+ eq(sessions.sdkSessionId, source.sdkSessionId),+ eq(sessions.model, source.model),+ source.providerId === null+ ? isNull(sessions.providerId)+ : eq(sessions.providerId, source.providerId),+ source.effort === null+ ? isNull(sessions.effort)+ : eq(+ sessions.effort,+ source.effort as (typeof sessions.$inferSelect)['effort'],+ ),+ eq(sessions.fastMode, source.fastMode),+ ];+ const write = await dbSnapshot.client.drizzle+ .update(sessions)+ .set({+ sdkSessionId: newSdkSessionId,+ model: target.model,+ providerId: target.providerId,+ effort: target.effort as (typeof sessions.$inferInsert)['effort'],+ fastMode: target.fastMode,+ updatedAt: now,+ })+ .where(and(...sourceRouteConditions))+ .run();+ if (write.changes === 0) return false;+ broadcastSessionPatched(+ targetSessionId,+ {+ sdkSessionId: newSdkSessionId,+ model: target.model,+ providerId: target.providerId,+ effort: target.effort,+ fastMode: target.fastMode,+ updatedAt: new Date(now).toISOString(),+ },+ ownerScope,+ );+ return true;+ },+ },+ { sessionId, target: targetCodexRoute },+ ).catch((error) => {+ if (isIpcError(error)) throw error;+ if (+ error instanceof Error &&+ error.message.startsWith('Codex provider thread relink was superseded')+ ) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Codex provider thread changed during model switch; retry the selection',+ );+ }+ throwIpcError('INTERNAL', 'Failed to rebuild Codex provider thread');+ });+ if (!relinked) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Codex provider thread changed during model switch; retry the selection',+ );+ }+ log.info('Codex provider thread and route committed atomically', {+ sessionId,+ fromThreadId: relinked.previousSdkSessionId,+ toThreadId: relinked.newSdkSessionId,+ providerId: targetCodexRoute.providerId,+ model: targetCodexRoute.model,+ });+ }+ : undefined;const rebuildLiveOrcaWorker =routeExplicit &&runtimeStatus.orcaRole === 'worker' &&@@ -15426,6 +15601,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见// shouldCloseSessionForCredentialSwitch.codexAuthInjection)。codexAuthInjection: getCodexProxyAuthInjectionState(),+ requiresCodexThreadRelink,+ ...(relinkCodexThread ? { relinkCodexThread } : {}),logger: log,}): { status: 'applied' as const };@@ -15471,7 +15648,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)commitControlStores();}}- if (internalOptions.source === 'user' && (isDeviceLinkInvoke() || atomicSelection)) {+ if (+ internalOptions.source === 'user' &&+ (isDeviceLinkInvoke() || atomicSelection) &&+ result.persistedRoute !== true+ ) {// device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;// 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的// 新调用都由 host 在解锁前一次落定全部字段。diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.tsindex 414692b8cd..da9ad729c2 100644--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts@@ -92,14 +92,21 @@ export interface ApplyRuntimeSetModelChangeInput {* 是否跨「远端压缩身份」边界;不传时该判定按未知保守处理(倾向关会话重建)。*/codexAuthInjection?: CodexProxyAuthInjection | null;+ /**+ * The host has proved that this local Codex selection crosses the explicit XD/OpenAI+ * credential boundary and has a persisted native thread to rebuild.+ */+ requiresCodexThreadRelink?: boolean;+ /** Closes over the captured Profile DB and atomically commits thread + full target route. */+ relinkCodexThread?: () => Promise<void>;logger?: RuntimeSetModelLogger;}export type ApplyRuntimeSetModelChangeResult =/** 直接生效(热切 route / 或已关会话待下次发送重建)。 */- | { status: 'applied' }+ | { status: 'applied'; persistedRoute?: true }/** 凭证形态要换但会话自己在跑:已登记 pending,turn 结束后自动生效。 */- | { status: 'deferred' };+ | { status: 'deferred'; persistedRoute?: never };export function isRemoteModelSwitchRouteChangeError(error: unknown): boolean {return (@@ -159,6 +166,10 @@ export async function applyRuntimeSetModelChange(codexAuthInjection: input.codexAuthInjection,}): false;+ const requiresCodexThreadRelink = input.requiresCodexThreadRelink === true;+ if (requiresCodexThreadRelink && !input.relinkCodexThread) {+ throw new Error(`Codex provider thread relink is required for session ${sessionId}`);+ }let selfBusyMemo: boolean | undefined;const isSelfBusy = (): boolean => {if (selfBusyMemo !== undefined) return selfBusyMemo;@@ -171,6 +182,20 @@ export async function applyRuntimeSetModelChange(return selfBusyMemo;};+ if (requiresCodexThreadRelink && isSelfBusy()) {+ throw new CredentialModeSwitchBusyError(+ [sessionId],+ `Cannot rebuild Codex provider thread while the session is busy: ${sessionId}`,+ );+ }++ if (!sess && requiresCodexThreadRelink) {+ await input.relinkCodexThread?.();+ if (providerId !== undefined) setSessionProvider(sessionId, nextProviderId);+ input.wakeSessionInputQueue?.(sessionId);+ return { status: 'applied', persistedRoute: true };+ }+if (sess?.agentKind === 'codex' &&!sess.remoteHostId &&@@ -203,7 +228,7 @@ export async function applyRuntimeSetModelChange();}- if (sess && shouldCloseSession) {+ if (sess && (shouldCloseSession || requiresCodexThreadRelink)) {if (isSelfBusy() && input.registerPendingCredentialSwitch) {await input.registerPendingCredentialSwitch(sessionId, {model,@@ -237,7 +262,11 @@ export async function applyRuntimeSetModelChange(} catch (err) {// 空闲判定与 close 之间的竞态(恰好起了新 turn):有 pending 通道就转延迟,// 没有(老调用方)保持抛 busy 的旧语义。- if (isCredentialModeSwitchBusyError(err) && input.registerPendingCredentialSwitch) {+ if (+ !requiresCodexThreadRelink &&+ isCredentialModeSwitchBusyError(err) &&+ input.registerPendingCredentialSwitch+ ) {input.registerPendingCredentialSwitch(sessionId, {model,providerId: nextProviderId,@@ -254,6 +283,9 @@ export async function applyRuntimeSetModelChange(}throw err;}+ if (requiresCodexThreadRelink) {+ await input.relinkCodexThread?.();+ }if (providerId !== undefined) setSessionProvider(sessionId, nextProviderId);// close + route 都落定后再唤醒队列:排队消息按新凭证形态 lazy-create 派发。input.wakeSessionInputQueue?.(sessionId);@@ -265,7 +297,9 @@ export async function applyRuntimeSetModelChange(fromModel: sess.model,toModel: model,});- return { status: 'applied' };+ return requiresCodexThreadRelink+ ? { status: 'applied', persistedRoute: true }+ : { status: 'applied' };}if (providerId !== undefined) {