Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(session): 开放运行时模型控制与自动降级 (#3364)
Chris Zhangcd659248c69b
diff --git a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts b/apps/desktop/src/main/__tests__/appSessionBoundary.test.tsindex 9b2b0432ab..99cf7b1830 100644--- a/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts+++ b/apps/desktop/src/main/__tests__/appSessionBoundary.test.ts@@ -25,8 +25,17 @@ vi.mock('../authBoundaryQuarantine.js', () => ({import {beginAppSessionBoundary,+ commitActiveAppSession,+ commitVolatileAppSession,+ getActiveAppSession,isAppSessionBoundaryPending,+ setAppSessionCommitBoundaryHook,} from '../appSessionState.js';+import {+ captureSessionRuntimeControlOwnerEpoch,+ clearAllSessionRuntimeControlStates,+ sessionRuntimeControlOwnerEpochMatches,+} from '../maker-ipc/sessionRuntimeControl.js';describe('application session boundary isolation', () => {it('does not treat a different durable Ghost projection owner as an App transition', () => {@@ -40,4 +49,62 @@ describe('application session boundary isolation', () => {release();expect(isAppSessionBoundaryPending()).toBe(false);});++ it('invalidates in-flight runtime mutations synchronously with the owner commit', () => {+ const captured = captureSessionRuntimeControlOwnerEpoch();+ const observedModes: string[] = [];+ setAppSessionCommitBoundaryHook(() => {+ observedModes.push(getActiveAppSession().mode);+ clearAllSessionRuntimeControlStates();+ });++ try {+ commitActiveAppSession('local');+ } finally {+ setAppSessionCommitBoundaryHook(null);+ }++ expect(observedModes).toEqual(['signed-out']);+ expect(sessionRuntimeControlOwnerEpochMatches(captured)).toBe(false);+ });++ it('keeps the runtime owner epoch across a same-owner generation bump', () => {+ const current = getActiveAppSession();+ const captured = captureSessionRuntimeControlOwnerEpoch();+ const hook = vi.fn();+ setAppSessionCommitBoundaryHook(hook);++ try {+ const bumped = commitActiveAppSession(+ current.mode,+ current.dataOwnerId ?? undefined,+ true,+ );++ expect(bumped.generation).toBe(current.generation + 1);+ expect(hook).not.toHaveBeenCalled();+ expect(sessionRuntimeControlOwnerEpochMatches(captured)).toBe(true);+ } finally {+ setAppSessionCommitBoundaryHook(null);+ }+ });++ it('does not create a boundary for a repeated volatile commit to the same owner', () => {+ const current = getActiveAppSession();+ const targetMode = current.mode === 'signed-out' ? 'local' : 'signed-out';+ const hook = vi.fn();+ setAppSessionCommitBoundaryHook(hook);++ try {+ const first = commitVolatileAppSession(targetMode);+ const captured = captureSessionRuntimeControlOwnerEpoch();+ const repeated = commitVolatileAppSession(targetMode);++ expect(hook).toHaveBeenCalledTimes(1);+ expect(repeated).toEqual(first);+ expect(sessionRuntimeControlOwnerEpochMatches(captured)).toBe(true);+ } finally {+ setAppSessionCommitBoundaryHook(null);+ }+ });});diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.tsindex 99b0b2f652..7b2fb9c36a 100644--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts@@ -534,7 +534,10 @@ describe('maker:event hot path ordering', () => {expect(source).toContain('coordinator.getAutoResumeAttemptToken(session.id) !== attemptToken');expect(source).toContain('autoResumeBookkeeping.hasWaitingSchedule(session.id, attemptToken)');expect(closedBlock).toContain(- 'const preserveAutoResumeIntent = shouldPreserveCodexReconnectStalledAutoResume(',+ 'shouldPreserveCodexReconnectStalledAutoResume(session, closeReason)',+ );+ expect(closedBlock).toContain(+ 'shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason)',);expect(closedBlock).toContain('if (preserveAutoResumeIntent) {');expect(closedBlock).toContain('autoResumeBookkeeping.teardown(session.id);');diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.tsindex 85d00f76f7..4bb54fb047 100644--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts@@ -459,7 +459,7 @@ describe('sendToSession ordering', () => {it('serializes SET_MODEL behind the send-time agent switch for the same session', () => {const setModelBlock = extractBetween(source,- 'ipcMain.handle(\n MAKER_INVOKE.SET_MODEL',+ 'const handleSetModel = async (','ipcMain.handle(MAKER_INVOKE.SET_EFFORT',);const directSendSwitchBlock = extractBetween(@@ -469,7 +469,7 @@ describe('sendToSession ordering', () => {);expect(setModelBlock).toContain(- 'return withSendToSessionLock(sessionId, async () => {',+ 'return withSendToSessionLock(sessionId, applyLocked);',);expect(setModelBlock).toContain('agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',@@ -477,45 +477,65 @@ describe('sendToSession ordering', () => {expect(setModelBlock).toContain('return { deferred: false, superseded: true };');expectOrder(setModelBlock,- 'return withSendToSessionLock(sessionId, async () => {',+ 'const applyLocked = async () => {','agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',);expectOrder(setModelBlock,'agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision',- 'applySetModelThenCancelAgentSwitchIntent(',+ 'applyRuntimeSetModelChange({',);expect(setModelBlock).toContain('if (isDeviceLinkInvoke()) {');expect(setModelBlock).toContain('if (atomicSelection) {');expect(setModelBlock).toContain('effort: atomicSelection.effort as');- expect(setModelBlock).toContain('setSessionEffort(sessionId, atomicSelection.effort);');- expect(setModelBlock).toContain('setSessionFastMode(sessionId, atomicSelection.fastMode);');- expect(setModelBlock).toContain('await sess.setEffort(');- expect(setModelBlock).toContain('await sess.setFastMode(atomicSelection.fastMode);');- expect(setModelBlock).toContain('if (isDeviceLinkInvoke() || atomicSelection) {');+ expect(setModelBlock).toContain('setSessionEffort(sessionId, selectionToCommit.effort);');+ expect(setModelBlock).toContain('setSessionFastMode(sessionId, selectionToCommit.fastMode);');+ expect(setModelBlock).toContain('applyRuntimeSelectionAxesWithRecovery({');+ expect(setModelBlock).toContain('restoreControlStores,');+ expect(setModelBlock).toContain('withRehydrateCloseSuppressed(sessionId');+ expect(setModelBlock).toMatch(+ /internalOptions\.source === 'user'\s*&&\s*\(isDeviceLinkInvoke\(\) \|\| atomicSelection\)/,+ );expect(setModelBlock).toContain('patch.effort = atomicSelection.effort;');expect(setModelBlock).toContain('patch.fastMode = atomicSelection.fastMode;');expect(setModelBlock).toContain('await persistSessionFields(sessionId, patch);');expect(setModelBlock).toContain('markRemoteSettingPersistedInsideHandler(response);');expectOrder(setModelBlock,- 'applySetModelThenCancelAgentSwitchIntent(',- 'setSessionEffort(sessionId, atomicSelection.effort);',+ 'applyRuntimeSetModelChange({',+ 'const commitControlStores',);expectOrder(setModelBlock,- 'effort: atomicSelection.effort as',- 'setSessionEffort(sessionId, atomicSelection.effort);',+ 'applyRuntimeSelectionAxesWithRecovery({',+ 'await persistSessionFields',);expectOrder(setModelBlock,- 'setSessionFastMode(sessionId, atomicSelection.fastMode);',+ 'setSessionFastMode(sessionId, selectionToCommit.fastMode);','await persistSessionFields(sessionId, patch);',);+ expect(setModelBlock.lastIndexOf('agentSwitchPending.clear(sessionId);')).toBeGreaterThan(+ setModelBlock.indexOf('await persistSessionFields(sessionId, patch);'),+ );expectOrder(setModelBlock,- 'await persistSessionFields(sessionId, patch);',- 'return response;',+ 'agentSwitchPending.clear(sessionId);',+ '...response,',+ );+ expect(setModelBlock).toContain('pendingCredentialSwitchHolder?.clear(sessionId);');+ expect(setModelBlock).toContain('restoreControlStores();');+ expect(setModelBlock).toContain('previousRuntime.pendingCredentialSwitch');+ expect(setModelBlock).toContain('withRehydrateCloseSuppressed(sessionId');+ expect(setModelBlock).toContain('recordRecoveredSessionRuntimeMutation(sessionId');+ expect(setModelBlock).toContain(+ 'sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)',+ );+ expect(setModelBlock).toContain('recovered runtime projection broadcast failed');+ expectOrder(+ setModelBlock,+ 'restoreControlStores();',+ 'throw persistenceError;',);expect(preloadSource).toContain('selection?: { effort: string; fastMode: boolean },');expectOrder(@@ -537,7 +557,7 @@ describe('sendToSession ordering', () => {it('仅 Device Link 归一化 SET_MODEL 的 JSON null 可选占位,本地仍走严格校验', () => {const setModelBlock = extractBetween(source,- 'ipcMain.handle(\n MAKER_INVOKE.SET_MODEL',+ 'const handleSetModel = async (','ipcMain.handle(MAKER_INVOKE.SET_EFFORT',);expect(setModelBlock).toContain('normalizeDeviceLinkSetModelWireArgs(');diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.tsnew file mode 100644index 0000000000..a3a084b488--- /dev/null+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts@@ -0,0 +1,445 @@+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { describe, expect, it } from 'vitest';++const mainRoot = resolve(__dirname, '..');+const bootstrapSource = readFileSync(resolve(mainRoot, 'bootstrap-electron.ts'), 'utf8').replace(+ /\r\n?/g,+ '\n',+);+const registerSource = readFileSync(resolve(mainRoot, 'maker-ipc/register.ts'), 'utf8').replace(+ /\r\n?/g,+ '\n',+);++function handlerBody(source: string, channel: string, nextChannel: string): string {+ const start = source.indexOf(channel);+ const end = source.indexOf(nextChannel, start + channel.length);+ expect(start).toBeGreaterThan(-1);+ expect(end).toBeGreaterThan(start);+ return source.slice(start, end);+}++describe('session runtime control wiring', () => {+ it('guards every fallback setting IPC before reading or mutating the setting', () => {+ for (const [channel, nextChannel] of [+ [+ 'MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_GET',+ 'MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_SET',+ ],+ [+ 'MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_SET',+ 'MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_RESET',+ ],+ ['MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_RESET', 'MAKER_IPC_INVOKE.COMPACTION_GET_PCT'],+ ] as const) {+ const body = handlerBody(bootstrapSource, channel, nextChannel);+ const guard = body.indexOf('assertTrustedAppRendererEvent(event);');+ expect(guard).toBeGreaterThan(-1);+ const storeAccess = Math.min(+ ...[+ 'sessionRuntimeFallbackWire()',+ 'writeSessionRuntimeFallbackEnabled(',+ 'resetSessionRuntimeFallbackSettings()',+ ]+ .map((needle) => body.indexOf(needle))+ .filter((index) => index >= 0),+ );+ expect(guard).toBeLessThan(storeAccess);+ }+ });++ it('clears runtime overrides synchronously at the owner commit boundary', () => {+ const body = handlerBody(+ bootstrapSource,+ 'setAppSessionCommitBoundaryHook(() => {',+ '// ── Custom protocol registration',+ );+ expect(body).toContain('clearAllSessionProviders();');+ expect(body).toContain('clearAllSessionRuntimeAxes();');+ expect(body.indexOf('clearAllSessionProviders();')).toBeLessThan(+ body.indexOf('clearAllSessionRuntimeControlStates();'),+ );+ expect(body.indexOf('clearAllSessionRuntimeAxes();')).toBeLessThan(+ body.indexOf('clearAllSessionRuntimeControlStates();'),+ );+ expect(body.indexOf('clearAllSessionRuntimeControlStates();')).toBeLessThan(+ body.indexOf('authManager.setStableOwnerPostCommitTask('),+ );+ expect(registerSource).toContain('effort: resolveRetainedRuntimeEffort({');+ expect(registerSource).toContain('targetModelHasFixedEffort,');+ expect(registerSource).toContain(+ 'fastMode: retainedSession.getFastMode() ?? previousRuntime.fastMode',+ );+ });++ it('serializes user effort and Fast mutations with model route changes', () => {+ const effort = handlerBody(+ registerSource,+ 'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',+ 'MAKER_INVOKE.SET_PERMISSION_MODE',+ );+ const fast = handlerBody(+ registerSource,+ 'MAKER_INVOKE.SET_FAST_MODE',+ 'MAKER_INVOKE.SET_THINKING_ENABLED',+ );+ for (const [body, applyCall] of [+ [effort, 'return await applyEffort();'],+ [fast, 'return await applyFastMode();'],+ ] as const) {+ expect(body).toContain('withSendToSessionLock(sessionId');+ expect(body.indexOf('withSendToSessionLock(sessionId')).toBeLessThan(+ body.indexOf(applyCall),+ );+ expect(body).toContain('await resolvePendingRuntimeAxisPatch(sessionId, livePatch)');+ expect(body).toContain(+ 'recordUserSessionRuntimeAxisMutation(sessionId, livePatch, pendingPatch)',+ );+ }+ });++ it('guards local user model changes before parsing input while preserving trusted internal paths', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const guard = setModel.indexOf(+ "if (internalOptions.source === 'user' && !isDeviceLinkInvoke()) {",+ );+ expect(guard).toBeGreaterThan(-1);+ expect(setModel.indexOf('assertTrustedAppRendererEvent(')).toBeGreaterThan(+ guard,+ );+ expect(setModel.indexOf('assertTrustedAppRendererEvent(')).toBeLessThan(+ setModel.indexOf("typeof sessionId !== 'string'"),+ );+ expect(setModel).toContain(+ '!isSupportedRuntimeEffort((selection as { effort?: unknown }).effort)',+ );+ expect(setModel).toContain("internalOptions.source !== 'user'");+ expect(registerSource).toMatch(+ /handleSetModel\(\s*undefined,\s*sessionId,\s*model,\s*providerId,\s*undefined,\s*selection,\s*options,?\s*\)/,+ );+ expect(setModel).toMatch(/\{\s*source:\s*'user',?\s*\}/);+ expect(setModel).not.toContain('ipcMain.handle(MAKER_INVOKE.SET_MODEL, handleSetModel)');+ });++ it('validates atomic user axes against the selected catalog model before side effects', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const axisValidation = setModel.indexOf('if (atomicSelection) {');+ expect(axisValidation).toBeGreaterThan(-1);+ expect(setModel).not.toContain(+ "if (internalOptions.source !== 'user' && atomicSelection)",+ );+ expect(setModel).toContain(+ "internalOptions.source === 'user' || internalOptions.effortExplicit === true",+ );+ expect(setModel).toContain(+ "internalOptions.source === 'user' || internalOptions.fastExplicit === true",+ );+ expect(setModel).toContain(+ "allowFixedEffortPlaceholder: internalOptions.source === 'user'",+ );+ expect(axisValidation).toBeLessThan(setModel.indexOf('applyRuntimeSetModelChange({'));+ expect(axisValidation).toBeLessThan(setModel.indexOf('persistSessionFields(sessionId'));+ });++ it('commits user effort and Fast state only after the live runtime call succeeds', () => {+ const effort = handlerBody(+ registerSource,+ 'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',+ 'MAKER_INVOKE.SET_PERMISSION_MODE',+ );+ const fast = handlerBody(+ registerSource,+ 'MAKER_INVOKE.SET_FAST_MODE',+ 'MAKER_INVOKE.SET_THINKING_ENABLED',+ );++ expect(effort.lastIndexOf('commit: commitEffort')).toBeGreaterThan(+ effort.indexOf('await applyRuntimeEffortWithRecovery({'),+ );+ expect(fast.lastIndexOf('commit: commitFastMode')).toBeGreaterThan(+ fast.indexOf('await sess.setFastMode(enabled);'),+ );+ for (const [body, persist, commit] of [+ [effort, 'persist: persistEffort', 'commit: commitEffort'],+ [fast, 'persist: persistFastMode', 'commit: commitFastMode'],+ ] as const) {+ expect(body).toContain('commitRuntimeAxisAfterPersistence({');+ expect(body.indexOf(persist)).toBeLessThan(body.indexOf(commit));+ expect(body).toContain('markRemoteSettingPersistedInsideHandler(remoteResponse);');+ expect(body).toContain('recoverRemoteRuntimeAxisPersistence(');+ expect(body).toContain('assertCanCommit: assertOwnerCurrent');+ }+ });++ it('cancels and publishes a deferred runtime mutation after settlement fails', () => {+ const settlement = handlerBody(+ registerSource,+ 'const settlePendingSessionRuntimeControl =',+ 'settlePendingSessionRuntimeControlHolder = settlePendingSessionRuntimeControl;',+ );+ const catchBlock = settlement.slice(settlement.indexOf('} catch (error) {'));++ expect(catchBlock).toContain(+ 'cancelPendingSessionRuntimeMutation(sessionId, pending.generation)',+ );+ expect(catchBlock).toContain('await broadcastSessionRuntimeProjection(sessionId)');+ expect(catchBlock.indexOf('cancelPendingSessionRuntimeMutation')).toBeLessThan(+ catchBlock.indexOf('broadcastSessionRuntimeProjection'),+ );+ });++ it('drops in-flight effort and Fast mutations after an owner boundary', () => {+ const effort = handlerBody(+ registerSource,+ 'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',+ 'MAKER_INVOKE.SET_PERMISSION_MODE',+ );+ const fast = handlerBody(+ registerSource,+ 'MAKER_INVOKE.SET_FAST_MODE',+ 'MAKER_INVOKE.SET_THINKING_ENABLED',+ );++ for (const body of [effort, fast]) {+ expect(body).toContain('const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();');+ expect(body).toContain('sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)');+ expect(body).toContain('assertCanCommit: assertOwnerCurrent');+ expect(body.indexOf('assertOwnerCurrent();')).toBeLessThan(+ body.indexOf('return await apply'),+ );+ }+ expect(registerSource).toContain(+ 'if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;',+ );+ });++ it('rejects terminal tasks inside the shared route lock before runtime mutations', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const terminalGuard = setModel.indexOf("runtimeStatus.status !== 'active'");+ expect(terminalGuard).toBeGreaterThan(setModel.indexOf('const applyLocked = async () => {'));+ expect(terminalGuard).toBeLessThan(setModel.indexOf('acceptSessionRuntimeMutation({'));+ expect(terminalGuard).toBeLessThan(setModel.indexOf('applyRuntimeSetModelChange({'));+ expect(setModel).toContain('return withSendToSessionLock(sessionId, applyLocked);');+ });++ it('rejects terminal tasks before effort or Fast mutations recreate runtime state', () => {+ const effort = handlerBody(+ registerSource,+ 'ipcMain.handle(MAKER_INVOKE.SET_EFFORT',+ 'MAKER_INVOKE.SET_PERMISSION_MODE',+ );+ const fast = handlerBody(+ registerSource,+ 'MAKER_INVOKE.SET_FAST_MODE',+ 'MAKER_INVOKE.SET_THINKING_ENABLED',+ );+ for (const [body, commit] of [+ [effort, 'commit: commitEffort'],+ [fast, 'commit: commitFastMode'],+ ] as const) {+ const terminalGuard = body.indexOf("runtimeStatus.status !== 'active'");+ expect(terminalGuard).toBeGreaterThan(-1);+ expect(terminalGuard).toBeLessThan(body.indexOf(commit));+ expect(body.indexOf('.select({ status: sessions.status })')).toBeLessThan(terminalGuard);+ expect(body).toContain('return withSendToSessionLock(sessionId');+ }+ });++ it('retains runtime state across process closes and clears it at task lifecycle boundaries', () => {+ const closeBoundary = handlerBody(+ registerSource,+ "if (status === 'closed') {",+ 'const closedDirectAbortBoundary',+ );+ const terminalCleanup = handlerBody(+ registerSource,+ 'setSessionRuntimeCleanup((sessionId) => {',+ 'disposePiPackagesChangedBroadcast?.();',+ );++ expect(closeBoundary).not.toContain('clearSessionRuntimeControlState(session.id);');+ expect(terminalCleanup).toContain('clearSessionRuntimeControlState(sessionId);');+ expect(terminalCleanup).toContain('clearSessionProvider(sessionId);');+ expect(terminalCleanup).toContain('setSessionEffort(sessionId, null);');+ expect(terminalCleanup).toContain('setSessionFastMode(sessionId, false);');+ });++ it('preserves the exact auto-resume attempt across a fallback route rebuild', () => {+ expect(registerSource).toContain(+ 'const pendingSessionRuntimeFallbackRebuilds = new WeakMap<Session, number>();',+ );+ expect(registerSource).toContain(+ 'pendingSessionRuntimeFallbackRebuilds.set(runtimeSession, attemptToken);',+ );+ expect(registerSource).toContain(+ 'pendingSessionRuntimeFallbackRebuilds.delete(fallbackRebuildSession);',+ );+ expect(registerSource).toContain(+ 'shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason)',+ );+ expect(registerSource).toContain('autoResumeBookkeeping.hasSchedule(session.id)');+ expect(registerSource).toContain(+ 'decision.episodeAttempt,\n decision.attemptToken,',+ );+ expect(registerSource).toContain('isRemoteModelSwitchRouteChangeError(error)');+ expect(registerSource).toContain(+ 'automatic session runtime fallback rebuilding frozen remote route',+ );+ expect(registerSource).toContain(+ 'await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));',+ );+ expect(registerSource).toContain('result = await applyCandidate();');+ });++ it('fences atomic model axis settlement after an owner boundary', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ expect(setModel).toContain('const assertRuntimeOwnerCurrent = (): void => {');+ expect(setModel).toContain('assertCanCommit: assertRuntimeOwnerCurrent,');++ const retainedRecovery = handlerBody(+ setModel,+ 'const reconcileRetainedLiveProfile = async (): Promise<void> => {',+ 'try {\n const result = routeExplicit',+ );+ const capabilityLookup = retainedRecovery.indexOf(+ 'const retainedProviders = await getDesktopProviderService().listProviders({',+ );+ const postLookupOwnerFence = retainedRecovery.indexOf(+ 'if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {',+ capabilityLookup,+ );+ const firstRecoveredStoreWrite = retainedRecovery.indexOf(+ 'setSessionProvider(sessionId, retainedProfile.providerId);',+ );+ expect(capabilityLookup).toBeGreaterThan(-1);+ expect(postLookupOwnerFence).toBeGreaterThan(capabilityLookup);+ expect(postLookupOwnerFence).toBeLessThan(firstRecoveredStoreWrite);+ });++ it('clears fixed-effort overrides from lazy bootstrap and the bridge effort store', () => {+ expect(registerSource).toContain('o.effort = runtimeOverride.effort ?? undefined;');+ expect(registerSource).toContain('setSessionEffort(session.id, runtimeOverride.effort);');+ expect(registerSource).toContain('setSessionEffort(sessionId, selectionToCommit.effort);');+ });++ it('keeps explicit provider null and fixed-effort null through runtime settlement', () => {+ expect(registerSource).toMatch(+ /effectiveProviderId === null\s*\? null\s*: \(normalizeSessionProviderId\(effectiveProviderId\) \?\? currentProviderId\)/,+ );+ expect(registerSource).toContain('effort: pending.profile.effort,');+ expect(registerSource).toContain('effort: candidate.effort, fastMode: candidate.fastMode');+ expect(registerSource).toContain('effort: next.effort, fastMode: next.fastMode');+ });++ it('projects runtime state into shared session snapshots and patch notifications', () => {+ expect(registerSource).toContain('setSessionRuntimeProjector((session) =>');+ expect(registerSource).toContain('setSessionRuntimeCleanup((sessionId) =>');+ expect(registerSource).toContain('broadcastSessionRuntimeProjection(sessionId');+ expect(registerSource).toContain('runtimeEffective: effective');+ expect(registerSource).toContain('runtimePending: control.pending');+ expect(registerSource).toContain("effort: effective.effort ?? '',");+ });++ it('counts fallback eligibility across the whole interrupted-turn episode', () => {+ expect(registerSource).toContain(+ 'decision.episodeAttempt,\n decision.attemptToken,',+ );+ });++ it('records failed fallback routes without allowing stale owner work to mutate state', () => {+ const fallback = handlerBody(+ registerSource,+ 'const maybeApplySessionRuntimeFallback = async (',+ 'const sessionControlService = createSessionControlService({',+ );+ expect(fallback).toContain(+ 'const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();',+ );+ expect(fallback).toContain(+ 'if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;',+ );+ expect(fallback).toContain('await withSendToSessionLock(sessionId, async () => {');+ expect(fallback).toContain("if (runtimeStatus?.status !== 'active') return;");+ expect(fallback).toContain('recordFailedSessionRuntimeFallbackCandidate(');+ expect(fallback).toContain('profiles.control.generation,');+ });++ it('commits runtime control before best-effort context bookkeeping', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ const runtimeCommit = setModel.indexOf('let generation: number;');+ const contextSnapshot = setModel.indexOf('await recordSessionContextSnapshot(');+ expect(runtimeCommit).toBeGreaterThan(-1);+ expect(contextSnapshot).toBeGreaterThan(runtimeCommit);+ expect(setModel.indexOf('recordUserSessionRuntimeMutation(sessionId)', runtimeCommit)).toBeLessThan(+ contextSnapshot,+ );+ expect(setModel.indexOf('settlePendingSessionRuntimeMutation(', runtimeCommit)).toBeLessThan(+ contextSnapshot,+ );+ expect(setModel.indexOf('acceptSessionRuntimeMutation({', runtimeCommit)).toBeLessThan(+ contextSnapshot,+ );+ expect(setModel.slice(runtimeCommit, contextSnapshot)).toContain('if (!response.deferred) {');+ expect(setModel.slice(runtimeCommit, contextSnapshot)).toContain('try {');+ expect(setModel).toContain('runtime model context snapshot refresh failed');+ });++ it('composes later partial runtime changes on the accepted pending profile', () => {+ expect(registerSource).toContain(+ 'const routeExplicit = patch.model !== undefined || patch.providerId !== undefined;',+ );+ expect(registerSource).toContain(+ 'const mergeBase = routeExplicit\n ? (profiles.control.pending?.profile ?? profiles.effective)\n : profiles.effective;',+ );+ expect(registerSource).toContain('mergeSessionRuntimeProfilePatch(mergeBase, patch)');+ expect(registerSource).toContain('routeExplicit,');+ expect(registerSource).toContain('effectiveProfile: profiles.effective,');+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ expect(setModel).toContain(+ 'if (internalOptions.deferWhileRunning && isSessionInTurn(sessionId))',+ );+ expect(setModel).toContain('deferSessionRuntimeAxisMutation({');+ expect(setModel).toContain('pendingPatch: pendingAxisPatch');+ expect(registerSource).toContain('routeExplicit: isPendingSessionRuntimeRouteExplicit(');+ expect(setModel).toContain('const result = routeExplicit');+ expect(setModel).toContain('acceptSessionRuntimeAxisMutation({');+ expect(setModel).toContain('applyEffort: routeExplicit || internalOptions.effortExplicit === true');+ expect(setModel).toContain('applyFastMode: routeExplicit || internalOptions.fastExplicit === true');+ });++ it('rebuilds live Orca Workers for model routes while preserving effort-only hot updates', () => {+ const setModel = handlerBody(+ registerSource,+ 'const handleSetModel = async (',+ 'const recoverRemoteRuntimeAxisPersistence',+ );+ expect(setModel).toContain("runtimeStatus.orcaRole === 'worker'");+ expect(setModel).toContain('forceSessionRebuild: rebuildLiveOrcaWorker');+ expect(setModel).toContain('if (rebuildLiveOrcaWorker && !response.deferred)');+ });+});diff --git a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.tsindex 2501763ee5..3df4ff37b9 100644--- a/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts+++ b/apps/desktop/src/main/__tests__/setSessionsStatusInDb.test.ts@@ -27,6 +27,7 @@ const h = vi.hoisted(() => ({isSessionStillRemovable: vi.fn(),cancelSessionOperations: vi.fn(),cleanupRemovedSession: vi.fn(),+ runtimeCleanup: vi.fn(),removeSessionRefs: vi.fn(),recycleWorktreeForRemovedSession: vi.fn(),isOwnerScopeCurrent: vi.fn(),@@ -80,6 +81,7 @@ import {recycleSessionWorktreeForStatusChange,setSessionRemovalCancelOperations,setSessionRemovalCleanup,+ setSessionRuntimeCleanup,setSessionsStatusInDb,} from '../localDb/ipc/sessions.js';import { setSessionRouteLockImplementation } from '../localDb/sessionRouteLock.js';@@ -97,12 +99,14 @@ beforeEach(() => {h.isOwnerScopeCurrent.mockReturnValue(true);setSessionRemovalCancelOperations(h.cancelSessionOperations);setSessionRemovalCleanup(h.cleanupRemovedSession);+ setSessionRuntimeCleanup(h.runtimeCleanup);setSessionRouteLockImplementation(h.withSendToSessionLock);});afterEach(() => {setSessionRemovalCancelOperations(null);setSessionRemovalCleanup(null);+ setSessionRuntimeCleanup(null);setSessionRouteLockImplementation(null);fs.rmSync(h.userDataPath, { recursive: true, force: true });});@@ -195,6 +199,37 @@ describe('setSessionsStatusInDb', () => {});});+ it('cleans archived runtime state before releasing the batch route locks', async () => {+ const order: string[] = [];+ h.isSessionStillRemovable.mockResolvedValueOnce(false);+ h.tx.mockImplementationOnce(async () => {+ order.push('status-commit');+ return [+ {+ sessionId: 's1',+ title: 'T1',+ workingDir: null,+ workspaceKind: 'dialogue',+ status: 'archived',+ },+ ];+ });+ h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));+ h.withSendToSessionLock.mockImplementationOnce(async (_sessionId, task) => {+ const result = await task();+ order.push('lock-released');+ return result;+ });++ await setSessionsStatusInDb(['s1'], 'archived');+ await vi.waitFor(() => {+ expect(h.isSessionStillRemovable).toHaveBeenCalledWith('s1', h.drizzle);+ });++ expect(order).toEqual(['status-commit', 'runtime-cleanup', 'lock-released']);+ expect(h.runtimeCleanup).toHaveBeenCalledWith('s1');+ });+it('rechecks current status before closing a session from a delayed archive task', async () => {h.tx.mockResolvedValueOnce([{diff --git a/apps/desktop/src/main/appSessionState.ts b/apps/desktop/src/main/appSessionState.tsindex ea42b8bdbf..5fc66ac715 100644--- a/apps/desktop/src/main/appSessionState.ts+++ b/apps/desktop/src/main/appSessionState.ts@@ -80,6 +80,16 @@ const store = createOverrideSettingsFile<PersistedAppSessionSettings>({let active: ActiveAppSession | null = null;let boundaryDepth = 0;+let appSessionCommitBoundaryHook: (() => void) | null = null;++/**+ * Register synchronous owner-scoped runtime invalidation at the exact commit edge.+ * The hook runs after the commit has been accepted but before the new owner is+ * visible, so stale async work cannot resume into the next owner's process state.+ */+export function setAppSessionCommitBoundaryHook(hook: (() => void) | null): void {+ appSessionCommitBoundaryHook = hook;+}function ensureLoaded(): ActiveAppSession {if (active) return active;@@ -168,16 +178,14 @@ export function commitActiveAppSession(if (!normalized) throw new Error('cloud app session requires a verified data owner');dataOwnerId = normalized;}+ const ownerChanged = previous.mode !== mode || previous.dataOwnerId !== dataOwnerId;- if (- previous.mode === mode- && previous.dataOwnerId === dataOwnerId- && !forceBumpGeneration- ) {+ if (!ownerChanged && !forceBumpGeneration) {return { ...previous };}store.writePatch({ activeMode: mode });+ if (ownerChanged) appSessionCommitBoundaryHook?.();active = {mode,dataOwnerId,@@ -205,6 +213,10 @@ export function commitVolatileAppSession(if (!normalized) throw new Error('cloud app session requires a verified data owner');dataOwnerId = normalized;}+ if (previous.mode === mode && previous.dataOwnerId === dataOwnerId) {+ return { ...previous };+ }+ appSessionCommitBoundaryHook?.();active = {mode,dataOwnerId,diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 455e11be1a..e58e3de6a1 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -636,6 +636,14 @@ import {resetSilentEncryptedRetrySettings,writeSilentEncryptedRetryEnabled,} from './maker-host/silent-encrypted-retry-store.js';+import {+ readSessionRuntimeFallbackSettingsState,+ resetSessionRuntimeFallbackSettings,+ writeSessionRuntimeFallbackEnabled,+} from './maker-host/session-runtime-fallback-store.js';+import { clearAllSessionProviders } from './maker-host/session-provider-store.js';+import { clearAllSessionRuntimeAxes } from './maker-host/session-effort-store.js';+import { clearAllSessionRuntimeControlStates } from './maker-ipc/sessionRuntimeControl.js';import {resolveOwnerScopedSecretStorageKey,getProviderSecretStore,@@ -826,6 +834,7 @@ import {getActiveDataOwnerPushStamp,isAppSessionBoundaryPending,ownerScopedUserDataPath,+ setAppSessionCommitBoundaryHook,} from './appSessionState.js';import {resolveNewMakerMenuCommand,@@ -2293,6 +2302,11 @@ setCodexImageAuthBinding({registerGhostIpc();registerPluginMarketIpc();registerPluginPublisherIpc();+setAppSessionCommitBoundaryHook(() => {+ clearAllSessionProviders();+ clearAllSessionRuntimeAxes();+ clearAllSessionRuntimeControlStates();+});authManager.setStableOwnerPostCommitTask(async ({ reason, scopeKey, dataOwnerId }) => {const builtinOutcome = await runStableOwnerPostCommitTask(reason, { scopeKey, dataOwnerId });if (builtinOutcome === 'deferred') return builtinOutcome;@@ -4233,6 +4247,23 @@ const registerIpcHandlers = () => {effective: 'immediate' as const,};});+ ipcMain.handle(MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_GET, async (event) => {+ assertTrustedAppRendererEvent(event);+ return sessionRuntimeFallbackWire();+ });+ ipcMain.handle(MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_SET, async (event, enabled: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof enabled !== 'boolean') {+ throwIpcError('INVALID_PARAMS', 'session runtime fallback enabled required (boolean)');+ }+ writeSessionRuntimeFallbackEnabled(enabled);+ return { ...sessionRuntimeFallbackWire(), effective: 'immediate' as const };+ });+ ipcMain.handle(MAKER_IPC_INVOKE.SESSION_RUNTIME_FALLBACK_RESET, async (event) => {+ assertTrustedAppRendererEvent(event);+ resetSessionRuntimeFallbackSettings();+ return { ...sessionRuntimeFallbackWire(), effective: 'immediate' as const };+ });ipcMain.handle(MAKER_IPC_INVOKE.COMPACTION_GET_PCT, async () => {return readCompactionPct();@@ -8807,6 +8838,15 @@ function silentEncryptedRetryWire() {};}+function sessionRuntimeFallbackWire() {+ const state = readSessionRuntimeFallbackSettingsState();+ return {+ enabled: state.value.enabled,+ isCustomized: state.isCustomized,+ defaultEnabled: state.defaults.enabled,+ };+}+function compactionWire() {const state = readCompactionState();return {diff --git a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.tsindex b9b7487d4f..fcf123c36c 100644--- a/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/orcaTeamStore.test.ts@@ -1,15 +1,18 @@import Database from 'better-sqlite3';import { drizzle } from 'drizzle-orm/better-sqlite3';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { DbClient } from '../client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';import { tx as runInprocTx } from '../worker/opHandlers/tx.js';+import { setSessionRouteLockImplementation } from '../sessionRouteLock.js';+import { setSessionRuntimeCleanup } from '../sessionRuntimeCleanup.js';import * as schema from '../schema.js';const h = vi.hoisted(() => ({tapWindowBroadcast: vi.fn(),notifyAgentIslandSessionPatch: vi.fn(),+ runtimeCleanup: vi.fn(),}));vi.mock('electron', () => ({@@ -29,7 +32,14 @@ describe('orcaTeamStore', () => {let currentClient: DbClient | null = null;let rawDb: Database.Database | null = null;+ beforeEach(() => {+ setSessionRuntimeCleanup(h.runtimeCleanup);+ setSessionRouteLockImplementation(null);+ });+afterEach(async () => {+ setSessionRuntimeCleanup(null);+ setSessionRouteLockImplementation(null);vi.clearAllMocks();if (currentClient) {clearCurrentDbClient(currentClient);@@ -104,6 +114,9 @@ describe('orcaTeamStore', () => {expect(h.notifyAgentIslandSessionPatch).toHaveBeenCalledWith('worker-session-2', {status: 'archived',});+ expect(h.runtimeCleanup).toHaveBeenCalledTimes(2);+ expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');+ expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-2');});it('never archives or broadcasts a worker task that is already deleted', async () => {@@ -127,6 +140,7 @@ describe('orcaTeamStore', () => {sessionId: 'worker-session-2',patch: { status: 'archived' },});+ expect(h.runtimeCleanup).not.toHaveBeenCalledWith('worker-session-2');});it('reconciles only still-active workers from inactive teams', async () => {@@ -153,6 +167,58 @@ describe('orcaTeamStore', () => {{ id: 'worker-session-1', status: 'archived' },{ id: 'worker-session-2', status: 'deleted' },]);+ expect(h.runtimeCleanup).toHaveBeenCalledTimes(1);+ expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');+ });++ it('cleans archived worker runtime state before releasing route locks and broadcasting', async () => {+ const { archiveWorkersByTeam } = await import('../orcaTeamStore.js');+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');+ await seedOrcaWorkers(client);++ const events: string[] = [];+ setSessionRuntimeCleanup((sessionId) => events.push(`cleanup:${sessionId}`));+ setSessionRouteLockImplementation(async (sessionId, task) => {+ events.push(`lock:${sessionId}:start`);+ const result = await task();+ events.push(`lock:${sessionId}:end`);+ return result;+ });+ h.tapWindowBroadcast.mockImplementation(() => {+ events.push('broadcast');+ });++ await archiveWorkersByTeam('team-1');++ expect(events).toEqual([+ 'lock:worker-session-1:start',+ 'lock:worker-session-2:start',+ 'cleanup:worker-session-1',+ 'cleanup:worker-session-2',+ 'lock:worker-session-2:end',+ 'lock:worker-session-1:end',+ 'broadcast',+ 'broadcast',+ ]);+ });++ it('cleans runtime state when a single worker is archived and skips deleted workers', async () => {+ const { archiveSingleWorkerSession } = await import('../orcaTeamStore.js');+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');+ await seedOrcaWorkers(client);++ await archiveSingleWorkerSession('worker-session-1');+ expect(h.runtimeCleanup).toHaveBeenCalledWith('worker-session-1');++ h.runtimeCleanup.mockClear();+ await client.exec('UPDATE sessions SET status = ? WHERE id = ?', [+ 'deleted',+ 'worker-session-2',+ ]);+ await archiveSingleWorkerSession('worker-session-2');+ expect(h.runtimeCleanup).not.toHaveBeenCalled();});it('preserves Pi worker identity in Orca projections', async () => {diff --git a/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.tsindex 4b118b9e11..533911d96f 100644--- a/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/sessionLegacyUsdProjection.test.ts@@ -5,9 +5,13 @@* 手机端等只消费 totalCostUsd 的读方在全量 reseed 后不丢新增 USD 花费。*/-import { describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it } from 'vitest';-import { sessionToCamel, type SessionRowWithCount } from '../mapper';+import { sessionToCamel, setSessionRuntimeProjector, type SessionRowWithCount } from '../mapper';++afterEach(() => {+ setSessionRuntimeProjector(null);+});function sessionRow(overrides: Partial<SessionRowWithCount>,@@ -84,3 +88,101 @@ describe('sessionToCamel legacy totalCostUsd projection', () => {expect(session.totalCostUsd).toBe(1.5);});});++describe('sessionToCamel runtime projection', () => {+ it('adds the effective runtime route to shared desktop and device-link snapshots', () => {+ setSessionRuntimeProjector((session) => ({+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ runtimeGeneration: 4,+ runtimeBaseline: {+ agentKind: 'codex',+ model: session.model,+ providerId: session.providerId ?? null,+ effort: session.effort,+ fastMode: session.fastMode,+ },+ runtimeEffective: {+ agentKind: 'codex',+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ },+ runtimePending: null,+ }));++ const session = sessionToCamel(+ sessionRow({+ agentKind: 'codex',+ model: 'gpt-baseline',+ providerId: 'xd',+ effort: 'high',+ fastMode: false,+ }),+ );++ expect(session).toMatchObject({+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ runtimeGeneration: 4,+ runtimeBaseline: {+ model: 'gpt-baseline',+ providerId: 'xd',+ effort: 'high',+ fastMode: false,+ },+ runtimeEffective: {+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ },+ runtimePending: null,+ });+ });++ it('clears the baseline effort when the effective runtime model has fixed strength', () => {+ setSessionRuntimeProjector((session) => ({+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: '',+ fastMode: false,+ runtimeGeneration: 5,+ runtimeBaseline: {+ agentKind: 'codex',+ model: session.model,+ providerId: session.providerId ?? null,+ effort: session.effort,+ fastMode: session.fastMode,+ },+ runtimeEffective: {+ agentKind: 'codex',+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: null,+ fastMode: false,+ },+ runtimePending: null,+ }));++ const session = sessionToCamel(+ sessionRow({ model: 'gpt-baseline', effort: 'high', providerId: 'xd' }),+ );++ expect(session.model).toBe('fixed-strength-model');+ expect(session.effort).toBe('');+ expect(session.runtimeEffective?.effort).toBeNull();+ });++ it('removes the injected runtime projection when the composition root is reset', () => {+ setSessionRuntimeProjector(() => ({ model: 'temporary-model' }));+ setSessionRuntimeProjector(null);++ expect(sessionToCamel(sessionRow({ model: 'persisted-model' })).model).toBe('persisted-model');+ });+});diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex 12a311090a..459593a45f 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -857,18 +857,17 @@ function orcaCancelStaleTeams(readyDb, args) {function orcaArchiveWorkersByTeam(readyDb, args) {const payload = asRecord(args, 'orca.archiveWorkersByTeam args');const teamId = expectString(payload.teamId, 'teamId');- const now = expectNumber(payload.now, 'now');- const selectCandidates = readyDb.prepare(- "SELECT sessions.id FROM orca_workers INNER JOIN sessions ON orca_workers.session_id = sessions.id WHERE orca_workers.team_id = ? AND sessions.status = 'active' ORDER BY sessions.id",+ const sessionIds = expectArray(payload.sessionIds, 'sessionIds').map((value, index) =>+ expectString(value, 'sessionIds[' + index + ']'),);+ const now = expectNumber(payload.now, 'now');const archiveSession = readyDb.prepare(- "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active' AND EXISTS (SELECT 1 FROM orca_workers WHERE orca_workers.session_id = sessions.id AND orca_workers.team_id = ?)",);return readyDb.transaction(() => {- const candidates = selectCandidates.all(teamId);const updatedIds = [];- for (const { id } of candidates) {- if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);+ for (const id of sessionIds) {+ if (archiveSession.run(now, id, teamId).changes > 0) updatedIds.push(id);}return updatedIds;})();@@ -877,22 +876,21 @@ function orcaArchiveWorkersByTeam(readyDb, args) {function orcaReconcileInactiveTeamWorkersForLead(readyDb, args) {const payload = asRecord(args, 'orca.reconcileInactiveTeamWorkersForLead args');const leadSessionId = expectString(payload.leadSessionId, 'leadSessionId');- const now = expectNumber(payload.now, 'now');- const selectCandidates = readyDb.prepare(- "SELECT sessions.id FROM orca_workers INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id INNER JOIN sessions ON orca_workers.session_id = sessions.id WHERE orca_teams.lead_session_id = ? AND orca_teams.status != 'active' AND sessions.status = 'active' ORDER BY sessions.id",+ const sessionIds = expectArray(payload.sessionIds, 'sessionIds').map((value, index) =>+ expectString(value, 'sessionIds[' + index + ']'),);+ const now = expectNumber(payload.now, 'now');const finishWorkers = readyDb.prepare("UPDATE orca_workers SET status = 'done', updated_at = ? WHERE team_id IN (SELECT id FROM orca_teams WHERE lead_session_id = ? AND status != 'active')",);const archiveSession = readyDb.prepare(- "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",+ "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active' AND EXISTS (SELECT 1 FROM orca_workers INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id WHERE orca_workers.session_id = sessions.id AND orca_teams.lead_session_id = ? AND orca_teams.status != 'active')",);return readyDb.transaction(() => {- const candidates = selectCandidates.all(leadSessionId);finishWorkers.run(now, leadSessionId);const updatedIds = [];- for (const { id } of candidates) {- if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);+ for (const id of sessionIds) {+ if (archiveSession.run(now, id, leadSessionId).changes > 0) updatedIds.push(id);}return updatedIds;})();@@ -905,6 +903,12 @@ function orcaUpsertWorker(readyDb, args) {const sessionId = expectString(payload.sessionId, 'sessionId');const now = expectNumber(payload.now, 'now');readyDb.transaction(() => {+ const activeTeam = readyDb.prepare(+ "SELECT 1 FROM orca_teams WHERE id = ? AND status = 'active' LIMIT 1",+ ).get(teamId);+ if (!activeTeam) {+ throw new Error('Orca team ' + teamId + ' is no longer active');+ }if (payload.focused === true) {readyDb.prepare('UPDATE orca_workers SET focused = 0, updated_at = ? WHERE team_id = ? AND focused = 1').run(now, teamId);}diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 7c269520bb..9d1029b4e7 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -2101,11 +2101,16 @@ describe('db worker tx handlers', () => {}await expect(- client.tx('orca.archiveWorkersByTeam', { teamId: 'active-team', now: 100 }),+ client.tx('orca.archiveWorkersByTeam', {+ teamId: 'active-team',+ sessionIds: ['active-worker'],+ now: 100,+ }),).resolves.toEqual(['active-worker']);await expect(client.tx('orca.reconcileInactiveTeamWorkersForLead', {leadSessionId: 'lead',+ sessionIds: ['orphan-worker'],now: 200,}),).resolves.toEqual(['orphan-worker']);@@ -2166,6 +2171,35 @@ describe('db worker tx handlers', () => {});});+ it.each([+ { label: 'bundled worker', useInlineWorker: false },+ { label: 'inline worker', useInlineWorker: true },+ ])('rejects a worker link persisted after its team has ended in the $label tx path', async ({ useInlineWorker }) => {+ await withClient(async (client) => {+ await seedSession(client, 'lead');+ await seedSession(client, 'late-worker', { orcaRole: 'worker' });+ await client.exec(+ 'INSERT INTO orca_teams (id, lead_session_id, status, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, ?, ?)',+ ['team-1', 'lead', 'completed', 1, 2, 2],+ );++ await expect(client.tx('orca.upsertWorker', {+ id: 'late-worker-link',+ teamId: 'team-1',+ sessionId: 'late-worker',+ status: 'idle',+ label: 'late',+ role: 'reviewer',+ focused: false,+ now: 3,+ })).rejects.toThrow('Orca team team-1 is no longer active');++ await expect(+ client.queryOne('SELECT id FROM orca_workers WHERE id = ?', ['late-worker-link']),+ ).resolves.toBeUndefined();+ }, { useInlineWorker });+ });+it('counts terminal workers until their sessions are archived', async () => {await withClient(async (client) => {await seedSession(client, 'lead');diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex a44cd9d087..835fe0b262 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -261,12 +261,14 @@ export interface OrcaCancelStaleTeamsArgs {/** Archive every still-active worker session linked to one team. */export interface OrcaArchiveWorkersByTeamArgs {teamId: string;+ sessionIds: string[];now: number;}/** Repair active worker sessions left behind under a lead's inactive teams. */export interface OrcaReconcileInactiveTeamWorkersForLeadArgs {leadSessionId: string;+ sessionIds: string[];now: number;}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex 82151cef27..05d7587e50 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -49,6 +49,7 @@ const h = vi.hoisted(() => ({routeLock: vi.fn(async <T>(_sessionId: string, task: () => Promise<T>): Promise<T> =>task(),) as SessionRouteLockMock,+ runtimeCleanup: vi.fn(),userDataDir: null as string | null,}));@@ -116,7 +117,12 @@ vi.mock('../../../cindy-brain/index.js', () => ({notifyGhostSessionEvent: vi.fn(),}));-import { registerSessionIpc, resumeDeletedPiSubagentCleanup } from '../sessions';+import {+ patchSessionMetaInDb,+ registerSessionIpc,+ resumeDeletedPiSubagentCleanup,+ setSessionRuntimeCleanup,+} from '../sessions';import { retireDeletedPiSubagentState } from '../piSubagentDeletion';import { setSessionRouteLockImplementation } from '../../sessionRouteLock';import { assertTrustedAppRendererEvent } from '../../../security/trustedAppRenderer.js';@@ -234,10 +240,12 @@ beforeEach(() => {h.userDataDir = mkdtempSync(path.join(os.tmpdir(), 'cindy-sessions-update-'));createDb();setSessionRouteLockImplementation(h.routeLock);+ setSessionRuntimeCleanup(h.runtimeCleanup);registerSessionIpc(undefined, { closeIdleSessionForMove: h.closeIdleSessionForMove });});afterEach(async () => {+ setSessionRuntimeCleanup(null);setSessionRouteLockImplementation(null);const dir = h.userDataDir;if (dir) {@@ -542,6 +550,38 @@ describe('local-db:sessions:update handler wiring', () => {});});+ it('cleans runtime state before releasing the local terminal status lock', async () => {+ const order: string[] = [];+ h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {+ const result = await task();+ order.push('lock-released');+ h.sqlite!.prepare("UPDATE sessions SET status = 'active' WHERE id = ?").run('codex-local');+ return result;+ });++ await invokeUpdate('codex-local', { status: 'archived' });++ expect(order).toEqual(['runtime-cleanup', 'lock-released']);+ expect(h.runtimeCleanup).toHaveBeenCalledOnce();+ });++ it('cleans runtime state before releasing the remote terminal status lock', async () => {+ const order: string[] = [];+ h.runtimeCleanup.mockImplementationOnce(() => order.push('runtime-cleanup'));+ h.routeLock.mockImplementationOnce(async (_sessionId, task) => {+ const result = await task();+ order.push('lock-released');+ h.sqlite!.prepare("UPDATE sessions SET status = 'active' WHERE id = ?").run('codex-local');+ return result;+ });++ await patchSessionMetaInDb('codex-local', { status: 'archived' });++ expect(order).toEqual(['runtime-cleanup', 'lock-released']);+ expect(h.runtimeCleanup).toHaveBeenCalledOnce();+ });+// 竞态收敛(review on #3225):写入与查询不在同一串行区间,归档写入后、查询前// 另一窗口可能已把行推进到 deleted。广播必须携带持久化后的 updated.status,// 否则副窗/控制端镜像会被请求值回滚成旧 UI 状态(已删除任务复活)。diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex bdb294e0f3..a247f8e15d 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -62,8 +62,11 @@ import { assertTrustedAppRendererEvent } from '../../security/trustedAppRendererimport { removeTurnChangeSetsForSession } from '../../turn-change-set/store.js';import { quiesceSessionBeforeWorktreeRecycle } from './sessionRemovalOperations.js';import { withSessionRouteLock, withSessionRouteLocks } from '../sessionRouteLock.js';+import { cleanupSessionRuntimeForTerminalStatus } from '../sessionRuntimeCleanup.js';import { broadcastSubagentRunsInvalidated } from './subagentRuns.js';+export { setSessionRuntimeCleanup } from '../sessionRuntimeCleanup.js';+const log = createLogger('sessions');const REMOTE_EDITABLE_META = new Set(['status', 'title', 'pinnedAt']);const initialSessionListLogged = new Set<string>();@@ -1462,7 +1465,10 @@ export function registerSessionIpc(await withStatusWriteLock(sid,p.status,- () => writeSessionPatch(db, sid, setObj, p.status),+ async () => {+ await writeSessionPatch(db, sid, setObj, p.status);+ cleanupSessionRuntimeForTerminalStatus(sid, p.status);+ },p.workingDir !== undefined,);// session-git-pr-context:/clear 经此处写 clearedAt——边界之前的消息对用户@@ -1675,6 +1681,7 @@ export async function patchSessionMetaInDb(await db.update(sessions).set({ summary: null }).where(eq(sessions.id, sessionId));row.summary = null;}+ cleanupSessionRuntimeForTerminalStatus(sessionId, patch.status);return sessionToCamel(row);});notifyAgentIslandSessionPatch(updated.id, {@@ -1827,16 +1834,20 @@ export async function setSessionsStatusInDb(if (sessionIds.length === 0) return [];const ownerScope = captureOwnerScope();const dbClient = getDbClient();- const applied = await withSessionRouteLocks(sessionIds, () =>- dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {+ const applied = await withSessionRouteLocks(sessionIds, async () => {+ const rows = await dbClient.tx('sessions.setStatus', { sessionIds, status }).catch((err) => {const code = (err as { code?: string }).code;const message = err instanceof Error ? err.message : String(err);if (code === 'NOT_FOUND' || code === 'INVALID_PARAMS' || code === 'PRECONDITION_FAILED') {throwIpcError(code, message);}throw err;- }),- );+ });+ for (const item of rows) {+ cleanupSessionRuntimeForTerminalStatus(item.sessionId, item.status);+ }+ return rows;+ });if (!isOwnerScopeCurrent(ownerScope))return applied.map((item) => ({sessionId: item.sessionId,diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 023b1f445b..dccdd3c031 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -63,6 +63,13 @@ type ProjectAutomationConsentInsert = typeof projectAutomationConsents.$inferInstype ScheduleRunRow = typeof scheduleRuns.$inferSelect;type ScheduleRunInsert = typeof scheduleRuns.$inferInsert;+type SessionRuntimeProjector = (session: Session) => Partial<Session>;+let sessionRuntimeProjector: SessionRuntimeProjector | null = null;++export function setSessionRuntimeProjector(projector: SessionRuntimeProjector | null): void {+ sessionRuntimeProjector = projector;+}+/*** SessionRow + 同 session 下 messages 总条数。IPC handler 必须通过 LEFT JOIN + GROUP BY* 或子查询同时带出 messageCount,再交给 `sessionToCamel`。@@ -183,7 +190,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {const legacyUsdProjection =row.totalCostUsd +(row.totalCostCurrency === 'USD' ? row.totalCostAmount : 0);- return {+ const base: Session = {id: row.id,userId: '', // 本地 db 已按 user 隔离,无需冗余存储title: row.title,@@ -227,6 +234,7 @@ export function sessionToCamel(row: SessionRowWithCount): Session {),summary: row.summary ?? null,};+ return sessionRuntimeProjector ? { ...base, ...sessionRuntimeProjector(base) } : base;}export function messageToCamel(row: MessageRow): Message {diff --git a/apps/desktop/src/main/localDb/orcaTeamStore.ts b/apps/desktop/src/main/localDb/orcaTeamStore.tsindex ee4beee359..e9395cf6c9 100644--- a/apps/desktop/src/main/localDb/orcaTeamStore.ts+++ b/apps/desktop/src/main/localDb/orcaTeamStore.ts@@ -8,6 +8,8 @@ import { createLogger } from '../logger.js';import { throwIpcError } from '../utils/ipcValidate.js';import { tapWindowBroadcast } from '../device-link/broadcast-tap.js';import { notifyAgentIslandSessionPatch } from './agentIslandSessionPatch.js';+import { withSessionRouteLock, withSessionRouteLocks } from './sessionRouteLock.js';+import { cleanupSessionRuntimeForTerminalStatus } from './sessionRuntimeCleanup.js';const log = createLogger('orca-team-store');@@ -246,9 +248,15 @@ export async function markTeamEnded(* orca_role 字段保留 'worker' 不动 — 历史上下文识别需要它。*/export async function archiveWorkersByTeam(teamId: string): Promise<string[]> {- const updatedIds = await getDbClient().tx('orca.archiveWorkersByTeam', {- teamId,- now: Date.now(),+ const candidateIds = await listActiveWorkerSessionIdsForTeam(teamId);+ const updatedIds = await withSessionRouteLocks(candidateIds, async () => {+ const ids = await getDbClient().tx('orca.archiveWorkersByTeam', {+ teamId,+ sessionIds: candidateIds,+ now: Date.now(),+ });+ for (const id of ids) cleanupSessionRuntimeForTerminalStatus(id, 'archived');+ return ids;});for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });return updatedIds;@@ -283,9 +291,15 @@ export async function markWorkersStatusByTeam(export async function reconcileInactiveTeamWorkersForLead(leadSessionId: string,): Promise<string[]> {- const updatedIds = await getDbClient().tx('orca.reconcileInactiveTeamWorkersForLead', {- leadSessionId,- now: Date.now(),+ const candidateIds = await listActiveWorkerSessionIdsForInactiveTeams(leadSessionId);+ const updatedIds = await withSessionRouteLocks(candidateIds, async () => {+ const ids = await getDbClient().tx('orca.reconcileInactiveTeamWorkersForLead', {+ leadSessionId,+ sessionIds: candidateIds,+ now: Date.now(),+ });+ for (const id of ids) cleanupSessionRuntimeForTerminalStatus(id, 'archived');+ return ids;});for (const id of updatedIds) broadcastSessionPatch(id, { status: 'archived' });return updatedIds;@@ -510,14 +524,44 @@ export async function setWorkerFocus(teamId: string, workerId: string): Promise<* 归档单个 worker session, 不牵连同 team 其他 worker。*/export async function archiveSingleWorkerSession(sessionId: string): Promise<void> {- const db = getDbClient().drizzle;- const now = Date.now();- const result = await db- .update(sessions)- .set({ status: 'archived', updatedAt: now })- .where(and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted')))- .run();- if (result.changes > 0) broadcastSessionPatch(sessionId, { status: 'archived' });+ const changed = await withSessionRouteLock(sessionId, async () => {+ const result = await getDbClient().drizzle+ .update(sessions)+ .set({ status: 'archived', updatedAt: Date.now() })+ .where(and(eq(sessions.id, sessionId), ne(sessions.status, 'deleted')))+ .run();+ if (result.changes === 0) return false;+ cleanupSessionRuntimeForTerminalStatus(sessionId, 'archived');+ return true;+ });+ if (changed) broadcastSessionPatch(sessionId, { status: 'archived' });+}++async function listActiveWorkerSessionIdsForTeam(teamId: string): Promise<string[]> {+ const rows = await getDbClient().drizzle+ .select({ id: sessions.id })+ .from(orcaWorkers)+ .innerJoin(sessions, eq(orcaWorkers.sessionId, sessions.id))+ .where(and(eq(orcaWorkers.teamId, teamId), eq(sessions.status, 'active')))+ .orderBy(sessions.id);+ return rows.map((row) => row.id);+}++async function listActiveWorkerSessionIdsForInactiveTeams(+ leadSessionId: string,+): Promise<string[]> {+ const rows = await getDbClient().drizzle+ .select({ id: sessions.id })+ .from(orcaWorkers)+ .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))+ .innerJoin(sessions, eq(orcaWorkers.sessionId, sessions.id))+ .where(and(+ eq(orcaTeams.leadSessionId, leadSessionId),+ ne(orcaTeams.status, 'active'),+ eq(sessions.status, 'active'),+ ))+ .orderBy(sessions.id);+ return rows.map((row) => row.id);}export async function setSessionOrcaRole(diff --git a/apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts b/apps/desktop/src/main/localDb/sessionRuntimeCleanup.tsnew file mode 100644index 0000000000..c15e05e55c--- /dev/null+++ b/apps/desktop/src/main/localDb/sessionRuntimeCleanup.ts@@ -0,0 +1,19 @@+type SessionRuntimeCleanup = (sessionId: string) => void;++let sessionRuntimeCleanup: SessionRuntimeCleanup | null = null;++/** Composition-root injection for Host-owned runtime routing state. */+export function setSessionRuntimeCleanup(cleanup: SessionRuntimeCleanup | null): void {+ sessionRuntimeCleanup = cleanup;+}++/**+ * Runtime model/provider/axis overrides survive ordinary process release, but+ * not task archive/delete boundaries. Call this while holding the task route+ * lock that commits the terminal status so a queued mutation cannot recreate+ * state between the DB write and cleanup.+ */+export function cleanupSessionRuntimeForTerminalStatus(sessionId: string, status: unknown): void {+ if (status !== 'deleted' && status !== 'archived') return;+ sessionRuntimeCleanup?.(sessionId);+}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex ee0c120923..fa2475bb72 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -1559,22 +1559,24 @@ function orcaCancelStaleTeams(db: Database.Database, args: unknown): void {function orcaArchiveWorkersByTeam(db: Database.Database, args: unknown): string[] {const payload = asRecord(args, 'orca.archiveWorkersByTeam args');const teamId = expectString(payload.teamId, 'teamId');- const now = expectNumber(payload.now, 'now');- const selectCandidates = db.prepare(- `SELECT sessions.id- FROM orca_workers- INNER JOIN sessions ON orca_workers.session_id = sessions.id- WHERE orca_workers.team_id = ? AND sessions.status = 'active'- ORDER BY sessions.id`,+ const sessionIds = expectArray(payload.sessionIds, 'sessionIds').map((value, index) =>+ expectString(value, `sessionIds[${index}]`),);+ const now = expectNumber(payload.now, 'now');const archiveSession = db.prepare(- "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",+ `UPDATE sessions+ SET status = 'archived', updated_at = ?+ WHERE id = ? AND status = 'active'+ AND EXISTS (+ SELECT 1 FROM orca_workers+ WHERE orca_workers.session_id = sessions.id+ AND orca_workers.team_id = ?+ )`,);const transaction = db.transaction(() => {- const candidates = selectCandidates.all(teamId) as Array<{ id: string }>;const updatedIds: string[] = [];- for (const { id } of candidates) {- if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);+ for (const id of sessionIds) {+ if (archiveSession.run(now, id, teamId).changes > 0) updatedIds.push(id);}return updatedIds;});@@ -1587,17 +1589,10 @@ function orcaReconcileInactiveTeamWorkersForLead(): string[] {const payload = asRecord(args, 'orca.reconcileInactiveTeamWorkersForLead args');const leadSessionId = expectString(payload.leadSessionId, 'leadSessionId');- const now = expectNumber(payload.now, 'now');- const selectCandidates = db.prepare(- `SELECT sessions.id- FROM orca_workers- INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id- INNER JOIN sessions ON orca_workers.session_id = sessions.id- WHERE orca_teams.lead_session_id = ?- AND orca_teams.status != 'active'- AND sessions.status = 'active'- ORDER BY sessions.id`,+ const sessionIds = expectArray(payload.sessionIds, 'sessionIds').map((value, index) =>+ expectString(value, `sessionIds[${index}]`),);+ const now = expectNumber(payload.now, 'now');const finishWorkers = db.prepare(`UPDATE orca_workersSET status = 'done', updated_at = ?@@ -1607,14 +1602,23 @@ function orcaReconcileInactiveTeamWorkersForLead()`,);const archiveSession = db.prepare(- "UPDATE sessions SET status = 'archived', updated_at = ? WHERE id = ? AND status = 'active'",+ `UPDATE sessions+ SET status = 'archived', updated_at = ?+ WHERE id = ? AND status = 'active'+ AND EXISTS (+ SELECT 1+ FROM orca_workers+ INNER JOIN orca_teams ON orca_workers.team_id = orca_teams.id+ WHERE orca_workers.session_id = sessions.id+ AND orca_teams.lead_session_id = ?+ AND orca_teams.status != 'active'+ )`,);const transaction = db.transaction(() => {- const candidates = selectCandidates.all(leadSessionId) as Array<{ id: string }>;finishWorkers.run(now, leadSessionId);const updatedIds: string[] = [];- for (const { id } of candidates) {- if (archiveSession.run(now, id).changes > 0) updatedIds.push(id);+ for (const id of sessionIds) {+ if (archiveSession.run(now, id, leadSessionId).changes > 0) updatedIds.push(id);}return updatedIds;});@@ -1628,6 +1632,12 @@ function orcaUpsertWorker(db: Database.Database, args: unknown): void {const sessionId = expectString(payload.sessionId, 'sessionId');const now = expectNumber(payload.now, 'now');db.transaction(() => {+ const activeTeam = db.prepare(+ "SELECT 1 FROM orca_teams WHERE id = ? AND status = 'active' LIMIT 1",+ ).get(teamId);+ if (!activeTeam) {+ throw new Error(`Orca team ${teamId} is no longer active`);+ }if (payload.focused === true) {db.prepare('UPDATE orca_workers SET focused = 0, updated_at = ? WHERE team_id = ? AND focused = 1').run(now, teamId);}diff --git a/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.tsindex 1b53ec34d0..759ad588f2 100644--- a/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/model-route-guard.test.ts@@ -568,6 +568,7 @@ describe('materializeExclusiveProviderRoute', () => {it('SET_MODEL undefined 保持当前 custom 来源,不会改绑 xAI', () => {expect(resolveSetModelGuardProviderId(undefined, 'my-litellm')).toBe('my-litellm');+ expect(resolveSetModelGuardProviderId(null, 'my-litellm')).toBeNull();expect(resolveExclusiveSetModelReroute(undefined,'my-litellm',diff --git a/apps/desktop/src/main/maker-host/__tests__/session-effort-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/session-effort-store.test.tsnew file mode 100644index 0000000000..e7875a30f3--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/session-effort-store.test.ts@@ -0,0 +1,35 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++describe('session effort store', () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it('clears a stale effort when a fixed-effort runtime profile supplies null', async () => {+ const { getSessionEffort, setSessionEffort } = await import('../session-effort-store');++ setSessionEffort('fixed-effort', 'xhigh');+ expect(getSessionEffort('fixed-effort')).toBe('xhigh');++ setSessionEffort('fixed-effort', null);+ expect(getSessionEffort('fixed-effort')).toBeNull();+ });++ it('clears every owner-scoped effort and Fast axis at an account boundary', async () => {+ const {+ clearAllSessionRuntimeAxes,+ getSessionEffort,+ getSessionFastMode,+ setSessionEffort,+ setSessionFastMode,+ } = await import('../session-effort-store');++ setSessionEffort('owner-effort', 'xhigh');+ setSessionFastMode('owner-fast', true);++ clearAllSessionRuntimeAxes();++ expect(getSessionEffort('owner-effort')).toBeNull();+ expect(getSessionFastMode('owner-fast')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/maker-host/session-effort-store.ts b/apps/desktop/src/main/maker-host/session-effort-store.tsindex 0cb30e20a0..971b01181d 100644--- a/apps/desktop/src/main/maker-host/session-effort-store.ts+++ b/apps/desktop/src/main/maker-host/session-effort-store.ts@@ -11,16 +11,19 @@** 纯内存;keyed by xdt sessionId(与 session-provider-store 同键)。未记录的会话 → effort 读到* null(bridge 回退默认档)、fast 读到 false(不发 service_tier)。条目是 sessionId → 短字符串 /- * 布尔,量级 = 本次运行触过的会话数,不做关闭清理(与 session-provider-store 同取舍;重启即清,- * 复开会话由 bootstrapSession / IM turnRunner 从 DB 重新 hydrate 覆盖)。+ * 布尔,量级 = 本次运行触过的会话数。普通进程关闭不清理,使 runtime override 能跨 lazy+ * rehydrate 保留;任务归档/删除的终态边界会清理,复开后由 bootstrapSession / IM turnRunner+ * 从 DB baseline 重新 hydrate。*/const bySession = new Map<string, string>();const fastBySession = new Set<string>();-/** 记下某会话当前 effort(SET_EFFORT / hydrate 时调用)。 */-export function setSessionEffort(sessionId: string, effort: string): void {- if (effort && effort.trim()) bySession.set(sessionId, effort.trim());+/** 记下某会话当前 effort(SET_EFFORT / hydrate 时调用); nullish/空值显式清除。 */+export function setSessionEffort(sessionId: string, effort: string | null | undefined): void {+ const normalized = effort?.trim();+ if (normalized) bySession.set(sessionId, normalized);+ else bySession.delete(sessionId);}/** 读取某会话 effort;未记录返回 null(bridge 走默认档)。 */@@ -38,3 +41,9 @@ export function setSessionFastMode(sessionId: string, enabled: boolean): void {export function getSessionFastMode(sessionId: string): boolean {return fastBySession.has(sessionId);}++/** 账户 / app-session 边界清理全部 owner-scoped 运行时轴。 */+export function clearAllSessionRuntimeAxes(): void {+ bySession.clear();+ fastBySession.clear();+}diff --git a/apps/desktop/src/main/maker-host/session-provider-store.ts b/apps/desktop/src/main/maker-host/session-provider-store.tsindex 7636a4132d..65c5e0b790 100644--- a/apps/desktop/src/main/maker-host/session-provider-store.ts+++ b/apps/desktop/src/main/maker-host/session-provider-store.ts@@ -54,3 +54,8 @@ export function hydrateSessionProvider(sessionId: string, providerId: string | nexport function clearSessionProvider(sessionId: string): void {bySession.delete(sessionId);}++/** 账户 / app-session 边界清理全部 owner-scoped 路由。 */+export function clearAllSessionProviders(): void {+ bySession.clear();+}diff --git a/apps/desktop/src/main/maker-host/session-runtime-fallback-store.ts b/apps/desktop/src/main/maker-host/session-runtime-fallback-store.tsnew file mode 100644index 0000000000..0800902cc3--- /dev/null+++ b/apps/desktop/src/main/maker-host/session-runtime-fallback-store.ts@@ -0,0 +1,45 @@+import { app } from 'electron';+import path from 'node:path';++import { desktopMakerLogger } from './logger-adapter.js';+import {+ createOverrideSettingsFile,+ type OverrideSettingsState,+} from './override-settings-file.js';++const log = desktopMakerLogger.child('session-runtime-fallback-store');++export interface SessionRuntimeFallbackSettings {+ enabled: boolean;+}++const DEFAULTS: SessionRuntimeFallbackSettings = { enabled: false };++const store = createOverrideSettingsFile<SessionRuntimeFallbackSettings>({+ filePath: () => path.join(app.getPath('userData'), 'session-runtime-fallback-settings.json'),+ defaults: DEFAULTS,+ normalize: (raw) => ({+ enabled:+ raw && typeof raw === 'object' && typeof (raw as { enabled?: unknown }).enabled === 'boolean'+ ? (raw as { enabled: boolean }).enabled+ : DEFAULTS.enabled,+ }),+ log,+ label: 'session runtime fallback',+});++export function readSessionRuntimeFallbackSettings(): SessionRuntimeFallbackSettings {+ return store.read();+}++export function readSessionRuntimeFallbackSettingsState(): OverrideSettingsState<SessionRuntimeFallbackSettings> {+ return store.readState();+}++export function writeSessionRuntimeFallbackEnabled(enabled: boolean): void {+ store.writePatch({ enabled });+}++export function resetSessionRuntimeFallbackSettings(): SessionRuntimeFallbackSettings {+ return store.reset();+}diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSelectionAxes.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSelectionAxes.test.tsnew file mode 100644index 0000000000..7352aa4443--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSelectionAxes.test.ts@@ -0,0 +1,385 @@+import { describe, expect, it, vi } from 'vitest';++import {+ applyRuntimeSelectionAxesWithRecovery,+ commitRuntimeAxisAfterPersistence,+ isSupportedRuntimeEffort,+ resolveRetainedRuntimeEffort,+} from '../runtimeSelectionAxes.js';++describe('isSupportedRuntimeEffort', () => {+ it('accepts catalog effort values and rejects unknown wire input', () => {+ expect(isSupportedRuntimeEffort('minimal')).toBe(true);+ expect(isSupportedRuntimeEffort('ultra')).toBe(true);+ expect(isSupportedRuntimeEffort('bogus')).toBe(false);+ expect(isSupportedRuntimeEffort(null)).toBe(false);+ });+});++describe('resolveRetainedRuntimeEffort', () => {+ it('clears stale live effort for a fixed-effort target', () => {+ expect(+ resolveRetainedRuntimeEffort({+ targetModelHasFixedEffort: true,+ requestedEffort: undefined,+ liveEffort: 'ultra',+ previousEffort: 'high',+ }),+ ).toBeNull();+ expect(+ resolveRetainedRuntimeEffort({+ targetModelHasFixedEffort: true,+ requestedEffort: null,+ liveEffort: null,+ previousEffort: 'high',+ }),+ ).toBeNull();+ });++ it('uses the retained live effort before the previous store for variable-effort models', () => {+ expect(+ resolveRetainedRuntimeEffort({+ targetModelHasFixedEffort: false,+ requestedEffort: undefined,+ liveEffort: 'xhigh',+ previousEffort: 'medium',+ }),+ ).toBe('xhigh');+ expect(+ resolveRetainedRuntimeEffort({+ targetModelHasFixedEffort: false,+ requestedEffort: undefined,+ liveEffort: null,+ previousEffort: 'medium',+ }),+ ).toBe('medium');+ });+});++describe('applyRuntimeSelectionAxesWithRecovery', () => {+ it('commits the control stores only after every live axis succeeds', async () => {+ const order: string[] = [];+ await applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'codex',+ setEffort: vi.fn(async () => {+ order.push('effort');+ }),+ setFastMode: vi.fn(async () => {+ order.push('fast');+ }),+ },+ effort: 'high',+ fastMode: true,+ commitControlStores: () => order.push('commit'),+ restoreControlStores: () => order.push('restore'),+ terminateSession: vi.fn(async () => {+ order.push('terminate');+ }),+ });++ expect(order).toEqual(['effort', 'fast', 'commit']);+ });++ it('applies only the explicitly requested Fast axis', async () => {+ const setEffort = vi.fn(async () => {});+ const setFastMode = vi.fn(async () => {});+ await applyRuntimeSelectionAxesWithRecovery({+ session: { agentKind: 'codex', setEffort, setFastMode },+ effort: 'high',+ fastMode: true,+ applyEffort: false,+ applyFastMode: true,+ commitControlStores: vi.fn(),+ restoreControlStores: vi.fn(),+ terminateSession: vi.fn(),+ });++ expect(setEffort).not.toHaveBeenCalled();+ expect(setFastMode).toHaveBeenCalledWith(true);+ });++ it('retires a live session before committing a fixed-effort profile', async () => {+ const order: string[] = [];+ const setEffort = vi.fn(async () => {+ order.push('effort');+ });+ const setFastMode = vi.fn(async () => {+ order.push('fast');+ });+ const restoreControlStores = vi.fn(() => order.push('restore'));++ await applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'codex',+ setEffort,+ setFastMode,+ },+ effort: null,+ fastMode: true,+ commitControlStores: () => order.push('commit'),+ restoreControlStores,+ terminateSession: vi.fn(async () => {+ order.push('terminate');+ }),+ });++ expect(order).toEqual(['terminate', 'commit']);+ expect(setEffort).not.toHaveBeenCalled();+ expect(setFastMode).not.toHaveBeenCalled();+ expect(restoreControlStores).not.toHaveBeenCalled();+ });++ it('does not restore or commit axis stores after the owner changes during a live RPC', async () => {+ const ownerBoundaryError = new Error('owner changed');+ let ownerCurrent = true;+ const commitControlStores = vi.fn();+ const restoreControlStores = vi.fn();+ const terminateSession = vi.fn();++ await expect(+ applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'codex',+ setEffort: vi.fn(async () => {+ ownerCurrent = false;+ }),+ setFastMode: vi.fn(),+ },+ effort: 'high',+ fastMode: true,+ assertCanCommit: () => {+ if (!ownerCurrent) throw ownerBoundaryError;+ },+ commitControlStores,+ restoreControlStores,+ terminateSession,+ }),+ ).rejects.toBe(ownerBoundaryError);++ expect(commitControlStores).not.toHaveBeenCalled();+ expect(restoreControlStores).not.toHaveBeenCalled();+ expect(terminateSession).not.toHaveBeenCalled();+ });++ it('does not commit axis stores after the owner changes during the Fast RPC', async () => {+ const ownerBoundaryError = new Error('owner changed');+ let ownerCurrent = true;+ const commitControlStores = vi.fn();+ const restoreControlStores = vi.fn();+ const terminateSession = vi.fn();++ await expect(+ applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'codex',+ setEffort: vi.fn(async () => undefined),+ setFastMode: vi.fn(async () => {+ ownerCurrent = false;+ }),+ },+ effort: 'high',+ fastMode: true,+ assertCanCommit: () => {+ if (!ownerCurrent) throw ownerBoundaryError;+ },+ commitControlStores,+ restoreControlStores,+ terminateSession,+ }),+ ).rejects.toBe(ownerBoundaryError);++ expect(commitControlStores).not.toHaveBeenCalled();+ expect(restoreControlStores).not.toHaveBeenCalled();+ expect(terminateSession).not.toHaveBeenCalled();+ });++ it('does not repopulate fixed-effort stores after the owner changes during termination', async () => {+ const ownerBoundaryError = new Error('owner changed');+ let ownerCurrent = true;+ const commitControlStores = vi.fn();+ const restoreControlStores = vi.fn();++ await expect(+ applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'claude-code',+ setEffort: vi.fn(),+ setFastMode: vi.fn(),+ },+ effort: null,+ fastMode: false,+ assertCanCommit: () => {+ if (!ownerCurrent) throw ownerBoundaryError;+ },+ commitControlStores,+ restoreControlStores,+ terminateSession: vi.fn(async () => {+ ownerCurrent = false;+ }),+ }),+ ).rejects.toBe(ownerBoundaryError);++ expect(commitControlStores).not.toHaveBeenCalled();+ expect(restoreControlStores).not.toHaveBeenCalled();+ });++ it('restores the old stores when a fixed-effort session cannot be retired', async () => {+ const terminationError = new Error('close rejected');+ const commitControlStores = vi.fn();+ const restoreControlStores = vi.fn();+ const recoverLiveProfileAfterTerminationFailure = vi.fn();++ await expect(+ applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'claude-code',+ setEffort: vi.fn(),+ setFastMode: vi.fn(),+ },+ effort: null,+ fastMode: false,+ commitControlStores,+ restoreControlStores,+ recoverLiveProfileAfterTerminationFailure,+ terminateSession: vi.fn(async () => {+ throw terminationError;+ }),+ }),+ ).rejects.toBe(terminationError);++ expect(restoreControlStores).toHaveBeenCalledOnce();+ expect(recoverLiveProfileAfterTerminationFailure).toHaveBeenCalledOnce();+ expect(commitControlStores).not.toHaveBeenCalled();+ });++ it('commits an axis only after persistence succeeds', async () => {+ const order: string[] = [];+ await commitRuntimeAxisAfterPersistence({+ persist: async () => {+ order.push('persist');+ },+ commit: () => order.push('commit'),+ });+ expect(order).toEqual(['persist', 'commit']);+ });++ it('recovers the live axis without committing when persistence fails', async () => {+ const persistenceError = new Error('sqlite rejected');+ const order: string[] = [];+ await expect(+ commitRuntimeAxisAfterPersistence({+ persist: async () => {+ order.push('persist');+ throw persistenceError;+ },+ commit: () => order.push('commit'),+ recoverAfterPersistenceFailure: async () => {+ order.push('recover');+ },+ }),+ ).rejects.toBe(persistenceError);+ expect(order).toEqual(['persist', 'recover']);+ });++ it('does not commit after the owner boundary changes during persistence', async () => {+ const ownerBoundaryError = new Error('owner changed');+ let ownerCurrent = true;+ const commit = vi.fn();++ await expect(+ commitRuntimeAxisAfterPersistence({+ persist: async () => {+ ownerCurrent = false;+ },+ assertCanCommit: () => {+ if (!ownerCurrent) throw ownerBoundaryError;+ },+ commit,+ }),+ ).rejects.toBe(ownerBoundaryError);++ expect(commit).not.toHaveBeenCalled();+ });++ it('does not run persistence recovery after the owner boundary changes', async () => {+ const persistenceError = new Error('sqlite rejected');+ const ownerBoundaryError = new Error('owner changed');+ const recoverAfterPersistenceFailure = vi.fn();++ await expect(+ commitRuntimeAxisAfterPersistence({+ persist: async () => {+ throw persistenceError;+ },+ assertCanCommit: () => {+ throw ownerBoundaryError;+ },+ commit: vi.fn(),+ recoverAfterPersistenceFailure,+ }),+ ).rejects.toBe(ownerBoundaryError);++ expect(recoverAfterPersistenceFailure).not.toHaveBeenCalled();+ });++ it('restores the old stores and retires a partially-mutated session on axis failure', async () => {+ const order: string[] = [];+ const axisError = new Error('fast transport disconnected');+ const commitControlStores = vi.fn(() => order.push('commit'));++ await expect(+ applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'codex',+ setEffort: vi.fn(async () => {+ order.push('effort');+ }),+ setFastMode: vi.fn(async () => {+ order.push('fast');+ throw axisError;+ }),+ },+ effort: 'xhigh',+ fastMode: true,+ commitControlStores,+ restoreControlStores: () => order.push('restore'),+ terminateSession: vi.fn(async () => {+ order.push('terminate');+ }),+ }),+ ).rejects.toBe(axisError);++ expect(order).toEqual(['effort', 'fast', 'restore', 'terminate']);+ expect(commitControlStores).not.toHaveBeenCalled();+ });++ it('reports both failures when the partially-mutated session cannot be retired', async () => {+ const axisError = new Error('effort rejected');+ const terminationError = new Error('close rejected');+ const recoverLiveProfileAfterTerminationFailure = vi.fn();+ const result = applyRuntimeSelectionAxesWithRecovery({+ session: {+ agentKind: 'claude-code',+ setEffort: vi.fn(async () => {+ throw axisError;+ }),+ setFastMode: vi.fn(async () => undefined),+ },+ effort: 'high',+ fastMode: false,+ commitControlStores: vi.fn(),+ restoreControlStores: vi.fn(),+ recoverLiveProfileAfterTerminationFailure,+ terminateSession: vi.fn(async () => {+ throw terminationError;+ }),+ });++ await expect(result).rejects.toMatchObject({+ name: 'AggregateError',+ errors: [axisError, terminationError],+ });+ expect(recoverLiveProfileAfterTerminationFailure).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.tsindex 3d675cc6c9..19a1329f31 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts@@ -5,7 +5,11 @@ import {getSessionProvider,setSessionProvider,} from '../../maker-host/session-provider-store.js';-import { applyRuntimeSetModelChange, type RuntimeSetModelMaker } from '../runtimeSetModel.js';+import {+ applyRuntimeSetModelChange,+ isRemoteModelSwitchRouteChangeError,+ type RuntimeSetModelMaker,+} from '../runtimeSetModel.js';const sessionProviderWriteObserver = vi.hoisted(() => ({current: null as ((sessionId: string, providerId: string | null) => void) | null,@@ -39,6 +43,22 @@ function rememberSession(sessionId: string): string {return sessionId;}+describe('isRemoteModelSwitchRouteChangeError', () => {+ it('recognizes both IPC codes and remote daemon message markers', () => {+ expect(+ isRemoteModelSwitchRouteChangeError({ code: 'REMOTE_MODEL_SWITCH_ROUTE_CHANGE' }),+ ).toBe(true);+ expect(+ isRemoteModelSwitchRouteChangeError(+ new Error('[REMOTE_MODEL_SWITCH_ROUTE_CHANGE] close and recreate'),+ ),+ ).toBe(true);+ expect(isRemoteModelSwitchRouteChangeError(new Error('ordinary set-model failure'))).toBe(+ false,+ );+ });+});+describe('applyRuntimeSetModelChange', () => {it('rolls back provider route when live setModel rejects', async () => {const sessionId = rememberSession('runtime-set-model-rollback');@@ -834,6 +854,71 @@ describe('applyRuntimeSetModelChange', () => {expect(wakeSessionInputQueue).toHaveBeenCalledOnce();});+ it('rebuilds an idle Orca Worker instead of hot-switching its live model', async () => {+ const sessionId = rememberSession('runtime-set-model-orca-worker-rebuild');+ setSessionProvider(sessionId, 'xd');+ const setModel = vi.fn(async () => {});+ const closeSession = vi.fn(async () => {});+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'codex',+ remoteHostId: null,+ model: 'gpt-5.5',+ setModel,+ }),+ listActiveSessions: () => [+ { id: sessionId, agentKind: 'codex', remoteHostId: null, isTurnRunning: () => false },+ ],+ closeSession,+ };++ await expect(applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.4',+ providerId: 'xd',+ forceSessionRebuild: true,+ clearPendingCredentialSwitch: vi.fn(),+ })).resolves.toEqual({ status: 'applied' });++ expect(closeSession).toHaveBeenCalledWith(sessionId);+ expect(setModel).not.toHaveBeenCalled();+ });++ it('defers a busy Orca Worker rebuild to the turn boundary', async () => {+ const sessionId = rememberSession('runtime-set-model-orca-worker-defer');+ setSessionProvider(sessionId, 'xd');+ const registerPendingCredentialSwitch = vi.fn();+ const setModel = vi.fn(async () => {});+ const maker: RuntimeSetModelMaker = {+ getSession: () => ({+ agentKind: 'codex',+ remoteHostId: null,+ model: 'gpt-5.5',+ setModel,+ }),+ listActiveSessions: () => [+ { id: sessionId, agentKind: 'codex', remoteHostId: null, isTurnRunning: () => true },+ ],+ closeSession: vi.fn(async () => {}),+ };++ await expect(applyRuntimeSetModelChange({+ maker,+ sessionId,+ model: 'gpt-5.4',+ providerId: 'xd',+ forceSessionRebuild: true,+ registerPendingCredentialSwitch,+ })).resolves.toEqual({ status: 'deferred' });++ expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {+ model: 'gpt-5.4',+ providerId: 'xd',+ });+ expect(setModel).not.toHaveBeenCalled();+ });+it('falls back to the busy throw when no pending channel is injected', async () => {// 老调用方(未注入 registerPendingCredentialSwitch)保持旧 fail-closed 语义。const sessionId = rememberSession('runtime-set-model-defer-no-channel');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.tsindex 8134e83ad6..4b41ef2747 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts@@ -90,6 +90,39 @@ function setup(opts?: {sessionExists: vi.fn(async () => opts?.exists ?? true),getLiveSession,getSessionActivitySnapshot: vi.fn(async () => activity),+ getSessionRuntimeDetails: vi.fn(async () => ({+ ...activity,+ runtimeGeneration: 0,+ baselineProfile: {+ agentKind: 'codex' as const,+ model: 'model',+ providerId: 'openai',+ effort: 'medium' as const,+ fastMode: false,+ },+ effectiveProfile: {+ agentKind: 'codex' as const,+ model: 'model',+ providerId: 'openai',+ effort: 'medium' as const,+ fastMode: false,+ },+ pendingMutation: null,+ fallbackEnabled: false,+ })),+ setSessionRuntime: vi.fn(async () => ({+ ok: true as const,+ status: 'applied' as const,+ generation: 1,+ effectiveProfile: {+ agentKind: 'codex' as const,+ model: 'next',+ providerId: 'openai',+ effort: 'high' as const,+ fastMode: false,+ },+ pendingMutation: null,+ })),assertExternalInputAllowed: vi.fn(async () => undefined),createQueuedMessage: vi.fn(async ({@@ -365,6 +398,32 @@ describe('session control domain service', () => {);});+ it('forwards an atomic runtime patch only after the target is known to exist', async () => {+ const { deps, service } = setup();+ await expect(+ service.setSessionRuntime({+ targetSessionId: 'target',+ expectedGeneration: 4,+ patch: { model: 'next', effort: 'high', fastMode: true },+ }),+ ).resolves.toMatchObject({ ok: true, status: 'applied', generation: 1 });+ expect(deps.setSessionRuntime).toHaveBeenCalledWith({+ targetSessionId: 'target',+ expectedGeneration: 4,+ patch: { model: 'next', effort: 'high', fastMode: true },+ });++ const missing = setup({ exists: false, live: false });+ await expect(+ missing.service.setSessionRuntime({+ targetSessionId: 'gone',+ expectedGeneration: 0,+ patch: { effort: 'high' },+ }),+ ).resolves.toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ expect(missing.deps.setSessionRuntime).not.toHaveBeenCalled();+ });+it('prefers an in-memory live session when persisted metadata is unavailable', async () => {const { deps, live, service } = setup();deps.sessionExists.mockRejectedValue(new Error('localDb not ready'));diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionProviderBootstrap.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionProviderBootstrap.test.tsindex 37bcc339d7..68fb25b15d 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionProviderBootstrap.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionProviderBootstrap.test.ts@@ -1,6 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';import {+ clearAllSessionProviders,clearSessionProvider,getSessionProvider,hydrateSessionProvider,@@ -84,4 +85,14 @@ describe('persistAndHydrateSessionProvider', () => {expect(getSessionProvider(TEST_SESSION_ID)).toBe('anthropic');});++ it('clears every owner-scoped provider route at an account boundary', () => {+ setSessionProvider(TEST_SESSION_ID, 'anthropic');+ setSessionProvider('session-provider-bootstrap-other', 'openai');++ clearAllSessionProviders();++ expect(getSessionProvider(TEST_SESSION_ID)).toBeNull();+ expect(getSessionProvider('session-provider-bootstrap-other')).toBeNull();+ });});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.tsnew file mode 100644index 0000000000..2b9f2d3416--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts@@ -0,0 +1,767 @@+import { afterEach, describe, expect, it } from 'vitest';+import type { ProviderView } from '@cindy/model-providers';++import {+ acceptSessionRuntimeAxisMutation,+ acceptSessionRuntimeMutation,+ cancelPendingSessionRuntimeMutation,+ captureSessionRuntimeControlOwnerEpoch,+ clearAllSessionRuntimeControlStates,+ clearSessionRuntimeControlState,+ deferSessionRuntimeAxisMutation,+ getSessionRuntimeControlSnapshot,+ isPendingSessionRuntimeRouteExplicit,+ mergeSessionRuntimeProfilePatch,+ pickSessionRuntimeFallback,+ recordFailedSessionRuntimeFallbackCandidate,+ recordRecoveredSessionRuntimeMutation,+ recordRecoveredSessionRuntimeAxisMutation,+ recordUserSessionRuntimeAxisMutation,+ recordUserSessionRuntimeMutation,+ resolveCompatibleSessionRuntimeAxisPatch,+ resolveSessionRuntimeAxes,+ sessionRuntimeControlOwnerEpochMatches,+ sessionRuntimeGenerationMatches,+ settlePendingSessionRuntimeMutation,+ type SessionRuntimeProfile,+} from '../sessionRuntimeControl.js';++afterEach(() => {+ clearAllSessionRuntimeControlStates();+});++const current: SessionRuntimeProfile = {+ agentKind: 'codex',+ model: 'gpt-main',+ providerId: 'openai',+ effort: 'high',+ fastMode: true,+};++function provider(+ id: string,+ models: Array<{+ id: string;+ defaults?: boolean;+ efforts?: SessionRuntimeProfile['effort'][];+ fast?: boolean;+ group?: string;+ mode?: string;+ }>,+ source: 'builtin' | 'user' = 'builtin',+): ProviderView {+ return {+ id,+ name: id,+ source,+ connected: true,+ agents: ['codex'],+ auth: { method: 'none' },+ routing: { codex: { wireProtocol: 'openai-responses' } },+ models: {+ codex: models.map((model) => ({+ id: model.id,+ name: model.id,+ contextWindow: 100_000,+ efforts: (model.efforts ?? ['medium']) as never,+ defaultEffort: (model.efforts?.[0] ?? 'medium') as never,+ supportsFastMode: model.fast,+ ...(model.group ? { group: model.group } : {}),+ ...(model.mode ? { mode: model.mode } : {}),+ ...(model.defaults ? { newSessionDefault: ['codex'] } : {}),+ })),+ },+ } as unknown as ProviderView;+}++describe('session runtime control state', () => {+ it('uses one monotonic generation for deferred and settled mutations', () => {+ const sessionId = 'runtime-generation';+ expect(sessionRuntimeGenerationMatches(sessionId, 0)).toBe(true);+ const generation = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: current,+ deferred: true,+ });+ expect(generation).toBe(1);+ expect(settlePendingSessionRuntimeMutation(sessionId, generation)).toBe(true);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation: 1,+ pending: null,+ effectiveOverride: current,+ });+ });++ it('a user selection invalidates pending and fallback state', () => {+ const sessionId = 'runtime-user-wins';+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'fallback',+ profile: current,+ deferred: true,+ });+ const generation = recordUserSessionRuntimeMutation(sessionId);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ pending: null,+ effectiveOverride: null,+ fallbackHop: 0,+ visitedRoutes: [],+ });+ });++ it('rejects a stale generation after a newer user mutation', () => {+ const sessionId = 'runtime-stale-generation';+ const observed = getSessionRuntimeControlSnapshot(sessionId).generation;+ recordUserSessionRuntimeMutation(sessionId);+ expect(sessionRuntimeGenerationMatches(sessionId, observed)).toBe(false);+ });++ it('a user effort change keeps an active temporary route but invalidates fallback progress', () => {+ const sessionId = 'runtime-user-axis';+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'fallback',+ profile: current,+ deferred: false,+ });+ recordUserSessionRuntimeAxisMutation(sessionId, { effort: 'max' });+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ effectiveOverride: { ...current, effort: 'max' },+ pending: null,+ fallbackHop: 0,+ visitedRoutes: [],+ });+ });++ it('preserves a deferred route when a user changes one runtime axis', () => {+ const sessionId = 'runtime-user-axis-pending';+ const pending = { ...current, model: 'gpt-next', providerId: 'xd', fastMode: false };+ const firstGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });++ const secondGeneration = recordUserSessionRuntimeAxisMutation(sessionId, {+ fastMode: true,+ });++ expect(secondGeneration).toBe(firstGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation: secondGeneration,+ effectiveOverride: null,+ pending: {+ generation: secondGeneration,+ source: 'agent',+ profile: { ...pending, fastMode: true },+ },+ fallbackHop: 0,+ visitedRoutes: [],+ });+ });++ it('applies an Agent axis patch without replacing its accepted pending route', () => {+ const sessionId = 'runtime-agent-axis-pending';+ const live = { ...current, model: 'gpt-live' };+ const pending = { ...current, model: 'gpt-next', providerId: 'xd', fastMode: false };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: live,+ deferred: false,+ });+ const pendingGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });++ const generation = acceptSessionRuntimeAxisMutation({+ sessionId,+ source: 'agent',+ profile: { ...live, effort: 'max' },+ pendingPatch: { effort: 'max' },+ });++ expect(generation).toBe(pendingGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: { ...live, effort: 'max' },+ pending: {+ generation,+ source: 'agent',+ profile: { ...pending, effort: 'max' },+ },+ });+ expect(isPendingSessionRuntimeRouteExplicit(sessionId, generation)).toBe(true);+ });++ it('records an Agent axis-only override when the live profile started from baseline', () => {+ const generation = acceptSessionRuntimeAxisMutation({+ sessionId: 'runtime-agent-axis-baseline',+ source: 'agent',+ profile: { ...current, effort: 'max' },+ pendingPatch: { effort: 'max' },+ });++ expect(getSessionRuntimeControlSnapshot('runtime-agent-axis-baseline')).toMatchObject({+ generation,+ effectiveOverride: { ...current, effort: 'max' },+ pending: null,+ });+ });++ it('defers an Agent axis-only patch without changing the busy live profile', () => {+ const sessionId = 'runtime-agent-axis-busy';+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: current,+ deferred: false,+ });++ const generation = deferSessionRuntimeAxisMutation({+ sessionId,+ source: 'agent',+ effectiveProfile: current,+ pendingPatch: { effort: 'max' },+ });++ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: current,+ pending: {+ generation,+ source: 'agent',+ profile: { ...current, effort: 'max' },+ },+ });+ expect(isPendingSessionRuntimeRouteExplicit(sessionId, generation)).toBe(false);+ });++ it('patches an accepted deferred route while keeping the effective route unchanged', () => {+ const sessionId = 'runtime-agent-axis-busy-with-route';+ const effective = { ...current, model: 'gpt-live', providerId: 'openai' };+ const pending = { ...current, model: 'gpt-next', providerId: 'xd', fastMode: false };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: effective,+ deferred: false,+ });+ const pendingGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });++ const generation = deferSessionRuntimeAxisMutation({+ sessionId,+ source: 'agent',+ effectiveProfile: effective,+ pendingPatch: { effort: 'max' },+ });++ expect(generation).toBe(pendingGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: effective,+ pending: {+ generation,+ source: 'agent',+ profile: { ...pending, effort: 'max' },+ },+ });+ expect(isPendingSessionRuntimeRouteExplicit(sessionId, generation)).toBe(true);+ });++ it('updates the live override and deferred route when a user changes one runtime axis', () => {+ const sessionId = 'runtime-user-axis-effective-and-pending';+ const effective = { ...current, model: 'gpt-live', providerId: 'openai' };+ const pending = { ...current, model: 'gpt-next', providerId: 'xd', fastMode: false };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: effective,+ deferred: false,+ });+ const pendingGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });++ const generation = recordUserSessionRuntimeAxisMutation(sessionId, {+ fastMode: true,+ effort: 'max',+ });++ expect(generation).toBe(pendingGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: { ...effective, fastMode: true, effort: 'max' },+ pending: {+ generation,+ source: 'agent',+ profile: { ...pending, fastMode: true, effort: 'max' },+ },+ });+ });++ it('keeps pending axes compatible while applying the user patch to the live override', () => {+ const sessionId = 'runtime-user-axis-incompatible-pending';+ const effective = { ...current, model: 'gpt-live' };+ const pending = {+ ...current,+ model: 'gpt-fixed',+ providerId: 'xd',+ effort: null,+ fastMode: false,+ };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: effective,+ deferred: false,+ });+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });++ recordUserSessionRuntimeAxisMutation(+ sessionId,+ { effort: 'ultra', fastMode: true },+ { effort: null, fastMode: false },+ );++ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ effectiveOverride: { ...effective, effort: 'ultra', fastMode: true },+ pending: { profile: pending },+ });+ });++ it('cancels only the unchanged pending generation after settlement fails', () => {+ const sessionId = 'runtime-cancel-pending';+ const effective = { ...current, model: 'gpt-live' };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: effective,+ deferred: false,+ });+ const generation = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: { ...current, model: 'gpt-next' },+ deferred: true,+ });++ expect(cancelPendingSessionRuntimeMutation(sessionId, generation - 1)).toBe(false);+ expect(cancelPendingSessionRuntimeMutation(sessionId, generation)).toBe(true);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: effective,+ pending: null,+ });+ expect(cancelPendingSessionRuntimeMutation('runtime-missing', 0)).toBe(false);+ expect(getSessionRuntimeControlSnapshot('runtime-missing')).toMatchObject({+ generation: 0,+ effectiveOverride: null,+ pending: null,+ });+ });++ it('records an unavoidable live profile after persistence recovery fails', () => {+ const sessionId = 'runtime-persistence-recovery';+ const observedGeneration = getSessionRuntimeControlSnapshot(sessionId).generation;+ const generation = recordRecoveredSessionRuntimeMutation(sessionId, current);++ expect(generation).toBe(observedGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: current,+ pending: null,+ fallbackHop: 0,+ visitedRoutes: [],+ });+ expect(sessionRuntimeGenerationMatches(sessionId, observedGeneration)).toBe(false);+ });++ it('records an unavoidable live axis while preserving a deferred route', () => {+ const sessionId = 'runtime-axis-recovery';+ const pending = { ...current, model: 'gpt-next', providerId: 'xd' };+ const pendingGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });+ const live = { ...current, effort: 'high' as const };++ const generation = recordRecoveredSessionRuntimeAxisMutation(sessionId, live);++ expect(generation).toBe(pendingGeneration + 1);+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({+ generation,+ effectiveOverride: live,+ pending: { generation, source: 'agent', profile: pending },+ });+ });++ it('clears one terminal session without disturbing another runtime override', () => {+ acceptSessionRuntimeMutation({+ sessionId: 'runtime-clear-one',+ source: 'agent',+ profile: current,+ deferred: false,+ });+ acceptSessionRuntimeMutation({+ sessionId: 'runtime-keep-one',+ source: 'agent',+ profile: { ...current, model: 'gpt-other' },+ deferred: false,+ });++ clearSessionRuntimeControlState('runtime-clear-one');++ expect(getSessionRuntimeControlSnapshot('runtime-clear-one')).toMatchObject({+ generation: 0,+ effectiveOverride: null,+ pending: null,+ });+ expect(getSessionRuntimeControlSnapshot('runtime-keep-one').effectiveOverride).toMatchObject({+ model: 'gpt-other',+ });+ });++ it('clears every runtime override at an account boundary', () => {+ const previousOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();+ acceptSessionRuntimeMutation({+ sessionId: 'runtime-owner-a',+ source: 'agent',+ profile: current,+ deferred: true,+ });+ acceptSessionRuntimeMutation({+ sessionId: 'runtime-owner-b',+ source: 'fallback',+ profile: { ...current, providerId: 'xd' },+ deferred: false,+ });++ clearAllSessionRuntimeControlStates();++ expect(getSessionRuntimeControlSnapshot('runtime-owner-a').generation).toBe(0);+ expect(getSessionRuntimeControlSnapshot('runtime-owner-b').generation).toBe(0);+ expect(sessionRuntimeControlOwnerEpochMatches(previousOwnerEpoch)).toBe(false);+ expect(sessionRuntimeControlOwnerEpochMatches(captureSessionRuntimeControlOwnerEpoch())).toBe(+ true,+ );+ });++ it('preserves null effort in a deferred fixed-effort switch', () => {+ const generation = acceptSessionRuntimeMutation({+ sessionId: 'runtime-fixed-effort',+ source: 'agent',+ profile: { ...current, effort: null },+ deferred: true,+ });++ expect(getSessionRuntimeControlSnapshot('runtime-fixed-effort').pending).toEqual({+ generation,+ source: 'agent',+ profile: { ...current, effort: null },+ });+ });++ it('composes a later partial patch on the already accepted pending profile', () => {+ const sessionId = 'runtime-compose-pending';+ const pending = { ...current, model: 'gpt-next', providerId: 'xd', fastMode: false };+ const firstGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: pending,+ deferred: true,+ });+ const firstSnapshot = getSessionRuntimeControlSnapshot(sessionId);+ expect(firstSnapshot.pending?.generation).toBe(firstGeneration);++ const composed = mergeSessionRuntimeProfilePatch(firstSnapshot.pending!.profile, {+ fastMode: true,+ });+ const secondGeneration = acceptSessionRuntimeMutation({+ sessionId,+ source: 'agent',+ profile: composed,+ deferred: true,+ });+ expect(secondGeneration).toBe(firstGeneration + 1);+ expect(settlePendingSessionRuntimeMutation(sessionId, secondGeneration)).toBe(true);+ expect(getSessionRuntimeControlSnapshot(sessionId).effectiveOverride).toEqual({+ ...pending,+ fastMode: true,+ });+ });+});++describe('session runtime fallback selection', () => {+ it('normalizes a user axis patch against the pending target capabilities', () => {+ const fixed = provider('xd', [+ { id: 'gpt-fixed', efforts: [], fast: false },+ ]).models.codex![0]!;+ expect(+ resolveCompatibleSessionRuntimeAxisPatch({+ model: fixed,+ profile: { ...current, model: 'gpt-fixed', effort: null, fastMode: false },+ patch: { effort: 'ultra', fastMode: true },+ }),+ ).toEqual({ effort: null, fastMode: false });+ });++ it('skips a failed candidate without consuming a fallback hop or generation', () => {+ const sessionId = 'runtime-failed-candidate';+ const candidate = { ...current, providerId: 'xd' };+ const observed = getSessionRuntimeControlSnapshot(sessionId);++ expect(+ recordFailedSessionRuntimeFallbackCandidate(sessionId, observed.generation, candidate),+ ).toBe(true);+ const afterFailure = getSessionRuntimeControlSnapshot(sessionId);+ expect(afterFailure).toMatchObject({+ generation: observed.generation,+ fallbackHop: observed.fallbackHop,+ visitedRoutes: ['xd\u0000gpt-main'],+ });++ expect(+ pickSessionRuntimeFallback({+ providers: [+ provider('openai', [{ id: 'gpt-main' }]),+ provider('xd', [{ id: 'gpt-main' }]),+ provider('other', [{ id: 'gpt-main' }]),+ ],+ current,+ visitedRoutes: afterFailure.visitedRoutes,+ currentHop: afterFailure.fallbackHop,+ maxHops: 2,+ }),+ ).toMatchObject({ providerId: 'other', model: 'gpt-main' });+ });++ it('does not record a failed candidate against a stale generation', () => {+ const sessionId = 'runtime-stale-failed-candidate';+ const observed = getSessionRuntimeControlSnapshot(sessionId).generation;+ recordUserSessionRuntimeMutation(sessionId);++ expect(+ recordFailedSessionRuntimeFallbackCandidate(sessionId, observed, {+ ...current,+ providerId: 'xd',+ }),+ ).toBe(false);+ expect(getSessionRuntimeControlSnapshot(sessionId).visitedRoutes).toEqual([]);+ });++ it('rejects explicit unsupported axes and normalizes inherited axes', () => {+ const model = provider('xd', [+ { id: 'gpt-main', efforts: ['medium'], fast: false },+ ]).models.codex![0]!;+ const fixedEffortModel = provider('xd', [+ { id: 'gpt-fixed', efforts: [], fast: false },+ ]).models.codex![0]!;+ expect(+ resolveSessionRuntimeAxes({+ model,+ effort: 'ultra',+ fastMode: false,+ effortExplicit: true,+ fastExplicit: false,+ }),+ ).toEqual({ ok: false, reason: 'effort-unavailable' });+ expect(+ resolveSessionRuntimeAxes({+ model,+ effort: 'high',+ fastMode: true,+ effortExplicit: false,+ fastExplicit: false,+ }),+ ).toEqual({ ok: true, effort: 'medium', fastMode: false });+ expect(+ resolveSessionRuntimeAxes({+ model: fixedEffortModel,+ effort: 'low',+ fastMode: false,+ effortExplicit: true,+ fastExplicit: false,+ }),+ ).toEqual({ ok: false, reason: 'effort-unavailable' });+ expect(+ resolveSessionRuntimeAxes({+ model: fixedEffortModel,+ effort: 'low',+ fastMode: false,+ effortExplicit: true,+ fastExplicit: false,+ allowFixedEffortPlaceholder: true,+ }),+ ).toEqual({ ok: true, effort: null, fastMode: false });+ });++ it('prefers the same model on another connected source', () => {+ const result = pickSessionRuntimeFallback({+ providers: [+ provider('openai', [{ id: 'gpt-main' }]),+ provider('xd', [{ id: 'gpt-main', efforts: ['medium'], fast: false }]),+ provider('other', [{ id: 'recommended', defaults: true }]),+ ],+ current,+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ });+ expect(result).toMatchObject({+ providerId: 'xd',+ model: 'gpt-main',+ effort: 'medium',+ fastMode: false,+ });+ });++ it('ignores disconnected sources even when they offer the same model', () => {+ const disconnected = provider('disconnected', [{ id: 'gpt-main' }]);+ disconnected.connected = false;+ expect(+ pickSessionRuntimeFallback({+ providers: [provider('openai', [{ id: 'gpt-main' }]), disconnected],+ current,+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ }),+ ).toBeNull();+ });++ it('uses only an explicitly declared same-harness default after exact-name routes', () => {+ const providers = [+ provider('openai', [{ id: 'gpt-main' }]),+ provider('xd', [{ id: 'arbitrary-first' }, { id: 'recommended', defaults: true }]),+ ];+ expect(+ pickSessionRuntimeFallback({+ providers,+ current,+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ }),+ ).toMatchObject({ providerId: 'xd', model: 'recommended' });+ });++ it('skips non-chat exact-name and default candidates before later usable routes', () => {+ expect(+ pickSessionRuntimeFallback({+ providers: [+ provider('openai', [{ id: 'gpt-main' }]),+ provider('image-copy', [{ id: 'gpt-main', mode: 'image_generation' }]),+ provider('chat-copy', [{ id: 'gpt-main' }]),+ ],+ current,+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ }),+ ).toMatchObject({ providerId: 'chat-copy', model: 'gpt-main' });++ expect(+ pickSessionRuntimeFallback({+ providers: [+ provider('openai', [{ id: 'gpt-main' }]),+ provider('image-default', [+ { id: 'image-recommended', defaults: true, mode: 'image_generation' },+ ]),+ provider('chat-default', [{ id: 'chat-recommended', defaults: true }]),+ ],+ current: { ...current, model: 'missing-model' },+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ }),+ ).toMatchObject({ providerId: 'chat-default', model: 'chat-recommended' });+ });++ it('keeps custom-group models selectable for a user provider', () => {+ expect(+ pickSessionRuntimeFallback({+ providers: [+ provider('openai', [{ id: 'gpt-main' }]),+ provider(+ 'custom',+ [{ id: 'gpt-image-custom', defaults: true, group: 'custom:custom' }],+ 'user',+ ),+ ],+ current: { ...current, model: 'missing-model' },+ visitedRoutes: [],+ currentHop: 0,+ maxHops: 2,+ }),+ ).toMatchObject({ providerId: 'custom', model: 'gpt-image-custom' });+ });++ it('stops at the hop limit and never revisits a route', () => {+ const providers = [provider('xd', [{ id: 'gpt-main' }])];+ expect(+ pickSessionRuntimeFallback({+ providers,+ current,+ visitedRoutes: ['xd\u0000gpt-main'],+ currentHop: 1,+ maxHops: 2,+ }),+ ).toBeNull();+ expect(+ pickSessionRuntimeFallback({+ providers,+ current,+ visitedRoutes: [],+ currentHop: 2,+ maxHops: 2,+ }),+ ).toBeNull();+ });++ it('persists the route being left so fallback cannot bounce A to B to A', () => {+ const sessionId = 'runtime-no-bounce';+ const next = { ...current, providerId: 'xd' };+ acceptSessionRuntimeMutation({+ sessionId,+ source: 'fallback',+ previousProfile: current,+ profile: next,+ deferred: false,+ });+ const state = getSessionRuntimeControlSnapshot(sessionId);+ expect(state.visitedRoutes).toEqual(+ expect.arrayContaining(['openai\u0000gpt-main', 'xd\u0000gpt-main']),+ );+ expect(+ pickSessionRuntimeFallback({+ providers: [provider('openai', [{ id: 'gpt-main' }])],+ current: next,+ visitedRoutes: state.visitedRoutes,+ currentHop: state.fallbackHop,+ maxHops: 2,+ }),+ ).toBeNull();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex d1c9f10a0c..c98f70af65 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -367,6 +367,9 @@ export const MAKER_INVOKE = {SILENT_ENCRYPTED_RETRY_GET: 'maker:silent-encrypted-retry:get',SILENT_ENCRYPTED_RETRY_SET: 'maker:silent-encrypted-retry:set',SILENT_ENCRYPTED_RETRY_RESET: 'maker:silent-encrypted-retry:reset',+ SESSION_RUNTIME_FALLBACK_GET: 'maker:session-runtime-fallback:get',+ SESSION_RUNTIME_FALLBACK_SET: 'maker:session-runtime-fallback:set',+ SESSION_RUNTIME_FALLBACK_RESET: 'maker:session-runtime-fallback:reset',/*** Claude Code 与 Pi 共用的自动上下文压缩触发阈值 —— <userData>/compaction-settings.json。* 经 runtimeConfig.autoCompactThresholdPct getter 热读,当前会话下一轮结束即按新值判断。diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 02992deef4..9216ba17f5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -35,7 +35,11 @@ import type {SessionSendResult,UserMessage,} from '@cindy/maker-core';-import { storedCustomProviderId } from '@cindy/model-providers';+import {+ effectiveSourceIdForModel,+ findCatalogModel,+ storedCustomProviderId,+} from '@cindy/model-providers';import { createId } from '@paralleldrive/cuid2';import {GATEWAY_PROXY_TOKEN_INVALID_REASON,@@ -60,7 +64,7 @@ import {isAppSessionBoundaryPending,} from '../appSessionState.js';import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';-import type { AgentMeta } from '../../renderer/lib/ccAgent.types';+import type { AgentMeta, Session as RendererSession } from '../../renderer/lib/ccAgent.types';import {deriveAutoTitleSeed,getAgentFacingText,@@ -212,7 +216,7 @@ import {updateMessageContent,} from '../localDb/ipc/messages.js';import { invalidateWorkersByLeadSingleFlight } from '../localDb/ipc/orcaWorkerListSingleFlight.js';-import { messageToCamel } from '../localDb/mapper.js';+import { messageToCamel, setSessionRuntimeProjector } from '../localDb/mapper.js';import { visibleMessageTextForConversationSearch } from '../localDb/conversationSearch.pure.js';import { buildReviewPrompt } from '../reviewer/reviewPrompt.js';import {@@ -279,6 +283,7 @@ import {getSessionRowSnapshotStrict,persistSessionFields,recycleSessionWorktreeForStatusChange,+ setSessionRuntimeCleanup,} from '../localDb/ipc/sessions.js';// sidebar-card-mode: turn-done 后刷新列表预览,并按需生成置顶卡片摘要import {@@ -567,6 +572,7 @@ import {recordTurnSpend,} from '../usageBroadcaster.js';import { requireEnum, requireObject, throwIpcError } from '../utils/ipcValidate.js';+import { isIpcError } from '../../shared/ipc-errors.js';import {runPiPackageListIpcBoundary,runPiPackageMutationIpcBoundary,@@ -710,7 +716,6 @@ import { tryInjectProjectContext } from './projectContextInject.js';import { registerMakerSessionCreateHandler } from './sessionCreateHandler.js';import {applyPendingAgentSwitchIfIdle,- applySetModelThenCancelAgentSwitchIntent,createPendingAgentSwitchRegistry,registerMakerSessionAgentSwitchHandler,type MakerSessionAgentSwitchHandlerDeps,@@ -758,6 +763,7 @@ import {} from '../maker-host/createDesktopProviderService.js';import { readOrcaWorkerProviderRoutingContext } from './orcaProviderRoutingContext.js';import {+ clearSessionProvider,getSessionProvider,hasSessionProvider,hydrateSessionProvider,@@ -813,10 +819,12 @@ import {storeCustomProviderKey,} from '../secrets/providerSecretStore.js';import {+ getSessionEffort,getSessionFastMode,setSessionEffort,setSessionFastMode,} from '../maker-host/session-effort-store.js';+import { readSessionRuntimeFallbackSettings } from '../maker-host/session-runtime-fallback-store.js';import {getModelVisibilityMirrorSnapshot,syncModelVisibilityMirrorForOwner,@@ -855,7 +863,42 @@ import {isCredentialModeSwitchBusyError,isLocalSessionBusy,} from '../maker-host/codex-credential-switch.js';-import { applyRuntimeSetModelChange } from './runtimeSetModel.js';+import {+ applyRuntimeSetModelChange,+ isRemoteModelSwitchRouteChangeError,+} from './runtimeSetModel.js';+import {+ applyRuntimeSelectionAxesWithRecovery,+ commitRuntimeAxisAfterPersistence,+ isSupportedRuntimeEffort,+ resolveRetainedRuntimeEffort,+} from './runtimeSelectionAxes.js';+import {+ acceptSessionRuntimeAxisMutation,+ acceptSessionRuntimeMutation,+ cancelPendingSessionRuntimeMutation,+ captureSessionRuntimeControlOwnerEpoch,+ clearSessionRuntimeControlState,+ deferSessionRuntimeAxisMutation,+ getPendingSessionRuntimeMutation,+ getSessionRuntimeControlSnapshot,+ isPendingSessionRuntimeRouteExplicit,+ mergeSessionRuntimeProfilePatch,+ pickSessionRuntimeFallback,+ recordFailedSessionRuntimeFallbackCandidate,+ recordRecoveredSessionRuntimeMutation,+ recordRecoveredSessionRuntimeAxisMutation,+ recordUserSessionRuntimeAxisMutation,+ recordUserSessionRuntimeMutation,+ resolveCompatibleSessionRuntimeAxisPatch,+ resolveSessionRuntimeAxes,+ sessionRuntimeGenerationMatches,+ sessionRuntimeControlOwnerEpochMatches,+ settlePendingSessionRuntimeMutation,+ type SessionRuntimeMutationSource,+ type SessionRuntimeAxisPatch,+ type SessionRuntimeProfile,+} from './sessionRuntimeControl.js';import { applyRuntimeEffortWithRecovery } from './runtimeSetEffort.js';import { normalizeDeviceLinkSetModelWireArgs } from './setModelWireArgs.js';import { PendingCredentialSwitchService } from './pendingCredentialSwitch.js';@@ -1013,12 +1056,37 @@ const silentStopAutoResumeGuard = new SilentStopAutoResumeGuard({// 中断自动续跑守卫(上游把已有产出的 turn 打断 → 自动替用户点一次「继续」)。// 与 silent-stop 那份**额度独立记账**,理由见 interruptedTurnAutoResume.ts 文件头。const interruptedTurnAutoResumeGuard = new InterruptedTurnAutoResumeGuard({- isEnabled: () => readInterruptedTurnAutoResumeSettings().enabled,+ isEnabled: () =>+ readInterruptedTurnAutoResumeSettings().enabled || readSessionRuntimeFallbackSettings().enabled,log: {debug: (message, meta) => log.debug(message, meta),warn: (message, meta) => log.warn(message, meta),},});+let settlePendingSessionRuntimeControlHolder: ((sessionId: string, reason: string) => void) | null =+ null;+let broadcastSessionRuntimeProjectionHolder:+ ((sessionId: string, baselineOverride?: SessionRuntimeProfile) => Promise<void>) | null = null;++function projectSessionRuntimeControl(+ sessionId: string,+ baseline: SessionRuntimeProfile,+): Partial<RendererSession> {+ const control = getSessionRuntimeControlSnapshot(sessionId);+ const effective = control.effectiveOverride ?? baseline;+ return {+ model: effective.model,+ providerId: effective.providerId,+ // Keep the legacy top-level wire axis string-compatible while explicitly+ // clearing stale effort; runtimeEffective retains the semantic null.+ effort: effective.effort ?? '',+ fastMode: effective.fastMode,+ runtimeGeneration: control.generation,+ runtimeBaseline: baseline,+ runtimeEffective: effective,+ runtimePending: control.pending,+ };+}// Schedule 不另建重试状态机:真正的恢复仍由 AgentInputCoordinator +// AutoResumeBookkeeping 独占。这里仅把「这一轮 scheduler run 已被普通自动续跑接管」@@ -1150,6 +1218,7 @@ const autoResumeBookkeeping = new AutoResumeBookkeeping({* a replacement Session can otherwise inherit a late close callback.*/const pendingCodexReconnectStalledRebuilds = new WeakMap<Session, number>();+const pendingSessionRuntimeFallbackRebuilds = new WeakMap<Session, number>();/*** 用户明确停止会话时统一撤销两类自动续跑与它们的退避簿记。@@ -1640,9 +1709,38 @@ interface OrcaCollabService {getSessionRuntime: (params: {targetSessionId: string;}) => Promise<- | { ok: true; runtime: Awaited<ReturnType<typeof readCanonicalSessionActivity>> }+ | { ok: true; runtime: import('./sessionControlService.js').SessionRuntimeDetails }| { ok: false; errorCode: 'NOT_FOUND' | 'HOST_NOT_READY' | 'INTERNAL'; message: string }>;+ setSessionRuntime: (params: {+ targetSessionId: string;+ expectedGeneration?: number;+ patch: {+ model?: string;+ providerId?: string | null;+ effort?: import('@cindy/maker-core').Effort;+ fastMode?: boolean;+ };+ }) => Promise<+ | {+ ok: true;+ status: 'applied' | 'deferred';+ generation: number;+ effectiveProfile: SessionRuntimeProfile;+ pendingMutation: ReturnType<typeof getPendingSessionRuntimeMutation>;+ }+ | {+ ok: false;+ errorCode:+ | 'NOT_FOUND'+ | 'CONFLICT'+ | 'INVALID_ARGS'+ | 'ROUTE_UNAVAILABLE'+ | 'HOST_NOT_READY'+ | 'INTERNAL';+ message: string;+ }+ >;sendToSession: (params: {/** 省略 → create 新 session;提供 → jump 到该既有 session。 */targetSessionId?: string;@@ -2712,6 +2810,27 @@ function shouldPreserveCodexReconnectStalledAutoResume(return autoResumeBookkeeping.hasWaitingSchedule(session.id, attemptToken);}+/**+ * Runtime fallback runs inside the already-fired retry callback. A route change+ * may synchronously close the old process before autoRetryLastError can reuse+ * its recovery record, so preserve only that exact callback token across the+ * requested close/rebuild handoff.+ */+function shouldPreserveSessionRuntimeFallbackAutoResume(+ session: WiredSession,+ closeReason: ReturnType<typeof getWiredSessionCloseReason>,+): boolean {+ const attemptToken = pendingSessionRuntimeFallbackRebuilds.get(session);+ if (attemptToken === undefined) return false;+ if (closeReason !== 'requested') return false;+ if (!interruptedTurnAutoResumeGuard.isCurrentAttempt(session.id, attemptToken)) return false;+ if (!autoResumeBookkeeping.isCurrentAttempt(session.id, attemptToken)) return false;+ const coordinator = agentInputCoordinatorHolder;+ if (!coordinator || !coordinator.isAutoResumePending(session.id)) return false;+ if (coordinator.getAutoResumeAttemptToken(session.id) !== attemptToken) return false;+ return autoResumeBookkeeping.hasSchedule(session.id);+}+/*** GoalController 已确认当前 turn 归自己所有后调用:复用输入协调器的 Stop 边界中断* vendor,同时保留用户已经排队的新指令并在终态收口后继续派发。@@ -3568,6 +3687,7 @@ async function settleSilentStopDone(noteClaudeSessionTurnState(sessionId, false);agentInputCoordinatorHolder?.onTurnEvent(sessionId, 'done');settlePendingCredentialSwitch(sessionId, `silent-stop:${reason}`);+ settlePendingSessionRuntimeControlHolder?.(sessionId, `silent-stop:${reason}`);deferredCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);@@ -4318,6 +4438,7 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void// (review P2 2026-07-04)。apply 内部串行 + 幂等,fire-and-forget 安全;// planned upgrade close 等场景多唤一次也只是 no-op。settlePendingCredentialSwitch(session.id, `event:${event.type}`);+ settlePendingSessionRuntimeControlHolder?.(session.id, `event:${event.type}`);deferredCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(session.id);refreshRemoteCodexMcpOnTurnSettledHolder?.(session.id);@@ -5572,15 +5693,14 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void});}if (status === 'closed') {+ const closeReason = getWiredSessionCloseReason(session);const closedDirectAbortBoundary = getDirectAbortBoundaryForClosingSession(session.id,session,);- const closeReason = getWiredSessionCloseReason(session);- const preserveAutoResumeIntent = shouldPreserveCodexReconnectStalledAutoResume(- session,- closeReason,- );+ const preserveAutoResumeIntent =+ shouldPreserveCodexReconnectStalledAutoResume(session, closeReason) ||+ shouldPreserveSessionRuntimeFallbackAutoResume(session, closeReason);pendingCodexReconnectStalledRebuilds.delete(session);try {cleanupPendingInteractionsForSession(session.id, 'session_closed');@@ -5778,6 +5898,59 @@ export function registerModelVisibilitySyncIpc(): void {export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions): void {log.info('registering maker:* IPC handlers');+ const broadcastSessionRuntimeProjection = async (+ sessionId: string,+ baselineOverride?: SessionRuntimeProfile,+ ): Promise<void> => {+ let baseline = baselineOverride;+ if (!baseline) {+ const [row] = await getDbClient()+ .drizzle.select({+ agentKind: sessions.agentKind,+ model: sessions.model,+ providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,+ })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!row) return;+ baseline = {+ agentKind: dbToMakerAgentKind(row.agentKind),+ model: row.model,+ providerId: row.providerId?.trim() || null,+ effort: row.effort,+ fastMode: row.fastMode === true,+ };+ }+ broadcastSessionPatched(+ sessionId,+ projectSessionRuntimeControl(sessionId, baseline) as Record<string, unknown>,+ );+ };+ broadcastSessionRuntimeProjectionHolder = broadcastSessionRuntimeProjection;+ setSessionRuntimeProjector((session) =>+ projectSessionRuntimeControl(session.id, {+ agentKind: dbToMakerAgentKind(session.agentKind),+ model: session.model,+ providerId: session.providerId?.trim() || null,+ effort: session.effort as SessionRuntimeProfile['effort'],+ fastMode: session.fastMode,+ }),+ );+ setSessionRuntimeCleanup((sessionId) => {+ clearSessionRuntimeControlState(sessionId);+ clearSessionProvider(sessionId);+ setSessionEffort(sessionId, null);+ setSessionFastMode(sessionId, false);+ void broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('session runtime cleanup projection failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ });disposePiPackagesChangedBroadcast?.();disposePiPackagesChangedBroadcast = onPiPackagesChanged(() => {for (const win of BrowserWindow.getAllWindows()) {@@ -7308,6 +7481,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)didInjectProjectContext: boolean;}> {await options.waitForAccountProviderModelsReady();+ const runtimeOverride =+ typeof o.id === 'string' ? getSessionRuntimeControlSnapshot(o.id).effectiveOverride : null;+ if (runtimeOverride && runtimeOverride.agentKind === o.agentKind) {+ o.model = runtimeOverride.model;+ o.providerId = runtimeOverride.providerId;+ o.effort = runtimeOverride.effort ?? undefined;+ o.fastMode = runtimeOverride.fastMode;+ }await applyPersistedReviewMode(o);const didInjectOrcaInstructions = o.reviewMode === true ? false : applyOrcaInstructions(o);const didInjectProjectContext =@@ -7376,7 +7557,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)const db = getDbClient().drizzle;await persistAndHydrateSessionProvider({sessionId: session.id,- providerId: o.providerId,+ providerId: runtimeOverride ? undefined : o.providerId,updateProviderId: async (targetSessionId, providerId) => {await db.update(sessions).set({ providerId }).where(eq(sessions.id, targetSessionId));},@@ -7397,8 +7578,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions).from(sessions).where(eq(sessions.id, session.id)).limit(1);- if (efRow?.effort) setSessionEffort(session.id, efRow.effort);- setSessionFastMode(session.id, !!efRow?.fastMode);+ if (runtimeOverride) {+ setSessionEffort(session.id, runtimeOverride.effort);+ setSessionFastMode(session.id, runtimeOverride.fastMode);+ } else {+ setSessionEffort(session.id, efRow?.effort);+ setSessionFastMode(session.id, !!efRow?.fastMode);+ }} catch (err) {log.debug('hydrate session provider failed (non-fatal)', {sessionId: session.id,@@ -8629,6 +8815,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)withCloseSuppressed: withRehydrateCloseSuppressed,pendingSwitches: agentSwitchPending,onPendingSwitchChanged: (sessionId, intent) => {+ if (intent) recordUserSessionRuntimeMutation(sessionId);broadcastSessionPatched(sessionId, { agentSwitchIntent: intent });},log,@@ -10664,10 +10851,407 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)});idleReleaseWatcher.start();+ type InternalRuntimeSelectionOptions = {+ source: 'user' | SessionRuntimeMutationSource;+ expectedGeneration?: number;+ deferWhileRunning?: boolean;+ applyingPendingGeneration?: number;+ previousProfile?: SessionRuntimeProfile;+ /** Effective profile observed by the Agent CAS read; axis-only patches use it as the live base. */+ effectiveProfile?: SessionRuntimeProfile;+ effortExplicit?: boolean;+ fastExplicit?: boolean;+ /** False only for Agent axis-only patches; model/provider routing stays untouched. */+ routeExplicit?: boolean;+ };+ let applySessionRuntimeSelection: (+ sessionId: string,+ model: string,+ providerId: string | null | undefined,+ selection: { effort: SessionRuntimeProfile['effort']; fastMode: boolean },+ options: InternalRuntimeSelectionOptions,+ ) => Promise<{+ deferred: boolean;+ superseded: boolean;+ generation?: number;+ effectiveProviderId?: string | null;+ }> = async () => {+ throw new Error('session runtime selection is not ready');+ };+ const settlingSessionRuntimeControls = new Set<string>();+ const settlePendingSessionRuntimeControl = (sessionId: string, reason: string): void => {+ if (settlingSessionRuntimeControls.has(sessionId)) return;+ const pending = getPendingSessionRuntimeMutation(sessionId);+ if (!pending) return;+ settlingSessionRuntimeControls.add(sessionId);+ void (async () => {+ try {+ const result = await applySessionRuntimeSelection(+ sessionId,+ pending.profile.model,+ pending.profile.providerId,+ {+ effort: pending.profile.effort,+ fastMode: pending.profile.fastMode,+ },+ {+ source: pending.source,+ expectedGeneration: pending.generation,+ applyingPendingGeneration: pending.generation,+ effortExplicit: pending.profile.effort !== null,+ fastExplicit: true,+ routeExplicit: isPendingSessionRuntimeRouteExplicit(+ sessionId,+ pending.generation,+ ),+ },+ );+ log.info('pending session runtime settled', {+ sessionId,+ reason,+ generation: pending.generation,+ superseded: result.superseded,+ });+ } catch (error) {+ const cancelled = cancelPendingSessionRuntimeMutation(sessionId, pending.generation);+ log.warn('pending session runtime settlement failed', {+ sessionId,+ reason,+ cancelled,+ error: error instanceof Error ? error.message : String(error),+ });+ if (cancelled) {+ await broadcastSessionRuntimeProjection(sessionId).catch((broadcastError) => {+ log.debug('cancelled pending runtime projection broadcast failed', {+ sessionId,+ error:+ broadcastError instanceof Error ? broadcastError.message : String(broadcastError),+ });+ });+ }+ } finally {+ settlingSessionRuntimeControls.delete(sessionId);+ const latest = getPendingSessionRuntimeMutation(sessionId);+ if (latest && latest.generation !== pending.generation) {+ settlePendingSessionRuntimeControl(sessionId, `${reason}:generation-advanced`);+ }+ }+ })();+ };+ settlePendingSessionRuntimeControlHolder = settlePendingSessionRuntimeControl;++ const readSessionRuntimeProfiles = async (sessionId: string) => {+ const meta = await maker.getSessionMeta(sessionId);+ if (!meta) return null;+ let baseline: SessionRuntimeProfile = {+ agentKind: meta.agentKind,+ model: meta.model,+ providerId: null,+ effort: meta.effort ?? null,+ fastMode: meta.fastMode === true,+ };+ try {+ const [row] = await getDbClient()+ .drizzle.select({+ agentKind: sessions.agentKind,+ model: sessions.model,+ providerId: sessions.providerId,+ effort: sessions.effort,+ fastMode: sessions.fastMode,+ })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (row) {+ baseline = {+ agentKind: dbToMakerAgentKind(row.agentKind),+ model: row.model,+ providerId: row.providerId?.trim() || null,+ effort: row.effort,+ fastMode: row.fastMode === true,+ };+ }+ } catch (error) {+ log.debug('session runtime baseline lookup failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ const control = getSessionRuntimeControlSnapshot(sessionId);+ const live = maker.getSession(sessionId);+ const effective: SessionRuntimeProfile = control.effectiveOverride ?? {+ agentKind: live?.agentKind ?? meta.agentKind,+ model: live?.model ?? meta.model,+ providerId: hasSessionProvider(sessionId)+ ? getSessionProvider(sessionId)+ : baseline.providerId,+ effort:+ (getSessionEffort(sessionId) as SessionRuntimeProfile['effort']) ?? meta.effort ?? null,+ fastMode: live ? getSessionFastMode(sessionId) : meta.fastMode === true,+ };+ return { baseline, effective, control };+ };++ const resolvePendingRuntimeAxisPatch = async (+ sessionId: string,+ patch: SessionRuntimeAxisPatch,+ ): Promise<SessionRuntimeAxisPatch> => {+ const pending = getPendingSessionRuntimeMutation(sessionId);+ if (!pending) return patch;+ try {+ const providers = await getDesktopProviderService().listProviders({+ allowSideEffects: false,+ catalog: getActiveCatalog(),+ });+ const pendingProviderId =+ pending.profile.providerId ??+ effectiveSourceIdForModel(+ providers,+ null,+ pending.profile.model,+ pending.profile.agentKind,+ );+ const provider = providers.find((candidate) => candidate.id === pendingProviderId);+ const model = findCatalogModel(provider, pending.profile.model, pending.profile.agentKind, {+ exact: true,+ });+ if (!model) return {};+ return resolveCompatibleSessionRuntimeAxisPatch({+ model,+ profile: pending.profile,+ patch,+ });+ } catch (error) {+ log.debug('pending runtime axis capability lookup failed', {+ sessionId,+ model: pending.profile.model,+ providerId: pending.profile.providerId,+ error: error instanceof Error ? error.message : String(error),+ });+ return {};+ }+ };++ const maybeApplySessionRuntimeFallback = async (+ sessionId: string,+ episodeAttempt: number,+ attemptToken: number,+ ): Promise<Session | null> => {+ if (!readSessionRuntimeFallbackSettings().enabled || episodeAttempt < 2) return null;+ const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();+ let runtimeSession: Session | null = null;+ try {+ const profiles = await readSessionRuntimeProfiles(sessionId);+ if (!profiles) return null;+ // A previously accepted Agent/fallback mutation owns the next boundary.+ // Do not let a later infrastructure retry replace that pending intent.+ if (profiles.control.pending) return null;+ const providers = await getDesktopProviderService().listProviders({+ allowSideEffects: false,+ catalog: getActiveCatalog(),+ });+ const currentForFallback =+ profiles.effective.providerId === null+ ? {+ ...profiles.effective,+ providerId: effectiveSourceIdForModel(+ providers,+ null,+ profiles.effective.model,+ profiles.effective.agentKind,+ ),+ }+ : profiles.effective;+ const candidate = pickSessionRuntimeFallback({+ providers,+ current: currentForFallback,+ visitedRoutes: profiles.control.visitedRoutes,+ currentHop: profiles.control.fallbackHop,+ maxHops: 2,+ });+ if (!candidate) return null;+ runtimeSession = maker.getSession(sessionId) ?? null;+ if (runtimeSession) {+ pendingSessionRuntimeFallbackRebuilds.set(runtimeSession, attemptToken);+ }+ const applyCandidate = () =>+ applySessionRuntimeSelection(+ sessionId,+ candidate.model,+ candidate.providerId,+ { effort: candidate.effort, fastMode: candidate.fastMode },+ {+ source: 'fallback',+ expectedGeneration: profiles.control.generation,+ previousProfile: currentForFallback,+ effortExplicit: false,+ fastExplicit: false,+ },+ );+ const recordFailedCandidate = async (): Promise<void> => {+ try {+ await withSendToSessionLock(sessionId, async () => {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;+ const [runtimeStatus] = await getDbClient()+ .drizzle.select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (runtimeStatus?.status !== 'active') return;+ recordFailedSessionRuntimeFallbackCandidate(+ sessionId,+ profiles.control.generation,+ candidate,+ );+ });+ } catch (recordError) {+ log.debug('automatic runtime fallback failed-candidate record skipped', {+ sessionId,+ providerId: candidate.providerId,+ model: candidate.model,+ error: recordError instanceof Error ? recordError.message : String(recordError),+ });+ }+ };+ let result: Awaited<ReturnType<typeof applySessionRuntimeSelection>>;+ try {+ result = await applyCandidate();+ } catch (error) {+ if (+ runtimeSession?.agentKind !== 'claude-code' ||+ !runtimeSession.remoteHostId ||+ !isRemoteModelSwitchRouteChangeError(error)+ ) {+ await recordFailedCandidate();+ throw error;+ }+ // SSH Claude daemons freeze endpoint/credential env at spawn. The old+ // Session is already registered in pendingSessionRuntimeFallbackRebuilds,+ // so this requested close preserves the exact auto-resume attempt while+ // lazy bootstrap recreates it from the accepted candidate profile.+ log.info('automatic session runtime fallback rebuilding frozen remote route', {+ sessionId,+ episodeAttempt,+ attemptToken,+ remoteHostId: runtimeSession.remoteHostId,+ toProviderId: candidate.providerId,+ toModel: candidate.model,+ });+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));+ try {+ result = await applyCandidate();+ } catch (retryError) {+ await recordFailedCandidate();+ throw retryError;+ }+ }+ log.info('automatic session runtime fallback evaluated', {+ sessionId,+ episodeAttempt,+ attemptToken,+ fromProviderId: currentForFallback.providerId,+ fromModel: currentForFallback.model,+ toProviderId: candidate.providerId,+ toModel: candidate.model,+ applied: !result.superseded,+ });+ return runtimeSession;+ } catch (error) {+ log.warn('automatic session runtime fallback skipped after switch failure', {+ sessionId,+ episodeAttempt,+ attemptToken,+ error: error instanceof Error ? error.message : String(error),+ });+ return runtimeSession;+ }+ };+const sessionControlService = createSessionControlService({sessionExists: async (sessionId) => (await maker.getSessionMeta(sessionId)) !== null,getLiveSession: (sessionId) => maker.getSession(sessionId) ?? null,getSessionActivitySnapshot: readCanonicalSessionActivity,+ getSessionRuntimeDetails: async (sessionId) => {+ const profiles = await readSessionRuntimeProfiles(sessionId);+ if (!profiles) throw new Error(`session ${sessionId} not found`);+ const activity = await readCanonicalSessionActivity(sessionId);+ const turnControl = maker.getSession(sessionId)?.getTurnControlSnapshot();+ return {+ ...activity,+ turnGeneration: turnControl?.turnGeneration ?? null,+ gracefulStopState: turnControl?.gracefulStopState ?? 'none',+ runtimeGeneration: profiles.control.generation,+ baselineProfile: profiles.baseline,+ effectiveProfile: profiles.effective,+ pendingMutation: profiles.control.pending,+ fallbackEnabled: readSessionRuntimeFallbackSettings().enabled,+ };+ },+ setSessionRuntime: async ({ targetSessionId, expectedGeneration, patch }) => {+ const profiles = await readSessionRuntimeProfiles(targetSessionId);+ if (!profiles) {+ return {+ ok: false,+ errorCode: 'NOT_FOUND',+ message: `session ${targetSessionId} not found`,+ };+ }+ const routeExplicit = patch.model !== undefined || patch.providerId !== undefined;+ const mergeBase = routeExplicit+ ? (profiles.control.pending?.profile ?? profiles.effective)+ : profiles.effective;+ const next = mergeSessionRuntimeProfilePatch(mergeBase, patch);+ let response: Awaited<ReturnType<typeof applySessionRuntimeSelection>>;+ try {+ response = await applySessionRuntimeSelection(+ targetSessionId,+ next.model,+ next.providerId,+ { effort: next.effort, fastMode: next.fastMode },+ {+ source: 'agent',+ expectedGeneration,+ deferWhileRunning: true,+ effectiveProfile: profiles.effective,+ effortExplicit: patch.effort !== undefined,+ fastExplicit: patch.fastMode !== undefined,+ routeExplicit,+ },+ );+ } catch (error) {+ const code = (error as { code?: unknown }).code;+ if (+ code === 'INVALID_PARAMS' ||+ code === 'CREDENTIAL_SWITCH_BUSY' ||+ code === 'REMOTE_MODEL_SWITCH_ROUTE_CHANGE' ||+ code === 'REMOTE_PROVIDER_UPDATING' ||+ code === 'REMOTE_PROVIDER_UNSUPPORTED' ||+ code === 'REMOTE_NATIVE_OAUTH_UNAVAILABLE'+ ) {+ return {+ ok: false,+ errorCode: 'ROUTE_UNAVAILABLE',+ message: error instanceof Error ? error.message : String(error),+ };+ }+ throw error;+ }+ if (response.superseded) {+ return {+ ok: false,+ errorCode: 'CONFLICT',+ message: `session runtime generation changed; read it again before retrying`,+ };+ }+ const control = getSessionRuntimeControlSnapshot(targetSessionId);+ return {+ ok: true,+ status: response.deferred ? 'deferred' : 'applied',+ generation: response.generation ?? control.generation,+ effectiveProfile: control.effectiveOverride ?? profiles.effective,+ pendingMutation: control.pending,+ };+ },assertExternalInputAllowed: assertReviewExternalInputAllowed,createQueuedMessage: async ({ targetSessionId, callerSessionId, queuedMessageId, message }) => {const meta = await maker.getSessionMeta(targetSessionId);@@ -10764,6 +11348,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)steerSession: (params) => sessionControlService.steerSession(params),stopSessionTurn: (params) => sessionControlService.stopSessionTurn(params),getSessionRuntime: (params) => sessionControlService.getSessionRuntime(params),+ setSessionRuntime: (params) => sessionControlService.setSessionRuntime(params),sendToSession: sendToSessionInternal,enableOrca: enableOrcaInternal,disableOrca: disableOrcaInternal,@@ -11667,6 +12252,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)markTurnEndedAfterPersistDrain(sessionId);noteClaudeSessionTurnState(sessionId, false);settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);+ settlePendingSessionRuntimeControlHolder?.(sessionId, `reconcile:${source}`);deferredCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);@@ -11730,6 +12316,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)markTurnEndedAfterPersistDrain(sessionId);noteClaudeSessionTurnState(sessionId, false);settlePendingCredentialSwitch(sessionId, `reconcile:${source}`);+ settlePendingSessionRuntimeControlHolder?.(sessionId, `reconcile:${source}`);deferredCodexRestartHolder?.onSessionSettled();agentInputCoordinatorHolder?.onExternalTurnSettled(sessionId);refreshRemoteCodexMcpOnTurnSettledHolder?.(sessionId);@@ -12084,7 +12671,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)decision.delayMs,(attempt) => {return (async () => {+ let fallbackRebuildSession: Session | null = null;try {+ fallbackRebuildSession = await maybeApplySessionRuntimeFallback(+ sessionId,+ decision.episodeAttempt,+ decision.attemptToken,+ );// 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery// 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),// autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚@@ -12132,6 +12725,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)sessionId,error: err instanceof Error ? err.message : String(err),});+ } finally {+ if (fallbackRebuildSession) {+ pendingSessionRuntimeFallbackRebuilds.delete(fallbackRebuildSession);+ }}})();},@@ -13975,207 +14572,646 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)// session 不存在(被 close / 还没 send 创建出来)就 no-op 不报错, 让 renderer// 可以乐观调用 (UI 更新先行, IPC 失败也不会回滚 UI, 老 agentManager 同语义)。- ipcMain.handle(- MAKER_INVOKE.SET_MODEL,- async (- _e,- sessionId: unknown,- model: unknown,- providerId?: unknown,- expectedAgentSwitchRevision?: unknown,- selection?: unknown,- ) => {- if (typeof sessionId !== 'string' || typeof model !== 'string') {- throwIpcError('INVALID_PARAMS', 'sessionId + model required');- }- const normalizedWireArgs = normalizeDeviceLinkSetModelWireArgs(- isDeviceLinkInvoke(),- deviceLinkInvokeControllerSupports(- CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,- ),- providerId,- expectedAgentSwitchRevision,- selection,+ const handleSetModel = async (+ event: Electron.IpcMainInvokeEvent | undefined,+ sessionId: unknown,+ model: unknown,+ providerId: unknown,+ expectedAgentSwitchRevision: unknown,+ selection: unknown,+ internalOptions: InternalRuntimeSelectionOptions,+ ) => {+ if (internalOptions.source === 'user' && !isDeviceLinkInvoke()) {+ assertTrustedAppRendererEvent(+ event as Parameters<typeof assertTrustedAppRendererEvent>[0],);- providerId = normalizedWireArgs.providerId;- expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;- selection = normalizedWireArgs.selection;- if (providerId !== undefined && providerId !== null && typeof providerId !== 'string') {- throwIpcError('INVALID_PARAMS', 'providerId must be string, null, or undefined');- }- if (- expectedAgentSwitchRevision !== undefined &&- (typeof expectedAgentSwitchRevision !== 'number' ||- !Number.isSafeInteger(expectedAgentSwitchRevision) ||- expectedAgentSwitchRevision < 0)- ) {- throwIpcError(- 'INVALID_PARAMS',- 'expectedAgentSwitchRevision must be a non-negative integer',- );- }- if (- selection !== undefined &&- (selection === null ||- typeof selection !== 'object' ||- Array.isArray(selection) ||- typeof (selection as { effort?: unknown }).effort !== 'string' ||- typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean')- ) {- throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');- }- const atomicSelection = selection as { effort: string; fastMode: boolean } | undefined;- // 与 send 事务共用 session 锁:发送时刻执行的跨引擎切换必须先落定,- // 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider- // 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。- return withSendToSessionLock(sessionId, async () => {- await assertReviewSettingsUnlocked(sessionId);- // 同引擎重选是 switch ack 后的第二段写入。另一控制端若在两段之间更新(含- // set→clear ABA),修订号已变化:旧 SET_MODEL 必须在任何 route/DB 副作用前让位。- if (- typeof expectedAgentSwitchRevision === 'number' &&- agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision- ) {- return { deferred: false, superseded: true };- }- // 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,- // 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link- // allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——- // 排队等待期间目标可能刚被停用,而同凭证族的变更即时生效、不经 deferred 收口- // 的重裁决,锁前裁决结果可能已过期。会话当前正用着的停用模型不受影响,这里只- // 拦「切过去」;隐式来源的原生默认落点被停用而有启用替代拷贝时,以显式来源- // 落地(与 bootstrapSession 同语义)。agentKind 读不到(会话行缺失等)时不拦。- // DB 存的是 'cc' | 'codex'(messages.agent_kind 口径),目录侧是 AgentKind。- const requestedProviderId = normalizeSessionProviderId(- typeof providerId === 'string' || providerId === null ? providerId : undefined,- );- let persistedProviderId: string | null = null;- let persistedProviderKnown = true;- if (requestedProviderId === undefined && !hasSessionProvider(sessionId)) {- try {- const db = getDbClient().drizzle;- const [row] = await db- .select({ providerId: sessions.providerId })- .from(sessions)- .where(eq(sessions.id, sessionId))- .limit(1);- persistedProviderId = row?.providerId?.trim() || null;- hydrateSessionProvider(sessionId, persistedProviderId);- } catch (err) {- persistedProviderKnown = false;- log.debug('set-model persisted provider lookup failed (non-fatal)', {+ }+ if (typeof sessionId !== 'string' || typeof model !== 'string') {+ throwIpcError('INVALID_PARAMS', 'sessionId + model required');+ }+ const normalizedWireArgs =+ internalOptions.source === 'user'+ ? normalizeDeviceLinkSetModelWireArgs(+ isDeviceLinkInvoke(),+ deviceLinkInvokeControllerSupports(+ CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1,+ ),+ providerId,+ expectedAgentSwitchRevision,+ selection,+ )+ : { providerId, expectedAgentSwitchRevision, selection };+ providerId = normalizedWireArgs.providerId;+ expectedAgentSwitchRevision = normalizedWireArgs.expectedAgentSwitchRevision;+ selection = normalizedWireArgs.selection;+ if (+ providerId !== undefined &&+ providerId !== null &&+ typeof providerId !== 'string'+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'providerId must be string, null, or undefined',+ );+ }+ if (+ expectedAgentSwitchRevision !== undefined &&+ (typeof expectedAgentSwitchRevision !== 'number' ||+ !Number.isSafeInteger(expectedAgentSwitchRevision) ||+ expectedAgentSwitchRevision < 0)+ ) {+ throwIpcError(+ 'INVALID_PARAMS',+ 'expectedAgentSwitchRevision must be a non-negative integer',+ );+ }+ if (+ selection !== undefined &&+ (selection === null ||+ typeof selection !== 'object' ||+ Array.isArray(selection) ||+ (!isSupportedRuntimeEffort((selection as { effort?: unknown }).effort) &&+ !(+ internalOptions.source !== 'user' &&+ (selection as { effort?: unknown }).effort === null+ )) ||+ typeof (selection as { fastMode?: unknown }).fastMode !== 'boolean')+ ) {+ throwIpcError('INVALID_PARAMS', 'selection must contain effort + fastMode');+ }+ let atomicSelection = selection as+ { effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;+ const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();+ const assertRuntimeOwnerCurrent = (): void => {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'app session changed during runtime selection; request dropped',+ );+ }+ };+ const supersededByOwnerBoundary = (): boolean => {+ if (sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return false;+ if (internalOptions.source === 'user') {+ assertRuntimeOwnerCurrent();+ }+ return true;+ };+ // 与 send 事务共用 session 锁:发送时刻执行的跨引擎切换必须先落定,+ // 后到的 SET_MODEL 才能写 route。否则切换 DB await 恢复后会用旧 provider+ // 覆盖用户刚选的新 route,形成 DB 与进程内路由分叉。+ const applyLocked = async () => {+ await assertReviewSettingsUnlocked(sessionId);+ if (supersededByOwnerBoundary()) {+ return { deferred: false, superseded: true };+ }+ // 归档/删除写入与本 handler 共用同一把 session route lock。拿锁后重读持久+ // 状态可封住两种次序:本请求先拿锁时终态写等待并在之后清理 override;终态+ // 先拿锁时旧请求看到非 active,不能在 cleanup 后重新建立 pending/override。+ const [runtimeStatus] = await getDbClient()+ .drizzle.select({ status: sessions.status, orcaRole: sessions.orcaRole })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!runtimeStatus) {+ return { deferred: false, superseded: true };+ }+ if (runtimeStatus.status !== 'active') {+ if (internalOptions.source === 'user') {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'archived or deleted task cannot change runtime selection',+ );+ }+ return { deferred: false, superseded: true };+ }+ if (+ internalOptions.source !== 'user' &&+ !sessionRuntimeGenerationMatches(+ sessionId,+ internalOptions.expectedGeneration,+ )+ ) {+ return { deferred: false, superseded: true };+ }+ const routeExplicit = internalOptions.routeExplicit !== false;+ // 同引擎重选是 switch ack 后的第二段写入。另一控制端若在两段之间更新(含+ // set→clear ABA),修订号已变化:旧 SET_MODEL 必须在任何 route/DB 副作用前让位。+ if (+ typeof expectedAgentSwitchRevision === 'number' &&+ agentSwitchPending.revision?.(sessionId) !== expectedAgentSwitchRevision+ ) {+ return { deferred: false, superseded: true };+ }+ // 停用轴准入(PR #744 review;第十二轮移入锁内):切换模型是一次新的路由选择,+ // 不得切到用户停用的模型 / 来源(本机选择器已过滤,但本 channel 在 device-link+ // allowlist 内,老控制端可直接点名)。裁决必须在拿到会话锁**之后**执行 ——+ // 排队等待期间目标可能刚被停用,而同凭证族的变更即时生效、不经 deferred 收口+ // 的重裁决,锁前裁决结果可能已过期。会话当前正用着的停用模型不受影响,这里只+ // 拦「切过去」;隐式来源的原生默认落点被停用而有启用替代拷贝时,以显式来源+ // 落地(与 bootstrapSession 同语义)。agentKind 读不到(会话行缺失等)时不拦。+ // DB 存的是 'cc' | 'codex'(messages.agent_kind 口径),目录侧是 AgentKind。+ const requestedProviderId = normalizeSessionProviderId(+ typeof providerId === 'string' || providerId === null+ ? providerId+ : undefined,+ );+ let persistedProviderId: string | null = null;+ let persistedProviderKnown = true;+ if (requestedProviderId === undefined && !hasSessionProvider(sessionId)) {+ try {+ const db = getDbClient().drizzle;+ const [row] = await db+ .select({ providerId: sessions.providerId })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ persistedProviderId = row?.providerId?.trim() || null;+ hydrateSessionProvider(sessionId, persistedProviderId);+ } catch (err) {+ persistedProviderKnown = false;+ log.debug('set-model persisted provider lookup failed (non-fatal)', {+ sessionId,+ error: err instanceof Error ? err.message : String(err),+ });+ }+ }+ const currentProviderId = resolveCurrentSetModelProviderId(+ hasSessionProvider(sessionId),+ getSessionProvider(sessionId),+ persistedProviderId,+ );+ const guardProviderId = resolveSetModelGuardProviderId(+ requestedProviderId,+ currentProviderId,+ );+ let effectiveProviderId = requestedProviderId;+ if (routeExplicit) {+ const dbAgentKind = getSessionDbAgentKind(sessionId);+ if (dbAgentKind) {+ const reroute = persistedProviderKnown+ ? await assertModelRouteUsable(+ dbToMakerAgentKind(dbAgentKind),+ model,+ guardProviderId,+ )+ : undefined;+ effectiveProviderId = resolveExclusiveSetModelReroute(+ requestedProviderId,+ currentProviderId,+ reroute,+ persistedProviderKnown,+ getActiveCatalog().providers,+ );+ }+ }+ if (atomicSelection) {+ const meta = await maker.getSessionMeta(sessionId);+ const runtimeAgentKind =+ maker.getSession(sessionId)?.agentKind ??+ (getSessionDbAgentKind(sessionId)+ ? dbToMakerAgentKind(getSessionDbAgentKind(sessionId))+ : meta?.agentKind);+ if (!runtimeAgentKind) {+ throwIpcError(+ 'INVALID_PARAMS',+ `session ${sessionId} has no runtime agent`,+ );+ }+ const selectedProviderId =+ effectiveProviderId === null+ ? null+ : (normalizeSessionProviderId(effectiveProviderId) ?? currentProviderId);+ const runtimeProviders = await getDesktopProviderService().listProviders({+ allowSideEffects: false,+ catalog: getActiveCatalog(),+ });+ const actualProviderId =+ selectedProviderId ??+ effectiveSourceIdForModel(+ runtimeProviders,+ null,+ model,+ runtimeAgentKind,+ );+ const provider = runtimeProviders.find(+ (candidate) => candidate.id === actualProviderId,+ );+ const catalogModel = findCatalogModel(provider, model, runtimeAgentKind, {+ exact: true,+ });+ if ((!provider?.connected && routeExplicit) || !catalogModel) {+ throwIpcError(+ 'INVALID_PARAMS',+ `model "${model}" is unavailable from provider "${actualProviderId ?? 'default'}"`,+ );+ }+ const axes = resolveSessionRuntimeAxes({+ model: catalogModel,+ effort: atomicSelection.effort,+ fastMode: atomicSelection.fastMode,+ effortExplicit:+ internalOptions.source === 'user' || internalOptions.effortExplicit === true,+ fastExplicit:+ internalOptions.source === 'user' || internalOptions.fastExplicit === true,+ allowFixedEffortPlaceholder: internalOptions.source === 'user',+ });+ if (!axes.ok && axes.reason === 'effort-unavailable') {+ throwIpcError(+ 'INVALID_PARAMS',+ `effort "${atomicSelection.effort}" is unavailable for model "${model}"`,+ );+ }+ if (!axes.ok) {+ throwIpcError(+ 'INVALID_PARAMS',+ `Fast is unavailable for model "${model}"`,+ );+ }+ atomicSelection = {+ effort: axes.effort,+ fastMode: axes.fastMode,+ };+ }+ const axisPatch: SessionRuntimeAxisPatch = {+ ...(internalOptions.effortExplicit === true && atomicSelection+ ? { effort: atomicSelection.effort }+ : {}),+ ...(internalOptions.fastExplicit === true && atomicSelection+ ? { fastMode: atomicSelection.fastMode }+ : {}),+ };+ const pendingAxisPatch = routeExplicit+ ? axisPatch+ : await resolvePendingRuntimeAxisPatch(sessionId, axisPatch);+ if (internalOptions.deferWhileRunning && isSessionInTurn(sessionId)) {+ const meta = await maker.getSessionMeta(sessionId);+ if (!meta) return { deferred: false, superseded: true };+ if (supersededByOwnerBoundary()) {+ return { deferred: false, superseded: true };+ }+ const generation = routeExplicit+ ? acceptSessionRuntimeMutation({sessionId,- error: err instanceof Error ? err.message : String(err),+ source: internalOptions.source === 'fallback' ? 'fallback' : 'agent',+ previousProfile: internalOptions.previousProfile,+ deferred: true,+ profile: {+ agentKind: maker.getSession(sessionId)?.agentKind ?? meta.agentKind,+ model,+ providerId:+ effectiveProviderId === undefined+ ? getSessionProvider(sessionId)+ : (normalizeSessionProviderId(effectiveProviderId) ?? null),+ effort: atomicSelection?.effort ?? null,+ fastMode: atomicSelection?.fastMode ?? getSessionFastMode(sessionId),+ },+ })+ : deferSessionRuntimeAxisMutation({+ sessionId,+ source: internalOptions.source === 'fallback' ? 'fallback' : 'agent',+ effectiveProfile: internalOptions.effectiveProfile ?? {+ agentKind: maker.getSession(sessionId)?.agentKind ?? meta.agentKind,+ model,+ providerId: currentProviderId,+ effort: getSessionEffort(sessionId) as SessionRuntimeProfile['effort'],+ fastMode: getSessionFastMode(sessionId),+ },+ pendingPatch: pendingAxisPatch,});- }+ await broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('deferred session runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return {+ deferred: true,+ superseded: false,+ generation,+ effectiveProviderId:+ normalizeSessionProviderId(effectiveProviderId) ?? null,+ };+ }+ const previousRuntime = {+ hadProviderRoute: hasSessionProvider(sessionId),+ providerId: getSessionProvider(sessionId),+ effort: getSessionEffort(sessionId) as SessionRuntimeProfile['effort'],+ fastMode: getSessionFastMode(sessionId),+ pendingCredentialSwitch: pendingCredentialSwitchHolder?.get(sessionId),+ hadLiveSession: maker.getSession(sessionId) !== undefined,+ };+ const liveSessionBeforeRouteChange = maker.getSession(sessionId);+ const targetProviderId =+ effectiveProviderId === undefined+ ? currentProviderId+ : (normalizeSessionProviderId(effectiveProviderId) ?? null);+ const rebuildLiveOrcaWorker =+ routeExplicit &&+ runtimeStatus.orcaRole === 'worker' &&+ liveSessionBeforeRouteChange !== undefined &&+ (liveSessionBeforeRouteChange.model !== model || currentProviderId !== targetProviderId);+ const restoreControlStores = () => {+ if (previousRuntime.hadProviderRoute) {+ setSessionProvider(sessionId, previousRuntime.providerId);+ } else {+ clearSessionProvider(sessionId);}- const currentProviderId = resolveCurrentSetModelProviderId(- hasSessionProvider(sessionId),- getSessionProvider(sessionId),- persistedProviderId,- );- const guardProviderId = resolveSetModelGuardProviderId(- requestedProviderId,- currentProviderId,- );- let effectiveProviderId = requestedProviderId;- {- const dbAgentKind = getSessionDbAgentKind(sessionId);- if (dbAgentKind) {- const reroute = persistedProviderKnown- ? await assertModelRouteUsable(- dbToMakerAgentKind(dbAgentKind),- model,- guardProviderId,- )- : undefined;- effectiveProviderId = resolveExclusiveSetModelReroute(- requestedProviderId,- currentProviderId,- reroute,- persistedProviderKnown,- getActiveCatalog().providers,+ setSessionEffort(sessionId, previousRuntime.effort);+ setSessionFastMode(sessionId, previousRuntime.fastMode);+ };+ const reconcileRetainedLiveProfile = async (): Promise<void> => {+ const retainedSession = maker.getSession(sessionId);+ if (!retainedSession || !sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {+ return;+ }+ const retainedProviderId =+ effectiveProviderId === undefined+ ? (previousRuntime.providerId ?? null)+ : (normalizeSessionProviderId(effectiveProviderId) ?? null);+ let targetModelHasFixedEffort = atomicSelection?.effort === null;+ if (!targetModelHasFixedEffort) {+ try {+ const retainedProviders = await getDesktopProviderService().listProviders({+ allowSideEffects: false,+ catalog: getActiveCatalog(),+ });+ const actualRetainedProviderId =+ retainedProviderId ??+ effectiveSourceIdForModel(+ retainedProviders,+ null,+ retainedSession.model,+ retainedSession.agentKind,+ );+ const retainedProvider = retainedProviders.find(+ (provider) => provider.id === actualRetainedProviderId,);+ targetModelHasFixedEffort =+ findCatalogModel(retainedProvider, retainedSession.model, retainedSession.agentKind, {+ exact: true,+ })?.efforts.length === 0;+ } catch (error) {+ log.debug('retained runtime model capability lookup failed', {+ sessionId,+ model: retainedSession.model,+ providerId: retainedProviderId,+ error: error instanceof Error ? error.message : String(error),+ });}}- try {- const result = await applySetModelThenCancelAgentSwitchIntent(- agentSwitchPending,+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {+ return;+ }+ const retainedProfile: SessionRuntimeProfile = {+ agentKind: retainedSession.agentKind,+ model: retainedSession.model,+ providerId: retainedProviderId,+ effort: resolveRetainedRuntimeEffort({+ targetModelHasFixedEffort,+ requestedEffort: atomicSelection?.effort,+ liveEffort: retainedSession.getEffort(),+ previousEffort: previousRuntime.effort,+ }),+ fastMode: retainedSession.getFastMode() ?? previousRuntime.fastMode,+ };+ if (effectiveProviderId !== undefined) {+ setSessionProvider(sessionId, retainedProfile.providerId);+ }+ setSessionEffort(sessionId, retainedProfile.effort);+ setSessionFastMode(sessionId, retainedProfile.fastMode);+ pendingCredentialSwitchHolder?.clear(sessionId);+ if (internalOptions.source === 'user') {+ recordRecoveredSessionRuntimeMutation(sessionId, retainedProfile);+ } else if (!routeExplicit) {+ recordRecoveredSessionRuntimeAxisMutation(sessionId, retainedProfile);+ } else {+ acceptSessionRuntimeMutation({sessionId,- () =>- applyRuntimeSetModelChange({- maker,- sessionId,- model,- providerId: effectiveProviderId,- ...(atomicSelection- ? {- effort: atomicSelection.effort as- 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',- }- : {}),- isSessionInTurn,- registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,- clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,- wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,- getPendingCredentialSwitch: getPendingCredentialSwitchTarget,- // 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见- // shouldCloseSessionForCredentialSwitch.codexAuthInjection)。- codexAuthInjection: getCodexProxyAuthInjectionState(),- logger: log,- }),- (id) =>- broadcastSessionPatched(id, {- agentSwitchIntent: null,- agentSwitchIntentCanceled: true,- }),- );- // deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示- // "任务结束后生效"而不是当成已即时切换。- const response = { deferred: result.status === 'deferred', superseded: false };+ source: internalOptions.source,+ previousProfile: internalOptions.previousProfile,+ profile: retainedProfile,+ deferred: false,+ });+ }+ agentSwitchPending.clear(sessionId);+ broadcastSessionPatched(sessionId, {+ agentSwitchIntent: null,+ agentSwitchIntentCanceled: true,+ });+ wakeSessionInputAfterCredentialSwitch(sessionId);+ await broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('recovered runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ };+ try {+ const result = routeExplicit+ ? await applyRuntimeSetModelChange({+ maker,+ sessionId,+ model,+ providerId: effectiveProviderId,+ ...(atomicSelection?.effort+ ? {+ effort: atomicSelection.effort as+ | 'minimal'+ | 'low'+ | 'medium'+ | 'high'+ | 'xhigh'+ | 'max'+ | 'ultra',+ }+ : {}),+ forceSessionRebuild: rebuildLiveOrcaWorker,+ isSessionInTurn,+ registerPendingCredentialSwitch:+ registerPendingCredentialSwitchForSession,+ clearPendingCredentialSwitch:+ clearPendingCredentialSwitchForSession,+ // Worker rebuild must publish the accepted runtime profile before queued input+ // can lazy-create the replacement execution unit.+ ...(!rebuildLiveOrcaWorker+ ? { wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch }+ : {}),+ getPendingCredentialSwitch: getPendingCredentialSwitchTarget,+ // 解析隐式来源的凭证家族,精确判定是否跨远端压缩身份边界(见+ // shouldCloseSessionForCredentialSwitch.codexAuthInjection)。+ codexAuthInjection: getCodexProxyAuthInjectionState(),+ logger: log,+ })+ : { status: 'applied' as const };+ // deferred = 会话自己在跑,选择已登记、turn 结束自动生效。renderer 据此提示+ // "任务结束后生效"而不是当成已即时切换。+ const response = {+ deferred: result.status === 'deferred',+ superseded: false,+ };+ if (supersededByOwnerBoundary()) {+ return { deferred: false, superseded: true };+ }+ if (atomicSelection) {+ const selectionToCommit = atomicSelection;+ // model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。+ // applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer+ // 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生+ // 旧请求尾写覆盖新选择。+ const commitControlStores = () => {+ setSessionEffort(sessionId, selectionToCommit.effort);+ setSessionFastMode(sessionId, selectionToCommit.fastMode);+ };+ const sess = maker.getSession(sessionId);+ if (+ sess &&+ result.status !== 'deferred' &&+ !pendingCredentialSwitchHolder?.has(sessionId)+ ) {+ await applyRuntimeSelectionAxesWithRecovery({+ session: sess,+ effort: selectionToCommit.effort,+ fastMode: selectionToCommit.fastMode,+ applyEffort: routeExplicit || internalOptions.effortExplicit === true,+ applyFastMode: routeExplicit || internalOptions.fastExplicit === true,+ assertCanCommit: assertRuntimeOwnerCurrent,+ commitControlStores,+ restoreControlStores,+ terminateSession: () =>+ withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId)),+ recoverLiveProfileAfterTerminationFailure: reconcileRetainedLiveProfile,+ });+ } else {+ commitControlStores();+ }+ }+ if (+ internalOptions.source === 'user' &&+ (isDeviceLinkInvoke() || atomicSelection)+ ) {+ // device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;+ // 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的+ // 新调用都由 host 在解锁前一次落定全部字段。+ const patch: Record<string, unknown> = { model };+ if (effectiveProviderId !== undefined) {+ patch.providerId = normalizeSessionProviderId(+ typeof effectiveProviderId === 'string'+ ? effectiveProviderId+ : null,+ );+ }if (atomicSelection) {- // model/provider/effort/fast 是一次选择快照,必须在同一把 session 锁内收敛。- // applyRuntimeSetModelChange 可能 close + wake;若 effort/fast 留给 renderer- // 后续独立调用,queue drain 会用新 model + 旧偏好重建,跨控制端时还会发生- // 旧请求尾写覆盖新选择。- setSessionEffort(sessionId, atomicSelection.effort);- setSessionFastMode(sessionId, atomicSelection.fastMode);- const sess = maker.getSession(sessionId);+ patch.effort = atomicSelection.effort;+ patch.fastMode = atomicSelection.fastMode;+ }+ try {+ await persistSessionFields(sessionId, patch);+ } catch (persistenceError) {+ // The live route and host stores are applied before SQLite so the+ // harness can switch atomically. If SQLite rejects, unwind every+ // in-memory side effect while generation/effectiveOverride still+ // describe the old profile.+ pendingCredentialSwitchHolder?.clear(sessionId);+ restoreControlStores();+ let recoveryError: unknown;if (- sess &&- result.status !== 'deferred' &&- !pendingCredentialSwitchHolder?.has(sessionId)+ result.status !== 'deferred'+ && previousRuntime.hadLiveSession+ && maker.getSession(sessionId)) {- await sess.setEffort(- atomicSelection.effort as- 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',- );- if (sess.agentKind === 'codex') {- await sess.setFastMode(atomicSelection.fastMode);+ try {+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));+ } catch (error) {+ recoveryError = error;}}- }- if (isDeviceLinkInvoke() || atomicSelection) {- // device-link 的通用持久化原本发生在 handler 返回、session 锁释放之后;- // 本地 renderer 的 sessionService.update 也有同一窗口。凡携带 selection 的- // 新调用都由 host 在解锁前一次落定全部字段。- const patch: Record<string, unknown> = { model };- if (effectiveProviderId !== undefined) {- patch.providerId = normalizeSessionProviderId(- typeof effectiveProviderId === 'string' ? effectiveProviderId : null,+ if (previousRuntime.pendingCredentialSwitch) {+ pendingCredentialSwitchHolder?.register(+ sessionId,+ previousRuntime.pendingCredentialSwitch,);+ } else if (!recoveryError) {+ wakeSessionInputAfterCredentialSwitch(sessionId);}- if (atomicSelection) {- patch.effort = atomicSelection.effort;- patch.fastMode = atomicSelection.fastMode;- }- await persistSessionFields(sessionId, patch);- if (isDeviceLinkInvoke()) {- // dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。- markRemoteSettingPersistedInsideHandler(response);+ if (recoveryError) {+ await reconcileRetainedLiveProfile();+ throw new AggregateError(+ [persistenceError, recoveryError],+ 'runtime selection persistence and session recovery both failed',+ );}+ throw persistenceError;+ }+ if (isDeviceLinkInvoke()) {+ // dispatch 继续兼容最小/旧 handler 的锁外回流;标记本结果避免重复写。+ markRemoteSettingPersistedInsideHandler(response);}+ }+ agentSwitchPending.clear(sessionId);+ broadcastSessionPatched(sessionId, {+ agentSwitchIntent: null,+ agentSwitchIntentCanceled: true,+ });+ if (supersededByOwnerBoundary()) {+ return { deferred: false, superseded: true };+ }+ let generation: number;+ if (internalOptions.source === 'user') {+ generation = recordUserSessionRuntimeMutation(sessionId);+ } else if (internalOptions.applyingPendingGeneration !== undefined) {if (!response.deferred) {+ settlePendingSessionRuntimeMutation(+ sessionId,+ internalOptions.applyingPendingGeneration,+ );+ }+ generation = getSessionRuntimeControlSnapshot(sessionId).generation;+ } else if (!routeExplicit) {+ const meta = await maker.getSessionMeta(sessionId);+ generation = acceptSessionRuntimeAxisMutation({+ sessionId,+ source: internalOptions.source,+ profile: {+ agentKind:+ maker.getSession(sessionId)?.agentKind ??+ meta?.agentKind ??+ 'claude-code',+ model,+ providerId: getSessionProvider(sessionId),+ effort: atomicSelection?.effort ?? previousRuntime.effort ?? null,+ fastMode: atomicSelection?.fastMode ?? previousRuntime.fastMode,+ },+ pendingPatch: pendingAxisPatch,+ });+ } else {+ const meta = await maker.getSessionMeta(sessionId);+ generation = acceptSessionRuntimeMutation({+ sessionId,+ source: internalOptions.source,+ previousProfile: internalOptions.previousProfile,+ deferred: response.deferred,+ profile: {+ agentKind:+ maker.getSession(sessionId)?.agentKind ??+ meta?.agentKind ??+ 'claude-code',+ model,+ providerId:+ effectiveProviderId === undefined+ ? getSessionProvider(sessionId)+ : (normalizeSessionProviderId(effectiveProviderId) ?? null),+ effort: atomicSelection?.effort ?? null,+ fastMode:+ atomicSelection?.fastMode ?? getSessionFastMode(sessionId),+ },+ });+ }+ if (rebuildLiveOrcaWorker && !response.deferred) {+ wakeSessionInputAfterCredentialSwitch(sessionId);+ }+ if (!response.deferred) {+ try {const currentAgentKind =maker.getSession(sessionId)?.agentKind ??dbToMakerAgentKind(getSessionDbAgentKind(sessionId));@@ -14203,20 +15239,127 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)verifiedWindow,);}+ } catch (error) {+ log.debug('runtime model context snapshot refresh failed', {+ sessionId,+ model,+ error: error instanceof Error ? error.message : String(error),+ });}- return response;- } catch (err) {- if (err instanceof CredentialModeSwitchBusyError) {- // 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,- // renderer toast 走 ipcError.CREDENTIAL_SWITCH_BUSY 专属文案。- throwIpcError('CREDENTIAL_SWITCH_BUSY', err.message);- }- throw err;}- });- },+ const projectionMeta = await maker.getSessionMeta(sessionId);+ const userBaselineOverride =+ internalOptions.source === 'user'+ ? {+ agentKind:+ maker.getSession(sessionId)?.agentKind ??+ projectionMeta?.agentKind ??+ 'claude-code',+ model,+ providerId:+ effectiveProviderId === undefined+ ? getSessionProvider(sessionId)+ : (normalizeSessionProviderId(effectiveProviderId) ?? null),+ effort:+ atomicSelection?.effort ??+ (getSessionEffort(sessionId) as+ | SessionRuntimeProfile['effort']+ | undefined) ??+ projectionMeta?.effort ??+ null,+ fastMode: atomicSelection?.fastMode ?? getSessionFastMode(sessionId),+ }+ : undefined;+ await broadcastSessionRuntimeProjection(sessionId, userBaselineOverride).catch((error) => {+ log.debug('session runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ return {+ ...response,+ generation,+ effectiveProviderId:+ normalizeSessionProviderId(effectiveProviderId) ?? null,+ };+ } catch (err) {+ if (err instanceof CredentialModeSwitchBusyError) {+ // 兜底(正常路径 busy 已转 deferred):切模型撞上凭证切换忙,独立 code,+ // renderer toast 走 ipcError.CREDENTIAL_SWITCH_BUSY 专属文案。+ throwIpcError('CREDENTIAL_SWITCH_BUSY', err.message);+ }+ throw err;+ }+ };+ return withSendToSessionLock(sessionId, applyLocked);+ };+ applySessionRuntimeSelection = (+ sessionId,+ model,+ providerId,+ selection,+ options,+ ) =>+ handleSetModel(+ undefined,+ sessionId,+ model,+ providerId,+ undefined,+ selection,+ options,+ );+ ipcMain.handle(+ MAKER_INVOKE.SET_MODEL,+ (event, sessionId, model, providerId, expectedAgentSwitchRevision, selection) =>+ handleSetModel(+ event,+ sessionId,+ model,+ providerId,+ expectedAgentSwitchRevision,+ selection,+ { source: 'user' },+ ),);+ const recoverRemoteRuntimeAxisPersistence = async (+ sessionId: string,+ previousProfile: SessionRuntimeProfile,+ patch: Pick<Partial<SessionRuntimeProfile>, 'effort' | 'fastMode'>,+ runtimeOwnerEpoch: string,+ ): Promise<void> => {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;+ try {+ await withRehydrateCloseSuppressed(sessionId, () => maker.closeSession(sessionId));+ } catch (recoveryError) {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;+ const retainedSession = maker.getSession(sessionId);+ if (retainedSession) {+ const retainedProfile: SessionRuntimeProfile = {+ ...previousProfile,+ agentKind: retainedSession.agentKind,+ model: retainedSession.model,+ ...patch,+ };+ if (patch.effort !== undefined) {+ setSessionEffort(sessionId, patch.effort);+ }+ if (patch.fastMode !== undefined) {+ setSessionFastMode(sessionId, patch.fastMode);+ }+ recordRecoveredSessionRuntimeAxisMutation(sessionId, retainedProfile);+ await broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('recovered runtime axis projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ throw recoveryError;+ }+ };+ipcMain.handle(MAKER_INVOKE.SET_EFFORT, async (event, sessionId: unknown, effort: unknown) => {// 轮 24-I3 HIGH:会话变更型 IPC 统一 sender 校验(对齐 SET_PERMISSION_MODE)——// 任意 WebView/受污染页面不得修改活会话偏好。device-link 远程控制端已授权。@@ -14226,44 +15369,128 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (typeof sessionId !== 'string' || typeof effort !== 'string') {throwIpcError('INVALID_PARAMS', 'sessionId + effort required');}- await assertReviewSettingsUnlocked(sessionId);- // 记下会话 effort:responses-bridge 模型(chatgpt/ / xai/)的 effort 无法经请求体流到 bridge,- // 由 compat-proxy 路由决策从这里读出、闭包进订阅直连 handler 的 prefs(不影响 session 是否在跑)。- setSessionEffort(sessionId, effort);- const sess = maker.getSession(sessionId);- if (!sess) {- log.debug('set-effort: session not found, no-op', { sessionId });- return;- }- // 有 pending 凭证切换 = 本会话的 model/effort 变更已整体延迟到 turn 结束重建:- // 跳过对仍在跑的旧 turn 的 runtime 推送(与 renderer 本地分支的 deferred 守卫同因,- // 这里是唯一 choke point,同时覆盖 device-link 远程入口;review P2 2026-07-04)。- // 持久化不受影响:本地由 renderer sessionService.update 落盘,远程由 device-link- // dispatch 的 persistRemoteSetting 按请求值落被控端 DB,重建时生效。- if (pendingCredentialSwitchHolder?.has(sessionId)) {- log.debug('set-effort: skipped live push (pending credential switch)', { sessionId });- return;- }- try {- const result = await applyRuntimeEffortWithRecovery({- applyRuntime: () =>- sess.setEffort(- effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',- ),- terminateSession: () => maker.closeSession(sessionId),- });- if (result === 'session-terminated') {- log.warn('set-effort: timed-out runtime session terminated for lazy rebuild', {+ const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();+ const assertOwnerCurrent = () => {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'app session changed during runtime effort update; request dropped',+ );+ }+ };+ const remoteInvoke = isDeviceLinkInvoke();+ const remoteResponse = remoteInvoke ? {} : undefined;+ const persistEffort = async () => {+ if (!remoteResponse) return;+ await persistSessionFields(sessionId, { effort });+ markRemoteSettingPersistedInsideHandler(remoteResponse);+ };+ const applyEffort = async () => {+ const [runtimeStatus] = await getDbClient()+ .drizzle.select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!runtimeStatus) {+ if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);+ return remoteResponse;+ }+ if (runtimeStatus.status !== 'active') {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'archived or deleted task cannot change runtime effort',+ );+ }+ const livePatch: SessionRuntimeAxisPatch = {+ effort: effort as SessionRuntimeProfile['effort'],+ };+ const pendingPatch = await resolvePendingRuntimeAxisPatch(sessionId, livePatch);+ const commitEffort = () => {+ recordUserSessionRuntimeAxisMutation(sessionId, livePatch, pendingPatch);+ // 记下会话 effort:responses-bridge 模型(chatgpt/ / xai/)的 effort 无法经请求体流到 bridge,+ // 由 compat-proxy 路由决策从这里读出、闭包进订阅直连 handler 的 prefs(不影响 session 是否在跑)。+ setSessionEffort(sessionId, effort);+ };+ const sess = maker.getSession(sessionId);+ if (!sess) {+ await commitRuntimeAxisAfterPersistence({+ persist: persistEffort,+ commit: commitEffort,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-effort: session not found, no-op', { sessionId });+ return remoteResponse;+ }+ // 有 pending 凭证切换 = 本会话的 model/effort 变更已整体延迟到 turn 结束重建:+ // 跳过对仍在跑的旧 turn 的 runtime 推送(与 renderer 本地分支的 deferred 守卫同因,+ // 这里是唯一 choke point,同时覆盖 device-link 远程入口;review P2 2026-07-04)。+ // 持久化不受影响:本地由 renderer sessionService.update 落盘,远程由 device-link+ // dispatch 的 persistRemoteSetting 按请求值落被控端 DB,重建时生效。+ if (pendingCredentialSwitchHolder?.has(sessionId)) {+ await commitRuntimeAxisAfterPersistence({+ persist: persistEffort,+ commit: commitEffort,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-effort: skipped live push (pending credential switch)', { sessionId });+ return remoteResponse;+ }+ try {+ const previousProfile = remoteInvoke+ ? (await readSessionRuntimeProfiles(sessionId))?.effective+ : undefined;+ const result = await applyRuntimeEffortWithRecovery({+ applyRuntime: () =>+ sess.setEffort(+ effort as 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',+ ),+ terminateSession: () => maker.closeSession(sessionId),+ });+ if (result === 'session-terminated') {+ log.warn('set-effort: timed-out runtime session terminated for lazy rebuild', {+ sessionId,+ });+ }+ await commitRuntimeAxisAfterPersistence({+ persist: persistEffort,+ commit: commitEffort,+ assertCanCommit: assertOwnerCurrent,+ ...(remoteInvoke && result === 'applied' && previousProfile+ ? {+ recoverAfterPersistenceFailure: () =>+ recoverRemoteRuntimeAxisPersistence(+ sessionId,+ previousProfile,+ { effort: effort as SessionRuntimeProfile['effort'] },+ runtimeOwnerEpoch,+ ),+ }+ : {}),+ });+ return remoteResponse;+ } catch (error) {+ if (isIpcError(error)) throw error;+ log.warn('set-effort runtime update failed', {sessionId,+ error: error instanceof Error ? error.message : String(error),});+ throwIpcError('INTERNAL', 'Runtime effort update failed');}- } catch (error) {- log.warn('set-effort runtime update failed', {- sessionId,- error: error instanceof Error ? error.message : String(error),- });- throwIpcError('INTERNAL', 'Runtime effort update failed');- }+ };+ return withSendToSessionLock(sessionId, async () => {+ await assertReviewSettingsUnlocked(sessionId);+ assertOwnerCurrent();+ try {+ return await applyEffort();+ } finally {+ await broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('set-effort runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ });});ipcMain.handle(@@ -14568,35 +15795,126 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (typeof sessionId !== 'string' || typeof enabled !== 'boolean') {throwIpcError('INVALID_PARAMS', 'sessionId + enabled required');}- await assertReviewSettingsUnlocked(sessionId);- // 记下会话 Fast 态:responses-bridge 模型(chatgpt/ 前缀)的 fast 无法经请求体流到 bridge,- // 由 compat-proxy 路由决策从这里读出、闭包进订阅直连 handler 的 prefs(与 SET_EFFORT 的 effort 同机制)。- setSessionFastMode(sessionId, enabled);- const sess = maker.getSession(sessionId);- if (!sess) {- log.debug('set-fast-mode: session not found, no-op', { sessionId });- return;- }- if (sess.agentKind === 'pi') {- // Pi 的 ChatGPT 请求不从 pi 请求体携带 Fast,而是由上面的 session store- // 在 compat-proxy 决策点闭包进 responses bridge prefs。到这里已经即时生效,- // 无需向 pi RPC 再发一份不存在的 set_fast_mode 控制命令。- log.debug('set-fast-mode: pi responses bridge state updated', { sessionId, enabled });- return;- }- if (sess.agentKind !== 'codex') {- log.debug('set-fast-mode: agent does not implement fast mode, no-op', {- sessionId,- agentKind: sess.agentKind,+ const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();+ const assertOwnerCurrent = () => {+ if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'app session changed during runtime Fast mode update; request dropped',+ );+ }+ };+ const remoteInvoke = isDeviceLinkInvoke();+ const remoteResponse = remoteInvoke ? {} : undefined;+ const persistFastMode = async () => {+ if (!remoteResponse) return;+ await persistSessionFields(sessionId, { fastMode: enabled });+ markRemoteSettingPersistedInsideHandler(remoteResponse);+ };+ const applyFastMode = async () => {+ const [runtimeStatus] = await getDbClient()+ .drizzle.select({ status: sessions.status })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ if (!runtimeStatus) {+ if (remoteResponse) markRemoteSettingPersistedInsideHandler(remoteResponse);+ return remoteResponse;+ }+ if (runtimeStatus.status !== 'active') {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'archived or deleted task cannot change runtime Fast mode',+ );+ }+ const livePatch: SessionRuntimeAxisPatch = { fastMode: enabled };+ const pendingPatch = await resolvePendingRuntimeAxisPatch(sessionId, livePatch);+ const commitFastMode = () => {+ recordUserSessionRuntimeAxisMutation(sessionId, livePatch, pendingPatch);+ // 记下会话 Fast 态:responses-bridge 模型(chatgpt/ 前缀)的 fast 无法经请求体流到 bridge,+ // 由 compat-proxy 路由决策从这里读出、闭包进订阅直连 handler 的 prefs(与 SET_EFFORT 的 effort 同机制)。+ setSessionFastMode(sessionId, enabled);+ };+ const sess = maker.getSession(sessionId);+ if (!sess) {+ await commitRuntimeAxisAfterPersistence({+ persist: persistFastMode,+ commit: commitFastMode,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-fast-mode: session not found, no-op', { sessionId });+ return remoteResponse;+ }+ if (sess.agentKind === 'pi') {+ // Pi 的 ChatGPT 请求不从 pi 请求体携带 Fast,而是由上面的 session store+ // 在 compat-proxy 决策点闭包进 responses bridge prefs。到这里已经即时生效,+ // 无需向 pi RPC 再发一份不存在的 set_fast_mode 控制命令。+ await commitRuntimeAxisAfterPersistence({+ persist: persistFastMode,+ commit: commitFastMode,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-fast-mode: pi responses bridge state updated', { sessionId, enabled });+ return remoteResponse;+ }+ if (sess.agentKind !== 'codex') {+ await commitRuntimeAxisAfterPersistence({+ persist: persistFastMode,+ commit: commitFastMode,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-fast-mode: agent does not implement fast mode, no-op', {+ sessionId,+ agentKind: sess.agentKind,+ });+ return remoteResponse;+ }+ // 同 set-effort:pending 凭证切换期间不触碰仍在跑的旧 turn,持久化走各自 DB 路径。+ if (pendingCredentialSwitchHolder?.has(sessionId)) {+ await commitRuntimeAxisAfterPersistence({+ persist: persistFastMode,+ commit: commitFastMode,+ assertCanCommit: assertOwnerCurrent,+ });+ log.debug('set-fast-mode: skipped live push (pending credential switch)', { sessionId });+ return remoteResponse;+ }+ const previousProfile = remoteInvoke+ ? (await readSessionRuntimeProfiles(sessionId))?.effective+ : undefined;+ await sess.setFastMode(enabled);+ await commitRuntimeAxisAfterPersistence({+ persist: persistFastMode,+ commit: commitFastMode,+ assertCanCommit: assertOwnerCurrent,+ ...(remoteInvoke && previousProfile+ ? {+ recoverAfterPersistenceFailure: () =>+ recoverRemoteRuntimeAxisPersistence(+ sessionId,+ previousProfile,+ { fastMode: enabled },+ runtimeOwnerEpoch,+ ),+ }+ : {}),});- return;- }- // 同 set-effort:pending 凭证切换期间不触碰仍在跑的旧 turn,持久化走各自 DB 路径。- if (pendingCredentialSwitchHolder?.has(sessionId)) {- log.debug('set-fast-mode: skipped live push (pending credential switch)', { sessionId });- return;- }- await sess.setFastMode(enabled);+ return remoteResponse;+ };+ return withSendToSessionLock(sessionId, async () => {+ await assertReviewSettingsUnlocked(sessionId);+ assertOwnerCurrent();+ try {+ return await applyFastMode();+ } finally {+ await broadcastSessionRuntimeProjection(sessionId).catch((error) => {+ log.debug('set-fast-mode runtime projection broadcast failed', {+ sessionId,+ error: error instanceof Error ? error.message : String(error),+ });+ });+ }+ });},);diff --git a/apps/desktop/src/main/maker-ipc/runtimeSelectionAxes.ts b/apps/desktop/src/main/maker-ipc/runtimeSelectionAxes.tsnew file mode 100644index 0000000000..c2b3ae1404--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/runtimeSelectionAxes.ts@@ -0,0 +1,139 @@+import type { AgentKind, Effort } from '@cindy/maker-core';+import { EFFORT_VALUES } from '@cindy/model-providers';++/** Runtime validation for effort values crossing IPC and Device Link boundaries. */+export function isSupportedRuntimeEffort(value: unknown): value is Effort {+ return typeof value === 'string' && (EFFORT_VALUES as readonly string[]).includes(value);+}++export function resolveRetainedRuntimeEffort(input: {+ targetModelHasFixedEffort: boolean;+ requestedEffort: Effort | null | undefined;+ liveEffort: Effort | null;+ previousEffort: Effort | null | undefined;+}): Effort | null {+ // Catalog capability is the request contract. A close failure leaves the old+ // handle in Session status=error, and the next send rebuilds it instead of+ // reusing its stale mutable effort, so never project that stale value onto a+ // fixed-effort model.+ if (input.targetModelHasFixedEffort || input.requestedEffort === null) return null;+ if (input.liveEffort !== null) return input.liveEffort;+ return input.previousEffort ?? null;+}++interface RuntimeSelectionAxesSession {+ agentKind: AgentKind;+ setEffort: (effort: Effort) => Promise<void>;+ setFastMode: (enabled: boolean) => Promise<void>;+}++export interface ApplyRuntimeSelectionAxesWithRecoveryInput {+ session: RuntimeSelectionAxesSession;+ effort: Effort | null;+ fastMode: boolean;+ applyEffort?: boolean;+ applyFastMode?: boolean;+ assertCanCommit?: () => void;+ commitControlStores: () => void;+ restoreControlStores: () => void;+ terminateSession: () => Promise<void>;+ recoverLiveProfileAfterTerminationFailure?: () => void | Promise<void>;+}++export interface CommitRuntimeAxisAfterPersistenceInput {+ persist: () => Promise<void>;+ commit: () => void;+ assertCanCommit?: () => void;+ recoverAfterPersistenceFailure?: () => Promise<void>;+}++/**+ * A Device Link axis change is not accepted until the controlled Desktop has+ * persisted its baseline. If persistence rejects after the live RPC succeeded,+ * retire or reconcile that Session before reporting the failed invoke.+ */+export async function commitRuntimeAxisAfterPersistence(+ input: CommitRuntimeAxisAfterPersistenceInput,+): Promise<void> {+ try {+ await input.persist();+ } catch (persistenceError) {+ // Owner transitions invalidate both the requested write and any recovery+ // against the old live Session. Fence that path before touching either.+ input.assertCanCommit?.();+ if (input.recoverAfterPersistenceFailure) {+ try {+ await input.recoverAfterPersistenceFailure();+ } catch (recoveryError) {+ throw new AggregateError(+ [persistenceError, recoveryError],+ 'runtime axis persistence and session recovery both failed',+ );+ }+ }+ throw persistenceError;+ }+ // Persistence may have yielded across an owner transition. The final store /+ // generation commit must therefore be fenced independently of the DB write.+ input.assertCanCommit?.();+ input.commit();+}++/**+ * Finishes the effort/Fast half of an already-applied model switch.+ *+ * Harness control calls are not transactional. If either axis rejects after the+ * model/provider changed, restore the old host-side routing stores and retire the+ * partially-mutated Session. The next send then rebuilds from the still-current+ * runtime-control generation instead of exposing a mixed live profile.+ */+export async function applyRuntimeSelectionAxesWithRecovery(+ input: ApplyRuntimeSelectionAxesWithRecoveryInput,+): Promise<void> {+ const applyEffort = input.applyEffort !== false;+ const applyFastMode = input.applyFastMode !== false;+ // A fixed-effort model has no representable live setEffort value. Keeping the+ // current Session would leave each harness's mutable effort on the previous+ // model, so retire the idle Session and let the next send rebuild from the+ // committed null-effort runtime profile.+ if (applyEffort && input.effort === null) {+ try {+ await input.terminateSession();+ } catch (terminationError) {+ input.assertCanCommit?.();+ input.restoreControlStores();+ await input.recoverLiveProfileAfterTerminationFailure?.();+ throw terminationError;+ }+ input.assertCanCommit?.();+ input.commitControlStores();+ return;+ }+ try {+ if (applyEffort) {+ // The null case returns through the fixed-effort rebuild branch above.+ await input.session.setEffort(input.effort as Effort);+ input.assertCanCommit?.();+ }+ if (applyFastMode && input.session.agentKind === 'codex') {+ await input.session.setFastMode(input.fastMode);+ input.assertCanCommit?.();+ }+ } catch (axisError) {+ input.assertCanCommit?.();+ input.restoreControlStores();+ try {+ await input.terminateSession();+ } catch (terminationError) {+ input.assertCanCommit?.();+ await input.recoverLiveProfileAfterTerminationFailure?.();+ throw new AggregateError(+ [axisError, terminationError],+ 'runtime selection axis update and session recovery both failed',+ );+ }+ throw axisError;+ }+ input.assertCanCommit?.();+ input.commitControlStores();+}diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.tsindex 95859c8ef2..3a04a27397 100644--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts@@ -49,6 +49,11 @@ export interface ApplyRuntimeSetModelChangeInput {model: string;providerId?: string | null;effort?: Effort;+ /**+ * Orca Worker 的 live model/provider 属于执行单元身份,不能热切。即使凭证+ * 形态相同,也必须沿用 credential-switch 的 idle close / busy defer 边界。+ */+ forceSessionRebuild?: boolean;isSessionInTurn?: (sessionId: string) => boolean;/*** 会话自己正在跑 turn 时的延迟生效登记(PendingCredentialSwitchService.register)。@@ -95,6 +100,13 @@ export type ApplyRuntimeSetModelChangeResult =/** 凭证形态要换但会话自己在跑:已登记 pending,turn 结束后自动生效。 */| { status: 'deferred' };+export function isRemoteModelSwitchRouteChangeError(error: unknown): boolean {+ return (+ (error as { code?: unknown } | null)?.code === 'REMOTE_MODEL_SWITCH_ROUTE_CHANGE' ||+ (error instanceof Error && error.message.includes('[REMOTE_MODEL_SWITCH_ROUTE_CHANGE]'))+ );+}+/*** 应用本地运行时 model/provider 切换。*@@ -132,7 +144,7 @@ export async function applyRuntimeSetModelChange(? pendingTarget.providerId: currentProviderId;const shouldCloseSession = sess- ? shouldCloseSessionForCredentialSwitch({+ ? input.forceSessionRebuild === true || shouldCloseSessionForCredentialSwitch({agentKind: sess.agentKind,remoteHostId: sess.remoteHostId,currentProviderId,diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.tsindex 98638f8ca2..bab4e15a1e 100644--- a/apps/desktop/src/main/maker-ipc/sessionControlService.ts+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts@@ -1,10 +1,16 @@import type {AgentKind,+ Effort,SessionGracefulStopResult,SessionTurnControlSnapshot,} from '@cindy/maker-core';import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';+import type {+ PendingSessionRuntimeMutation,+ SessionRuntimeProfile,+} from './sessionRuntimeControl.js';+import {updateQueuedMessageText,type AgentInputQueuedMessage,@@ -36,8 +42,26 @@ export type SessionStopResult =}| Failure<'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY'>;+export interface SessionRuntimeDetails extends SessionActivitySnapshot {+ runtimeGeneration: number;+ baselineProfile: SessionRuntimeProfile;+ effectiveProfile: SessionRuntimeProfile;+ pendingMutation: PendingSessionRuntimeMutation | null;+ fallbackEnabled: boolean;+}+export type SessionRuntimeResult =- { ok: true; runtime: SessionActivitySnapshot } | Failure<'NOT_FOUND'>;+ { ok: true; runtime: SessionRuntimeDetails } | Failure<'NOT_FOUND'>;++export type SessionRuntimeSetResult =+ | {+ ok: true;+ status: 'applied' | 'deferred';+ generation: number;+ effectiveProfile: SessionRuntimeProfile;+ pendingMutation: PendingSessionRuntimeMutation | null;+ }+ | Failure<'NOT_FOUND' | 'CONFLICT' | 'INVALID_ARGS' | 'ROUTE_UNAVAILABLE'>;export interface SessionControlLiveSession {agentKind: AgentKind;@@ -57,6 +81,17 @@ export interface SessionControlServiceDeps {sessionExists(sessionId: string): Promise<boolean>;getLiveSession(sessionId: string): SessionControlLiveSession | null;getSessionActivitySnapshot(sessionId: string): Promise<SessionActivitySnapshot>;+ getSessionRuntimeDetails(sessionId: string): Promise<SessionRuntimeDetails>;+ setSessionRuntime(params: {+ targetSessionId: string;+ expectedGeneration?: number;+ patch: {+ model?: string;+ providerId?: string | null;+ effort?: Effort;+ fastMode?: boolean;+ };+ }): Promise<SessionRuntimeSetResult>;assertExternalInputAllowed(sessionId: string): Promise<void>;createQueuedMessage(params: {targetSessionId: string;@@ -223,17 +258,36 @@ export function createSessionControlService(deps: SessionControlServiceDeps) {async getSessionRuntime(params: { targetSessionId: string }): Promise<SessionRuntimeResult> {const missing = await ensureTarget(params.targetSessionId);if (missing) return missing;- const activity = await deps.getSessionActivitySnapshot(params.targetSessionId);+ const [activity, details] = await Promise.all([+ deps.getSessionActivitySnapshot(params.targetSessionId),+ deps.getSessionRuntimeDetails(params.targetSessionId),+ ]);const control = deps.getLiveSession(params.targetSessionId)?.getTurnControlSnapshot();return {ok: true,runtime: {+ ...details,...activity,turnGeneration: control?.turnGeneration ?? null,gracefulStopState: control?.gracefulStopState ?? 'none',},};},++ async setSessionRuntime(params: {+ targetSessionId: string;+ expectedGeneration?: number;+ patch: {+ model?: string;+ providerId?: string | null;+ effort?: Effort;+ fastMode?: boolean;+ };+ }): Promise<SessionRuntimeSetResult> {+ const missing = await ensureTarget(params.targetSessionId);+ if (missing) return missing;+ return deps.setSessionRuntime(params);+ },};}diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.tsnew file mode 100644index 0000000000..78f4ad8199--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts@@ -0,0 +1,487 @@+import type { AgentKind, Effort } from '@cindy/maker-core';+import {+ connectedProvidersForAgent,+ isModelSelectableForNewRoute,+ type CatalogModel,+ type ProviderView,+} from '@cindy/model-providers';++export type SessionRuntimeMutationSource = 'agent' | 'fallback';++export interface SessionRuntimeProfile {+ agentKind: AgentKind;+ model: string;+ providerId: string | null;+ effort: Effort | null;+ fastMode: boolean;+}++export interface PendingSessionRuntimeMutation {+ generation: number;+ source: SessionRuntimeMutationSource;+ profile: SessionRuntimeProfile;+}++export interface SessionRuntimeControlSnapshot {+ generation: number;+ effectiveOverride: SessionRuntimeProfile | null;+ pending: PendingSessionRuntimeMutation | null;+ fallbackHop: number;+ visitedRoutes: string[];+}++export type SessionRuntimeProfilePatch = Partial<+ Pick<SessionRuntimeProfile, 'model' | 'providerId' | 'effort' | 'fastMode'>+>;++export type SessionRuntimeAxisPatch = Pick<+ Partial<SessionRuntimeProfile>,+ 'effort' | 'fastMode'+>;++export function mergeSessionRuntimeProfilePatch(+ base: SessionRuntimeProfile,+ patch: SessionRuntimeProfilePatch,+): SessionRuntimeProfile {+ return {+ ...base,+ ...(patch.model !== undefined ? { model: patch.model } : {}),+ ...(patch.providerId !== undefined ? { providerId: patch.providerId } : {}),+ ...(patch.effort !== undefined ? { effort: patch.effort } : {}),+ ...(patch.fastMode !== undefined ? { fastMode: patch.fastMode } : {}),+ };+}++interface SessionRuntimeControlState {+ generation: number;+ effectiveOverride: SessionRuntimeProfile | null;+ pending: PendingSessionRuntimeMutation | null;+ pendingRouteExplicit: boolean;+ fallbackHop: number;+ visitedRoutes: Set<string>;+}++const states = new Map<string, SessionRuntimeControlState>();+let ownerEpoch = 0;++function routeKey(profile: Pick<SessionRuntimeProfile, 'providerId' | 'model'>): string {+ return `${profile.providerId ?? ''}\u0000${profile.model}`;+}++function stateFor(sessionId: string): SessionRuntimeControlState {+ let state = states.get(sessionId);+ if (!state) {+ state = {+ generation: 0,+ effectiveOverride: null,+ pending: null,+ pendingRouteExplicit: true,+ fallbackHop: 0,+ visitedRoutes: new Set(),+ };+ states.set(sessionId, state);+ }+ return state;+}++export function sessionRuntimeGenerationMatches(+ sessionId: string,+ expectedGeneration: number | undefined,+): boolean {+ return expectedGeneration === undefined || (states.get(sessionId)?.generation ?? 0) === expectedGeneration;+}++export function recordUserSessionRuntimeMutation(sessionId: string): number {+ const state = stateFor(sessionId);+ state.generation += 1;+ state.effectiveOverride = null;+ state.pending = null;+ state.pendingRouteExplicit = true;+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ return state.generation;+}++/**+ * Persistence failed after the live Session had already switched, and the+ * compensating close could not retire it. Keep that unavoidable live profile+ * explicit so readers and CAS do not continue from the stale DB baseline.+ */+export function recordRecoveredSessionRuntimeMutation(+ sessionId: string,+ profile: SessionRuntimeProfile,+): number {+ const state = stateFor(sessionId);+ state.generation += 1;+ state.effectiveOverride = profile;+ state.pending = null;+ state.pendingRouteExplicit = true;+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ return state.generation;+}++/**+ * A user axis RPC reached the live Session but its baseline persistence and+ * compensating close both failed. Keep the observed live profile explicit while+ * preserving any earlier accepted deferred route.+ */+export function recordRecoveredSessionRuntimeAxisMutation(+ sessionId: string,+ profile: SessionRuntimeProfile,+): number {+ const state = stateFor(sessionId);+ state.generation += 1;+ state.effectiveOverride = profile;+ if (state.pending) {+ state.pending = { ...state.pending, generation: state.generation };+ }+ return state.generation;+}++export function recordUserSessionRuntimeAxisMutation(+ sessionId: string,+ patch: SessionRuntimeAxisPatch,+ pendingPatch: SessionRuntimeAxisPatch = patch,+): number {+ const state = stateFor(sessionId);+ state.generation += 1;+ const pending = state.pending;+ state.pending = pending+ ? {+ ...pending,+ generation: state.generation,+ profile: { ...pending.profile, ...pendingPatch },+ }+ : null;+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ if (state.effectiveOverride) {+ state.effectiveOverride = { ...state.effectiveOverride, ...patch };+ }+ return state.generation;+}++/**+ * Agent axis-only patches share the CAS/generation contract with model changes,+ * but must not route, persist a baseline, or cancel an already accepted route.+ */+export function acceptSessionRuntimeAxisMutation(params: {+ sessionId: string;+ source: SessionRuntimeMutationSource;+ profile: SessionRuntimeProfile;+ pendingPatch: SessionRuntimeAxisPatch;+}): number {+ const state = stateFor(params.sessionId);+ state.generation += 1;+ state.effectiveOverride = params.profile;+ if (state.pending) {+ state.pending = {+ ...state.pending,+ generation: state.generation,+ profile: { ...state.pending.profile, ...params.pendingPatch },+ };+ }+ if (params.source === 'agent') {+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ }+ return state.generation;+}++/**+ * A busy task must leave its current turn untouched. Queue an Agent axis-only+ * patch at the same boundary as route changes, preserving any route that was+ * already accepted for that boundary and leaving the effective profile intact.+ */+export function deferSessionRuntimeAxisMutation(params: {+ sessionId: string;+ source: SessionRuntimeMutationSource;+ effectiveProfile: SessionRuntimeProfile;+ pendingPatch: SessionRuntimeAxisPatch;+}): number {+ const state = stateFor(params.sessionId);+ const hadPendingMutation = state.pending !== null;+ state.generation += 1;+ state.pending = state.pending+ ? {+ ...state.pending,+ generation: state.generation,+ profile: { ...state.pending.profile, ...params.pendingPatch },+ }+ : {+ generation: state.generation,+ source: params.source,+ profile: { ...params.effectiveProfile, ...params.pendingPatch },+ };+ if (!hadPendingMutation) state.pendingRouteExplicit = false;+ if (params.source === 'agent') {+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ }+ return state.generation;+}++export function resolveCompatibleSessionRuntimeAxisPatch(params: {+ model: CatalogModel;+ profile: SessionRuntimeProfile;+ patch: SessionRuntimeAxisPatch;+}): SessionRuntimeAxisPatch {+ const axes = resolveSessionRuntimeAxes({+ model: params.model,+ effort:+ params.patch.effort !== undefined+ ? params.patch.effort+ : params.profile.effort,+ fastMode: params.patch.fastMode ?? params.profile.fastMode,+ effortExplicit: false,+ fastExplicit: false,+ });+ if (!axes.ok) return {};+ return {+ ...(params.patch.effort !== undefined ? { effort: axes.effort } : {}),+ ...(params.patch.fastMode !== undefined ? { fastMode: axes.fastMode } : {}),+ };+}++export function acceptSessionRuntimeMutation(params: {+ sessionId: string;+ source: SessionRuntimeMutationSource;+ profile: SessionRuntimeProfile;+ previousProfile?: SessionRuntimeProfile;+ deferred: boolean;+}): number {+ const state = stateFor(params.sessionId);+ state.generation += 1;+ const accepted: PendingSessionRuntimeMutation = {+ generation: state.generation,+ source: params.source,+ profile: params.profile,+ };+ state.pending = params.deferred ? accepted : null;+ state.pendingRouteExplicit = true;+ if (!params.deferred) state.effectiveOverride = params.profile;+ if (params.source === 'fallback') {+ state.fallbackHop += 1;+ if (params.previousProfile) state.visitedRoutes.add(routeKey(params.previousProfile));+ state.visitedRoutes.add(routeKey(params.profile));+ } else {+ state.fallbackHop = 0;+ state.visitedRoutes.clear();+ }+ return state.generation;+}++export function recordFailedSessionRuntimeFallbackCandidate(+ sessionId: string,+ expectedGeneration: number,+ profile: SessionRuntimeProfile,+): boolean {+ const state = stateFor(sessionId);+ if (state.generation !== expectedGeneration) return false;+ state.visitedRoutes.add(routeKey(profile));+ return true;+}++export function settlePendingSessionRuntimeMutation(+ sessionId: string,+ generation: number,+): boolean {+ const state = stateFor(sessionId);+ const pending = state.pending;+ if (!pending || pending.generation !== generation || state.generation !== generation)+ return false;+ state.pending = null;+ state.pendingRouteExplicit = true;+ state.effectiveOverride = pending.profile;+ return true;+}++export function cancelPendingSessionRuntimeMutation(+ sessionId: string,+ generation: number,+): boolean {+ const state = states.get(sessionId);+ const pending = state?.pending;+ if (!state || !pending || pending.generation !== generation || state.generation !== generation) {+ return false;+ }+ state.pending = null;+ state.pendingRouteExplicit = true;+ return true;+}++export function isPendingSessionRuntimeRouteExplicit(+ sessionId: string,+ generation: number,+): boolean {+ const state = states.get(sessionId);+ if (!state?.pending || state.pending.generation !== generation) return true;+ return state.pendingRouteExplicit;+}++export function getPendingSessionRuntimeMutation(+ sessionId: string,+): PendingSessionRuntimeMutation | null {+ return states.get(sessionId)?.pending ?? null;+}++export function getSessionRuntimeControlSnapshot(sessionId: string): SessionRuntimeControlSnapshot {+ const state = states.get(sessionId);+ if (!state) {+ return {+ generation: 0,+ effectiveOverride: null,+ pending: null,+ fallbackHop: 0,+ visitedRoutes: [],+ };+ }+ return {+ generation: state.generation,+ effectiveOverride: state.effectiveOverride,+ pending: state.pending,+ fallbackHop: state.fallbackHop,+ visitedRoutes: [...state.visitedRoutes],+ };+}++export function clearSessionRuntimeControlState(sessionId: string): void {+ states.delete(sessionId);+}++export function clearAllSessionRuntimeControlStates(): void {+ ownerEpoch += 1;+ states.clear();+}++export function captureSessionRuntimeControlOwnerEpoch(): string {+ return String(ownerEpoch);+}++export function sessionRuntimeControlOwnerEpochMatches(expected: string): boolean {+ return captureSessionRuntimeControlOwnerEpoch() === expected;+}++const EFFORT_ORDER: readonly Effort[] = [+ 'minimal',+ 'low',+ 'medium',+ 'high',+ 'xhigh',+ 'max',+ 'ultra',+];++export function resolveCompatibleSessionRuntimeEffort(+ model: CatalogModel,+ requested: Effort | null,+): Effort | null {+ if (model.efforts.length === 0) return null;+ if (requested && model.efforts.includes(requested)) return requested;+ if (model.defaultEffort && model.efforts.includes(model.defaultEffort))+ return model.defaultEffort;+ if (!requested) return model.efforts[0] ?? null;+ const requestedRank = EFFORT_ORDER.indexOf(requested);+ return (+ [...model.efforts].sort(+ (a, b) =>+ Math.abs(EFFORT_ORDER.indexOf(a) - requestedRank) -+ Math.abs(EFFORT_ORDER.indexOf(b) - requestedRank),+ )[0] ?? null+ );+}++export function resolveSessionRuntimeAxes(params: {+ model: CatalogModel;+ effort: Effort | null;+ fastMode: boolean;+ effortExplicit: boolean;+ fastExplicit: boolean;+ allowFixedEffortPlaceholder?: boolean;+}):+ | { ok: true; effort: Effort | null; fastMode: boolean }+ | { ok: false; reason: 'effort-unavailable' | 'fast-unavailable' } {+ if (+ params.effortExplicit &&+ params.effort !== null &&+ !params.model.efforts.includes(params.effort) &&+ !(+ params.allowFixedEffortPlaceholder === true &&+ params.model.efforts.length === 0+ )+ ) {+ return { ok: false, reason: 'effort-unavailable' };+ }+ if (params.fastExplicit && params.fastMode && params.model.supportsFastMode !== true) {+ return { ok: false, reason: 'fast-unavailable' };+ }+ return {+ ok: true,+ effort: resolveCompatibleSessionRuntimeEffort(params.model, params.effort),+ fastMode: params.fastMode && params.model.supportsFastMode === true,+ };+}++export function pickSessionRuntimeFallback(params: {+ providers: readonly ProviderView[];+ current: SessionRuntimeProfile;+ visitedRoutes: readonly string[];+ maxHops: number;+ currentHop: number;+}): SessionRuntimeProfile | null {+ if (params.currentHop >= params.maxHops) return null;+ const visited = new Set(params.visitedRoutes);+ visited.add(routeKey(params.current));+ const rail = connectedProvidersForAgent([...params.providers], params.current.agentKind);+ const candidates: Array<{ providerId: string; model: CatalogModel }> = [];++ for (const provider of rail) {+ for (const model of provider.models[params.current.agentKind] ?? []) {+ if (+ !isModelSelectableForNewRoute(model, {+ userProvider: provider.source === 'user',+ })+ ) {+ continue;+ }+ if (model.id === params.current.model && provider.id !== params.current.providerId) {+ candidates.push({ providerId: provider.id, model });+ }+ }+ }+ for (const provider of rail) {+ for (const model of provider.models[params.current.agentKind] ?? []) {+ if (+ !isModelSelectableForNewRoute(model, {+ userProvider: provider.source === 'user',+ })+ ) {+ continue;+ }+ if (!model.newSessionDefault?.includes(params.current.agentKind)) continue;+ candidates.push({ providerId: provider.id, model });+ }+ }++ for (const candidate of candidates) {+ const key = routeKey({ providerId: candidate.providerId, model: candidate.model.id });+ if (visited.has(key)) continue;+ const axes = resolveSessionRuntimeAxes({+ model: candidate.model,+ effort: params.current.effort,+ fastMode: params.current.fastMode,+ effortExplicit: false,+ fastExplicit: false,+ });+ if (!axes.ok) continue;+ return {+ agentKind: params.current.agentKind,+ model: candidate.model.id,+ providerId: candidate.providerId,+ effort: axes.effort,+ fastMode: axes.fastMode,+ };+ }+ return null;+}diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 86dd7f0b98..fdfe50ce1a 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -319,6 +319,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcsteerSession: wrap((service, params) => service.steerSession(params)),stopSessionTurn: wrap((service, params) => service.stopSessionTurn(params)),getSessionRuntime: wrap((service, params) => service.getSessionRuntime(params)),+ setSessionRuntime: wrap((service, params) => service.setSessionRuntime(params)),},setCurrentSessionTitle: async ({ sessionId, title }) => {if (!tryGetDbClient()) {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex bc10e80208..f7bcfa2412 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -6208,6 +6208,25 @@ contextBridge.exposeInMainWorld('electronAPI', {defaultEnabled: boolean;effective: 'immediate';}> => ipcRenderer.invoke('maker:silent-encrypted-retry:reset'),+ sessionRuntimeFallbackGet: (): Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }> => ipcRenderer.invoke('maker:session-runtime-fallback:get'),+ sessionRuntimeFallbackSet: (+ enabled: boolean,+ ): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:session-runtime-fallback:set', enabled),+ sessionRuntimeFallbackReset: (): Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }> => ipcRenderer.invoke('maker:session-runtime-fallback:reset'),// Claude Code 自动上下文压缩阈值。仅对新建会话生效。compactionGetPct: (): Promise<number> => ipcRenderer.invoke('maker:compaction:get-pct'),diff --git a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.tsindex 8e4f1fe694..2d020d0260 100644--- a/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteProjectsStore.test.ts@@ -228,6 +228,63 @@ describe('remoteProjectsStore', () => {expect(getSessionDeviceId('s1')).toBe('dev-B'); // origin 标记不丢});+ it('合并被控端运行时模型投影并同步有效设置轴', () => {+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1')]);+ remoteProjectsStore.applyPatch('dev-B', 's1', {+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ runtimeGeneration: 3,+ runtimeBaseline: {+ agentKind: 'codex',+ model: 'gpt-baseline',+ providerId: 'xd',+ effort: 'high',+ fastMode: false,+ },+ runtimeEffective: {+ agentKind: 'codex',+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ },+ runtimePending: null,+ });++ expect(remoteProjectsStore.getMergedRemoteSessions()[0]).toMatchObject({+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ runtimeGeneration: 3,+ runtimeEffective: { model: 'gpt-runtime', providerId: 'openai' },+ });+ });++ it('固定强度运行时模型显式清除旧 effort', () => {+ remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1', { effort: 'high' })]);+ remoteProjectsStore.applyPatch('dev-B', 's1', {+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: '',+ runtimeEffective: {+ agentKind: 'codex',+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: null,+ fastMode: false,+ },+ });++ expect(remoteProjectsStore.getMergedRemoteSessions()[0]).toMatchObject({+ model: 'fixed-strength-model',+ effort: '',+ runtimeEffective: { effort: null },+ });+ });+it('status=deleted 移出分片,archived 保留完整行供归档筛选展示', () => {remoteProjectsStore.setDeviceSessions('dev-B', 'B', [mk('s1'), mk('s2')]);remoteProjectsStore.applyPatch('dev-B', 's1', { status: 'deleted' });diff --git a/apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx b/apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsxnew file mode 100644index 0000000000..1498449a13--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx@@ -0,0 +1,100 @@+import { useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { RefreshCcw } from 'lucide-react';++import { Switch } from '@/components/ui/switch';+import { useSessionRuntimeFallback } from '@/hooks/useSessionRuntimeFallback';+import { createLogger } from '@/lib/logger';+import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';+import { DefaultOverrideControls } from './DefaultOverrideControls';++const log = createLogger('SessionRuntimeFallbackCell');++export function SessionRuntimeFallbackCell() {+ const { t } = useTranslation();+ const { enabled, isCustomized, setEnabled, setIsCustomized } = useSessionRuntimeFallback();+ const [pending, setPending] = useState(false);++ const handleToggle = useCallback(+ async (next: boolean) => {+ const previous = enabled;+ setEnabled(next);+ setPending(true);+ try {+ const settings = await window.electronAPI.maker.sessionRuntimeFallbackSet(next);+ setEnabled(settings.enabled);+ setIsCustomized(settings.isCustomized);+ toast.success(+ t(+ next+ ? 'settings.sessionRuntimeFallback.toast.enabled'+ : 'settings.sessionRuntimeFallback.toast.disabled',+ ),+ );+ } catch (error) {+ log.warn('sessionRuntimeFallbackSet failed', error);+ setEnabled(previous);+ toast.error(+ error instanceof Error+ ? error.message+ : t('settings.sessionRuntimeFallback.toast.toggleFailed'),+ );+ } finally {+ setPending(false);+ }+ },+ [enabled, setEnabled, setIsCustomized, t],+ );++ const handleReset = useCallback(async () => {+ setPending(true);+ try {+ const settings = await window.electronAPI.maker.sessionRuntimeFallbackReset();+ setEnabled(settings.enabled);+ setIsCustomized(settings.isCustomized);+ toast.success(t('settings.defaults.restored'));+ } catch (error) {+ log.warn('sessionRuntimeFallbackReset failed', error);+ toast.error(error instanceof Error ? error.message : t('settings.defaults.restoreFailed'));+ } finally {+ setPending(false);+ }+ }, [setEnabled, setIsCustomized, t]);++ return (+ <div className="flex items-center justify-between gap-3 px-4 py-[14px]">+ <div className="flex items-center gap-3">+ <div+ className={cn(+ 'flex h-9 w-9 shrink-0 items-center justify-center rounded-lg',+ 'bg-[var(--settings-input-bg)]',+ )}+ >+ <RefreshCcw size={18} className="text-[var(--settings-section-title)]" />+ </div>+ <div className="flex flex-col gap-[8px]">+ <p className="text-14 font-medium leading-none text-[var(--settings-section-title)]">+ {t('settings.sessionRuntimeFallback.cell.label')}+ </p>+ <p className="text-12 leading-[1.4] text-[var(--settings-section-desc)]">+ {t('settings.sessionRuntimeFallback.cell.description')}+ </p>+ </div>+ </div>+ <div className="flex items-center gap-2">+ <DefaultOverrideControls+ isCustomized={isCustomized}+ disabled={pending}+ onReset={() => void handleReset()}+ />+ <Switch+ checked={enabled}+ disabled={pending}+ onCheckedChange={(value) => void handleToggle(value)}+ aria-label={t('settings.sessionRuntimeFallback.toggleAria')}+ />+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/TipsSection.tsx b/apps/desktop/src/renderer/components/settings/TipsSection.tsxindex 9882e5f94b..2906db7fbf 100644--- a/apps/desktop/src/renderer/components/settings/TipsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/TipsSection.tsx@@ -6,8 +6,9 @@** 当前 cell:* 1. SilentEncryptedRetryCell — 静默 invalid_encrypted_content 重试- * 2. ChatEmbeddingCell — 启用聊天记录语义索引 (chat-history-embedder)- * 3. MessageNavRailCell — 显示提问导航条 (默认关闭)+ * 2. SessionRuntimeFallbackCell — 任务运行时自动模型 fallback+ * 3. ChatEmbeddingCell — 启用聊天记录语义索引 (chat-history-embedder)+ * 4. MessageNavRailCell — 显示提问导航条 (默认关闭)** 新增 cell 直接加在 container 内, divider 由相邻选择器 `[&>*+*]:border-t` 自动* 应用, 不需要修改任何 cell 组件。@@ -24,6 +25,7 @@ import { usePromptRecommendationPreference } from '@/hooks/usePromptRecommendatiimport { ChatEmbeddingCell } from './ChatEmbeddingCell';import { MessageNavRailCell } from './MessageNavRailCell';+import { SessionRuntimeFallbackCell } from './SessionRuntimeFallbackCell';import { SilentEncryptedRetryCell } from './SilentEncryptedRetryCell';export function TipsSection() {@@ -87,6 +89,7 @@ export function TipsSection() {/></div><SilentEncryptedRetryCell />+ <SessionRuntimeFallbackCell />{mode !== 'local' ? <ChatEmbeddingCell /> : null}<MessageNavRailCell /></div>diff --git a/apps/desktop/src/renderer/hooks/useSessionRuntimeFallback.ts b/apps/desktop/src/renderer/hooks/useSessionRuntimeFallback.tsnew file mode 100644index 0000000000..f08a650770--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useSessionRuntimeFallback.ts@@ -0,0 +1,33 @@+import { useCallback, useEffect, useState } from 'react';++import {+ getSessionRuntimeFallbackEnabled,+ setSessionRuntimeFallbackEnabled,+ subscribeSessionRuntimeFallbackEnabled,+} from '@/lib/sessionRuntimeFallbackStore';++export function useSessionRuntimeFallback() {+ const [enabled, setEnabledState] = useState(getSessionRuntimeFallbackEnabled);+ const [isCustomized, setIsCustomized] = useState(false);+ const setEnabled = useCallback((next: boolean) => setSessionRuntimeFallbackEnabled(next), []);++ useEffect(() => {+ let cancelled = false;+ void window.electronAPI.maker+ .sessionRuntimeFallbackGet()+ .then((settings) => {+ if (cancelled) return;+ setSessionRuntimeFallbackEnabled(settings.enabled);+ setEnabledState(settings.enabled);+ setIsCustomized(Boolean(settings.isCustomized));+ })+ .catch(() => undefined);+ const unsubscribe = subscribeSessionRuntimeFallbackEnabled(setEnabledState);+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);++ return { enabled, isCustomized, setEnabled, setIsCustomized };+}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex dbf426fbb4..b6ea3022e9 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3166,6 +3166,18 @@"toggleFailed": "Failed to switch silent encrypted-content retry"}},+ "sessionRuntimeFallback": {+ "cell": {+ "label": "Automatic task model fallback",+ "description": "After repeated connection or capacity failures, try another connected source for the same model, then a model explicitly recommended for the current agent. It never switches agents or changes your saved selection. Off by default."+ },+ "toggleAria": "Toggle automatic task model fallback",+ "toast": {+ "enabled": "Automatic task model fallback is on.",+ "disabled": "Automatic task model fallback is off.",+ "toggleFailed": "Failed to change automatic task model fallback"+ }+ },"remoteControl": {"title": "Remote Connection","description": "Control your other signed-in devices remotely, or connect to a remote host over SSH.",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 7422342c6d..fd09a0cb95 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3165,6 +3165,18 @@"toggleFailed": "暗号化コンテンツの静かな再試行の切り替えに失敗しました"}},+ "sessionRuntimeFallback": {+ "cell": {+ "label": "タスクモデルの自動フォールバック",+ "description": "接続または容量エラーが続くと、同じモデルの別の接続済みプロバイダー、次に現在の Agent で明示的に推奨されたモデルを試します。Agent や保存済みの選択は変更しません。デフォルトはオフです。"+ },+ "toggleAria": "タスクモデルの自動フォールバックを切り替え",+ "toast": {+ "enabled": "タスクモデルの自動フォールバックをオンにしました。",+ "disabled": "タスクモデルの自動フォールバックをオフにしました。",+ "toggleFailed": "タスクモデルの自動フォールバックの切り替えに失敗しました"+ }+ },"remoteControl": {"title": "リモート接続","description": "同じアカウントのデバイスを相互に遠隔操作したり、SSH でリモートホストに接続したりできます。",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 54cb7b8b17..cb7cdef622 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3165,6 +3165,18 @@"toggleFailed": "암호화 콘텐츠 자동 재시도 전환에 실패했습니다"}},+ "sessionRuntimeFallback": {+ "cell": {+ "label": "작업 모델 자동 대체",+ "description": "연결 또는 용량 오류가 반복되면 같은 모델의 다른 연결된 제공자를 먼저 시도하고, 이어서 현재 Agent에 명시적으로 추천된 모델을 시도합니다. Agent나 저장된 선택은 바꾸지 않습니다. 기본값은 꺼짐입니다."+ },+ "toggleAria": "작업 모델 자동 대체 전환",+ "toast": {+ "enabled": "작업 모델 자동 대체가 켜졌습니다.",+ "disabled": "작업 모델 자동 대체가 꺼졌습니다.",+ "toggleFailed": "작업 모델 자동 대체 전환에 실패했습니다"+ }+ },"remoteControl": {"title": "원격 연결","description": "같은 계정의 기기를 서로 원격으로 제어하거나 SSH로 원격 호스트에 연결합니다.",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 9563bbeb5b..b8a211dfab 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3157,6 +3157,18 @@"toggleFailed": "切换静默加密内容重试失败"}},+ "sessionRuntimeFallback": {+ "cell": {+ "label": "任务模型自动降级",+ "description": "连接或容量故障连续发生时,先切换到同名模型的其他已连接来源,再尝试当前 Agent 明确推荐的模型;不会切换 Agent,也不会改掉你保存的选择。默认关闭。"+ },+ "toggleAria": "切换任务模型自动降级",+ "toast": {+ "enabled": "已开启任务模型自动降级。",+ "disabled": "已关闭任务模型自动降级。",+ "toggleFailed": "切换任务模型自动降级失败"+ }+ },"remoteControl": {"title": "远程连接","description": "在同账号的设备之间互相远程操控,或通过 SSH 连接远端主机。",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 736afb4aae..7cb0a92e32 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3157,6 +3157,18 @@"toggleFailed": "切換靜默加密內容重試失敗"}},+ "sessionRuntimeFallback": {+ "cell": {+ "label": "任務模型自動降級",+ "description": "連線或容量故障連續發生時,先切換到同名模型的其他已連線來源,再嘗試目前 Agent 明確推薦的模型;不會切換 Agent,也不會改掉你儲存的選擇。預設關閉。"+ },+ "toggleAria": "切換任務模型自動降級",+ "toast": {+ "enabled": "已開啟任務模型自動降級。",+ "disabled": "已關閉任務模型自動降級。",+ "toggleFailed": "切換任務模型自動降級失敗"+ }+ },"remoteControl": {"title": "遠端連線","description": "在同帳號的裝置之間互相遠端操控,或透過 SSH 連線遠端主機。",diff --git a/apps/desktop/src/renderer/lib/ccAgent.types.ts b/apps/desktop/src/renderer/lib/ccAgent.types.tsindex 7000e7c6b2..e713bad5a0 100644--- a/apps/desktop/src/renderer/lib/ccAgent.types.ts+++ b/apps/desktop/src/renderer/lib/ccAgent.types.ts@@ -222,6 +222,11 @@ export interface Session {contextTokens: number;contextWindow: number;fastMode: boolean;+ /** Host-only temporary route; absent on older Desktop/device-link peers. */+ runtimeGeneration?: number;+ runtimeBaseline?: SessionRuntimeProfileProjection;+ runtimeEffective?: SessionRuntimeProfileProjection;+ runtimePending?: SessionRuntimePendingProjection | null;/*** 计划模式一级开关(与 permissionMode 正交):开启时 agent 先产出计划、经审批后再执行。* 计划批准后 agent 自动退出并经 plan_mode_changed → sessions:patched 回流为 false。@@ -308,6 +313,20 @@ export interface Session {summary?: string | null;}+export interface SessionRuntimeProfileProjection {+ agentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ providerId: string | null;+ effort: Effort | null;+ fastMode: boolean;+}++export interface SessionRuntimePendingProjection {+ generation: number;+ source: 'agent' | 'fallback';+ profile: SessionRuntimeProfileProjection;+}+// 'error':turn 失败的 terminal error 持久化行(main 的 onTurnErrorEvent 落库)。// 让"你没开着会话时发生的失败"重开会话 / 重启 app 后仍可见 —— 此前 error 只存// 内存(coordinator projection + store.error),事后点进会话毫无痕迹,红点无从追溯。diff --git a/apps/desktop/src/renderer/lib/sessionRuntimeFallbackStore.ts b/apps/desktop/src/renderer/lib/sessionRuntimeFallbackStore.tsnew file mode 100644index 0000000000..f6f5fa8fe6--- /dev/null+++ b/apps/desktop/src/renderer/lib/sessionRuntimeFallbackStore.ts@@ -0,0 +1,33 @@+const STORAGE_KEY = 'sessionRuntimeFallback.enabled';++type Subscriber = (value: boolean) => void;+const subscribers = new Set<Subscriber>();++export function getSessionRuntimeFallbackEnabled(): boolean {+ try {+ return localStorage.getItem(STORAGE_KEY) === 'true';+ } catch {+ return false;+ }+}++export function setSessionRuntimeFallbackEnabled(next: boolean): void {+ try {+ localStorage.setItem(STORAGE_KEY, next ? 'true' : 'false');+ } catch {+ // Main remains authoritative; this mirror only keeps open windows in sync.+ }+ subscribers.forEach((subscriber) => subscriber(next));+}++export function subscribeSessionRuntimeFallbackEnabled(subscriber: Subscriber): () => void {+ subscribers.add(subscriber);+ const onStorage = (event: StorageEvent) => {+ if (event.key === STORAGE_KEY) subscriber(getSessionRuntimeFallbackEnabled());+ };+ window.addEventListener('storage', onStorage);+ return () => {+ subscribers.delete(subscriber);+ window.removeEventListener('storage', onStorage);+ };+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8ff8262b85..fdbcafcc40 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5631,6 +5631,23 @@ interface ElectronAPI {defaultEnabled: boolean;effective: 'immediate';}>;+ sessionRuntimeFallbackGet: () => Promise<{+ enabled: boolean;+ isCustomized?: boolean;+ defaultEnabled?: boolean;+ }>;+ sessionRuntimeFallbackSet: (enabled: boolean) => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;+ sessionRuntimeFallbackReset: () => Promise<{+ enabled: boolean;+ isCustomized: boolean;+ defaultEnabled: boolean;+ effective: 'immediate';+ }>;/** Claude Code 自动上下文压缩触发百分比。仅对新建会话生效 */compactionGetPct: () => Promise<number>;diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex cdf5b3e254..111af62061 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -438,6 +438,85 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.getSessions()[0].agentSwitchIntent).toBeNull();});+ it('applies runtime model projections and preserves them only for legacy snapshots', () => {+ const runtimeBaseline = {+ agentKind: 'codex' as const,+ model: 'gpt-baseline',+ providerId: 'xd',+ effort: 'high',+ fastMode: false,+ };+ const runtimeEffective = {+ agentKind: 'codex' as const,+ model: 'gpt-runtime',+ providerId: 'openai',+ effort: 'xhigh',+ fastMode: true,+ };+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);+ remoteSessionStore.applySessionPatch('dev-1', 's1', {+ model: runtimeEffective.model,+ providerId: runtimeEffective.providerId,+ effort: runtimeEffective.effort,+ fastMode: runtimeEffective.fastMode,+ runtimeGeneration: 3,+ runtimeBaseline,+ runtimeEffective,+ runtimePending: null,+ });++ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', { title: 'Legacy snapshot' }),+ ]);+ expect(remoteSessionStore.getSessions()[0]).toMatchObject({+ title: 'Legacy snapshot',+ runtimeGeneration: 3,+ runtimeBaseline,+ runtimeEffective,+ runtimePending: null,+ });++ const settledBaseline = { ...runtimeBaseline, model: 'gpt-user-selected' };+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [+ session('s1', {+ model: settledBaseline.model,+ runtimeGeneration: 0,+ runtimeBaseline: settledBaseline,+ runtimeEffective: settledBaseline,+ runtimePending: null,+ }),+ ]);+ expect(remoteSessionStore.getSessions()[0]).toMatchObject({+ model: 'gpt-user-selected',+ runtimeGeneration: 0,+ runtimeBaseline: settledBaseline,+ runtimeEffective: settledBaseline,+ runtimePending: null,+ });+ });++ it('clears stale effort for a fixed-strength runtime model', () => {+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { effort: 'high' })]);+ remoteSessionStore.applySessionPatch('dev-1', 's1', {+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: '',+ runtimeEffective: {+ agentKind: 'codex',+ model: 'fixed-strength-model',+ providerId: 'openai',+ effort: null,+ fastMode: false,+ },+ });++ expect(remoteSessionStore.getSessions()[0]).toMatchObject({+ model: 'fixed-strength-model',+ effort: '',+ runtimeEffective: { effort: null },+ });+ });+it('does not let a draft sentinel snapshot replace an optimistic first-message title', () => {remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: '帮我排查登录失败' }),diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.tsindex a8a00e3143..c619dde519 100644--- a/apps/mobile/src/session/remoteSessionStore.ts+++ b/apps/mobile/src/session/remoteSessionStore.ts@@ -1231,18 +1231,26 @@ function applyPendingTitlePreview(session: RemoteSession): RemoteSession {}/**- * SQLite session 快照不包含 desktop main 内存里的 pending Agent intent。全量列表 / getSession- * 对账只能刷新持久化字段,不能顺手抹掉已由 push / 权威查询写入的运行时镜像;显式携带该字段- * 的新快照仍优先(包括 null)。+ * 老 Desktop 的 SQLite session 快照不包含 main 内存里的 pending Agent intent / runtime+ * projection。全量列表 / getSession 对账只能刷新它实际携带的字段,不能顺手抹掉已由 push /+ * 权威查询写入的运行时镜像;新 Desktop 显式携带这些字段时仍优先(包括 null)。*/-function preserveSessionRuntimeFields(fresh: RemoteSession, local: RemoteSession | undefined): RemoteSession {+function preserveSessionRuntimeFields(+ fresh: RemoteSession,+ local: RemoteSession | undefined,+): RemoteSession {if (!local) return fresh;let next = fresh;- if (- !Object.prototype.hasOwnProperty.call(fresh, 'agentSwitchIntent')- && local.agentSwitchIntent !== undefined- ) {- next = { ...next, agentSwitchIntent: local.agentSwitchIntent };+ for (const key of [+ 'agentSwitchIntent',+ 'runtimeGeneration',+ 'runtimeBaseline',+ 'runtimeEffective',+ 'runtimePending',+ ] as const) {+ if (!Object.prototype.hasOwnProperty.call(fresh, key) && local[key] !== undefined) {+ next = { ...next, [key]: local[key] };+ }}return next;}diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.tsindex 4f6ab2dcf5..feff62dd42 100644--- a/apps/mobile/src/session/types.ts+++ b/apps/mobile/src/session/types.ts@@ -33,6 +33,11 @@ export interface RemoteSession {effort: string;permissionMode: string;fastMode: boolean;+ /** Temporary host runtime route; optional for older controlled Desktop versions. */+ runtimeGeneration?: number;+ runtimeBaseline?: RemoteSessionRuntimeProfile;+ runtimeEffective?: RemoteSessionRuntimeProfile;+ runtimePending?: RemoteSessionRuntimePending | null;/** 计划模式一级开关(#494,与 permissionMode 正交)。被控端 sessionToCamel 带出,* 一次性消耗(plan_mode_changed)后经 sessions:patched 回流置 false;老被控端缺省。 */planModeEnabled?: boolean;@@ -83,6 +88,20 @@ export interface RemoteSession {pendingLocalCreation?: boolean;}+export interface RemoteSessionRuntimeProfile {+ agentKind: 'claude-code' | 'codex' | 'pi';+ model: string;+ providerId: string | null;+ effort: string | null;+ fastMode: boolean;+}++export interface RemoteSessionRuntimePending {+ generation: number;+ source: 'agent' | 'fallback';+ profile: RemoteSessionRuntimeProfile;+}+export interface RemoteMessage {id: string;clientId: string;diff --git a/docs/product-rules/README.md b/docs/product-rules/README.mdindex 965ad4a46e..3676903e2f 100644--- a/docs/product-rules/README.md+++ b/docs/product-rules/README.md@@ -19,3 +19,5 @@身份命名与默认值方向、区域相关 UI 标注与对外口径。- [`task-and-conversation-naming.md`](task-and-conversation-naming.md):`session` 的中文叫「任务」,任务 / 对话 / 消息的分层定义与判定规则,以及「任务」与 `task` 的歧义处理。+- [`session-runtime-control.md`](session-runtime-control.md):Agent 调整任务模型、来源、+ 推理强度与 Fast 的统一控制面,baseline/effective/pending 状态和自动降级边界。diff --git a/docs/product-rules/session-runtime-control.md b/docs/product-rules/session-runtime-control.mdnew file mode 100644index 0000000000..97f9202add--- /dev/null+++ b/docs/product-rules/session-runtime-control.md@@ -0,0 +1,49 @@+# 任务运行时控制与自动降级++## 目标++Cindy 允许 Agent 通过统一会话控制面查询和临时调整当前任务或指定任务的模型、来源、+推理强度与 Fast。该能力服务于 Skill 的任务类型路由和故障恢复,不替代用户在界面中保存的+模型偏好。++## 状态模型++每个任务同时维护四类状态:++- `baseline`:用户保存到任务记录的模型、来源、推理强度与 Fast。+- `effective`:当前实际生效的运行时组合;Agent 临时切换和自动降级只改这一层。+- `pending`:任务忙碌时已接受、等待当前 turn 结束的运行时组合。+- `generation`:运行时控制面的单调版本。跨任务修改应先读后写并携带 generation,避免旧请求覆盖新选择。++用户在模型选择器中的完整选择会清除临时运行时组合;用户单独修改推理强度或 Fast 时,+该轴立即成为新基线,同时保留仍在使用的临时模型路由。应用重启后只恢复 baseline。++## Agent 控制面++- `get_session_runtime`:`session_id` 可省略;省略时查询当前任务。返回活动状态、baseline、+ effective、pending、generation 和自动降级开关。+- `set_session_runtime`:`session_id` 可省略;原子提交来源、模型、推理强度与 Fast 的任意子集。+- 当前或目标任务忙碌时不修改进行中的 turn,返回 `deferred`,在下一个 turn 边界生效。+- 不允许借此切换 Harness;跨 Harness 仍走独立的人机切换流程。+- Agent 的修改不写回任务 baseline。语义失败是否提高推理强度或换更强模型,由 Agent 或 Skill 明确请求。++## 自动降级++设置中的“任务模型自动降级”默认关闭。开启后只复用宿主现有的安全自动续跑入口,+即已被白名单识别为连接、超时、过载或容量问题的失败;认证失败、权限拒绝、用户取消、+协议或参数错误不触发。++顺序固定为:++1. 让 Harness 现有的有限重试先处理瞬时故障。+2. 切换到同一模型的其他已连接、未停用来源。+3. 若仍失败,只尝试目录通过 `newSessionDefault` 为当前 Harness 明确声明的模型。++自动降级不采用“可用列表第一个”之类的隐式兜底,不跨 Harness;每个任务最多换路两次,+记录已访问的 `(来源, 模型)`,禁止 `A → B → A` 回环。用户修改运行时选择后立即清空本轮降级轨迹。++## 跨端边界++运行时控制由 Desktop host 独占,MCP、Renderer 与 Device Link 都复用同一原子切换路径。+手机和 SSH 控制端无需新增独立状态机;它们读取任务状态时看到同一 baseline/effective/pending+投影。远程控制的授权边界保持不变。diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.tsindex 4724f36e3d..e6cc500bed 100644--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts@@ -194,6 +194,19 @@ describe("cindy_helper MCP server", () => {gracefulStopState: "none" as const,},})),+ setSessionRuntime: vi.fn(async () => ({+ ok: true as const,+ status: "applied" as const,+ generation: 1,+ effectiveProfile: {+ agentKind: "codex" as const,+ model: "gpt-5.6-sol",+ providerId: "openai",+ effort: "high" as const,+ fastMode: false,+ },+ pendingMutation: null,+ })),},},{@@ -223,6 +236,7 @@ describe("cindy_helper MCP server", () => {"steer_session","stop_session_turn","get_session_runtime",+ "set_session_runtime",]));} finally {await client.close();diff --git a/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.tsindex e61d37c715..ce1be09206 100644--- a/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts+++ b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts@@ -4,6 +4,7 @@ import { XdtHelperToolRegistry, type XdtHelperToolResult } from '../lizi_xdtHelpimport {registerCancelSessionQueuedMessageTool,registerGetSessionRuntimeTool,+ registerSetSessionRuntimeTool,registerSteerSessionTool,registerStopSessionTurnTool,registerUpdateSessionQueuedMessageTool,@@ -54,6 +55,19 @@ function setup(opts?: { sessionId?: string | undefined }) {gracefulStopState: 'waiting-for-safe-point' as const,},})),+ setSessionRuntime: vi.fn(async ({ patch }) => ({+ ok: true as const,+ status: 'applied' as const,+ generation: 2,+ effectiveProfile: {+ agentKind: 'codex' as const,+ model: patch.model ?? 'gpt-5.6-sol',+ providerId: patch.providerId ?? 'openai',+ effort: patch.effort ?? 'high',+ fastMode: patch.fastMode ?? false,+ },+ pendingMutation: null,+ })),};const registry = new XdtHelperToolRegistry();registerUpdateSessionQueuedMessageTool(registry, deps);@@ -61,10 +75,57 @@ function setup(opts?: { sessionId?: string | undefined }) {registerSteerSessionTool(registry, deps);registerStopSessionTurnTool(registry, deps);registerGetSessionRuntimeTool(registry, deps);+ registerSetSessionRuntimeTool(registry, deps);return { deps, registry };}describe('cindy_helper session control tools', () => {+ it('atomically changes the current session runtime with generation CAS', async () => {+ const { deps, registry } = setup();+ const result = parse(+ await registry.call('set_session_runtime', {+ model: 'gpt-5.6-sol',+ effort: 'high',+ fast: true,+ expected_generation: 1,+ }),+ );++ expect(result).toMatchObject({+ ok: true,+ session_id: 'caller-session',+ status: 'applied',+ generation: 2,+ effective_boundary: 'immediate',+ effective: {+ harness: 'codex',+ model: 'gpt-5.6-sol',+ provider_id: 'openai',+ effort: 'high',+ fast: true,+ },+ });+ expect(deps.setSessionRuntime).toHaveBeenCalledWith({+ targetSessionId: 'caller-session',+ expectedGeneration: 1,+ patch: { model: 'gpt-5.6-sol', effort: 'high', fastMode: true },+ });+ });++ it('requires a bound current session when session_id is omitted', async () => {+ const { registry } = setup({ sessionId: undefined });+ expect(+ parse(await registry.call('set_session_runtime', { effort: 'high' })),+ ).toMatchObject({ ok: false, errorCode: 'NO_SESSION_CONTEXT' });+ });++ it('requires a read-before-write generation token', async () => {+ const { registry } = setup();+ expect(+ parse(await registry.call('set_session_runtime', { effort: 'high' })),+ ).toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });+ });+it('updates and cancels only through the caller-bound ownership context', async () => {const { deps, registry } = setup();@@ -156,6 +217,11 @@ describe('cindy_helper session control tools', () => {last_activity_at: '2026-08-16T01:00:05.000Z',current_action_summary: '正在运行工具 Bash',graceful_stop_state: 'waiting-for-safe-point',+ generation: 0,+ baseline: null,+ effective: null,+ pending: null,+ fallback_enabled: false,});});diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 9ad704cefe..16634d1209 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -47,6 +47,7 @@ import {registerSteerSessionTool,registerStopSessionTurnTool,registerGetSessionRuntimeTool,+ registerSetSessionRuntimeTool,registerGetChatHistoryTool,registerSearchChatHistoryTool,registerSubmitGithubIssueTool,@@ -77,7 +78,7 @@ export type {const D_LIST_TOOLS ='探索 cindy_helper 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。' +`传 category=cindy → ${BRAND_NAME} 自省类只读工具(get_capabilities / get_current_session_id);` +- '传 category=control → 会话控制工具(标题/归档、本人排队消息编辑撤回、same-turn 插话、优雅停止、运行探针);' ++ '传 category=control → 会话控制工具(标题/归档、本人排队消息编辑撤回、same-turn 插话、优雅停止、运行探针与模型控制);' +'传 category=history → 只读查询本地数据库聊天历史' +'(list_workdirs / list_sessions / list_session_queue / get_chat_history 按元数据捞, search_chat_history 按内容语义找),' +'用于让用户基于自己的对话历史组织 memory / 知识库;' +@@ -93,7 +94,7 @@ const D_CALL_TOOL ='调用 cindy_helper 中的某个具体工具(如 get_capabilities / get_current_session_id / ' +'set_current_session_title / rename_sessions / send_to_session / list_session_queue / ' +'update_session_queued_message / cancel_session_queued_message / steer_session / ' +- 'stop_session_turn / get_session_runtime / get_chat_history / submit_github_issue)。' ++ 'stop_session_turn / get_session_runtime / set_session_runtime / get_chat_history / submit_github_issue)。' +'先用 list_tools 拿工具名 + 简介。' +'错误码:`UNKNOWN_TOOL` = 工具名不存在;`INVALID_ARGS` = 参数 schema 校验失败(返回 schema 自纠);' +'tool 自身的业务错(如 NO_SESSION_CONTEXT / INVALID_FILTER / HOST_NOT_READY / INTERNAL)' +@@ -339,6 +340,7 @@ export function createXdtHelperMcpServer(registerSteerSessionTool(registry, controlDeps);registerStopSessionTurnTool(registry, controlDeps);registerGetSessionRuntimeTool(registry, controlDeps);+ registerSetSessionRuntimeTool(registry, controlDeps);}// Feedback 类工具: 仅 host 注入了 githubIssue 回调时注册。diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.tsindex b36e08fc8b..1bdd705dc0 100644--- a/packages/lizi-mcps/src/xdt-helper/index.ts+++ b/packages/lizi-mcps/src/xdt-helper/index.ts@@ -112,8 +112,10 @@ export {registerSteerSessionTool,registerStopSessionTurnTool,registerGetSessionRuntimeTool,+ registerSetSessionRuntimeTool,type SessionControlDeps,type SessionQueueControlErrorCode,+ type SessionRuntimeProfile,type SessionRuntimeSnapshot,type SessionSteerErrorCode,type SessionStopErrorCode,diff --git a/packages/lizi-mcps/src/xdt-helper/session_control.ts b/packages/lizi-mcps/src/xdt-helper/session_control.tsindex a89975ba92..35d65ac2d0 100644--- a/packages/lizi-mcps/src/xdt-helper/session_control.ts+++ b/packages/lizi-mcps/src/xdt-helper/session_control.ts@@ -1,4 +1,5 @@import { BRAND_NAME } from '@cindy/maker-shared/branding';+import type { AgentKind, Effort } from '@cindy/maker-core';import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';import { z } from 'zod';@@ -22,7 +23,25 @@ export type SessionSteerErrorCode =export type SessionStopErrorCode = 'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY';-export type SessionRuntimeSnapshot = SessionActivitySnapshot;+export interface SessionRuntimeProfile {+ agentKind: AgentKind;+ model: string;+ providerId: string | null;+ effort: Effort | null;+ fastMode: boolean;+}++export interface SessionRuntimeSnapshot extends SessionActivitySnapshot {+ runtimeGeneration?: number;+ baselineProfile?: SessionRuntimeProfile;+ effectiveProfile?: SessionRuntimeProfile;+ pendingMutation?: {+ generation: number;+ source: 'agent' | 'fallback';+ profile: SessionRuntimeProfile;+ } | null;+ fallbackEnabled?: boolean;+}export interface SessionControlDeps {getSessionContext: () => LiziMcpSessionContext;@@ -57,6 +76,26 @@ export interface SessionControlDeps {getSessionRuntime(params: {targetSessionId: string;}): Promise<ControlResult<{ runtime: SessionRuntimeSnapshot }, 'NOT_FOUND'>>;+ setSessionRuntime(params: {+ targetSessionId: string;+ expectedGeneration?: number;+ patch: {+ model?: string;+ providerId?: string | null;+ effort?: Effort;+ fastMode?: boolean;+ };+ }): Promise<+ ControlResult<+ {+ status: 'applied' | 'deferred';+ generation: number;+ effectiveProfile: SessionRuntimeProfile;+ pendingMutation: SessionRuntimeSnapshot['pendingMutation'];+ },+ 'NOT_FOUND' | 'CONFLICT' | 'INVALID_ARGS' | 'ROUTE_UNAVAILABLE'+ >+ >;}function requireCallerSession(deps: SessionControlDeps): string | null {@@ -211,17 +250,21 @@ export function registerGetSessionRuntimeTool(category: 'control',description:'只读查询本机 session 的统一状态:记录生命周期、运行/等待/正常结束/出错结束、标题工作流语义、' +- '开始时间、最后活动时间、动作摘要和优雅停止状态;' ++ '开始时间、最后活动时间、动作摘要、优雅停止状态,以及运行时模型组合、待生效修改和 generation;' +'不返回提示词正文、工具参数或凭证。',inputShape: {- session_id: z.string().min(1).describe('目标 session id。'),+ session_id: z.string().min(1).optional().describe('目标 session id;省略时查询当前任务。'),},handler: async ({ session_id }) => {- const result = await deps.getSessionRuntime({ targetSessionId: session_id });+ const targetSessionId = session_id ?? requireCallerSession(deps);+ if (!targetSessionId) {+ return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,请显式提供 session_id。');+ }+ const result = await deps.getSessionRuntime({ targetSessionId });if (!result.ok) return mapControlFailure(result);const runtime = result.runtime;return okPayload({- session_id,+ session_id: targetSessionId,phase: runtime.phase,active: runtime.phase === 'running' || runtime.phase === 'needs-interaction',record_status: runtime.recordStatus ?? null,@@ -234,6 +277,103 @@ export function registerGetSessionRuntimeTool(runtime.lastActivityAtMs === null ? null : new Date(runtime.lastActivityAtMs).toISOString(),current_action_summary: runtime.currentActionSummary,graceful_stop_state: runtime.gracefulStopState,+ generation: runtime.runtimeGeneration ?? 0,+ baseline: runtime.baselineProfile ? runtimeProfilePayload(runtime.baselineProfile) : null,+ effective: runtime.effectiveProfile ? runtimeProfilePayload(runtime.effectiveProfile) : null,+ pending: runtime.pendingMutation+ ? {+ generation: runtime.pendingMutation.generation,+ source: runtime.pendingMutation.source,+ profile: runtimeProfilePayload(runtime.pendingMutation.profile),+ }+ : null,+ fallback_enabled: runtime.fallbackEnabled ?? false,+ });+ },+ });+}++const EFFORT_VALUES = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const;++function runtimeProfilePayload(profile: SessionRuntimeProfile) {+ return {+ harness: profile.agentKind,+ model: profile.model,+ provider_id: profile.providerId,+ effort: profile.effort,+ fast: profile.fastMode,+ };+}++export function registerSetSessionRuntimeTool(+ registry: XdtHelperToolRegistry,+ deps: SessionControlDeps,+): void {+ registry.register({+ name: 'set_session_runtime',+ category: 'control',+ description:+ '原子调整当前或指定本机任务的模型来源、模型、推理强度与 Fast。省略 session_id 时作用于当前任务;' ++ '忙碌任务在当前 turn 结束后生效。先用 get_session_runtime 读取 generation,再用 expected_generation 防止覆盖并发修改。' ++ '不切换 harness,不修改用户保存的默认选择。',+ inputShape: {+ session_id: z.string().min(1).optional().describe('目标 session id;省略时使用当前任务。'),+ provider_id: z+ .string()+ .min(1)+ .nullable()+ .optional()+ .describe('来源 id;null 表示恢复该模型的默认来源。'),+ model: z.string().min(1).optional().describe('目标模型 id。'),+ effort: z.enum(EFFORT_VALUES).optional().describe('推理强度。省略表示保持当前值。'),+ fast: z.boolean().optional().describe('是否启用 Fast。'),+ expected_generation: z+ .number()+ .int()+ .nonnegative()+ .optional()+ .describe('来自 get_session_runtime 的 generation。'),+ },+ handler: async ({ session_id, provider_id, model, effort, fast, expected_generation }) => {+ const targetSessionId = session_id ?? requireCallerSession(deps);+ if (!targetSessionId) {+ return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,请显式提供 session_id。');+ }+ if (+ provider_id === undefined &&+ model === undefined &&+ effort === undefined &&+ fast === undefined+ ) {+ return errorPayload('INVALID_ARGS', '至少提供 provider_id、model、effort 或 fast 之一。');+ }+ if (expected_generation === undefined) {+ return errorPayload('INVALID_ARGS', '请先调用 get_session_runtime,并传回 expected_generation。');+ }+ const result = await deps.setSessionRuntime({+ targetSessionId,+ expectedGeneration: expected_generation,+ patch: {+ ...(provider_id !== undefined ? { providerId: provider_id } : {}),+ ...(model !== undefined ? { model } : {}),+ ...(effort !== undefined ? { effort } : {}),+ ...(fast !== undefined ? { fastMode: fast } : {}),+ },+ });+ if (!result.ok) return mapControlFailure(result);+ return okPayload({+ session_id: targetSessionId,+ status: result.status,+ generation: result.generation,+ effective: runtimeProfilePayload(result.effectiveProfile),+ pending: result.pendingMutation+ ? {+ generation: result.pendingMutation.generation,+ source: result.pendingMutation.source,+ profile: runtimeProfilePayload(result.pendingMutation.profile),+ }+ : null,+ effective_boundary: result.status === 'deferred' ? 'next_turn' : 'immediate',});},});diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex c9f6218e49..7e4be94f94 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1827,6 +1827,8 @@ export interface AgentSessionHandle {/** 当前 maker 进程内记录的 Fast mode 状态;不支持的 agent 不实现。 */getFastMode?(): boolean;+ /** 当前 maker 进程内记录的思考强度;固定强度模型可返回 null。 */+ getEffort?(): Effort | null;// ── Rewind ────────────────────────────────────────────────────────────────// Claude 走 SDK message uuid + file checkpoint;Codex 走 app-server thread/rollbackdiff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 7221b94745..77c3ff7b40 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -6311,6 +6311,10 @@ export class ClaudeCodeAgent extends BaseAgent {mutableFastMode = enabled;},+ getEffort() {+ return mutableEffort;+ },+getFastMode() {return mutableFastMode;},diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex b1deb22ded..e9b1cd6c0d 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -12186,6 +12186,10 @@ export class CodexAgent extends BaseAgent {await pushThreadSettings({ effort: clamped });},+ getEffort() {+ return mutableEffort;+ },+async setPermissionMode(newMode: PermissionMode) {if (reviewMode) {log.debug('setPermissionMode ignored for hard read-only Review session', {diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 35122de2cf..262f743843 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -2463,6 +2463,7 @@ export class PiAgent extends BaseAgent {let mutablePiProviderId = initialProvider;let mutableProviderId: string | null | undefined = opts.providerId ?? authProviderId;let activeEffortSnapshot = initialEffortSnapshot;+ let mutableEffort: Effort | null = startupEffort ?? null;let currentAutoReviewIntent = '';const autoReviewDecisionCache = new Map<string, Promise<AutoReviewDecision>>();const setAutoReviewIntent = (content: UserMessage['content']): void => {@@ -5297,6 +5298,11 @@ export class PiAgent extends BaseAgent {level: effortToPiThinkingLevel(effort),}));if (!resp.success) throw new Error(`pi set_thinking_level failed: ${resp.error ?? 'unknown'}`);+ mutableEffort = effort;+ },++ getEffort() {+ return mutableEffort;},async setThinkingEnabled(enabled: boolean): Promise<void> {diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.tsindex 2a9f3246e6..3ddbbc1552 100644--- a/packages/maker-core/src/session.ts+++ b/packages/maker-core/src/session.ts@@ -1480,6 +1480,10 @@ export class Session {return this.handle.getFastMode?.() ?? null;}+ getEffort(): Effort | null {+ return this.handle.getEffort?.() ?? null;+ }+/*** 运行时合并 vendorOptions (浅合并到内部 closure)。* 用于 host 中途切换 session-specific 配置(典型场景:Orca 协同模式 toggle,