Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): 切模后按目标模型收敛思考档位

Zhang Yunjina64660e5e9f9
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 7df1f30ea4..b78826cbbf 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -758,6 +758,39 @@ describe('session runtime control wiring', () => {
);
});
+ it('carries the Pi thinking intent through every staged selection replay', () => {
+ const body = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const early = body.slice(body.indexOf('// A picker click'), body.indexOf('const axisPatch:'));
+ // 点选暂存:intent 必须带上思考意图,否则发送时回放会丢档位。
+ expect(early).toContain('{ thinking: atomicSelection.thinking }');
+ // 发送回放 / deferred 结算另两条重建链也不能丢。
+ expect(registerSource).toContain('{ thinking: intent.thinking }');
+ expect(registerSource).toContain('{ thinking: pending.thinking }');
+ expect(
+ registerSource.split('{ thinking: atomicSelection.thinking }').length,
+ ).toBeGreaterThanOrEqual(3);
+ // 回合中延期(deferLockedSelection)的两条登记都要暂存思考意图:只靠结算侧回放
+ // pending.thinking 不够,登记时不写就恒为 undefined,原症状会在「回合中切模」
+ // 场景原样复现。
+ const defer = body.slice(
+ body.indexOf('const deferLockedSelection = async () =>'),
+ body.indexOf('if (runtimeStatus.remoteHostId && isSessionInTurn(sessionId)) {'),
+ );
+ expect(defer).toContain('acceptSessionRuntimeMutation({');
+ expect(defer).toContain('deferSessionRuntimeAxisMutation({');
+ expect(
+ defer.split('{ thinking: atomicSelection.thinking }').length - 1,
+ ).toBeGreaterThanOrEqual(2);
+ // 非 Pi 引擎绝不能收到 thinkingEnabled(只有 Pi 的 set_model 会消费它)。
+ expect(registerSource).toContain(
+ "runtimeAgentKind === 'pi' && atomicSelection?.thinking !== undefined",
+ );
+ });
+
it('resumes native Codex history across credentials and reserves window rebuilding for send', () => {
const body = handlerBody(
registerSource,
diff --git a/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts b/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts
index 8175a5f8e1..dc941bf496 100644
--- a/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/newMakerDefaultsCache.test.ts
@@ -10,6 +10,7 @@ import {
syncNewMakerDraftCache,
getNewMakerModelTuning,
setProviderModelMemoryCache,
+ setThinkingEnabledInMemory,
type NewMakerDraftSnapshot,
} from '../newMakerDefaultsCache.js';
@@ -134,6 +135,23 @@ describe('getRemoteNewMakerDefaults (device-link 远程草稿镜像)', () => {
expect(getThinkingEnabledFromMemory('pi', null, 'qwen3.8:27b-mxfp8')).toBeUndefined();
});
+ it('writes a single thinking switch into the mirror without dropping other entries', () => {
+ setProviderModelMemoryCache({
+ 'pi:cindy-local-ollama': {
+ effortByModel: { 'qwen3.8:27b-mxfp8': 'high' },
+ fastByModel: { 'qwen3.8:27b-mxfp8': true },
+ thinkingByModel: { 'qwen3.8:27b-mxfp8': false },
+ },
+ 'codex:openai': { effortByModel: {}, fastByModel: {} },
+ });
+
+ // 跨引擎切换提交后主进程局部写入:普通 send 的 lazy-create 只读该镜像。
+ setThinkingEnabledInMemory('pi', 'cindy-local-ollama', 'qwen3.8:27b-mxfp8', true);
+
+ expect(getThinkingEnabledFromMemory('pi', 'cindy-local-ollama', 'qwen3.8:27b-mxfp8')).toBe(true);
+ expect(getThinkingEnabledFromMemory('codex', 'openai', 'gpt-5')).toBeUndefined();
+ });
+
it('providerModelMemory 镜像就绪时随返回(device-link 草稿列表行的真实读源)', () => {
setProviderModelMemoryCache({
'claude-code:anthropic': { effortByModel: { 'claude-opus-4-8': 'low' }, fastByModel: { 'claude-opus-4-8': true } },
diff --git a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
index 40108eb2b6..61e58637ca 100644
--- a/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
+++ b/apps/desktop/src/main/maker-host/newMakerDefaultsCache.ts
@@ -131,6 +131,30 @@ export function setProviderModelMemoryCache(snapshot: ProviderModelMemorySnapsho
providerMemoryCache = snapshot;
}
+/**
+ * 局部写入某 (agent, provider, model) 的思考开关。跨引擎切换提交后由主进程调用:
+ * 普通 send 的 lazy-create 只读镜像(不经过 bootstrap),远端推送尚未回流时也能
+ * 读到用户刚选的值,避免新建会话用旧偏好。
+ */
+export function setThinkingEnabledInMemory(
+ agentKind: 'claude-code' | 'codex' | 'pi',
+ providerId: string | null | undefined,
+ model: string | undefined,
+ enabled: boolean,
+): void {
+ if (!providerId || !model) return;
+ const key = `${agentKind}:${providerId}`;
+ const entry = providerMemoryCache?.[key];
+ providerMemoryCache = {
+ ...(providerMemoryCache ?? {}),
+ [key]: {
+ effortByModel: entry?.effortByModel ?? {},
+ fastByModel: entry?.fastByModel ?? {},
+ thinkingByModel: { ...entry?.thinkingByModel, [model]: enabled },
+ },
+ };
+}
+
export interface WorkerDefaultsFromNewMaker {
model?: string;
effort?: string;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
index e90d54ff95..0e41a75c28 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
@@ -421,6 +421,61 @@ describe('applyRuntimeSetModelChange', () => {
});
});
+ it('forwards the Pi thinking intent to live setModel', async () => {
+ const sessionId = rememberSession('runtime-set-model-thinking-intent');
+ setSessionProvider(sessionId, 'native-a');
+ const setModel = vi.fn(async () => {});
+ const maker: RuntimeSetModelMaker = {
+ getSession: () => ({
+ agentKind: 'pi',
+ remoteHostId: null,
+ model: 'local-model',
+ setModel,
+ }),
+ listActiveSessions: () => [],
+ closeSession: vi.fn(async () => {}),
+ };
+
+ await applyRuntimeSetModelChange({
+ maker,
+ sessionId,
+ model: 'target-model',
+ providerId: 'native-a',
+ thinkingEnabled: false,
+ });
+
+ expect(setModel).toHaveBeenCalledWith('target-model', {
+ providerId: 'native-a',
+ thinkingEnabled: false,
+ });
+ });
+
+ it('omits the thinking intent when the caller has none', async () => {
+ const sessionId = rememberSession('runtime-set-model-no-thinking-intent');
+ setSessionProvider(sessionId, 'native-a');
+ const setModel = vi.fn(async () => {});
+ const maker: RuntimeSetModelMaker = {
+ getSession: () => ({
+ agentKind: 'pi',
+ remoteHostId: null,
+ model: 'local-model',
+ setModel,
+ }),
+ listActiveSessions: () => [],
+ closeSession: vi.fn(async () => {}),
+ };
+
+ await applyRuntimeSetModelChange({
+ maker,
+ sessionId,
+ model: 'target-model',
+ providerId: 'native-a',
+ });
+
+ // 严格匹配:无意图时不得给 runtime 添加 thinkingEnabled 键(保持旧行为)。
+ expect(setModel).toHaveBeenCalledWith('target-model', { providerId: 'native-a' });
+ });
+
it('hot-applies a same-provider Claude model change while the turn is running',
async () => {
// 闸门 fail-open 之后走这条:Opus → Fable / Cindy 同凭证热切,不关会话、不丢 effort。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
index 6c86d1ce66..744824bab5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionAgentSwitchHandler.test.ts
@@ -116,6 +116,41 @@ describe('same-engine selection at send', () => {
expect(h.calls).toEqual([]);
});
+ it('keeps the staged thinking intent when a later edit only changes effort or fast', async () => {
+ const h = selectionHarness();
+ await performSessionAgentSwitch(h.deps, {
+ sessionId: 's1', targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ effort: 'high', fastMode: false, thinking: true,
+ });
+ expect(h.pending.get('s1')?.thinking).toBe(true);
+ // 意图期内改档位(只带 effort)必须继承已暂存的 thinking;否则结算回放会把它丢成 undefined,
+ // Pi 就会保留上一个模型的 off。
+ await performSessionAgentSwitch(h.deps, {
+ sessionId: 's1', targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ effort: 'max', fastMode: false,
+ });
+ expect(h.pending.get('s1')).toMatchObject({ effort: 'max', thinking: true });
+ // 显式改开关时以新值为准,并原样回放到发送结算。
+ await performSessionAgentSwitch(h.deps, {
+ sessionId: 's1', targetAgentKind: 'codex', model: 'gpt-6-astra', providerId: 'openai',
+ effort: 'max', fastMode: false, thinking: false,
+ });
+ expect(h.pending.get('s1')?.thinking).toBe(false);
+ await applyPendingAgentSwitchIfIdle(h.deps, 's1');
+ expect(h.apply).toHaveBeenCalledWith(expect.objectContaining({ thinking: false }));
+ });
+
+ it('does not inherit a staged thinking intent when the target model changes', async () => {
+ const h = selectionHarness();
+ await performSessionAgentSwitch(h.deps, { ...validParams, thinking: false });
+ expect(h.pending.get('s1')?.thinking).toBe(false);
+
+ // 改选到另一个模型:旧模型的开关不适用,不能继承(否则新模型被串成 off)。
+ await performSessionAgentSwitch(h.deps, { ...validParams, model: 'gpt-7-nova' });
+ expect(h.pending.get('s1')?.model).toBe('gpt-7-nova');
+ expect(h.pending.get('s1')?.thinking).toBeUndefined();
+ });
+
it('keeps an internal cross-engine apply that already reached its target as a no-op', async () => {
const h = selectionHarness();
const select = vi.spyOn(h.deps, 'selectSameAgentModel');
@@ -167,6 +202,57 @@ describe('same-engine selection at send', () => {
});
describe('performSessionAgentSwitch', () => {
+ it('stages and forwards the Pi thinking intent across an engine switch', async () => {
+ let row = makeRow();
+ const bootstraps: Array<{ thinkingEnabled?: boolean } | undefined> = [];
+ const remembered: Array<{
+ agentKind: string;
+ providerId: string | null;
+ model: string;
+ thinking: boolean;
+ }> = [];
+ const pendingSwitches = createPendingAgentSwitchRegistry();
+ const { deps } = makeDeps({
+ pendingSwitches,
+ rememberThinkingIntent: (input) => {
+ remembered.push(input);
+ },
+ getSessionRow: async () => ({ ...row }),
+ applyAgentSwitchToDb: async (_id, patch) => {
+ row = {
+ ...row,
+ agentKind: patch.agentKind,
+ model: patch.model,
+ providerId: patch.providerId ?? null,
+ };
+ },
+ bootstrapSwitchedSession: async (_id, opts) => {
+ bootstraps.push(opts);
+ },
+ });
+
+ await performSessionAgentSwitch(deps, {
+ sessionId: 's1',
+ targetAgentKind: 'pi',
+ model: 'deepseek-v4.1-flash',
+ providerId: 'opencode-go',
+ thinking: true,
+ });
+ // 跨引擎 intent 也必须记住思考意图,否则发送重建时只能靠被控端镜像/默认值。
+ expect(deps.pendingSwitches?.get('s1')?.thinking).toBe(true);
+
+ await applyPendingAgentSwitchIfIdle(deps, 's1', { bootstrapAfterSwitch: true });
+ expect(bootstraps.at(-1)).toEqual({ thinkingEnabled: true });
+ // 跨引擎提交后把选择落到本机偏好镜像:普通 send 的 lazy-create 只读镜像,
+ // 不经过 bootstrap,远端推送未回流时会用到旧值。
+ expect(remembered.at(-1)).toEqual({
+ agentKind: 'pi',
+ providerId: 'opencode-go',
+ model: 'deepseek-v4.1-flash',
+ thinking: true,
+ });
+ });
+
it('cycles Claude → Codex → Pi → Claude → Codex and recovers a broken parked thread once', async () => {
let row = makeRow();
const parked = new Map<string, string>();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts
index ff6ddcbf79..d78e856592 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionRuntimeControl.test.ts
@@ -306,6 +306,125 @@ describe('session runtime control state', () => {
expect(isPendingSessionRuntimeRouteExplicit(sessionId, generation)).toBe(true);
});
+ it('keeps the Pi thinking intent when an axis-only patch defers the selection', () => {
+ const sessionId = 'runtime-agent-axis-busy-thinking';
+ acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: current,
+ deferred: false,
+ });
+
+ // 用户明确关掉思考:延期期间必须把这个意图留在 pending 里,否则结算重放时
+ // Pi 收不到 thinkingEnabled,档位就会跨模型漂移(原症状)。
+ const generation = deferSessionRuntimeAxisMutation({
+ sessionId,
+ source: 'agent',
+ effectiveProfile: current,
+ pendingPatch: { effort: 'max' },
+ thinking: false,
+ });
+
+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({
+ generation,
+ pending: {
+ generation,
+ profile: { ...current, effort: 'max' },
+ thinking: false,
+ },
+ });
+ });
+
+ it('preserves an already staged thinking intent when a later axis patch omits it', () => {
+ const sessionId = 'runtime-agent-axis-keeps-thinking';
+ const pending = { ...current, model: 'gpt-next', providerId: 'xd' };
+ acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: current,
+ deferred: true,
+ thinking: true,
+ });
+
+ const generation = deferSessionRuntimeAxisMutation({
+ sessionId,
+ source: 'agent',
+ effectiveProfile: current,
+ pendingPatch: { effort: 'max' },
+ });
+
+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({
+ generation,
+ pending: { generation, thinking: true },
+ });
+ });
+
+ it('inherits a staged thinking intent when a later deferred click cannot resolve one', () => {
+ const sessionId = 'runtime-deferred-inherits-thinking';
+ acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: current,
+ deferred: true,
+ thinking: false,
+ });
+
+ // 同一个目标下的第二次延期点击算不出意图(undefined):继承上一次明确表达,
+ // 不静默清空。
+ const generation = acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: { ...current, effort: 'max' },
+ deferred: true,
+ });
+
+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({
+ generation,
+ pending: { generation, thinking: false },
+ });
+
+ // 明确意图仍然以本次为准(不被继承值反向覆盖)。
+ const replaced = acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: { ...current, model: 'gpt-next-2' },
+ deferred: true,
+ thinking: true,
+ });
+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({
+ generation: replaced,
+ pending: { generation: replaced, thinking: true },
+ });
+ });
+
+ it('does not inherit a staged thinking intent when the deferred target changes', () => {
+ const sessionId = 'runtime-deferred-target-changed-thinking';
+ acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: current,
+ deferred: true,
+ thinking: false,
+ });
+
+ // 换到另一个模型(旧客户端未带思考字段):旧模型的开关不适用,不能继承,
+ // 否则结算回放会把模型 B 的思考关掉。
+ const generation = acceptSessionRuntimeMutation({
+ sessionId,
+ source: 'agent',
+ profile: { ...current, model: 'gpt-next', providerId: 'xd' },
+ deferred: true,
+ });
+
+ expect(getSessionRuntimeControlSnapshot(sessionId)).toMatchObject({
+ generation,
+ pending: { generation },
+ });
+ expect(
+ getSessionRuntimeControlSnapshot(sessionId).pending?.thinking,
+ ).toBeUndefined();
+ });
+
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' };
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 37968902ce..4a2a834b8e 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -497,6 +497,7 @@ import {
type ProviderModelMemorySnapshot,
syncNewMakerDraftCache,
setProviderModelMemoryCache,
+ setThinkingEnabledInMemory,
setWorkerCreationPrefsCache,
} from '../maker-host/newMakerDefaultsCache.js';
import {
@@ -8390,7 +8391,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
setPendingHandoff: (sessionId, handoff, expectedGeneration) =>
agentHandoffPending.set(sessionId, handoff, expectedGeneration),
readPendingHandoffGeneration: (sessionId) => agentHandoffPending.readGeneration(sessionId),
- bootstrapSwitchedSession: async (sessionId) => {
+ rememberThinkingIntent: ({ agentKind, providerId, model, thinking }) => {
+ setThinkingEnabledInMemory(agentKind, providerId, model, thinking);
+ },
+ bootstrapSwitchedSession: async (sessionId, opts) => {
// 切换已提交,从 DB 行(新引擎值)重建 live session。resumeSessionId 直接取
// 行上的 sdk_session_id:切换事务在有停泊绑定时已把它落成停泊 id(Phase 2
// 切回续接),否则为 null = 全新原生会话,上下文由交接注入承接——与
@@ -8413,6 +8417,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fastMode: !!row.fastMode,
permissionMode: (row.permissionMode ?? 'ask') as CreateOpts['permissionMode'],
planMode: false,
+ // 跨引擎意图期内改的思考开关必须显式带入:否则 createSession 只能读被控端
+ // 镜像/默认值,与用户刚选的不一致(device-link 远程场景)。
+ ...(opts?.thinkingEnabled !== undefined
+ ? { thinkingEnabled: opts.thinkingEnabled }
+ : {}),
title: row.title ?? undefined,
resumeSessionId: row.sdkSessionId ?? undefined,
// 远端会话切换引擎后仍是远端:带回 remoteHostId 并走 ensure (SSH
@@ -8445,6 +8454,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const result = await applySessionRuntimeSelection(sessionId, intent.model, intent.providerId, {
effort: (intent.effort ?? null) as SessionRuntimeProfile['effort'],
fastMode: intent.fastMode ?? false,
+ ...(intent.thinking !== undefined ? { thinking: intent.thinking } : {}),
}, { source: 'user', sessionLockHeld: true, applyingUserSelectionOnSend: applyNow,
runtimeSource: intent.runtimeSource, assertSelectionCurrent });
return result;
@@ -11187,6 +11197,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
effort: SessionRuntimeProfile['effort'];
fastMode: boolean;
confirmedContextWindow?: number;
+ /** Pi-only:目标模型的思考开关意图;随暂存选择/换窗重试一并回放。 */
+ thinking?: boolean;
},
options: InternalRuntimeSelectionOptions,
) => Promise<{
@@ -11216,6 +11228,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const settleSelection = {
effort: pending.profile.effort,
fastMode: pending.profile.fastMode,
+ ...(pending.thinking !== undefined ? { thinking: pending.thinking } : {}),
};
const settleOptions = {
source: pending.source,
@@ -15990,6 +16003,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const confirmedContextWindow = (selection as { confirmedContextWindow?: unknown } | undefined)
?.confirmedContextWindow;
const selectionEffort = (selection as { effort?: unknown } | undefined)?.effort;
+ const selectionThinking = (selection as { thinking?: unknown } | undefined)?.thinking;
+ if (selectionThinking !== undefined && typeof selectionThinking !== 'boolean') {
+ // 与 SWITCH_SESSION_AGENT 同口径:非 boolean 的 thinking 当作「未提供」,不让
+ // 历史/异常客户端的多余字段把整次模型切换打成 INVALID_PARAMS。
+ delete (selection as { thinking?: unknown }).thinking;
+ }
if (
selection !== undefined &&
(selection === null ||
@@ -16016,7 +16035,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
);
}
let atomicSelection = selection as
- { effort: SessionRuntimeProfile['effort']; fastMode: boolean } | undefined;
+ { effort: SessionRuntimeProfile['effort']; fastMode: boolean; thinking?: boolean } | undefined;
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
const assertSharedTaskCurrent = captureSharedTaskSettingGuard(sessionId);
const assertRuntimeOwnerCurrent = (): void => {
@@ -16227,9 +16246,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (!axes.ok) {
throwIpcError('INVALID_PARAMS', `Fast is unavailable for model "${model}"`);
}
+ const retainedThinking = atomicSelection.thinking;
atomicSelection = {
effort: axes.effort,
fastMode: axes.fastMode,
+ ...(retainedThinking !== undefined ? { thinking: retainedThinking } : {}),
};
}
// A picker click records intent only. Keep the persisted route and native binding
@@ -16247,6 +16268,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
providerId: effectiveProviderId === undefined ? currentProviderId : effectiveProviderId,
effort: atomicSelection ? atomicSelection.effort ?? undefined : runtimeStatus.effort ?? undefined,
fastMode: atomicSelection?.fastMode ?? runtimeStatus.fastMode,
+ ...(atomicSelection?.thinking !== undefined ? { thinking: atomicSelection.thinking } : {}),
};
agentSwitchPending.set(sessionId, intent);
agentSwitchDeps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));
@@ -16280,6 +16302,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
source: internalOptions.source === 'fallback' ? 'fallback' : 'agent',
previousProfile: internalOptions.previousProfile,
deferred: true,
+ // 回合中延期同样要记住思考意图:结算时 settleSelection 会把它回放给
+ // runtime,否则 Pi 收不到 thinkingEnabled,上一个模型的 off 会原样漂给新
+ // 模型(原症状)。
+ ...(atomicSelection?.thinking !== undefined
+ ? { thinking: atomicSelection.thinking }
+ : {}),
profile: buildDeferredRuntimeSelectionProfile({
agentKind: maker.getSession(sessionId)?.agentKind ?? meta.agentKind,
model,
@@ -16302,6 +16330,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
fastMode: getSessionFastMode(sessionId),
},
pendingPatch: pendingAxisPatch,
+ ...(atomicSelection?.thinking !== undefined
+ ? { thinking: atomicSelection.thinking }
+ : {}),
});
// A later accepted route supersedes an earlier context-only rebuild.
if (routeExplicit && getPendingCredentialSwitchTarget(sessionId)?.forceSessionRebuild) {
@@ -16812,6 +16843,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
}
: {}),
+ // Pi 切模后不重置 thinking level:把 renderer 记录的目标模型思考开关
+ // 意图交给 runtime,由 Pi 按目标模型能力快照收敛(否则上一个模型的
+ // off/旧档位会漂移给新模型)。非 Pi 引擎忽略该参数。
+ ...(runtimeAgentKind === 'pi' && atomicSelection?.thinking !== undefined
+ ? { thinkingEnabled: atomicSelection.thinking }
+ : {}),
forceSessionRebuild:
rebuildLiveOrcaWorker ||
(atomicSelection?.effort === null && runtimeAgentKind !== 'pi'),
@@ -17121,6 +17158,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
source: internalOptions.source,
previousProfile: internalOptions.previousProfile,
deferred: response.deferred,
+ ...(atomicSelection?.thinking !== undefined
+ ? { thinking: atomicSelection.thinking }
+ : {}),
profile: {
agentKind: maker.getSession(sessionId)?.agentKind ?? meta?.agentKind ?? 'claude-code',
model,
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index 30d6a3a05c..105329a932 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -26,7 +26,7 @@ interface RuntimeSetModelSession {
model: string;
setModel: (
model: string,
- opts?: { providerId?: string | null; effort?: Effort },
+ opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean },
) => Promise<void>;
requiresModelSwitchRebuild?: (
model: string,
@@ -58,6 +58,12 @@ export interface ApplyRuntimeSetModelChangeInput {
model: string;
providerId?: string | null;
effort?: Effort;
+ /**
+ * Pi-only:目标模型的思考开关意图(renderer 的 providerModelMemory 记忆,缺省开)。
+ * Pi 的 set_model 不会重置 thinking level,不收敛就会让上一个模型的 off/旧档位
+ * 漂移给新模型(实报:切模后模型把推理写进正文)。非 Pi 引擎忽略。
+ */
+ thinkingEnabled?: boolean;
/**
* Orca Worker 的 live model/provider 属于执行单元身份,不能热切。即使凭证
* 形态相同,也必须沿用 credential-switch 的 idle close / busy defer 边界。
@@ -404,6 +410,7 @@ export async function applyRuntimeSetModelChange(
? { providerId: nextProviderId }
: {}),
...(effort !== undefined ? { effort } : {}),
+ ...(input.thinkingEnabled !== undefined ? { thinkingEnabled: input.thinkingEnabled } : {}),
});
} catch (err) {
if (providerId !== undefined) {
diff --git a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
index 6cf2190d75..e239fee000 100644
--- a/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionAgentSwitchHandler.ts
@@ -195,7 +195,14 @@ export interface MakerSessionAgentSwitchHandlerDeps {
/** 读交接注册表的当前代次(在读历史之前取一次)。 */
readPendingHandoffGeneration?(sessionId: string): number;
/** 从 DB 行(切换已提交后的新值)重建 live session;抛错 = 引擎未就绪。 */
- bootstrapSwitchedSession(sessionId: string): Promise<void>;
+ /** 记录用户对目标模型的思考开关选择(跨引擎切换提交后落本机偏好镜像)。 */
+ rememberThinkingIntent?(input: {
+ agentKind: AgentKind;
+ providerId: string | null;
+ model: string;
+ thinking: boolean;
+ }): void;
+ bootstrapSwitchedSession(sessionId: string, opts?: { thinkingEnabled?: boolean }): Promise<void>;
/**
* close→bootstrap 窗口的 onClose 重副作用抑制(desktop 注入
* withRehydrateCloseSuppressed)——切换的瞬态 close 绝不能触发 worktree
@@ -252,6 +259,12 @@ export interface PendingAgentSwitchIntent {
providerId: string | null | undefined;
effort?: string;
fastMode?: boolean;
+ /**
+ * Pi-only:目标模型的思考开关意图(renderer 记忆,缺省开)。发送时刻回放暂存
+ * 选择时必须一并应用,否则上一模型的 off 会残留——Pi 的 set_model 不重置
+ * thinking level。
+ */
+ thinking?: boolean;
/** resume 回落事务失败后的内部恢复载荷;下一次 send 先重试这笔原子事务。 */
resumeFallbackRecovery?: {
boundaryClientId: string | null;
@@ -344,6 +357,17 @@ export async function applySetModelThenCancelAgentSwitchIntent<T>(
return result;
}
+/** 带思考意图重建?不传时保持单参调用形状(既有调用方/断言都不受影响)。 */
+function bootstrapSwitchedSessionWithThinking(
+ deps: MakerSessionAgentSwitchHandlerDeps,
+ sessionId: string,
+ thinkingEnabled: boolean | undefined,
+): Promise<void> {
+ return thinkingEnabled === undefined
+ ? deps.bootstrapSwitchedSession(sessionId)
+ : deps.bootstrapSwitchedSession(sessionId, { thinkingEnabled });
+}
+
/** 业务体(纯依赖注入,单测直接调):校验 → 交接 → 提交 → 重建。 */
export async function performSessionAgentSwitch(
deps: MakerSessionAgentSwitchHandlerDeps,
@@ -355,6 +379,11 @@ export async function performSessionAgentSwitch(
/** 目标引擎下应生效的 effort / fastMode(renderer 按目标目录与预设解析好带入)。 */
effort?: unknown;
fastMode?: unknown;
+ /**
+ * Pi-only:目标模型的思考开关意图。重登记(意图期内改档位 / 改选 / 切思考
+ * 开关)时必须带上;缺省时由同引擎分支继承既有 intent,不能静默丢字段。
+ */
+ thinking?: unknown;
/**
* pending-apply 路径(send 事务派发前执行):跳过新引擎立即重建——send 随后
* 的 lazy-create 会按 DB 新值 spawn(reconcileCreateOptsWithDb 校正兜底),
@@ -376,6 +405,9 @@ export async function performSessionAgentSwitch(
},
): Promise<SessionAgentSwitchResult> {
const { sessionId, targetAgentKind, model, providerId, signal } = params;
+ // Pi 跨引擎重建时同样要带上思考开关意图:不传就容易落到被控端镜像/默认值,
+ // 与用户在意图期内刚改的开关不一致(device-link 远程场景最明显)。
+ const thinkingEnabled = typeof params.thinking === 'boolean' ? params.thinking : undefined;
throwIfAgentSwitchAborted(signal);
if (typeof sessionId !== 'string' || sessionId.length === 0) {
throwIpcError('INVALID_PARAMS', 'sessionId required');
@@ -436,12 +468,28 @@ export async function performSessionAgentSwitch(
// Only picker calls stage a model choice here. Internal cross-engine apply/recovery
// callers retain the existing same-engine no-op; send consumes staged choices below.
if (deps.selectSameAgentModel && !params.applyNow) {
+ // 重登记可能不带思考意图(旧调用方 / 只改 effort·Fast):仍指向同一个目标时
+ // 继承既有 intent,否则登记时的快照被覆盖成 undefined,结算回放会丢掉思考
+ // 档位收敛;目标已换(改选到别的模型)时不继承——旧模型的开关不适用,
+ // 宁可当未提供,让运行时按目标模型自己的能力处理。
+ const existingIntent = deps.pendingSwitches?.get?.(sessionId);
+ const sameTarget =
+ existingIntent !== undefined &&
+ existingIntent.model === model &&
+ (existingIntent.providerId ?? null) === (normalizedProviderId ?? null);
+ const thinking =
+ typeof params.thinking === 'boolean'
+ ? params.thinking
+ : sameTarget
+ ? existingIntent?.thinking
+ : undefined;
const result = await deps.selectSameAgentModel(sessionId, {
targetAgentKind,
model,
providerId: normalizedProviderId,
...(typeof params.effort === 'string' ? { effort: params.effort } : {}),
...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),
+ ...(typeof thinking === 'boolean' ? { thinking } : {}),
sameAgentSelection: true,
...(params.runtimeSource ? { runtimeSource: params.runtimeSource } : {}),
}, false, params.assertSelectionCurrent);
@@ -501,6 +549,7 @@ export async function performSessionAgentSwitch(
providerId: normalizedProviderId,
...(typeof params.effort === 'string' && params.effort ? { effort: params.effort } : {}),
...(typeof params.fastMode === 'boolean' ? { fastMode: params.fastMode } : {}),
+ ...(typeof params.thinking === 'boolean' ? { thinking: params.thinking } : {}),
};
deps.pendingSwitches.set(sessionId, intent);
deps.onPendingSwitchChanged?.(sessionId, projectPendingAgentSwitchIntent(intent));
@@ -583,6 +632,16 @@ export async function performSessionAgentSwitch(
if (normalizedProviderId !== undefined) {
deps.setSessionProvider(sessionId, normalizedProviderId);
}
+ if (typeof thinkingEnabled === 'boolean') {
+ // 跨引擎切换提交后把用户的思考选择落到本机偏好镜像:普通 send 的 lazy-create
+ // 只读镜像(不经过 bootstrap),否则远端推送未回流时会用旧值建会话。
+ deps.rememberThinkingIntent?.({
+ agentKind: targetAgentKind,
+ providerId: normalizedProviderId ?? row.providerId ?? null,
+ model,
+ thinking: thinkingEnabled,
+ });
+ }
const boundaryContent: AgentSwitchBoundaryContent = {
fromAgentKind: fromDbKind,
@@ -617,7 +676,7 @@ export async function performSessionAgentSwitch(
// 每次发送反复失败且无人回落。
if (parked || !params.skipBootstrap) {
try {
- await deps.bootstrapSwitchedSession(sessionId);
+ await bootstrapSwitchedSessionWithThinking(deps, sessionId, thinkingEnabled);
} catch (err) {
if (parked) {
// ---- resume 回落:清停泊 id → 换全量交接 → 全新原生会话重试 ----
@@ -699,7 +758,7 @@ export async function performSessionAgentSwitch(
deps.setPendingHandoff(sessionId, fullHandoff, handoffGeneration);
if (fallbackCommitted) {
try {
- await deps.bootstrapSwitchedSession(sessionId);
+ await bootstrapSwitchedSessionWithThinking(deps, sessionId, thinkingEnabled);
} catch (err2) {
engineReady = false;
deps.log.warn('agent-switch: fresh bootstrap after resume fallback failed', {
@@ -783,7 +842,7 @@ export function applyPendingAgentSwitchIfIdle(
}
throwIfAgentSwitchAborted(opts?.signal);
if (opts?.bootstrapAfterSwitch && !deps.getLiveSession(sessionId)) {
- await deps.bootstrapSwitchedSession(sessionId);
+ await bootstrapSwitchedSessionWithThinking(deps, sessionId, intent.thinking);
}
return;
}
@@ -818,6 +877,7 @@ export function applyPendingAgentSwitchIfIdle(
providerId: intent.providerId,
effort: intent.effort,
fastMode: intent.fastMode,
+ thinking: intent.thinking,
// 普通 maker send 随后会按 DB 真源 lazy-create,无需在 apply 内多 spawn 一次;
// Goal / IM / scheduler 三条直发路径没有该 lazy-create 事务,必须先把新引擎
// bootstrap 好再拿 live session 发送,否则会继续持有已关闭的旧 session。
@@ -870,6 +930,7 @@ export function registerMakerSessionAgentSwitchHandler(
providerId: unknown,
effort: unknown,
fastMode: unknown,
+ thinking: unknown,
) => {
const context = getDeviceLinkInvokeContext();
const guard = createSharedTaskSettingGuard(context?.sharedTask, String(sessionId), context?.sharedTaskSetting ?? { admitted: false });
@@ -880,6 +941,7 @@ export function registerMakerSessionAgentSwitchHandler(
providerId,
effort,
fastMode,
+ thinking,
assertSelectionCurrent: guard.admit,
});
return typeof sessionId === 'string' && sessionId && deps.withSessionLock
diff --git a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
index f0cdb0af56..86a1189b20 100644
--- a/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionRuntimeControl.ts
@@ -21,6 +21,11 @@ export interface PendingSessionRuntimeMutation {
generation: number;
source: SessionRuntimeMutationSource;
profile: SessionRuntimeProfile;
+ /**
+ * Pi-only:该选择的思考开关意图(renderer 记忆,缺省开)。settle 重放时随
+ * selection 一并应用;不落 DB(会随 runtimePending 投影带出,renderer 不消费)。
+ */
+ thinking?: boolean;
}
export interface SessionRuntimeControlSnapshot {
@@ -222,6 +227,8 @@ export function deferSessionRuntimeAxisMutation(params: {
source: SessionRuntimeMutationSource;
effectiveProfile: SessionRuntimeProfile;
pendingPatch: SessionRuntimeAxisPatch;
+ /** Pi-only:延期期间也要记住目标模型的思考开关意图(结算重放时用)。 */
+ thinking?: boolean;
}): number {
const state = stateFor(params.sessionId);
const hadPendingMutation = state.pending !== null;
@@ -231,11 +238,13 @@ export function deferSessionRuntimeAxisMutation(params: {
...state.pending,
generation: state.generation,
profile: { ...state.pending.profile, ...params.pendingPatch },
+ ...(params.thinking !== undefined ? { thinking: params.thinking } : {}),
}
: {
generation: state.generation,
source: params.source,
profile: { ...params.effectiveProfile, ...params.pendingPatch },
+ ...(params.thinking !== undefined ? { thinking: params.thinking } : {}),
};
if (!hadPendingMutation) state.pendingRouteExplicit = false;
if (params.source === 'agent') {
@@ -273,13 +282,27 @@ export function acceptSessionRuntimeMutation(params: {
profile: SessionRuntimeProfile;
previousProfile?: SessionRuntimeProfile;
deferred: boolean;
+ thinking?: boolean;
}): number {
const state = stateFor(params.sessionId);
+ const previousPending = state.pending;
state.generation += 1;
+ // 延期替换时若本次没算出意图(undefined),且仍指向**同一个目标**(model 与
+ // provider 都相同),继承上一份 pending:一次「无法判定」的点击不该把用户刚
+ // 表达过的思考开关悄悄清掉。换到别的模型时不继承——旧模型的开关不适用,
+ // 否则 A 的 off 会串给 B;false / true 是明确意图,永远以本次为准。
+ const samePendingTarget =
+ previousPending != null &&
+ previousPending.profile.model === params.profile.model &&
+ (previousPending.profile.providerId ?? null) === (params.profile.providerId ?? null);
+ const acceptedThinking =
+ params.thinking ??
+ (params.deferred && samePendingTarget ? previousPending?.thinking : undefined);
const accepted: PendingSessionRuntimeMutation = {
generation: state.generation,
source: params.source,
profile: params.profile,
+ ...(acceptedThinking !== undefined ? { thinking: acceptedThinking } : {}),
};
state.pending = params.deferred ? accepted : null;
state.pendingRouteExplicit = true;
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index cf9dc71701..c030c7adc6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6596,14 +6596,16 @@ contextBridge.exposeInMainWorld('electronAPI', {
// providerId 可选 —— 选了某供应商的模型时一并传,决定本会话路由到哪个上游/钥匙。
// 不传 = 不改动该会话的供应商选择(老调用兼容);传 null = 清除选择回落默认路由。
// 返回 { deferred } —— deferred=true 表示会话自己在跑 turn,凭证切换已登记为
- // pending、turn 结束自动生效(renderer 据此提示"任务结束后生效")。旧被控端 /
+ // pending、turn 结束自动生效(renderer 据此提示“任务结束后生效”)。旧被控端 /
// 老 host 可能返回 undefined,调用方按非 deferred 处理。
+ // selection.thinking(Pi-only) = 目标模型的思考开关意图,Pi 用它收敛切模后的
+ // thinking level;其它引擎忽略。
setModel: (
sessionId: string,
model: string,
providerId?: string | null,
expectedAgentSwitchRevision?: number,
- selection?: { effort: string | null; fastMode: boolean },
+ selection?: { effort: string | null; fastMode: boolean; thinking?: boolean },
): Promise<{ deferred: boolean; superseded?: boolean } | undefined> =>
ipcRenderer.invoke(
'maker:set-model',
@@ -6626,6 +6628,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
providerId?: string | null,
effort?: string,
fastMode?: boolean,
+ thinking?: boolean,
): Promise<{
switched: boolean;
agentKind: 'claude-code' | 'codex' | 'pi';
@@ -6643,6 +6646,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
providerId,
effort,
fastMode,
+ thinking,
),
// 读 main 权威的 pending 切换意图(内存态,不落库)。重开视图 / 远程会话重连后
// 用它恢复乐观显示——否则用户登记的意图在 UI 上凭空消失,下一条消息却按意图切换。
diff --git a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
index 9d04dc7048..5c107ec696 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputModelSelectorRouting.test.ts
@@ -67,6 +67,55 @@ describe('ChatInput model source switching wiring', () => {
expect(modelChange).toMatch(/maker\.setModel\(\s*sessionId,\s*newModelId,\s*undefined,/);
});
+ it('snapshots the target model thinking intent into the atomic selection', () => {
+ const modelStart = chatInputSource.indexOf('const performModelChange = useCallback(');
+ const providerStart = chatInputSource.indexOf('const performProviderChange = useCallback(');
+ const handleStart = chatInputSource.indexOf(
+ 'const handleProviderChange = useCallback(',
+ providerStart,
+ );
+ const modelChange = chatInputSource.slice(modelStart, providerStart);
+ const providerChange = chatInputSource.slice(providerStart, handleStart);
+
+ // 意图计算统一走 resolveModelThinkingIntent:缺记忆按 UI 默认开,来源/引擎未知时不猜。
+ expect(chatInputSource).toMatch(
+ /function resolveModelThinkingIntent\([\s\S]*?getThinking[\s\S]*?\?\?\s*true[\s\S]*?\n\}/,
+ );
+ // 换模型:本地 + 远程两条原子选择都带上;缺意图时不传(Pi 侧保持现状)。
+ expect(modelChange).toMatch(/const nextThinking = resolveModelThinkingIntent\(\{/);
+ expect(modelChange.match(/thinking: nextThinking/g)).toHaveLength(2);
+ // 失败回滚同样要带(与换来源分支对称):否则回滚那次不下发档位,Pi 会停在
+ // 失败那次收敛后的档位上。
+ expect(modelChange).toMatch(/const rollbackThinking = resolveModelThinkingIntent\(\{/);
+ expect(modelChange.match(/thinking: rollbackThinking/g)).toHaveLength(1);
+ // 换来源(含失败回滚)同样要带,否则切到 Pi 新路由时旧档位会残留。
+ expect(
+ providerChange.match(/const targetThinking = resolveModelThinkingIntent\(\{/g),
+ ).toHaveLength(2);
+ expect(providerChange).toMatch(/const rollbackThinking = resolveModelThinkingIntent\(\{/);
+ expect(providerChange.match(/thinking: targetThinking/g)).toHaveLength(2);
+ expect(providerChange.match(/thinking: rollbackThinking/g)).toHaveLength(1);
+ });
+
+ it('replays the thinking intent through agent-switch staging and thinking toggles', () => {
+ const agentSwitchStart = chatInputSource.indexOf('const performAgentSwitch = useCallback(');
+ const agentSwitchEnd = chatInputSource.indexOf(
+ 'const handleUnifiedDraftSelect = useCallback(',
+ agentSwitchStart,
+ );
+ const agentSwitch = chatInputSource.slice(agentSwitchStart, agentSwitchEnd);
+ // switchSessionAgent 的第 7 参必须带上目标 (引擎,来源,模型) 的思考意图。
+ expect(agentSwitch).toMatch(/const targetThinking =[\s\S]*?getThinking/);
+ expect(agentSwitch).toMatch(/switchSessionAgent\([\s\S]*?targetThinking,\s*\);/);
+
+ const toggleStart = chatInputSource.indexOf('onThinkingChange={async (enabled) => {');
+ const toggleEnd = chatInputSource.indexOf('modelMemory={modelMemory}', toggleStart);
+ const toggle = chatInputSource.slice(toggleStart, toggleEnd);
+ // 意图期内切开关必须写回 staged 意图(否则发送结算按旧快照把思考又打开)。
+ expect(toggle).toContain('getAgentSwitchIntent(sessionId)');
+ expect(toggle).toContain('thinking: enabled');
+ });
+
it('keeps exact-window confirmation local and removes it from device-link calls', () => {
const guardStart = chatInputSource.indexOf(
'const confirmModelSwitchContextGuard = useCallback(',
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 99bb71fa84..f70fc78209 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -1075,6 +1075,28 @@ function deriveSyntheticAtQuery(editor: Editor, anchor: number, rangeEnd: number
return text;
}
+/**
+ * Pi 切模/切来源时随 selection 携带的目标模型思考开关意图。
+ *
+ * 与思考开关展示同一口径:记忆缺失按 UI 默认(开)处理;引擎/来源/模型未知时
+ * 返回 undefined(不猜、不改 Pi 现状)。Pi 的 set_model 不重置 thinking level,
+ * 不带上这个意图就会让上一个模型的 off/旧档位漂移到新模型。
+ */
+function resolveModelThinkingIntent(input: {
+ kind: Parameters<typeof getProviderModelThinking>[0] | null | undefined;
+ providerId: string | null | undefined;
+ modelId: string | null | undefined;
+ memory: ModelMemoryAccessors | undefined;
+ deviceLinkDeviceId: string | null | undefined;
+}): boolean | undefined {
+ const { kind, providerId, modelId, memory, deviceLinkDeviceId } = input;
+ if (!kind || !providerId || !modelId) return undefined;
+ const remembered =
+ memory?.getThinking?.(kind, providerId, modelId) ??
+ (!deviceLinkDeviceId ? getProviderModelThinking(kind, providerId, modelId) : undefined);
+ return remembered ?? true;
+}
+
export function ChatInput({
onSend,
sessionId,
@@ -6506,10 +6528,11 @@ export function ChatInput({
targetAgentKind: 'claude-code' | 'codex' | 'pi',
newModelId: string,
providerId: string | null = null,
- // 意图期内的档位/Fast 改动经此显式覆盖(用户手选优先于记忆/默认解析)。
+ // 意图期内的档位/Fast/思考开关改动经此显式覆盖(用户手选优先于记忆/默认解析)。
overrides?: {
effort?: Effort;
fastMode?: boolean;
+ thinking?: boolean;
},
): Promise<boolean> => {
// ★ 返回值 = **本端请求的完整配置真的落到会话上了没有**(2026-08-17 review 确立
@@ -6578,6 +6601,14 @@ export function ChatInput({
!!providerId &&
!!modelMemory &&
(modelMemory.getFast(targetAgentKind, providerId, newModelId) ?? false);
+ // Pi 的思考开关意图:显式 override 优先,否则按目标 (引擎,来源,模型) 记忆,
+ // 缺记忆按 UI 默认开;没有来源/记忆时不猜(不传该参)。
+ const targetThinking =
+ overrides?.thinking !== undefined
+ ? overrides.thinking
+ : providerId && modelMemory
+ ? (modelMemory.getThinking?.(targetAgentKind, providerId, newModelId) ?? true)
+ : undefined;
// 会话级操作按来源路由:device-link 远程会话隧道到被控端(意图注册表与引擎
// 交接都在那边),本机会话零变化直连本机 maker。
@@ -6595,6 +6626,7 @@ export function ChatInput({
providerId,
newEffort,
targetFast,
+ targetThinking,
);
// device-link 往返期间可以切到另一个任务:同一路由下 ChatInput 会带着新
// sessionId 继续渲染,sameEngineReselectRef 等闭包也已指向新会话。旧会话的
@@ -7118,6 +7150,17 @@ export function ChatInput({
fastSupported: modelFastSupported(newModelId, effectiveSourceId),
requestedFast: restoredFast,
});
+ // Pi 切模后不重置 thinking level:把目标模型(同来源)的思考开关意图一起放进
+ // 选择快照,让被控端/本机 runtime 在切换成功后收敛档位,避免上一个模型的 off
+ // 残留到新模型(模型只能把推理写进正文)。缺记忆时按 UI 默认(开)处理;
+ // 来源/引擎未知时不猜(不传该字段)。旧被控端会忽略这个额外字段。
+ const nextThinking = resolveModelThinkingIntent({
+ kind: currentModelAgentKind,
+ providerId: effectiveSourceId,
+ modelId: newModelId,
+ memory: modelMemory,
+ deviceLinkDeviceId,
+ });
try {
if (sessionId) {
// 切模型时 fast 恢复该 (供应商, 模型) 的记忆值(对齐 effort);模型不支持 → false。
@@ -7151,7 +7194,8 @@ export function ChatInput({
? ({
effort: atomicEffort,
fastMode: atomicFast,
- } as { effort: string | null; fastMode: boolean })
+ ...(nextThinking !== undefined ? { thinking: nextThinking } : {}),
+ } as { effort: string | null; fastMode: boolean; thinking?: boolean })
: undefined,
);
if (remoteSetModelResult?.superseded) {
@@ -7212,8 +7256,14 @@ export function ChatInput({
{
effort: atomicEffort,
fastMode: atomicFast,
+ ...(nextThinking !== undefined ? { thinking: nextThinking } : {}),
...(confirmedContextWindow ? { confirmedContextWindow } : {}),
- } as { effort: string | null; fastMode: boolean },
+ } as {
+ effort: string | null;
+ fastMode: boolean;
+ thinking?: boolean;
+ confirmedContextWindow?: number;
+ },
);
},
);
@@ -7283,10 +7333,20 @@ export function ChatInput({
localRuntimeSwitchSeqBySessionRef.current.get(sessionId) &&
!getSessionDeviceId(sessionId)
) {
+ // 失败回滚同样要带旧模型的思考意图:否则回滚这次不下发档位,Pi 会停在
+ // 失败那次收敛后的档位(可能是 off),与 UI 显示的旧模型选择不一致。
+ const rollbackThinking = resolveModelThinkingIntent({
+ kind: currentModelAgentKind,
+ providerId: effectiveSourceId,
+ modelId: rollbackModelAfterPersistFailure.model,
+ memory: modelMemory,
+ deviceLinkDeviceId,
+ });
await window.electronAPI.maker
.setModel(sessionId, rollbackModelAfterPersistFailure.model, undefined, undefined, {
effort: activeEffort,
fastMode,
+ ...(rollbackThinking !== undefined ? { thinking: rollbackThinking } : {}),
})
.catch((rollbackErr) => {
log.warn('model change rollback failed:', rollbackErr);
@@ -7699,6 +7759,13 @@ export function ChatInput({
? reconciledFast
: resolveFast(targetModel, newProviderId),
});
+ const targetThinking = resolveModelThinkingIntent({
+ kind: currentModelAgentKind,
+ providerId: newProviderId,
+ modelId: targetModel,
+ memory: modelMemory,
+ deviceLinkDeviceId,
+ });
// 乐观显示目标 (model, effort, provider) + 置灰 selector,等被控端 echo 回流;失败回滚 provider/快照。
setPendingRemoteSwitch({
model: targetModel,
@@ -7723,7 +7790,8 @@ export function ChatInput({
? ({
effort: remoteAtomicEffort,
fastMode: restoredFast,
- } as { effort: string | null; fastMode: boolean })
+ ...(targetThinking !== undefined ? { thinking: targetThinking } : {}),
+ } as { effort: string | null; fastMode: boolean; thinking?: boolean })
: undefined,
);
if (remoteSetModelResult?.superseded) {
@@ -7794,6 +7862,13 @@ export function ChatInput({
fastSupported: modelFastSupported(modelId, newProviderId),
requestedFast,
});
+ const targetThinking = resolveModelThinkingIntent({
+ kind: currentModelAgentKind,
+ providerId: newProviderId,
+ modelId,
+ memory: modelMemory,
+ deviceLinkDeviceId,
+ });
const switchSeqBySession = localRuntimeSwitchSeqBySessionRef.current;
const rollbackSeq = (switchSeqBySession.get(sessionId) ?? 0) + 1;
switchSeqBySession.set(sessionId, rollbackSeq);
@@ -7820,8 +7895,14 @@ export function ChatInput({
{
effort: atomicEffort,
fastMode: restoredFast,
+ ...(targetThinking !== undefined ? { thinking: targetThinking } : {}),
...(confirmedContextWindow ? { confirmedContextWindow } : {}),
- } as { effort: string | null; fastMode: boolean },
+ } as {
+ effort: string | null;
+ fastMode: boolean;
+ thinking?: boolean;
+ confirmedContextWindow?: number;
+ },
);
},
);
@@ -7912,10 +7993,18 @@ export function ChatInput({
rollbackProvider.seq === localRuntimeSwitchSeqBySessionRef.current.get(sessionId) &&
!isRemoteSession
) {
+ const rollbackThinking = resolveModelThinkingIntent({
+ kind: currentModelAgentKind,
+ providerId: rollbackProvider.providerId,
+ modelId: rollbackProvider.model,
+ memory: modelMemory,
+ deviceLinkDeviceId,
+ });
await window.electronAPI.maker
.setModel(sessionId, rollbackProvider.model, rollbackProvider.providerId, undefined, {
effort: activeEffort,
fastMode,
+ ...(rollbackThinking !== undefined ? { thinking: rollbackThinking } : {}),
})
.catch((rollbackErr) => {
log.warn('provider change rollback failed:', rollbackErr);
@@ -8831,6 +8920,18 @@ export function ChatInput({
);
}
}
+ // 意图期内(点选尚未发送)必须把开关写回 staged 意图:否则结算回放
+ // 会按登记时的旧快照下发档位,把用户刚关掉的思考又打开(或反之)。
+ if (sessionId && currentModelAgentKind) {
+ const intent = makerChatStore.getAgentSwitchIntent(sessionId);
+ if (intent) {
+ await performAgentSwitch(intent.target, intent.model, intent.providerId, {
+ ...(intent.effort ? { effort: intent.effort as Effort } : {}),
+ fastMode: intent.fastMode,
+ thinking: enabled,
+ });
+ }
+ }
if (sessionId) {
const api = deviceLinkDeviceId
? makerApiForDevice(deviceLinkDeviceId)
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 8b2cb15d4e..c803286173 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -6037,7 +6037,7 @@ interface ElectronAPI {
model: string,
providerId?: string | null,
expectedAgentSwitchRevision?: number,
- selection?: { effort: string | null; fastMode: boolean },
+ selection?: { effort: string | null; fastMode: boolean; thinking?: boolean },
) => Promise<{ deferred: boolean; superseded?: boolean } | undefined>;
/**
* session-agent-switch:同一会话切换 agent 引擎(claude-code ↔ codex)。
@@ -6053,6 +6053,7 @@ interface ElectronAPI {
providerId?: string | null,
effort?: string,
fastMode?: boolean,
+ thinking?: boolean,
) => Promise<{
switched: boolean;
agentKind: 'claude-code' | 'codex' | 'pi';
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 78791f5a73..aef3740ba8 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -77,7 +77,18 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
Cindy 显式设置:models.json、`settings.json` 的 `transport:sse` 与 `retry.maxRetries=6`
(`retry.provider.maxRetries` 保持 0)、`--append-system-prompt`、`--session-dir`、启动时 RPC
-`set_auto_compaction{enabled:true}` / `set_thinking_level`。Pi 原生负责 threshold 与 overflow 压缩;
+`set_auto_compaction{enabled:true}` / `set_thinking_level`。切换模型成功后按目标模型的思考意图
+再下发一次 `set_thinking_level`(Pi 的 `set_model` 不重置 level;不收敛会让上一个模型的 off/旧档位
+漂移给新模型——实测推理模型在 off 下把思考写进正文)。思考意图由 renderer 的原子 selection 携带
+(主进程只对 Pi 转成 `thinkingEnabled`,点选暂存与 deferred 重放一并回放);目标档位不在启动快照内时
+按默认档/首档回落(同 `reconcilePiStartupEffort` 口径),目标声明不支持思考时明确 `off`,能力未知
+则不动。实现见 `packages/maker-core/src/agents/pi/index.ts` 的 `switchModel` 末尾,
+回归见 `pi-provider-routing.test.ts` 的 thinking-level 用例。跨引擎切换提交时还会把这次选择写进
+本机偏好镜像(普通 send 走 lazy-create 只读镜像、不经过 bootstrap),避免远端推送未回流时新建会话
+用旧值。已知未覆盖面:Bot 设置保存、
+agent/scheduler/IM 回滚等**旁路入口**热切 Pi 模型时没有 thinking 载体(`SessionRuntimeProfile`
+不含该字段),这些路径仍可能保留旧档位;需要补载体或按目标快照收敛后才能彻底消除。
+Pi 原生负责 threshold 与 overflow 压缩;
Cindy 消费 compaction 事件做 UI、usage、digest 投影,并只在本机原生自动压缩确定性失败后锁存
下一次发送前换窗。设置页的 Pi 百分比默认 90%(已有显式 override 保留),在每次启动或恢复
Pi 任务时冻结,并写入该任务 `settings.json` 的 `compaction.reserveTokens`
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index f4caa86fa8..3da071c8cd 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -2271,8 +2271,8 @@ export interface AgentSessionHandle {
/** Host tool approval uses the same live intent/model/scope as native tool approval. */
reviewAutoPermissionAction?(action: ReviewableAction): Promise<AutoReviewDecision>;
- /** 运行时切换模型 —— 不支持时抛 NotSupportedError */
- setModel?(model: string, opts?: { providerId?: string | null; effort?: Effort }): Promise<void>;
+ /** 运行时切换模型 —— 不支持时抛 NotSupportedError。thinkingEnabled = 目标模型的思考开关意图(Pi 用它收敛切模后的 thinking level)。 */
+ setModel?(model: string, opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void>;
/**
* 当前 provider handle 是否必须先关闭、再由同一业务任务 cold resume 才能应用目标模型。
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index 871af071c9..6850b1ac8e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -3582,6 +3582,623 @@ describe("Pi provider-aware model routing", () => {
await handle.close();
});
+ it("re-applies the retained thinking level to the target model after a model switch", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ { id: "model-b", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-level-after-switch",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true });
+
+ // Pi 的 set_model 不重置 thinking level:必须在切换完成后按保留档位重下发,
+ // 否则上一个模型的 off/旧档位会漂移给新模型。
+ const switched = captured.requests.slice(beforeSwitch);
+ const setModelIndex = switched.findIndex(
+ (request) => request.type === "set_model" && request.modelId === "model-b",
+ );
+ const levelIndex = switched.findIndex(
+ (request) => request.type === "set_thinking_level",
+ );
+ expect(setModelIndex).toBeGreaterThanOrEqual(0);
+ expect(levelIndex).toBeGreaterThan(setModelIndex);
+ expect(switched[levelIndex]).toEqual({ type: "set_thinking_level", level: "high" });
+ await handle.close();
+ });
+
+ it("turns thinking off after a model switch when the caller reports thinking is off", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ { id: "model-b", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-off-after-switch",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: false });
+
+ const switched = captured.requests.slice(beforeSwitch);
+ expect(switched).toContainEqual({ type: "set_thinking_level", level: "off" });
+ await handle.close();
+ });
+
+ it("turns thinking off when the target model has no thinking levels at all", async () => {
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "model-a",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: null, high: null, xhigh: null, max: null },
+ },
+ { id: "model-b" },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: [], defaultEffort: null },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-off-non-reasoning-target",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "low",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", {
+ providerId: "native-a",
+ effort: "low",
+ thinkingEnabled: true,
+ });
+
+ // 目标模型声明为不支持思考:明确发 off,不能把上一个模型的档位带过去。
+ const switched = captured.requests.slice(beforeSwitch);
+ expect(switched).toContainEqual({ type: "set_thinking_level", level: "off" });
+ await handle.close();
+ });
+
+ it("falls back to a supported level when the retained effort is unavailable on the target", async () => {
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "model-a",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: null, high: "high", xhigh: null, max: null },
+ },
+ {
+ id: "model-b",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: "medium", high: null, xhigh: null, max: null },
+ },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "medium"], defaultEffort: "medium" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-effort-fallback",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true });
+
+ // high 不在目标快照:不能保持旧档位(在新模型的 map 里是 null = 关思考),
+ // 必须回落到目标可用档位。
+ const switched = captured.requests.slice(beforeSwitch);
+ expect(switched).toContainEqual({ type: "set_thinking_level", level: "low" });
+ await handle.close();
+ });
+
+ it("prefers the target model default effort when the retained effort is unavailable", async () => {
+ const baseDeps = byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "model-a",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: null, high: "high", xhigh: null, max: null },
+ },
+ {
+ id: "model-b",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: "medium", high: null, xhigh: null, max: null },
+ },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "medium"], defaultEffort: "medium" },
+ ],
+ );
+ const agent = new PiAgent({
+ ...baseDeps,
+ resolvePiRuntimeModelDescriptor: (_providerId, modelId) =>
+ modelId === "model-b"
+ ? {
+ id: "model-b",
+ displayName: "B",
+ contextWindow: 200_000,
+ efforts: ["low", "medium"],
+ defaultEffort: "medium",
+ }
+ : null,
+ });
+ const handle = await agent.startSession({
+ sessionId: "thinking-default-effort-fallback",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true });
+
+ expect(captured.requests.slice(beforeSwitch)).toContainEqual({
+ type: "set_thinking_level",
+ level: "medium",
+ });
+ await handle.close();
+ });
+
+ it("applies the target snapshot when a thinking-on switch carries no effort at all", async () => {
+ const baseDeps = byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ {
+ id: "model-a",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: null, high: "high", xhigh: null, max: null },
+ },
+ {
+ id: "model-b",
+ reasoning: true,
+ thinkingLevelMap: { minimal: null, low: "low", medium: "medium", high: null, xhigh: null, max: null },
+ },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "medium"], defaultEffort: "medium" },
+ ],
+ );
+ const agent = new PiAgent({
+ ...baseDeps,
+ resolvePiRuntimeModelDescriptor: (_providerId, modelId) =>
+ modelId === "model-b"
+ ? {
+ id: "model-b",
+ displayName: "B",
+ contextWindow: 200_000,
+ efforts: ["low", "medium"],
+ defaultEffort: "medium",
+ }
+ : null,
+ });
+ // 无 effort 目录的 BYOM 会话:selection 不带档位、会话也没有保留档位。
+ const handle = await agent.startSession({
+ sessionId: "thinking-no-effort-on-switch",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true });
+
+ // 用户明确要开思考、目标也支持:即使没有可用的期望档位也必须按目标快照收敛,
+ // 不能什么都不发——否则上一个模型的 off 会原样留下(推理进正文)。
+ expect(captured.requests.slice(beforeSwitch)).toContainEqual({
+ type: "set_thinking_level",
+ level: "medium",
+ });
+ await handle.close();
+ });
+
+ it("reopens thinking at the session effort instead of a hardcoded xhigh", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [{ id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } }],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-reopen-keeps-effort",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const before = captured.requests.length;
+
+ await handle.setThinkingEnabled!(true);
+
+ // 显式打开思考要回到会话当前的期望档位(high),而不是固定 xhigh:否则用户
+ // 选好的档位被抹平,紧随其后的切模还会按被抹平的档位归一化。
+ expect(captured.requests.slice(before)).toContainEqual({
+ type: "set_thinking_level",
+ level: "high",
+ });
+ await handle.close();
+ });
+
+ it("keeps the session effort when thinking is toggled off and back on", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [{ id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } }],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-toggle-keeps-effort",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const before = captured.requests.length;
+
+ await handle.setThinkingEnabled!(false);
+ await handle.setThinkingEnabled!(true);
+
+ // 关掉思考不丢档位记忆:再打开要回到用户选的 high,而不是启动档位/默认档。
+ expect(
+ captured.requests
+ .slice(before)
+ .filter((request) => request.type === "set_thinking_level"),
+ ).toEqual([
+ { type: "set_thinking_level", level: "off" },
+ { type: "set_thinking_level", level: "high" },
+ ]);
+ await handle.close();
+ });
+
+ it("retries the post-switch thinking level once before giving up", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ let failNextThinking = false;
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: { sessionFile: "/mock/s.jsonl", model: { contextWindow: 200_000 } },
+ };
+ }
+ if (command.type === "set_model") {
+ return { success: true, data: { contextWindow: 200_000 } };
+ }
+ if (command.type === "set_thinking_level") {
+ if (failNextThinking) {
+ failNextThinking = false;
+ return { success: false, error: "transient" };
+ }
+ return { success: true, data: {} };
+ }
+ return { success: true, data: {} };
+ };
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ { id: "model-b", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-retry-after-switch",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const before = captured.requests.length;
+ failNextThinking = true;
+
+ await handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true });
+
+ // 瞬时拒绝重试一次:两次下发都发出去,切模本身仍然成功。
+ expect(
+ captured.requests
+ .slice(before)
+ .filter((request) => request.type === "set_thinking_level"),
+ ).toHaveLength(2);
+ await handle.close();
+ });
+
+ it("does not touch the thinking level when the caller sends no thinking intent", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ { id: "model-b", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-untouched-without-intent",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+ const beforeSwitch = captured.requests.length;
+
+ await handle.setModel!("model-b", { providerId: "native-a" });
+
+ // 老调用方(无 intent)保持既有语义:只切模型,不动 thinking level。
+ expect(
+ captured.requests
+ .slice(beforeSwitch)
+ .some((request) => request.type === "set_thinking_level"),
+ ).toBe(false);
+ await handle.close();
+ });
+
+ it("keeps the model switch successful when the post-switch thinking level is rejected", async () => {
+ const denseMap = {
+ minimal: "minimal",
+ low: "low",
+ medium: "medium",
+ high: "high",
+ xhigh: "xhigh",
+ max: "max",
+ } as const;
+ captured.requestHandler = async (command) => {
+ if (command.type === "get_state") {
+ return {
+ success: true,
+ data: { sessionFile: "/mock/s.jsonl", model: { contextWindow: 200_000 } },
+ };
+ }
+ if (command.type === "set_model") {
+ return { success: true, data: { contextWindow: 200_000 } };
+ }
+ if (command.type === "set_thinking_level") {
+ return { success: false, error: "unsupported level" };
+ }
+ return { success: true, data: {} };
+ };
+ const agent = new PiAgent(
+ byomDeps(
+ async () => ({
+ providers: [
+ {
+ id: "native-a",
+ name: "Native A",
+ baseUrl: "http://a.test",
+ api: "openai-responses",
+ models: [
+ { id: "model-a", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ { id: "model-b", reasoning: true, thinkingLevelMap: { ...denseMap } },
+ ],
+ },
+ ],
+ env: {},
+ }),
+ [
+ { id: "model-a", displayName: "A", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ { id: "model-b", displayName: "B", contextWindow: 200_000, efforts: ["low", "high"], defaultEffort: "low" },
+ ],
+ ),
+ );
+ const handle = await agent.startSession({
+ sessionId: "thinking-rejected-after-switch",
+ workingDir: cwd,
+ model: "model-a",
+ providerId: "native-a",
+ effort: "high",
+ });
+
+ // 档位收敛失败不能把已经确认的模型切换改判成失败(否则上层会回滚 route)。
+ await expect(
+ handle.setModel!("model-b", { providerId: "native-a", thinkingEnabled: true }),
+ ).resolves.toBeUndefined();
+ expect(handle.model).toBe("model-b");
+ await handle.close();
+ });
+
it("accepts the low placeholder after switching to a non-reasoning gateway model", async () => {
const availableModels: readonly ModelDescriptor[] = [
{
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index aa29a114f2..9c19558577 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -6156,7 +6156,7 @@ export class PiAgent extends BaseAgent {
};
const switchModel = async (
model: string,
- setOpts?: { providerId?: string | null; effort?: Effort },
+ setOpts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean },
): Promise<void> => {
const requestedProviderId = setOpts && Object.hasOwn(setOpts, 'providerId')
? setOpts.providerId
@@ -6580,6 +6580,104 @@ export class PiAgent extends BaseAgent {
'subagent delegation stays disabled for this session (fail-closed)',
);
}
+ // Pi 的 set_model 不会重置 thinking level:上一个模型留下的 off / 旧档位会原样
+ // 继承给目标模型(典型:从不支持思考的模型切到推理模型后,模型只能把推理写进
+ // 正文)。桌面端在 selection 里携带目标模型的思考开关意图;这里在路由已确认后
+ // 按目标模型的启动快照把档位归一化下发一次,不再让档位跨模型漂移。
+ //
+ // 目标是否支持思考由启动快照判定(models.json 生成口径:gateway 看 efforts
+ // 非空、native 看 reasoning),空档位 ⟺ 不思考——这类模型明确发 off,避免把
+ // 上一个模型的档位带过去(Pi 会把 thinkingLevelMap 里的 null 当成关闭
+ // reasoning)。快照未知时不猜、不动 Pi 现有档位。
+ //
+ // 失败只告警、不抛:模型切换已经成功,抛出会让上层回滚 route / 终止会话,反而
+ // 制造「Pi 已切模、宿主认为没切」的分裂。用户可在 UI 上重新选择。
+ if (setOpts && typeof setOpts.thinkingEnabled === 'boolean') {
+ const requestedEffort = setOpts.effort ?? mutableEffort ?? startupEffort ?? null;
+ const nativeTarget = provider !== PI_PROVIDER_ID
+ ? nativeProviderById.get(provider)?.models.find(
+ (candidate) => candidate.id === resolveNativeModelId(provider, model),
+ )
+ : undefined;
+ const targetReasoning = provider !== PI_PROVIDER_ID
+ ? nativeTarget?.reasoning === true
+ : nextEffortSnapshot === undefined
+ ? undefined
+ : nextEffortSnapshot.length > 0;
+ let level: string | null = null;
+ let appliedEffort: Effort | null = null;
+ if (!setOpts.thinkingEnabled || targetReasoning === false) {
+ level = 'off';
+ } else if (targetReasoning === true) {
+ const usable = nextEffortSnapshot && nextEffortSnapshot.length > 0
+ ? nextEffortSnapshot
+ : undefined;
+ // 用户明确要开思考、目标也支持:即使这次 selection 没带档位(BYOM/无 effort
+ // 目录的会话),也要按启动快照收敛——不能什么都不发,否则上一个模型的 off 会
+ // 原样留下。口径与 reconcilePiStartupEffort 一致:优先目录默认档,否则首档。
+ if (usable) {
+ const preferredDefault =
+ this.deps.resolvePiRuntimeModelDescriptor?.(mutableProviderId ?? null, model)
+ ?.defaultEffort ?? null;
+ const reconciled =
+ requestedEffort && usable.includes(requestedEffort)
+ ? requestedEffort
+ : preferredDefault && usable.includes(preferredDefault)
+ ? preferredDefault
+ : usable[0];
+ if (requestedEffort && !usable.includes(requestedEffort)) {
+ // 启动快照(本次 spawn 冻结)与活跃目录可能漂移:此时 Pi 实际跑的档位与
+ // main 持久化/UI 显示的档位不一致,留一条日志便于排障。
+ deps.logger.warn('pi: thinking effort reconciled after model switch', {
+ model,
+ provider,
+ requestedEffort,
+ appliedEffort: reconciled,
+ });
+ } else if (!requestedEffort) {
+ // 会话本来就没期望档位(BYOM/无 effort 目录):同样要留下观察点,
+ // 否则 DB/投影显示 null 而 Pi 实跑默认档,漂移无从发现。
+ deps.logger.info('pi: thinking level defaulted to the target snapshot after model switch', {
+ model,
+ provider,
+ appliedEffort: reconciled,
+ });
+ }
+ appliedEffort = reconciled;
+ level = effortToPiThinkingLevel(reconciled);
+ }
+ }
+ if (level) {
+ // 拒绝可能是瞬时(例如 Pi 正在处理前一条档位请求):重试一次再放弃。
+ // 仍失败只告警:模型路由已经确认,抛出会让上层回滚它。
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ try {
+ const resp = await proc.request({ type: 'set_thinking_level', level });
+ if (resp.success) {
+ if (appliedEffort) mutableEffort = appliedEffort;
+ break;
+ }
+ if (attempt === 1) {
+ deps.logger.warn('pi: set_thinking_level rejected after model switch', {
+ model,
+ provider,
+ level,
+ error: resp.error,
+ });
+ }
+ } catch (err) {
+ if (attempt === 1) {
+ deps.logger.warn('pi: set_thinking_level failed after model switch', {
+ model,
+ provider,
+ level,
+ message: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ }
+ }
+ }
};
const handle: AgentSessionHandle = {
@@ -7166,7 +7264,7 @@ export class PiAgent extends BaseAgent {
return (window ?? undefined) !== ctx.workingContextWindow;
},
- async setModel(model: string, setOpts?: { providerId?: string | null; effort?: Effort }): Promise<void> {
+ async setModel(model: string, setOpts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void> {
if (reviewMode) return;
// 会话级串行闸:整段"写待切换快照 → set_model RPC → 落定/回滚"必须是一个临界区。
// 并发或连点切换(本地 + 远程控制端同时切)若交错,A 写 pending、B 写 pending、A 落定 B 的
@@ -7199,11 +7297,23 @@ export class PiAgent extends BaseAgent {
async setThinkingEnabled(enabled: boolean): Promise<void> {
if (reviewMode) return;
+ // 打开时回到会话当前的期望档位,而不是固定 xhigh:显式开关不该把用户选好的
+ // max/medium 抹平——否则紧随其后的切模按 mutableEffort 归一化时又会把它降档。
+ // 没有期望档位时才回到历史默认 xhigh。
+ const targetEffort = enabled ? mutableEffort ?? startupEffort ?? null : null;
+ const level = targetEffort
+ ? effortToPiThinkingLevel(targetEffort)
+ : enabled
+ ? 'xhigh'
+ : 'off';
const resp = await proc.request({
type: 'set_thinking_level',
- level: enabled ? 'xhigh' : 'off',
+ level,
});
if (!resp.success) throw new Error(`pi set_thinking_level failed: ${resp.error ?? 'unknown'}`);
+ // 只在打开时更新档位记忆:关掉思考不丢档位——档位是用户的独立选择,
+ // 再打开应回到原档位,而不是回落到启动时的档位。
+ if (enabled) mutableEffort = targetEffort ?? 'xhigh';
},
async setPermissionMode(mode): Promise<void> {
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 85b0fecd9e..b85dda1bc0 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -1707,7 +1707,7 @@ export class Session {
// ── 运行时切换 ─────────────────────────────────────────────────────────────
- async setModel(model: string, opts?: { providerId?: string | null; effort?: Effort }): Promise<void> {
+ async setModel(model: string, opts?: { providerId?: string | null; effort?: Effort; thinkingEnabled?: boolean }): Promise<void> {
if (!this.capabilities.switchModel.supported) {
throw new NotSupportedError('switchModel', this.capabilities.switchModel);
}