Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: migrate reasoning effort params to user-level model-instance config (#17985)

YuTengjing03929d283bd3
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index f00621ba3cd..8222c2f041f 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2,6 +2,7 @@ import { type AgentState } from '@lobechat/agent-runtime';
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { ToolNameResolver } from '@lobechat/context-engine';
import { consumeStreamUntilDone, ModelEmptyError } from '@lobechat/model-runtime';
+import type * as ModelBank from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as ContextEngineering from '@/server/modules/Mecha/ContextEngineering';
@@ -78,10 +79,16 @@ vi.mock('@lobechat/model-runtime', async () => {
// retry path and these tests share a single class identity for instanceof.
const { isEmptyModelCompletion, ModelEmptyError } =
await import('../../../../../../packages/model-runtime/src/errors/modelEmptyCompletion');
+ // Same treatment: the reasoning-config merge is pure, and the replay gate
+ // reads its output (e.g. the DeepSeek V4 thinking opt-out), so use the real
+ // implementation instead of a drifting stub.
+ const { resolveEffectiveReasoningChatConfig } =
+ await import('../../../../../../packages/model-runtime/src/utils/modelExtendParams');
return {
// The executor resolves extend params via this helper; an empty result keeps
// the runtime payload unchanged, matching this suite's pre-existing behavior.
applyModelExtendParams: vi.fn(() => ({})),
+ resolveEffectiveReasoningChatConfig,
consumeStreamUntilDone: vi.fn().mockResolvedValue(undefined),
// `llmErrorClassification.ts` reads these at module-load time; an empty
// spec map is fine here because this suite never exercises the runtime
@@ -107,7 +114,11 @@ vi.mock('@/business/client/model-bank/loadModels', () => ({
}));
// model-bank is a TypeScript source file that cannot be dynamically imported in vitest
-vi.mock('model-bank', () => ({
+vi.mock('model-bank', async (importOriginal) => ({
+ // serverCallLlmContextHints gates the model-instance reasoning-config DB
+ // read on the real MODEL_REASONING_EXTEND_PARAMS list
+ MODEL_REASONING_EXTEND_PARAMS: (await importOriginal<typeof ModelBank>())
+ .MODEL_REASONING_EXTEND_PARAMS,
LOBE_DEFAULT_MODEL_LIST: mockBuiltinModels,
ModelProvider: {
LobeHub: 'lobehub',
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
new file mode 100644
index 00000000000..85da42ffcfe
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
@@ -0,0 +1,227 @@
+import type { CallLLMPayload } from '@lobechat/agent-runtime';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeExecutorContext } from '../context';
+import { resolveServerCallLlmContextHints } from './serverCallLlmContextHints';
+
+const loadModelsMock = vi.hoisted(() => vi.fn());
+const findByIdAndProviderMock = vi.hoisted(() => vi.fn());
+const getModelReasoningConfigMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/business/client/model-bank/loadModels', () => ({
+ loadModels: loadModelsMock,
+}));
+
+vi.mock('@/database/models/aiModel', () => ({
+ AiModelModel: class {
+ findByIdAndProvider = findByIdAndProviderMock;
+ getModelReasoningConfig = getModelReasoningConfigMock;
+ },
+}));
+
+const createCtx = (agentConfig: any): RuntimeExecutorContext =>
+ ({
+ agentConfig,
+ messageModel: {} as RuntimeExecutorContext['messageModel'],
+ operationId: 'operation-1',
+ serverDB: {} as RuntimeExecutorContext['serverDB'],
+ stepIndex: 0,
+ streamManager: {} as RuntimeExecutorContext['streamManager'],
+ toolExecutionService: {} as RuntimeExecutorContext['toolExecutionService'],
+ userId: 'user-1',
+ }) satisfies RuntimeExecutorContext;
+
+const llmPayload = { messages: [] } as unknown as CallLLMPayload;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+
+ loadModelsMock.mockResolvedValue([
+ {
+ abilities: {},
+ displayName: 'GPT-4',
+ id: 'gpt-4',
+ providerId: 'openai',
+ settings: { extendParams: ['reasoningEffort'] },
+ },
+ {
+ abilities: {},
+ displayName: 'DeepSeek V4 Pro',
+ id: 'deepseek-v4-pro',
+ providerId: 'deepseek',
+ settings: { extendParams: ['deepseekV4ReasoningEffort'] },
+ },
+ {
+ abilities: {},
+ displayName: 'GPT-4o Mini',
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ settings: {},
+ },
+ ]);
+ findByIdAndProviderMock.mockResolvedValue(undefined);
+ getModelReasoningConfigMock.mockResolvedValue(undefined);
+});
+
+describe('resolveServerCallLlmContextHints - model-instance reasoning config', () => {
+ it('should apply the user model-instance reasoning config', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).toHaveBeenCalledWith('gpt-4', 'openai');
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
+ });
+
+ it('should resolve extend params from the user DB row for custom models', async () => {
+ findByIdAndProviderMock.mockResolvedValue({
+ displayName: 'My Custom Reasoner',
+ settings: { extendParams: ['reasoningEffort'] },
+ });
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'my-custom-model',
+ provider: 'custom-provider',
+ });
+
+ expect(getModelReasoningConfigMock).toHaveBeenCalledWith('my-custom-model', 'custom-provider');
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
+ });
+
+ it('should honor reasoning extend params added to a builtin model via DB settings', async () => {
+ // Provider-settings edits store extendParams on the user's own model row;
+ // the client merges them over the bundled card, so the server must too
+ findByIdAndProviderMock.mockResolvedValue({
+ settings: { extendParams: ['reasoningEffort'] },
+ });
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).toHaveBeenCalledWith('gpt-4o-mini', 'openai');
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
+ });
+
+ it('should treat an explicitly emptied extendParams row as an opt-out', async () => {
+ // Clearing extendParams in provider settings replaces the card's list on
+ // the client (array-replacement merge); the server must not fall back to
+ // the bundled card and resurrect the removed reasoning params
+ findByIdAndProviderMock.mockResolvedValue({ settings: { extendParams: [] } });
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'high' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ expect(hints.resolvedExtendParams).toEqual({});
+ });
+
+ it('should skip the reasoning config DB read for models without reasoning extend params', async () => {
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ expect(hints.resolvedExtendParams).toEqual({});
+ });
+
+ it('should ignore stale reasoning fields left in agent chatConfig', async () => {
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: { reasoningEffort: 'low' } }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toEqual({});
+ });
+
+ it('should apply extend params from instance config even without agent chatConfig', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'medium' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({}),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'medium' });
+ });
+
+ it('should let explicit sub-agent overrides win over the instance config', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({
+ chatConfig: {},
+ subAgentChatConfigOverride: { reasoningEffort: 'high' },
+ }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
+ });
+
+ it('should derive the DeepSeek V4 thinking opt-out from the instance config', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ deepseekV4ReasoningEffort: 'none' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ // stale agent value says 'high', but the instance config opts out
+ ctx: createCtx({ chatConfig: { deepseekV4ReasoningEffort: 'high' } }),
+ llmPayload,
+ model: 'deepseek-v4-pro',
+ provider: 'deepseek',
+ });
+
+ expect(hints.shouldReplayAssistantReasoning).toBe(false);
+ expect(hints.resolvedExtendParams).toEqual({ thinking: { type: 'disabled' } });
+ });
+
+ it('should keep DeepSeek V4 forced reasoning replay when no opt-out is saved', async () => {
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: createCtx({ chatConfig: {} }),
+ llmPayload,
+ model: 'deepseek-v4-pro',
+ provider: 'deepseek',
+ });
+
+ expect(hints.shouldReplayAssistantReasoning).toBe(true);
+ });
+
+ it('should not read the instance config when the ctx has no user scope', async () => {
+ const ctx = createCtx({ chatConfig: {} });
+ ctx.userId = undefined;
+
+ await resolveServerCallLlmContextHints({
+ ctx,
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
index b9c1d423b6f..0a2089701cb 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
@@ -6,9 +6,15 @@ import {
isDeepSeekV4FamilyModel,
isKimiAlwaysPreserveThinkingModel,
type ModelExtendParams,
+ resolveEffectiveReasoningChatConfig,
} from '@lobechat/model-runtime';
-import type { UIChatMessage } from '@lobechat/types';
-import { type ExtendParamsType, ModelProvider } from 'model-bank';
+import type { LobeAgentChatConfig, UIChatMessage } from '@lobechat/types';
+import {
+ type AiModelReasoningConfig,
+ type ExtendParamsType,
+ MODEL_REASONING_EXTEND_PARAMS,
+ ModelProvider,
+} from 'model-bank';
import { AiModelModel } from '@/database/models/aiModel';
@@ -78,30 +84,77 @@ export const resolveServerCallLlmContextHints = async ({
modelCard?.displayName ??
(provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);
- // Custom/remote user models aren't in the bundled model bank, so both cards
- // miss. Fall back to the user's own AI model record so server-side runs still
- // surface identity (the inbox `{{model}}` fallback no longer exists).
- if (!modelDisplayName && ctx.serverDB && ctx.userId) {
+ const aiModelModel =
+ ctx.serverDB && ctx.userId
+ ? new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId)
+ : undefined;
+
+ // The user's own AI model row serves two purposes: custom/remote models miss
+ // both bundled cards entirely (displayName + extendParams live only on the
+ // row), and builtin models may carry user-edited `settings.extendParams`
+ // from a provider-settings edit, which the client honors by merging user
+ // settings over the card. One indexed read per attempt.
+ let userModelRow: Awaited<ReturnType<AiModelModel['findByIdAndProvider']>> | undefined;
+ if (aiModelModel) {
try {
- const aiModelModel = new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId);
- const userModel = await aiModelModel.findByIdAndProvider(model, provider);
- modelDisplayName = userModel?.displayName ?? undefined;
+ userModelRow = await aiModelModel.findByIdAndProvider(model, provider);
} catch (error) {
- log('Failed to resolve user model display name for %s: %O', model, error);
+ log('Failed to resolve user model row for %s: %O', model, error);
+ }
+ }
+ // User-set displayName wins, matching the client list merge
+ modelDisplayName = userModelRow?.displayName ?? modelDisplayName;
+
+ // User-edited settings win over the bundled card, matching the client's
+ // `getEnabledModels` settings merge (arrays replace wholesale there, so an
+ // explicit empty array is an opt-out from the card's params, not a miss β€”
+ // only a row without `extendParams` falls back to the cards).
+ let modelExtendParams: string[] | undefined = userModelRow?.settings?.extendParams ?? undefined;
+
+ if (modelExtendParams === undefined) {
+ modelExtendParams = readExtendParams(modelCard);
+
+ // Aggregation providers (e.g. `lobehub`) may serve a model without copying
+ // its origin `settings.extendParams`. Fall back to the canonical model card
+ // (matched by id across any provider) so reasoning/thinking params like
+ // `thinkingLevel` still reach the model. Mirrors the client-side
+ // `transformToAiModelList` re-namespacing behavior.
+ if (!modelExtendParams || modelExtendParams.length === 0) {
+ modelExtendParams = readExtendParams(canonicalModelCard);
}
}
- let modelExtendParams = readExtendParams(modelCard);
-
- // Aggregation providers (e.g. `lobehub`) may serve a model without copying
- // its origin `settings.extendParams`. Fall back to the canonical model card
- // (matched by id across any provider) so reasoning/thinking params like
- // `thinkingLevel` still reach the model. Mirrors the client-side
- // `transformToAiModelList` re-namespacing behavior.
- if (!modelExtendParams || modelExtendParams.length === 0) {
- modelExtendParams = readExtendParams(canonicalModelCard);
+ // Reasoning fields (effort family + reasoningMode) are user-level
+ // model-instance settings (personal scope, cross-workspace): same-named
+ // agent chatConfig values are ignored and the saved per-model config applies
+ // instead β€” except explicit sub-agent overrides, which stay honored.
+ // Only read the saved config when the model can actually consume it
+ // (applyModelExtendParams ignores it otherwise) β€” this runs on every server
+ // LLM attempt, so non-reasoning models must not pay the extra DB read.
+ const modelHasReasoningExtendParams = (modelExtendParams ?? []).some((param) =>
+ (MODEL_REASONING_EXTEND_PARAMS as readonly string[]).includes(param),
+ );
+ let modelReasoningConfig: AiModelReasoningConfig | undefined;
+ if (aiModelModel && modelHasReasoningExtendParams) {
+ try {
+ modelReasoningConfig = await aiModelModel.getModelReasoningConfig(model, provider);
+ } catch (error) {
+ log('Failed to resolve model reasoning config for %s: %O', model, error);
+ }
}
+ const agentChatConfig: LobeAgentChatConfig | undefined = agentConfig?.chatConfig;
+ const subAgentChatConfigOverride: Partial<LobeAgentChatConfig> | undefined =
+ agentConfig?.subAgentChatConfigOverride ?? undefined;
+ const effectiveChatConfig =
+ agentChatConfig || modelReasoningConfig || subAgentChatConfigOverride
+ ? resolveEffectiveReasoningChatConfig({
+ agentChatConfig: agentChatConfig ?? {},
+ modelReasoningConfig,
+ subAgentReasoningOverrides: subAgentChatConfigOverride,
+ })
+ : undefined;
+
const modelSupportsPreserveThinkingFromCard =
Array.isArray(modelExtendParams) && modelExtendParams.includes('preserveThinking');
// Kimi K2.7+ Code has preserved thinking always active and cannot opt out.
@@ -124,7 +177,7 @@ export const resolveServerCallLlmContextHints = async ({
// forces reasoning history in the payload builder β€” suppressing it there
// would reintroduce the 400/answer-hidden behavior.
const deepseekV4ThinkingDisabled =
- isDeepSeekV4FamilyModel(model) && agentConfig?.chatConfig?.deepseekV4ReasoningEffort === 'none';
+ isDeepSeekV4FamilyModel(model) && effectiveChatConfig?.deepseekV4ReasoningEffort === 'none';
const deepseekForcesPreserveThinking =
isDeepSeekThinkingEligibleModel(model) && !deepseekV4ThinkingDisabled;
const modelForcesPreserveThinking = kimiForcesPreserveThinking || deepseekForcesPreserveThinking;
@@ -143,9 +196,9 @@ export const resolveServerCallLlmContextHints = async ({
? preserveThinkingConfigured
: undefined;
- const resolvedModelExtendParams = agentConfig?.chatConfig
+ const resolvedModelExtendParams = effectiveChatConfig
? applyModelExtendParams({
- chatConfig: agentConfig.chatConfig,
+ chatConfig: effectiveChatConfig,
extendParams: modelExtendParams as ExtendParamsType[] | undefined,
model,
})
diff --git a/apps/server/src/routers/lambda/__tests__/aiModel.test.ts b/apps/server/src/routers/lambda/__tests__/aiModel.test.ts
index f108fde285f..d8c0725aa22 100644
--- a/apps/server/src/routers/lambda/__tests__/aiModel.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiModel.test.ts
@@ -311,4 +311,69 @@ describe('aiModelRouter', () => {
expect(mockClearRemote).toHaveBeenCalledWith('provider-1');
});
+
+ it('should get model reasoning config', async () => {
+ const mockGet = vi.fn().mockResolvedValue({ gpt5_6ReasoningEffort: 'high' });
+ vi.mocked(AiModelModel).mockImplementation(
+ () =>
+ ({
+ getModelReasoningConfig: mockGet,
+ }) as any,
+ );
+
+ const caller = aiModelRouter.createCaller(mockCtx);
+
+ const result = await caller.getAiModelReasoningConfig({
+ id: 'gpt-5.6-sol',
+ providerId: 'openai',
+ });
+
+ expect(mockGet).toHaveBeenCalledWith('gpt-5.6-sol', 'openai');
+ expect(result).toEqual({ gpt5_6ReasoningEffort: 'high' });
+ });
+
+ it('should update model reasoning config', async () => {
+ const mockUpdate = vi.fn().mockResolvedValue(undefined);
+ vi.mocked(AiModelModel).mockImplementation(
+ () =>
+ ({
+ updateModelReasoningConfig: mockUpdate,
+ }) as any,
+ );
+
+ const caller = aiModelRouter.createCaller(mockCtx);
+
+ await caller.updateAiModelReasoningConfig({
+ id: 'gpt-5.6-sol',
+ providerId: 'openai',
+ value: { gpt5_6ReasoningEffort: 'xhigh', reasoningMode: 'pro' },
+ });
+
+ expect(mockUpdate).toHaveBeenCalledWith('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'xhigh',
+ reasoningMode: 'pro',
+ });
+ });
+
+ it('should reject invalid reasoning config values', async () => {
+ const mockUpdate = vi.fn();
+ vi.mocked(AiModelModel).mockImplementation(
+ () =>
+ ({
+ updateModelReasoningConfig: mockUpdate,
+ }) as any,
+ );
+
+ const caller = aiModelRouter.createCaller(mockCtx);
+
+ await expect(
+ caller.updateAiModelReasoningConfig({
+ id: 'gpt-5.6-sol',
+ providerId: 'openai',
+ value: { gpt5_6ReasoningEffort: 'ultra' } as any,
+ }),
+ ).rejects.toThrow();
+
+ expect(mockUpdate).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/routers/lambda/aiModel.ts b/apps/server/src/routers/lambda/aiModel.ts
index 3e7b7878a84..0721c47152f 100644
--- a/apps/server/src/routers/lambda/aiModel.ts
+++ b/apps/server/src/routers/lambda/aiModel.ts
@@ -1,6 +1,7 @@
import { TRPCError } from '@trpc/server';
import { type AiProviderModelListItem } from 'model-bank';
import {
+ AiModelReasoningConfigSchema,
AiModelTypeSchema,
CreateAiModelSchema,
ToggleAiModelEnableSchema,
@@ -118,7 +119,24 @@ export const aiModelRouter = router({
.input(CreateAiModelSchema)
.mutation(async ({ input, ctx }) => {
const existingModel = await ctx.aiModelModel.findByIdAndProvider(input.id, input.providerId);
- if (existingModel) throwDuplicateAiModelError(input.id);
+ if (existingModel) {
+ // A preference-only shell (just a saved reasoning config, hidden from
+ // lists β€” e.g. left after clearing remote models) is not a real
+ // duplicate: promote it into the custom model being created. `update`
+ // upserts and shallow-merges `config`, preserving the chatConfig.
+ if (!AiModelModel.isPreferenceOnlyRow(existingModel)) {
+ throwDuplicateAiModelError(input.id);
+ }
+
+ // enabled defaults to true, matching the plain create() path
+ // (CreateAiModelSchema carries no enabled field)
+ await ctx.aiModelModel.update(input.id, input.providerId, {
+ ...input,
+ enabled: true,
+ source: 'custom',
+ });
+ return input.id;
+ }
try {
const data = await ctx.aiModelModel.create(input);
@@ -138,6 +156,15 @@ export const aiModelRouter = router({
return ctx.aiModelModel.findById(input.id);
}),
+ // Personal-scope by design (workspaceId ignored): the user's default reasoning
+ // params for a model instance are keyed by userId + providerId + modelId and
+ // shared across workspaces. See AiModelModel.getModelReasoningConfig.
+ getAiModelReasoningConfig: aiModelProcedure
+ .input(z.object({ id: z.string(), providerId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ return await ctx.aiModelModel.getModelReasoningConfig(input.id, input.providerId);
+ }),
+
getAiProviderModelList: aiModelProcedure
.input(
z.object({
@@ -189,6 +216,23 @@ export const aiModelRouter = router({
return ctx.aiModelModel.update(input.id, input.providerId, input.value);
}),
+ // Intentionally NOT gated by `ai_model:update`: this writes a personal
+ // preference (scoped by userId with workspaceId NULL, see
+ // AiModelModel.updateModelReasoningConfig), so workspace members without the
+ // shared model-management permission must still be able to save it. Matches
+ // the ungated getAiModelReasoningConfig read above.
+ updateAiModelReasoningConfig: aiModelProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ providerId: z.string(),
+ value: AiModelReasoningConfigSchema,
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ return ctx.aiModelModel.updateModelReasoningConfig(input.id, input.providerId, input.value);
+ }),
+
updateAiModelOrder: aiModelProcedure
.use(withScopedPermission('ai_model:update'))
.input(
diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.ts
index 232e4566ffb..0b4610695ef 100644
--- a/apps/server/src/services/agent/index.ts
+++ b/apps/server/src/services/agent/index.ts
@@ -2,7 +2,7 @@ import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';
import { BUILTIN_AGENTS } from '@lobechat/builtin-agents';
import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';
import { type LobeChatDatabase } from '@lobechat/database';
-import { type AgentItem, type LobeAgentConfig } from '@lobechat/types';
+import { type AgentItem, type LobeAgentChatConfig, type LobeAgentConfig } from '@lobechat/types';
import { cleanObject, merge } from '@lobechat/utils';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
@@ -31,7 +31,14 @@ const log = debug('lobe-agent:service');
* Used when returning agent config from database (id is always present).
*/
export type AgentConfigWithId = LobeAgentConfig &
- Pick<AgentItem, 'id' | 'slug' | 'userId' | 'visibility' | 'workspaceId'>;
+ Pick<AgentItem, 'id' | 'slug' | 'userId' | 'visibility' | 'workspaceId'> & {
+ /**
+ * Raw callSubAgent chatConfig override, stamped by execAgent alongside the
+ * merged chatConfig. The LLM context hints need it to re-apply explicit
+ * sub-agent reasoning choices over the user's model-instance defaults.
+ */
+ subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
+ };
interface AgentWelcomeData {
openQuestions: string[];
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 68ab638b850..6e32219ee6c 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1412,6 +1412,11 @@ export class AiAgentService {
agentConfig.chatConfig =
resolveSubAgentChatConfig(agentConfig.chatConfig, chatConfigOverride) ??
agentConfig.chatConfig;
+ // Keep the raw override so the LLM context hints can re-apply explicit
+ // sub-agent reasoning choices over the user's model-instance defaults β€”
+ // the merged chatConfig alone can't distinguish them from stale agent
+ // values, which the reasoning-config migration ignores.
+ agentConfig.subAgentChatConfigOverride = chatConfigOverride;
}
// Persistence-attribution agent id. Background Agent Signal runs (memory /
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 1e569cfd254..c73d1f069e8 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -890,6 +890,18 @@
"rag.referenceChunks": "Reference Source",
"rag.userQuery.actions.delete": "Delete Query Rewrite",
"rag.userQuery.actions.regenerate": "Regenerate Query",
+ "reasoningEffort.levels.high": "High",
+ "reasoningEffort.levels.low": "Low",
+ "reasoningEffort.levels.max": "Max",
+ "reasoningEffort.levels.medium": "Medium",
+ "reasoningEffort.levels.minimal": "Minimal",
+ "reasoningEffort.levels.no_think": "Off",
+ "reasoningEffort.levels.none": "Off",
+ "reasoningEffort.levels.xhigh": "Extra High",
+ "reasoningEffort.mode.pro": "Pro",
+ "reasoningEffort.mode.standard": "Standard",
+ "reasoningEffort.title": "Reasoning Effort",
+ "reasoningEffort.updateFailed": "Failed to update reasoning effort, please try again",
"regenerate": "Regenerate",
"resource.artifacts.buildLog.copy": "Copy logs",
"resource.artifacts.buildLog.copySuccess": "Build logs copied",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4b73e975ca4..d43e5832709 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -890,6 +890,18 @@
"rag.referenceChunks": "引用源",
"rag.userQuery.actions.delete": "εˆ ι™€ Query 重写",
"rag.userQuery.actions.regenerate": "ι‡ζ–°η”Ÿζˆ Query",
+ "reasoningEffort.levels.high": "高",
+ "reasoningEffort.levels.low": "低",
+ "reasoningEffort.levels.max": "ζœ€ε€§",
+ "reasoningEffort.levels.medium": "δΈ­",
+ "reasoningEffort.levels.minimal": "ζœ€ε°",
+ "reasoningEffort.levels.no_think": "ε…³ι—­",
+ "reasoningEffort.levels.none": "ε…³ι—­",
+ "reasoningEffort.levels.xhigh": "θΆ…ι«˜",
+ "reasoningEffort.mode.pro": "Pro",
+ "reasoningEffort.mode.standard": "Standard",
+ "reasoningEffort.title": "ζŽ¨η†εΌΊεΊ¦",
+ "reasoningEffort.updateFailed": "ζŽ¨η†εΌΊεΊ¦ζ›΄ζ–°ε€±θ΄₯οΌŒθ―·ι‡θ―•",
"regenerate": "ι‡ζ–°η”Ÿζˆ",
"resource.artifacts.buildLog.copy": "倍刢ζ—₯εΏ—",
"resource.artifacts.buildLog.copySuccess": "ζž„ε»Ίζ—₯εΏ—ε·²ε€εˆΆ",
diff --git a/packages/database/src/models/__tests__/aiModel.test.ts b/packages/database/src/models/__tests__/aiModel.test.ts
index ab67c53e4a3..35fb954811a 100644
--- a/packages/database/src/models/__tests__/aiModel.test.ts
+++ b/packages/database/src/models/__tests__/aiModel.test.ts
@@ -239,6 +239,213 @@ describe('AiModelModel', () => {
userId,
});
});
+
+ it('should merge config instead of replacing it, preserving chatConfig', async () => {
+ const { id } = await aiProviderModel.create({ id: 'gpt-5.6-sol', providerId: 'azure' });
+ await aiProviderModel.updateModelReasoningConfig(id, 'azure', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+
+ // The old model-config modal only knows deploymentName; saving it must not
+ // wipe the sibling chatConfig namespace.
+ await aiProviderModel.update(id, 'azure', { config: { deploymentName: 'my-deploy' } });
+
+ const row = await aiProviderModel.findByIdAndProvider(id, 'azure');
+ expect(row!.config).toEqual({
+ chatConfig: { gpt5_6ReasoningEffort: 'high' },
+ deploymentName: 'my-deploy',
+ });
+ });
+ });
+
+ describe('model reasoning config (personal scope)', () => {
+ it('should create a preference-only row without flipping enabled or source', async () => {
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'xhigh',
+ reasoningMode: 'pro',
+ });
+
+ const row = await serverDB.query.aiModels.findFirst({
+ where: and(eq(aiModels.id, 'gpt-5.6-sol'), eq(aiModels.userId, userId)),
+ });
+ expect(row!.config).toEqual({
+ chatConfig: { gpt5_6ReasoningEffort: 'xhigh', reasoningMode: 'pro' },
+ });
+ // A row that exists only to hold the preference must not change model
+ // visibility (enabled NULL falls back to builtin defaults) nor claim an
+ // origin that would block later remote-sync updates.
+ expect(row!.enabled).toBeNull();
+ expect(row!.source).toBeNull();
+ expect(row!.workspaceId).toBeNull();
+ });
+
+ it('should merge partial chatConfig writes and preserve sibling config keys', async () => {
+ await aiProviderModel.create({ id: 'gpt-5.6-sol', providerId: 'openai' });
+ await aiProviderModel.update('gpt-5.6-sol', 'openai', {
+ config: { deploymentName: 'keep-me' },
+ });
+
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ reasoningMode: 'pro',
+ });
+
+ const config = await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai');
+ expect(config).toEqual({ gpt5_6ReasoningEffort: 'high', reasoningMode: 'pro' });
+
+ const row = await aiProviderModel.findByIdAndProvider('gpt-5.6-sol', 'openai');
+ expect(row!.config).toMatchObject({ deploymentName: 'keep-me' });
+ });
+
+ it('should read/write the personal row even when scoped to a workspace', async () => {
+ await workspaceAiModelModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'low',
+ });
+
+ // Written to the personal row (workspaceId NULL), not the workspace row
+ const rows = await serverDB.query.aiModels.findMany({
+ where: and(eq(aiModels.id, 'gpt-5.6-sol'), eq(aiModels.userId, userId)),
+ });
+ expect(rows).toHaveLength(1);
+ expect(rows[0].workspaceId).toBeNull();
+
+ // And readable through both scopes β€” the preference is cross-workspace
+ expect(await workspaceAiModelModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'low',
+ });
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'low',
+ });
+ });
+
+ it('should isolate configs across providers and users', async () => {
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'azure')).toBeUndefined();
+
+ const otherUserModel = new AiModelModel(serverDB, 'user2');
+ expect(await otherUserModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toBeUndefined();
+ });
+
+ it('should survive a remote model list sync', async () => {
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+
+ await aiProviderModel.batchUpdateAiModels('openai', [
+ {
+ contextWindowTokens: 400_000,
+ displayName: 'GPT-5.6 Sol',
+ enabled: true,
+ id: 'gpt-5.6-sol',
+ source: 'remote',
+ type: 'chat',
+ } as AiProviderModelListItem,
+ ]);
+
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'high',
+ });
+ });
+
+ it('should survive clearing remote models after a sync', async () => {
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+
+ // Sync claims the preference row as remote too (so its synced metadata
+ // stays clearable); clearRemoteModels demotes chatConfig-holding remote
+ // rows instead of deleting them, so the preference still survives
+ await aiProviderModel.batchUpdateAiModels('openai', [
+ {
+ contextWindowTokens: 400_000,
+ displayName: 'GPT-5.6 Sol',
+ enabled: true,
+ id: 'gpt-5.6-sol',
+ source: 'remote',
+ type: 'chat',
+ },
+ { enabled: true, id: 'some-remote-model', source: 'remote', type: 'chat' },
+ ] as AiProviderModelListItem[]);
+ await aiProviderModel.clearRemoteModels('openai');
+
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'high',
+ });
+ // Demoted back to a hidden preference-only shell β€” the synced metadata
+ // must not linger as a ghost list entry after clearing remote models
+ const row = await aiProviderModel.findByIdAndProvider('gpt-5.6-sol', 'openai');
+ expect(AiModelModel.isPreferenceOnlyRow(row!)).toBe(true);
+ // The plain remote row is still cleared as before
+ expect(await aiProviderModel.findByIdAndProvider('some-remote-model', 'openai')).toBe(
+ undefined,
+ );
+ });
+
+ it('should survive clearing remote models saved in remote-first order', async () => {
+ // Row created by the remote fetch first...
+ await aiProviderModel.batchUpdateAiModels('openai', [
+ {
+ contextWindowTokens: 400_000,
+ displayName: 'GPT-5.6 Sol',
+ enabled: true,
+ id: 'gpt-5.6-sol',
+ source: 'remote',
+ type: 'chat',
+ },
+ { enabled: true, id: 'some-remote-model', source: 'remote', type: 'chat' },
+ ] as AiProviderModelListItem[]);
+ // ...then the user saves a preference onto the remote row
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+
+ await aiProviderModel.clearRemoteModels('openai');
+
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'high',
+ });
+ // Demoted to a preference-only row: remote identity and metadata stripped
+ const row = await aiProviderModel.findByIdAndProvider('gpt-5.6-sol', 'openai');
+ expect(row!.source).toBeNull();
+ expect(row!.displayName).toBeNull();
+ expect(row!.contextWindowTokens).toBeNull();
+ expect(row!.enabled).toBeNull();
+ // The plain remote row is still cleared
+ expect(await aiProviderModel.findByIdAndProvider('some-remote-model', 'openai')).toBe(
+ undefined,
+ );
+ });
+
+ it('should identify preference-only shells', async () => {
+ await aiProviderModel.updateModelReasoningConfig('gpt-5.6-sol', 'openai', {
+ gpt5_6ReasoningEffort: 'high',
+ });
+ await aiProviderModel.create({ enabled: true, id: 'real-model', providerId: 'openai' });
+
+ const shell = await aiProviderModel.findByIdAndProvider('gpt-5.6-sol', 'openai');
+ const realModel = await aiProviderModel.findByIdAndProvider('real-model', 'openai');
+
+ expect(AiModelModel.isPreferenceOnlyRow(shell!)).toBe(true);
+ expect(AiModelModel.isPreferenceOnlyRow(realModel!)).toBe(false);
+
+ // Promoting a shell via update (the createAiModel duplicate-bypass path)
+ // keeps the saved preference
+ await aiProviderModel.update('gpt-5.6-sol', 'openai', {
+ displayName: 'Recreated',
+ enabled: true,
+ source: 'custom',
+ });
+ expect(await aiProviderModel.getModelReasoningConfig('gpt-5.6-sol', 'openai')).toEqual({
+ gpt5_6ReasoningEffort: 'high',
+ });
+ const promoted = await aiProviderModel.findByIdAndProvider('gpt-5.6-sol', 'openai');
+ expect(AiModelModel.isPreferenceOnlyRow(promoted!)).toBe(false);
+ });
});
describe('getModelListByProviderId', () => {
diff --git a/packages/database/src/models/aiModel.ts b/packages/database/src/models/aiModel.ts
index c7771aadda2..f7f93777fd5 100644
--- a/packages/database/src/models/aiModel.ts
+++ b/packages/database/src/models/aiModel.ts
@@ -1,5 +1,7 @@
import { and, asc, desc, eq, isNotNull, isNull, sql } from 'drizzle-orm';
import type {
+ AiModelConfig,
+ AiModelReasoningConfig,
AiModelSortMap,
AiProviderModelListItem,
EnabledAiModel,
@@ -28,6 +30,12 @@ export class AiModelModel {
private scopeWhere = () =>
buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, aiModels);
+ /**
+ * Personal scope regardless of the active workspace (userId + workspaceId IS NULL).
+ * Used by the model-instance reasoning-config helpers, which are cross-workspace.
+ */
+ private personalScopeWhere = () => buildWorkspaceWhere({ userId: this.userId }, aiModels);
+
private values<T extends object>(base: T) {
return buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, base);
}
@@ -76,6 +84,26 @@ export class AiModelModel {
return array.length === 0;
}
+ /**
+ * Whether a row exists only to persist the personal reasoning preference
+ * (`config.chatConfig`): created by {@link AiModelModel.updateModelReasoningConfig}
+ * or left behind when {@link AiModelModel.clearRemoteModels} demotes a remote
+ * row. Such shells carry no user-visible identity β€” list reads hide them and
+ * duplicate checks must not treat them as real models.
+ */
+ static isPreferenceOnlyRow = (row: {
+ contextWindowTokens?: number | null;
+ displayName?: string | null;
+ enabled?: boolean | null;
+ releasedAt?: string | null;
+ source?: string | null;
+ }) =>
+ row.source == null &&
+ row.enabled == null &&
+ row.displayName == null &&
+ row.contextWindowTokens == null &&
+ row.releasedAt == null;
+
create = async (params: NewAiModelItem) => {
const values = this.normalizeAiModelValues(params);
@@ -178,15 +206,87 @@ export class AiModelModel {
update = async (id: string, providerId: string, value: Partial<AiModelSelectItem>) => {
const normalizedValue = this.normalizeAiModelValues(value);
+ const set: Record<string, unknown> = { ...normalizedValue };
+ // Shallow-merge `config` instead of replacing the column: callers send partial
+ // config (the model-config modal only knows `deploymentName`), and a full
+ // replace would silently wipe sibling keys such as the user's `chatConfig`
+ // model-instance reasoning defaults.
+ if (normalizedValue.config !== undefined && normalizedValue.config !== null) {
+ set.config = sql`COALESCE(ai_models.config, '{}'::jsonb) || excluded.config`;
+ }
+
return this.db
.insert(aiModels)
.values(this.values({ ...normalizedValue, id, providerId, updatedAt: new Date() }))
.onConflictDoUpdate({
- set: normalizedValue,
+ set,
...this.conflictTarget(),
});
};
+ /**
+ * Personal-scope read of the user's per-model-instance reasoning defaults
+ * (`config.chatConfig`). Deliberately ignores the active workspace: the
+ * preference is keyed by userId + providerId + modelId and shared across
+ * workspaces by design.
+ */
+ getModelReasoningConfig = async (
+ id: string,
+ providerId: string,
+ ): Promise<AiModelReasoningConfig | undefined> => {
+ const row = await this.db.query.aiModels.findFirst({
+ columns: { config: true },
+ where: and(
+ eq(aiModels.id, id),
+ eq(aiModels.providerId, providerId),
+ this.personalScopeWhere(),
+ ),
+ });
+
+ return (row?.config as AiModelConfig | null)?.chatConfig;
+ };
+
+ /**
+ * Personal-scope partial update of `config.chatConfig` (see
+ * getModelReasoningConfig for the scoping rationale).
+ */
+ updateModelReasoningConfig = async (
+ id: string,
+ providerId: string,
+ chatConfig: AiModelReasoningConfig,
+ ) => {
+ const config: AiModelConfig = { chatConfig };
+
+ return this.db
+ .insert(aiModels)
+ .values({
+ config,
+ id,
+ providerId,
+ updatedAt: new Date(),
+ userId: this.userId,
+ // No `enabled` / `source` on purpose: a row created only to hold the
+ // preference must not flip model visibility (enabled NULL falls back to
+ // the builtin default in AiInfraRepos.getEnabledModels) nor claim an
+ // origin that would block later remote-sync updates.
+ workspaceId: null,
+ })
+ .onConflictDoUpdate({
+ set: {
+ // Nested merge: keep sibling config keys (deploymentName, enabledSearch)
+ // and previously saved chatConfig fields absent from this partial write.
+ config: sql`jsonb_set(
+ COALESCE(ai_models.config, '{}'::jsonb),
+ '{chatConfig}',
+ COALESCE(ai_models.config -> 'chatConfig', '{}'::jsonb) || ${JSON.stringify(chatConfig)}::jsonb
+ )`,
+ updatedAt: new Date(),
+ },
+ target: [aiModels.id, aiModels.providerId, aiModels.userId],
+ targetWhere: isNull(aiModels.workspaceId),
+ });
+ };
+
toggleModelEnabled = async (value: ToggleAiModelEnableParams) => {
const now = new Date();
const insertValues = {
@@ -367,7 +467,12 @@ export class AiModelModel {
THEN COALESCE(ai_models.type, excluded.type)
ELSE ai_models.type
END`,
- // source marks model origin (remote/custom/builtin); once set, never overwrite
+ // source marks model origin (remote/custom/builtin); once set, never
+ // overwrite. A preference-only row (source NULL, config.chatConfig β€”
+ // see updateModelReasoningConfig) IS claimed as remote here so the
+ // synced metadata stays clearable; clearRemoteModels then demotes
+ // rows carrying a chatConfig instead of deleting them, so the
+ // personal preference survives either way.
source: sql`COALESCE(ai_models.source, excluded.source)`,
updatedAt: sql`excluded.updated_at`,
// Note: enabled is intentionally omitted to preserve user toggle state
@@ -424,15 +529,51 @@ export class AiModelModel {
};
clearRemoteModels(providerId: string) {
- return this.db
- .delete(aiModels)
- .where(
- and(
- eq(aiModels.providerId, providerId),
- eq(aiModels.source, AiModelSourceEnum.Remote),
- this.scopeWhere(),
- ),
- );
+ return this.db.transaction(async (trx) => {
+ // A remote row that accumulated a personal reasoning preference
+ // (remote-first order: fetched, then the user saved an Effort default β€”
+ // see updateModelReasoningConfig) must not lose it. Demote the row to a
+ // preference-only shape (strip remote metadata, drop the remote source)
+ // instead of deleting it.
+ await trx
+ .update(aiModels)
+ .set({
+ abilities: null,
+ config: sql`jsonb_build_object('chatConfig', ${aiModels.config} -> 'chatConfig')`,
+ contextWindowTokens: null,
+ description: null,
+ displayName: null,
+ enabled: null,
+ organization: null,
+ parameters: null,
+ pricing: null,
+ releasedAt: null,
+ settings: null,
+ sort: null,
+ source: null,
+ updatedAt: new Date(),
+ })
+ .where(
+ and(
+ eq(aiModels.providerId, providerId),
+ eq(aiModels.source, AiModelSourceEnum.Remote),
+ // NOT `config -> 'chatConfig' IS NOT NULL`: jsonb null tests in
+ // WHERE clauses crash the production engine (see jsonbNullTest)
+ sql`COALESCE(${aiModels.config} ->> 'chatConfig', '') <> ''`,
+ this.scopeWhere(),
+ ),
+ );
+
+ return trx
+ .delete(aiModels)
+ .where(
+ and(
+ eq(aiModels.providerId, providerId),
+ eq(aiModels.source, AiModelSourceEnum.Remote),
+ this.scopeWhere(),
+ ),
+ );
+ });
}
clearModelsByProvider(providerId: string) {
diff --git a/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts b/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts
index 3db0eb436a7..d067f78b756 100644
--- a/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts
+++ b/packages/database/src/repositories/aiInfra/__tests__/getAiProviderModelList.test.ts
@@ -86,6 +86,32 @@ describe('AiInfraRepos', () => {
);
});
+ it('should hide preference-only shells without a builtin card', async () => {
+ const mockUserModels = [
+ // Preference-only shell (e.g. left after clearRemoteModels demoted a
+ // remote row with a saved reasoning preference): no identity at all
+ {
+ config: { chatConfig: { reasoningEffort: 'high' } },
+ id: 'gone-remote-model',
+ type: 'chat' as const,
+ },
+ // Preference row for a builtin model keeps merging onto its card
+ {
+ config: { chatConfig: { reasoningEffort: 'low' } },
+ id: 'gpt-4',
+ type: 'chat' as const,
+ },
+ ] as AiProviderModelListItem[];
+ const mockBuiltinModels = [{ displayName: 'GPT-4', enabled: true, id: 'gpt-4' }];
+
+ vi.spyOn(repo.aiModelModel, 'getModelListByProviderId').mockResolvedValue(mockUserModels);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue(mockBuiltinModels);
+
+ const result = await repo.getAiProviderModelList('openai');
+
+ expect(result.map((m) => m.id)).toEqual(['gpt-4']);
+ });
+
it('should use builtin models', async () => {
const providerId = 'ai21';
diff --git a/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts b/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
index 863fef9fac6..2ce4e38df62 100644
--- a/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
+++ b/packages/database/src/repositories/aiInfra/__tests__/getEnabledModels.test.ts
@@ -94,6 +94,56 @@ describe('AiInfraRepos', () => {
);
});
+ it('should keep the builtin deploymentName when the user row only stores chatConfig', async () => {
+ const mockProviders = [
+ {
+ enabled: true,
+ id: 'volcengine',
+ name: 'Volcengine',
+ sort: 1,
+ source: 'builtin' as const,
+ },
+ ];
+
+ // Preference-only row created by updateModelReasoningConfig: its config
+ // holds just chatConfig, but must not shadow the builtin card's
+ // config.deploymentName that findDeploymentName relies on
+ const mockAllModels = [
+ {
+ config: { chatConfig: { reasoningEffort: 'high' } },
+ id: 'deepseek-v4',
+ providerId: 'volcengine',
+ type: 'chat' as const,
+ },
+ ] as any[];
+
+ vi.spyOn(repo, 'getAiProviderList').mockResolvedValue(mockProviders);
+ vi.spyOn(repo.aiModelModel, 'getAllModels').mockResolvedValue(mockAllModels);
+ vi.spyOn(repo as any, 'fetchBuiltinModels').mockResolvedValue([
+ {
+ abilities: {},
+ config: { deploymentName: 'deepseek-v4-250801' },
+ displayName: 'DeepSeek V4',
+ enabled: true,
+ id: 'deepseek-v4',
+ type: 'chat' as const,
+ },
+ ]);
+
+ const result = await repo.getEnabledModels();
+
+ expect(result).toContainEqual(
+ expect.objectContaining({
+ config: {
+ chatConfig: { reasoningEffort: 'high' },
+ deploymentName: 'deepseek-v4-250801',
+ },
+ id: 'deepseek-v4',
+ providerId: 'volcengine',
+ }),
+ );
+ });
+
it('should handle case when user model not found', async () => {
const mockProviders = [
{ enabled: true, id: 'openai', name: 'OpenAI', sort: 1, source: 'builtin' as const },
diff --git a/packages/database/src/repositories/aiInfra/index.ts b/packages/database/src/repositories/aiInfra/index.ts
index 9434e98fc3a..0440f76a7df 100644
--- a/packages/database/src/repositories/aiInfra/index.ts
+++ b/packages/database/src/repositories/aiInfra/index.ts
@@ -165,7 +165,11 @@ export class AiInfraRepos {
const mergedModel = {
...item,
abilities: !isEmpty(user.abilities) ? user.abilities : item.abilities || {},
- config: !isEmpty(user.config) ? user.config : item.config,
+ // Deep-merge instead of replacing: a user row holding only a
+ // reasoning preference (`config.chatConfig`) must not drop the
+ // builtin card's `config.deploymentName` (Azure/Volcengine-style
+ // providers resolve the request model from it)
+ config: !isEmpty(user.config) ? merge(item.config || {}, user.config) : item.config,
contextWindowTokens:
typeof user.contextWindowTokens === 'number'
? user.contextWindowTokens
@@ -374,11 +378,20 @@ export class AiInfraRepos {
}
// Filter out DB residual models that are no longer in the builtin list for branding provider
+ const builtinIds = new Set(defaultModels.map((m) => m.id));
if (providerId === BRANDING_PROVIDER) {
- const builtinIds = new Set(defaultModels.map((m) => m.id));
mergedModel = mergedModel.filter((m) => builtinIds.has(m.id));
}
+ // Preference-only shells β€” rows persisting just `config.chatConfig` (created
+ // by updateModelReasoningConfig, or left behind when clearRemoteModels
+ // demotes a remote row with a saved reasoning preference) β€” carry no
+ // user-visible identity. With no builtin card to merge onto, hide the
+ // ID-only entry instead of listing a ghost disabled model.
+ mergedModel = mergedModel.filter(
+ (m) => builtinIds.has(m.id) || !AiModelModel.isPreferenceOnlyRow(m),
+ );
+
mergedModel = mergedModel.filter(isAiModelVisible);
let list = mergedModel.map((m) =>
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d041ae6b4ba..285a691eb69 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -970,6 +970,18 @@ export default {
'rag.referenceChunks': 'Reference Source',
'rag.userQuery.actions.delete': 'Delete Query Rewrite',
'rag.userQuery.actions.regenerate': 'Regenerate Query',
+ 'reasoningEffort.levels.high': 'High',
+ 'reasoningEffort.levels.low': 'Low',
+ 'reasoningEffort.levels.max': 'Max',
+ 'reasoningEffort.levels.medium': 'Medium',
+ 'reasoningEffort.levels.minimal': 'Minimal',
+ 'reasoningEffort.levels.no_think': 'Off',
+ 'reasoningEffort.levels.none': 'Off',
+ 'reasoningEffort.levels.xhigh': 'Extra High',
+ 'reasoningEffort.mode.pro': 'Pro',
+ 'reasoningEffort.mode.standard': 'Standard',
+ 'reasoningEffort.title': 'Reasoning Effort',
+ 'reasoningEffort.updateFailed': 'Failed to update reasoning effort, please try again',
'regenerate': 'Regenerate',
'roleAndArchive': 'Agent Profile & History',
'memory.effort.desc': 'Control how aggressively the AI retrieves and updates memory.',
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index f8ba3948084..1cce49f5c45 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -314,7 +314,133 @@ export interface AIBaseModelCard {
export const isAiModelVisible = (model: { visible?: boolean }) => model.visible !== false;
+/**
+ * User-level default reasoning params for a model instance (userId + providerId + modelId),
+ * stored under `ai_models.config.chatConfig` on the personal-scope row (workspaceId IS NULL).
+ *
+ * Field names intentionally mirror the same-named `LobeAgentChatConfig` fields so
+ * `applyModelExtendParams` can consume this object unchanged. Deliberately narrow:
+ * only the reasoning-effort family + `reasoningMode` β€” other extend params
+ * (textVerbosity, thinking budget/level, ...) remain agent-scoped for now.
+ */
+export interface AiModelReasoningConfig {
+ codexMaxReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';
+ deepseekV4ReasoningEffort?: 'none' | 'high' | 'max';
+ effort?: 'low' | 'medium' | 'high' | 'max';
+ glm5_2ReasoningEffort?: 'high' | 'max';
+ gpt5_1ReasoningEffort?: 'none' | 'low' | 'medium' | 'high';
+ gpt5_2ProReasoningEffort?: 'medium' | 'high' | 'xhigh';
+ gpt5_2ReasoningEffort?: 'none' | 'low' | 'medium' | 'high' | 'xhigh';
+ gpt5_6ReasoningEffort?: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
+ gpt5ReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
+ grok4_3ReasoningEffort?: 'none' | 'low' | 'medium' | 'high';
+ grok4_5ReasoningEffort?: 'low' | 'medium' | 'high';
+ grok4_20ReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';
+ hy3ReasoningEffort?: 'no_think' | 'low' | 'high';
+ kimiK3ReasoningEffort?: 'low' | 'high' | 'max';
+ opus47Effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
+ reasoningEffort?: 'low' | 'medium' | 'high';
+ reasoningMode?: 'standard' | 'pro';
+ ring2_6ReasoningEffort?: 'high' | 'xhigh';
+ step3_5ReasoningEffort?: 'low' | 'high';
+}
+
+export const AiModelReasoningConfigSchema = z.object({
+ codexMaxReasoningEffort: z.enum(['low', 'medium', 'high', 'xhigh']).optional(),
+ deepseekV4ReasoningEffort: z.enum(['none', 'high', 'max']).optional(),
+ effort: z.enum(['low', 'medium', 'high', 'max']).optional(),
+ glm5_2ReasoningEffort: z.enum(['high', 'max']).optional(),
+ gpt5_1ReasoningEffort: z.enum(['none', 'low', 'medium', 'high']).optional(),
+ gpt5_2ProReasoningEffort: z.enum(['medium', 'high', 'xhigh']).optional(),
+ gpt5_2ReasoningEffort: z.enum(['none', 'low', 'medium', 'high', 'xhigh']).optional(),
+ gpt5_6ReasoningEffort: z.enum(['none', 'low', 'medium', 'high', 'xhigh', 'max']).optional(),
+ gpt5ReasoningEffort: z.enum(['minimal', 'low', 'medium', 'high']).optional(),
+ grok4_3ReasoningEffort: z.enum(['none', 'low', 'medium', 'high']).optional(),
+ grok4_5ReasoningEffort: z.enum(['low', 'medium', 'high']).optional(),
+ grok4_20ReasoningEffort: z.enum(['low', 'medium', 'high', 'xhigh']).optional(),
+ hy3ReasoningEffort: z.enum(['no_think', 'low', 'high']).optional(),
+ kimiK3ReasoningEffort: z.enum(['low', 'high', 'max']).optional(),
+ opus47Effort: z.enum(['low', 'medium', 'high', 'xhigh', 'max']).optional(),
+ reasoningEffort: z.enum(['low', 'medium', 'high']).optional(),
+ reasoningMode: z.enum(['standard', 'pro']).optional(),
+ ring2_6ReasoningEffort: z.enum(['high', 'xhigh']).optional(),
+ step3_5ReasoningEffort: z.enum(['low', 'high']).optional(),
+});
+
+/**
+ * The extend params covered by AiModelReasoningConfig. Each entry is both an
+ * ExtendParamsType value and the AiModelReasoningConfig key it reads from β€”
+ * used to filter which model-instance defaults a given model actually supports.
+ */
+export const MODEL_REASONING_EXTEND_PARAMS = Object.keys(
+ AiModelReasoningConfigSchema.shape,
+) as (keyof AiModelReasoningConfig)[];
+
+/**
+ * Ordered level list per reasoning param (low β†’ high), mirroring the
+ * ControlsForm slider level definitions so select-style controls can render
+ * the same choices.
+ */
+export const MODEL_REASONING_PARAM_LEVELS: {
+ [K in keyof AiModelReasoningConfig]-?: readonly NonNullable<AiModelReasoningConfig[K]>[];
+} = {
+ codexMaxReasoningEffort: ['low', 'medium', 'high', 'xhigh'],
+ deepseekV4ReasoningEffort: ['none', 'high', 'max'],
+ effort: ['low', 'medium', 'high', 'max'],
+ glm5_2ReasoningEffort: ['high', 'max'],
+ gpt5_1ReasoningEffort: ['none', 'low', 'medium', 'high'],
+ gpt5_2ProReasoningEffort: ['medium', 'high', 'xhigh'],
+ gpt5_2ReasoningEffort: ['none', 'low', 'medium', 'high', 'xhigh'],
+ gpt5_6ReasoningEffort: ['none', 'low', 'medium', 'high', 'xhigh', 'max'],
+ gpt5ReasoningEffort: ['minimal', 'low', 'medium', 'high'],
+ grok4_3ReasoningEffort: ['none', 'low', 'medium', 'high'],
+ grok4_5ReasoningEffort: ['low', 'medium', 'high'],
+ grok4_20ReasoningEffort: ['low', 'medium', 'high', 'xhigh'],
+ hy3ReasoningEffort: ['no_think', 'low', 'high'],
+ kimiK3ReasoningEffort: ['low', 'high', 'max'],
+ opus47Effort: ['low', 'medium', 'high', 'xhigh', 'max'],
+ reasoningEffort: ['low', 'medium', 'high'],
+ reasoningMode: ['standard', 'pro'],
+ ring2_6ReasoningEffort: ['high', 'xhigh'],
+ step3_5ReasoningEffort: ['low', 'high'],
+};
+
+/**
+ * Fallback level shown when the user has not saved a model-instance value,
+ * mirroring each ControlsForm slider's defaultValue (gpt5_2ReasoningEffort is
+ * model-dependent there: 'medium' for gpt-5.5, 'none' otherwise).
+ */
+export const MODEL_REASONING_PARAM_DEFAULTS: {
+ [K in keyof AiModelReasoningConfig]-?: NonNullable<AiModelReasoningConfig[K]>;
+} = {
+ codexMaxReasoningEffort: 'medium',
+ deepseekV4ReasoningEffort: 'high',
+ effort: 'high',
+ glm5_2ReasoningEffort: 'max',
+ gpt5_1ReasoningEffort: 'none',
+ gpt5_2ProReasoningEffort: 'medium',
+ gpt5_2ReasoningEffort: 'none',
+ gpt5_6ReasoningEffort: 'medium',
+ gpt5ReasoningEffort: 'medium',
+ grok4_3ReasoningEffort: 'low',
+ grok4_5ReasoningEffort: 'high',
+ grok4_20ReasoningEffort: 'medium',
+ hy3ReasoningEffort: 'high',
+ kimiK3ReasoningEffort: 'max',
+ opus47Effort: 'high',
+ reasoningEffort: 'medium',
+ reasoningMode: 'standard',
+ ring2_6ReasoningEffort: 'high',
+ step3_5ReasoningEffort: 'low',
+};
+
export interface AiModelConfig {
+ /**
+ * User-level default reasoning params for this model instance; see
+ * AiModelReasoningConfig. Not synced from remote model lists.
+ */
+ chatConfig?: AiModelReasoningConfig;
+
/**
* used in azure and volcengine
*/
@@ -569,6 +695,9 @@ export interface AiProviderModelListItem {
// Update
export const UpdateAiModelSchema = z.object({
abilities: AiModelAbilitiesSchema.optional(),
+ // NOTE: `chatConfig` is deliberately NOT accepted here β€” model-instance reasoning
+ // defaults go through the dedicated updateAiModelReasoningConfig procedure so the
+ // generic update path can never carry (and thus never stomp) that namespace.
config: z
.object({
deploymentName: z.string().optional(),
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index 7dac521dc6c..5e42d63b700 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -92,6 +92,8 @@ export {
type ModelExtendParams,
resolveDefaultEnableAdaptiveThinkingForModel,
resolveDefaultThinkingLevelForModel,
+ resolveEffectiveReasoningChatConfig,
+ type ResolveEffectiveReasoningChatConfigContext,
} from './utils/modelExtendParams';
export { isDeepSeekThinkingEligibleModel, isDeepSeekV4FamilyModel } from './utils/modelParse';
export { isAutoGeneratedImageModelId } from './utils/postProcessModelList';
diff --git a/packages/model-runtime/src/utils/modelExtendParams.test.ts b/packages/model-runtime/src/utils/modelExtendParams.test.ts
index 589ac64d53a..2bc5f75ea2f 100644
--- a/packages/model-runtime/src/utils/modelExtendParams.test.ts
+++ b/packages/model-runtime/src/utils/modelExtendParams.test.ts
@@ -5,6 +5,7 @@ import {
applyModelExtendParams,
resolveDefaultEnableAdaptiveThinkingForModel,
resolveDefaultThinkingLevelForModel,
+ resolveEffectiveReasoningChatConfig,
} from './modelExtendParams';
const chatConfig = (config: Partial<LobeAgentChatConfig> = {}): LobeAgentChatConfig =>
@@ -262,3 +263,71 @@ describe('resolveDefaultThinkingLevelForModel', () => {
expect(resolveDefaultThinkingLevelForModel('gemini-3.1-flash-lite')).toBe('minimal');
});
});
+
+describe('resolveEffectiveReasoningChatConfig', () => {
+ it('should strip migrated reasoning fields from the agent chat config', () => {
+ const result = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig({
+ gpt5_6ReasoningEffort: 'max',
+ reasoningEffort: 'high',
+ reasoningMode: 'pro',
+ textVerbosity: 'low',
+ thinkingBudget: 2048,
+ }),
+ });
+
+ // Legacy agent-level values must not leak into the payload path
+ expect(result.gpt5_6ReasoningEffort).toBeUndefined();
+ expect(result.reasoningEffort).toBeUndefined();
+ expect(result.reasoningMode).toBeUndefined();
+ // Non-migrated params stay agent-scoped
+ expect(result.textVerbosity).toBe('low');
+ expect(result.thinkingBudget).toBe(2048);
+ });
+
+ it('should apply model-instance defaults over the stripped agent config', () => {
+ const result = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig({ gpt5_6ReasoningEffort: 'low' }),
+ modelReasoningConfig: { gpt5_6ReasoningEffort: 'xhigh', reasoningMode: 'pro' },
+ });
+
+ expect(result.gpt5_6ReasoningEffort).toBe('xhigh');
+ expect(result.reasoningMode).toBe('pro');
+ });
+
+ it('should let explicit sub-agent overrides win over model-instance defaults', () => {
+ const result = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig(),
+ modelReasoningConfig: { gpt5_6ReasoningEffort: 'xhigh', reasoningMode: 'pro' },
+ subAgentReasoningOverrides: { gpt5_6ReasoningEffort: 'low' },
+ });
+
+ expect(result.gpt5_6ReasoningEffort).toBe('low');
+ // Fields the sub-agent did not set still fall back to the model-instance value
+ expect(result.reasoningMode).toBe('pro');
+ });
+
+ it('should ignore non-reasoning fields smuggled into the override objects', () => {
+ const result = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig({ textVerbosity: 'high' }),
+ modelReasoningConfig: { textVerbosity: 'low' } as never,
+ });
+
+ expect(result.textVerbosity).toBe('high');
+ });
+
+ it('should produce the same extend params on both runtimes for a stale agent value', () => {
+ const effective = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig({ gpt5_6ReasoningEffort: 'low' }),
+ modelReasoningConfig: { gpt5_6ReasoningEffort: 'max' },
+ });
+
+ const params = applyModelExtendParams({
+ chatConfig: effective,
+ extendParams: ['reasoningMode', 'gpt5_6ReasoningEffort', 'textVerbosity'],
+ model: 'gpt-5.6-sol',
+ });
+
+ expect(params.reasoning_effort).toBe('max');
+ });
+});
diff --git a/packages/model-runtime/src/utils/modelExtendParams.ts b/packages/model-runtime/src/utils/modelExtendParams.ts
index 61b3670834d..54fdfeb4294 100644
--- a/packages/model-runtime/src/utils/modelExtendParams.ts
+++ b/packages/model-runtime/src/utils/modelExtendParams.ts
@@ -1,8 +1,62 @@
import type { LobeAgentChatConfig } from '@lobechat/types';
-import type { ExtendParamsType } from 'model-bank';
+import type { AiModelReasoningConfig, ExtendParamsType } from 'model-bank';
+import { MODEL_REASONING_EXTEND_PARAMS } from 'model-bank';
import { isAdaptiveThinkingDefaultOnModel } from '../providers/anthropic/modelId';
+export interface ResolveEffectiveReasoningChatConfigContext {
+ /**
+ * The agent's chat config. Migrated reasoning fields (effort family +
+ * reasoningMode) are stripped β€” since the model-instance migration they are
+ * user-level per-model settings, and legacy agent values must not leak into
+ * outbound payloads.
+ */
+ agentChatConfig: LobeAgentChatConfig;
+ /**
+ * The user's per-model-instance defaults (`ai_models.config.chatConfig`,
+ * personal scope).
+ */
+ modelReasoningConfig?: AiModelReasoningConfig | null;
+ /**
+ * Explicit sub-agent overrides (`agencyConfig.subagent.chatConfig`). Unlike the
+ * main agent, a sub-agent's reasoning fields stay honored when the user set them,
+ * winning over the model-instance defaults.
+ */
+ subAgentReasoningOverrides?: AiModelReasoningConfig | null;
+}
+
+const pickReasoningFields = (config?: AiModelReasoningConfig | null): AiModelReasoningConfig => {
+ const result: AiModelReasoningConfig = {};
+ if (!config) return result;
+
+ for (const key of MODEL_REASONING_EXTEND_PARAMS) {
+ const value = config[key];
+ if (value !== undefined) (result as Record<string, unknown>)[key] = value;
+ }
+
+ return result;
+};
+
+/**
+ * Builds the effective chat config for reasoning-param resolution, shared by the
+ * client chat service and the server agent runtime so both produce the same
+ * payload: agent config without the migrated fields ← model-instance defaults ←
+ * explicit sub-agent overrides. Field-level model support is still enforced by
+ * `applyModelExtendParams`, which only reads fields the model card declares.
+ */
+export const resolveEffectiveReasoningChatConfig = (
+ ctx: ResolveEffectiveReasoningChatConfigContext,
+): LobeAgentChatConfig => {
+ const base: LobeAgentChatConfig = { ...ctx.agentChatConfig };
+ for (const key of MODEL_REASONING_EXTEND_PARAMS) delete base[key];
+
+ return {
+ ...base,
+ ...pickReasoningFields(ctx.modelReasoningConfig),
+ ...pickReasoningFields(ctx.subAgentReasoningOverrides),
+ };
+};
+
/**
* Extended parameters for model runtime
*/
@@ -28,10 +82,7 @@ export interface ModelExtendParams {
}
type ThinkingLevelExtendParam =
- | 'thinkingLevel'
- | 'thinkingLevel2'
- | 'thinkingLevel3'
- | 'thinkingLevel4';
+ 'thinkingLevel' | 'thinkingLevel2' | 'thinkingLevel3' | 'thinkingLevel4';
type ThinkingLevelValue = NonNullable<LobeAgentChatConfig['thinkingLevel']>;
diff --git a/src/features/ChatInput/ActionBar/Effort/Controls.tsx b/src/features/ChatInput/ActionBar/Effort/Controls.tsx
new file mode 100644
index 00000000000..5a6897a2a42
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Effort/Controls.tsx
@@ -0,0 +1,138 @@
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Divider } from 'antd';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { CheckIcon } from 'lucide-react';
+import type { AiModelReasoningConfig } from 'model-bank';
+import { MODEL_REASONING_PARAM_DEFAULTS, MODEL_REASONING_PARAM_LEVELS } from 'model-bank';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+const styles = createStaticStyles(({ css }) => ({
+ active: css`
+ background: ${cssVar.colorFillTertiary};
+ `,
+ check: css`
+ font-size: 16px;
+ color: ${cssVar.colorPrimary};
+ `,
+ label: css`
+ font-size: 14px;
+ color: ${cssVar.colorText};
+ `,
+ option: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border: none;
+ border-radius: ${cssVar.borderRadius};
+
+ text-align: start;
+
+ background: transparent;
+
+ transition: background-color 0.2s;
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+}));
+
+interface OptionProps {
+ active: boolean;
+ label: string;
+ onClick: () => void;
+}
+
+// A real <button> so keyboard-only and screen-reader users can focus each
+// level and toggle it with Enter/Space
+const Option = memo<OptionProps>(({ active, label, onClick }) => (
+ <button
+ aria-pressed={active}
+ className={cx(styles.option, active && styles.active)}
+ type={'button'}
+ onClick={onClick}
+ >
+ <span className={styles.label}>{label}</span>
+ {active && <Icon className={styles.check} icon={CheckIcon} />}
+ </button>
+));
+
+interface ControlsProps {
+ model: string;
+ provider: string;
+}
+
+const Controls = memo<ControlsProps>(({ model, provider }) => {
+ const { t } = useTranslation('chat');
+
+ const reasoningParams = useAiInfraStore(
+ aiModelSelectors.modelReasoningExtendParams(model, provider),
+ isEqual,
+ );
+ const config = useAiInfraStore(aiModelSelectors.modelReasoningConfig(model, provider), isEqual);
+ const updating = useAiInfraStore(
+ aiModelSelectors.isModelReasoningConfigUpdating(model, provider),
+ );
+ const updateModelReasoningConfig = useAiInfraStore((s) => s.updateModelReasoningConfig);
+
+ // modelReasoningExtendParams only returns MODEL_REASONING_EXTEND_PARAMS
+ // entries, so the narrowing cast is safe
+ const effortKey = reasoningParams.find((param) => param !== 'reasoningMode') as
+ Exclude<keyof AiModelReasoningConfig, 'reasoningMode'> | undefined;
+ const hasReasoningMode = reasoningParams.includes('reasoningMode');
+
+ // Keep the same model-dependent fallback as the ControlsForm slider
+ const effortDefault = effortKey
+ ? effortKey === 'gpt5_2ReasoningEffort' && model === 'gpt-5.5'
+ ? 'medium'
+ : MODEL_REASONING_PARAM_DEFAULTS[effortKey]
+ : undefined;
+ const effortValue = (effortKey && config?.[effortKey]) ?? effortDefault;
+ const modeValue = config?.reasoningMode ?? MODEL_REASONING_PARAM_DEFAULTS.reasoningMode;
+
+ const handleSelect = async (patch: AiModelReasoningConfig) => {
+ if (updating) return;
+ // failure already rolls back and toasts inside the store action
+ await updateModelReasoningConfig(model, provider, patch).catch(() => {});
+ };
+
+ return (
+ <Flexbox gap={4} style={{ opacity: updating ? 0.6 : undefined }}>
+ {effortKey &&
+ MODEL_REASONING_PARAM_LEVELS[effortKey].map((level) => (
+ <Option
+ active={effortValue === level}
+ key={level}
+ label={t(`reasoningEffort.levels.${level}`)}
+ onClick={() => handleSelect({ [effortKey]: level })}
+ />
+ ))}
+ {hasReasoningMode && (
+ <>
+ {effortKey && <Divider style={{ margin: 0 }} />}
+ {MODEL_REASONING_PARAM_LEVELS.reasoningMode.map((mode) => (
+ <Option
+ active={modeValue === mode}
+ key={mode}
+ label={t(`reasoningEffort.mode.${mode}`)}
+ onClick={() => handleSelect({ reasoningMode: mode })}
+ />
+ ))}
+ </>
+ )}
+ </Flexbox>
+ );
+});
+
+export default Controls;
diff --git a/src/features/ChatInput/ActionBar/Effort/index.tsx b/src/features/ChatInput/ActionBar/Effort/index.tsx
new file mode 100644
index 00000000000..95f9a4a221b
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Effort/index.tsx
@@ -0,0 +1,60 @@
+import { GaugeIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+import { ChatInputAction } from '../components/ChatInputAction';
+import Controls from './Controls';
+
+const EffortAction = memo<{ model: string; provider: string }>(({ model, provider }) => {
+ const { t } = useTranslation('chat');
+
+ // The saved model-instance reasoning defaults are fetched by
+ // ReasoningConfigLoader (mounted in ChatInputProvider), so the dropdown and
+ // the send pipeline (modelParamsResolver) read the same store value.
+ return (
+ <ChatInputAction
+ icon={GaugeIcon}
+ showTooltip={false}
+ title={t('reasoningEffort.title')}
+ popover={{
+ content: <Controls model={model} provider={provider} />,
+ maxWidth: 280,
+ minWidth: 200,
+ placement: 'topLeft',
+ styles: {
+ content: {
+ padding: 4,
+ },
+ },
+ }}
+ />
+ );
+});
+
+/**
+ * Reasoning-effort select for the chat input. The value is a user-level
+ * model-instance setting (userId + providerId + modelId, personal scope) β€”
+ * not part of the agent's chatConfig β€” so it follows the user across agents.
+ *
+ * Mounted on every chat surface; renders nothing unless the effective model
+ * declares a reasoning-effort family extend param (or reasoningMode).
+ */
+const Effort = memo(() => {
+ const agentId = useAgentId();
+ const { model, provider } = useEffectiveModel(agentId);
+ const hasReasoningParams = useAiInfraStore(
+ aiModelSelectors.isModelHasReasoningExtendParams(model, provider),
+ );
+
+ if (!hasReasoningParams) return null;
+
+ return <EffortAction model={model} provider={provider} />;
+});
+
+Effort.displayName = 'Effort';
+
+export default Effort;
diff --git a/src/features/ChatInput/ActionBar/Params/Controls.tsx b/src/features/ChatInput/ActionBar/Params/Controls.tsx
index 5c2a50585f7..fe6c48f57bc 100644
--- a/src/features/ChatInput/ActionBar/Params/Controls.tsx
+++ b/src/features/ChatInput/ActionBar/Params/Controls.tsx
@@ -3,6 +3,7 @@ import {
resolveSubAgentChatConfig,
resolveSubAgentModel,
} from '@lobechat/const';
+import { resolveEffectiveReasoningChatConfig } from '@lobechat/model-runtime/utils/modelExtendParams';
import { Flexbox, Icon, SliderWithInput, TextArea } from '@lobehub/ui';
import { Select, Switch } from '@lobehub/ui/base-ui';
import { Form as AntdForm } from 'antd';
@@ -10,6 +11,7 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';
import { debounce } from 'es-toolkit/compat';
import isEqual from 'fast-deep-equal';
import { ChevronDown, ChevronUp } from 'lucide-react';
+import { MODEL_REASONING_EXTEND_PARAMS } from 'model-bank';
import type { ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -418,6 +420,8 @@ const PARAM_CONFIG = {
const PARAM_ORDER: ParamKey[] = ['temperature', 'top_p', 'frequency_penalty', 'presence_penalty'];
+const REASONING_PARAMS_SET = new Set<string>(MODEL_REASONING_EXTEND_PARAMS);
+
const ADVANCED_OPEN_STORAGE_KEY = 'lobehub-chat-input-params-advanced-open';
const MODEL_CONFIG_OPEN_STORAGE_KEY = 'lobehub-chat-input-params-model-config-open';
@@ -533,7 +537,21 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
(s) => agentByIdSelectors.getAgentConfigById(agentId)(s) || DEFAULT_AGENT_CONFIG,
isEqual,
);
- const { disabledParams, hasModelConfig, model, provider } = useParamsModelConfig(agentId);
+ const { disabledParams, model, provider } = useParamsModelConfig(agentId);
+ const modelExtendParamsList = useAiInfraStore(
+ aiModelSelectors.modelExtendParams(model, provider),
+ isEqual,
+ );
+ // Reasoning fields are user-level model-instance settings now (edited via
+ // the ChatInput Effort control); only non-reasoning params warrant this section
+ const hasModelConfig = (modelExtendParamsList ?? []).some(
+ (param) => !REASONING_PARAMS_SET.has(param),
+ );
+ // Same reason: hide the legacy Advanced raw `params.reasoning_effort` for
+ // those models β€” the send path strips it in favor of the instance config
+ const hasReasoningExtendParams = (modelExtendParamsList ?? []).some((param) =>
+ REASONING_PARAMS_SET.has(param),
+ );
const enableAgentMode = useAgentStore(agentByIdSelectors.getAgentEnableModeById(agentId));
const [form] = AntdForm.useForm();
const [advancedOpen, setAdvancedOpen] = useState(() => getStoredOpen(ADVANCED_OPEN_STORAGE_KEY));
@@ -628,12 +646,41 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
const subAgentModelValue = config.agencyConfig?.subagent?.model
? resolveSubAgentModel(config.agencyConfig.subagent)
: undefined;
- // Effective sub-agent chatConfig: the parent's chatConfig with the
- // `agencyConfig.subagent.chatConfig` overrides merged on top β€” the exact
- // config the sub-agent run uses, so the controls below are WYSIWYG.
+ const rawSubAgentChatConfig = config.agencyConfig?.subagent?.chatConfig;
+ const subAgentHasReasoningParams = useAiInfraStore(
+ aiModelSelectors.isModelHasReasoningExtendParams(
+ subAgentModelValue?.model || '',
+ subAgentModelValue?.provider || '',
+ ),
+ );
+ const subAgentModelReasoningConfig = useAiInfraStore(
+ aiModelSelectors.modelReasoningConfig(
+ subAgentModelValue?.model || '',
+ subAgentModelValue?.provider || '',
+ ),
+ isEqual,
+ );
+ // Warm the overridden sub-agent model's saved reasoning defaults β€”
+ // ReasoningConfigLoader only fetches the main effective model
+ const useFetchAiModelReasoningConfig = useAiInfraStore((s) => s.useFetchAiModelReasoningConfig);
+ useFetchAiModelReasoningConfig(
+ subAgentHasReasoningParams ? subAgentModelValue?.model : undefined,
+ subAgentHasReasoningParams ? subAgentModelValue?.provider : undefined,
+ );
+ // Effective sub-agent chatConfig, built the same way the run does
+ // (resolveModelExtendParams / serverCallLlmContextHints): merged parent
+ // config with the migrated reasoning fields stripped ← model-instance
+ // defaults ← explicit sub-agent overrides. Without the same sanitizing, a
+ // legacy parent `chatConfig.reasoningEffort` would show a value the run
+ // ignores, so the controls below stay WYSIWYG.
const subAgentChatConfig = useMemo(
- () => resolveSubAgentChatConfig(config.chatConfig, config.agencyConfig?.subagent?.chatConfig),
- [config.chatConfig, config.agencyConfig?.subagent?.chatConfig],
+ () =>
+ resolveEffectiveReasoningChatConfig({
+ agentChatConfig: resolveSubAgentChatConfig(config.chatConfig, rawSubAgentChatConfig) ?? {},
+ modelReasoningConfig: subAgentModelReasoningConfig,
+ subAgentReasoningOverrides: rawSubAgentChatConfig,
+ }),
+ [config.chatConfig, rawSubAgentChatConfig, subAgentModelReasoningConfig],
);
const subAgentHasModelConfig = useAiInfraStore(
aiModelSelectors.isModelHasExtendParams(
@@ -944,6 +991,7 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
{modelConfigOpen && (
<div className={styles.modelConfigSection}>
<ControlsForm
+ hideReasoningParams
disabled={!canCreate}
model={model}
provider={provider}
@@ -1031,44 +1079,51 @@ const Controls = memo<ControlsProps>(({ setUpdating, updating, variant = 'popove
/>
)}
</ControlRow>
- <ControlRow
- tag="reasoning_effort"
- title={t('settingModel.reasoningEffort.title')}
- tooltip={t('settingModel.reasoningEffort.desc')}
- action={
- <Switch
- checked={Boolean(enableReasoningEffort)}
- size={'small'}
- onChange={(checked) => {
- if (checked && typeof reasoningEffortValue !== 'string') {
- form.setFieldValue(['params', 'reasoning_effort'], 'medium');
+ {!hasReasoningExtendParams && (
+ <ControlRow
+ tag="reasoning_effort"
+ title={t('settingModel.reasoningEffort.title')}
+ tooltip={t('settingModel.reasoningEffort.desc')}
+ action={
+ <Switch
+ checked={Boolean(enableReasoningEffort)}
+ size={'small'}
+ onChange={(checked) => {
+ if (checked && typeof reasoningEffortValue !== 'string') {
+ form.setFieldValue(['params', 'reasoning_effort'], 'medium');
+ }
+ handleFieldChange(['chatConfig', 'enableReasoningEffort'], checked);
+ }}
+ />
+ }
+ >
+ {enableReasoningEffort && (
+ <Select
+ size={'small'}
+ style={{ width: '100%' }}
+ options={[
+ { label: t('settingModel.reasoningEffort.options.low'), value: 'low' },
+ {
+ label: t('settingModel.reasoningEffort.options.medium'),
+ value: 'medium',
+ },
+ {
+ label: t('settingModel.reasoningEffort.options.high'),
+ value: 'high',
+ },
+ ]}
+ value={
+ typeof reasoningEffortValue === 'string'
+ ? reasoningEffortValue
+ : 'medium'
}
- handleFieldChange(['chatConfig', 'enableReasoningEffort'], checked);
- }}
- />
- }
- >
- {enableReasoningEffort && (
- <Select
- size={'small'}
- style={{ width: '100%' }}
- options={[
- { label: t('settingModel.reasoningEffort.options.low'), value: 'low' },
- {
- label: t('settingModel.reasoningEffort.options.medium'),
- value: 'medium',
- },
- { label: t('settingModel.reasoningEffort.options.high'), value: 'high' },
- ]}
- value={
- typeof reasoningEffortValue === 'string' ? reasoningEffortValue : 'medium'
- }
- onChange={(value) => {
- handleFieldChange(['params', 'reasoning_effort'], value);
- }}
- />
- )}
- </ControlRow>
+ onChange={(value) => {
+ handleFieldChange(['params', 'reasoning_effort'], value);
+ }}
+ />
+ )}
+ </ControlRow>
+ )}
</div>
)}
</>
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index 1dc3bec3616..52b217919e2 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -57,6 +57,7 @@ import { ChatInputAction } from '../components/ChatInputAction';
import { useControls as useKnowledgeControls } from '../Knowledge/useControls';
import { useMemoryEnabled } from '../Memory/useMemoryEnabled';
import { useControls as useToolsControls } from '../Tools/useControls';
+import { useEffortMenuItem } from './useEffortMenuItem';
const hotArea = css`
&::before {
@@ -399,6 +400,8 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
[updateAgentChatConfig],
);
+ const effortItem = useEffortMenuItem();
+
const handleToggleParams = useCallback(() => {
close();
if (isParamsPanelActive) {
@@ -658,6 +661,10 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
},
// Agent Gateway directly below the formatting toolbar.
...gatewayItem,
+ // Reasoning intensity β€” a personal per-model preference, so it is NOT
+ // gated on canConfigureResource; hidden only when the model has no
+ // reasoning extend params (the hook returns []).
+ ...effortItem,
// Advanced parameter settings β€” only when resources can be configured.
...(canConfigureResource
? [
@@ -742,6 +749,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
activeSearchOption,
activeTopicId,
canConfigureResource,
+ effortItem,
enableTopicAcceptance,
tVerify,
canUploadImage,
diff --git a/src/features/ChatInput/ActionBar/Plus/useEffortMenuItem.tsx b/src/features/ChatInput/ActionBar/Plus/useEffortMenuItem.tsx
new file mode 100644
index 00000000000..d0e60dcc312
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Plus/useEffortMenuItem.tsx
@@ -0,0 +1,174 @@
+import { Icon } from '@lobehub/ui';
+import { css, cssVar, cx } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { CheckIcon, ChevronRight, GaugeIcon } from 'lucide-react';
+import type { AiModelReasoningConfig } from 'model-bank';
+import { MODEL_REASONING_PARAM_DEFAULTS, MODEL_REASONING_PARAM_LEVELS } from 'model-bank';
+import type { ReactNode } from 'react';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from '../../hooks/useAgentId';
+import { useEffectiveModel } from '../../hooks/useEffectiveModel';
+import { type ActionDropdownMenuItems } from '../components/ActionDropdown';
+
+const activeLabel = css`
+ display: flex;
+ gap: 16px;
+ align-items: center;
+ justify-content: space-between;
+
+ width: 100%;
+
+ color: inherit;
+`;
+
+const currentValue = css`
+ overflow: hidden;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+`;
+
+/**
+ * "Reasoning intensity" submenu for the "+" menu. The value is a user-level
+ * model-instance setting (userId + providerId + modelId, personal scope) β€” not
+ * agent resource configuration β€” so it must stay visible regardless of
+ * `canConfigureResource`. Returns no items unless the effective model declares
+ * a reasoning-effort family extend param (or reasoningMode).
+ *
+ * The saved model-instance defaults are fetched by ReasoningConfigLoader
+ * (mounted in ChatInputProvider), so this submenu and the send pipeline
+ * (modelParamsResolver) read the same store value.
+ */
+export const useEffortMenuItem = (): ActionDropdownMenuItems => {
+ const { t } = useTranslation('chat');
+ const agentId = useAgentId();
+ const { model, provider } = useEffectiveModel(agentId);
+
+ const hasReasoningParams = useAiInfraStore(
+ aiModelSelectors.isModelHasReasoningExtendParams(model, provider),
+ );
+ const reasoningParams = useAiInfraStore(
+ aiModelSelectors.modelReasoningExtendParams(model, provider),
+ isEqual,
+ );
+ const config = useAiInfraStore(aiModelSelectors.modelReasoningConfig(model, provider), isEqual);
+ const updating = useAiInfraStore(
+ aiModelSelectors.isModelReasoningConfigUpdating(model, provider),
+ );
+ const updateModelReasoningConfig = useAiInfraStore((s) => s.updateModelReasoningConfig);
+
+ return useMemo<ActionDropdownMenuItems>(() => {
+ if (!hasReasoningParams) return [];
+
+ // modelReasoningExtendParams only returns MODEL_REASONING_EXTEND_PARAMS
+ // entries, so the narrowing cast is safe
+ const effortKey = reasoningParams.find((param) => param !== 'reasoningMode') as
+ Exclude<keyof AiModelReasoningConfig, 'reasoningMode'> | undefined;
+ const hasReasoningMode = reasoningParams.includes('reasoningMode');
+
+ // Keep the same model-dependent fallback as the ControlsForm slider
+ const effortDefault = effortKey
+ ? effortKey === 'gpt5_2ReasoningEffort' && model === 'gpt-5.5'
+ ? 'medium'
+ : MODEL_REASONING_PARAM_DEFAULTS[effortKey]
+ : undefined;
+ const effortValue = (effortKey && config?.[effortKey]) ?? effortDefault;
+ const modeValue = config?.reasoningMode ?? MODEL_REASONING_PARAM_DEFAULTS.reasoningMode;
+
+ const handleSelect = async (patch: AiModelReasoningConfig) => {
+ if (updating) return;
+ // failure already rolls back and toasts inside the store action
+ await updateModelReasoningConfig(model, provider, patch).catch(() => {});
+ };
+
+ const renderActive = (label: ReactNode, active: boolean) =>
+ active ? (
+ <div className={cx(activeLabel)}>
+ <span>{label}</span>
+ <Icon icon={CheckIcon} size={14} />
+ </div>
+ ) : (
+ label
+ );
+
+ const effortChildren: ActionDropdownMenuItems = effortKey
+ ? MODEL_REASONING_PARAM_LEVELS[effortKey].map((level) => ({
+ key: `effort-${level}`,
+ label: renderActive(t(`reasoningEffort.levels.${level}`), effortValue === level),
+ onClick: () => handleSelect({ [effortKey]: level }),
+ }))
+ : [];
+
+ const modeChildren: ActionDropdownMenuItems = hasReasoningMode
+ ? MODEL_REASONING_PARAM_LEVELS.reasoningMode.map((mode) => ({
+ key: `effort-mode-${mode}`,
+ label: renderActive(t(`reasoningEffort.mode.${mode}`), modeValue === mode),
+ onClick: () => handleSelect({ reasoningMode: mode }),
+ }))
+ : [];
+
+ // When the model exposes both params, wrap each list in a labeled group so
+ // users can tell "effort level" and "reasoning mode" are two independent
+ // settings (each carries its own check mark). A single-param submenu stays
+ // flat β€” the parent row already names it.
+ const children: ActionDropdownMenuItems =
+ effortChildren.length > 0 && modeChildren.length > 0
+ ? [
+ {
+ children: effortChildren,
+ key: 'effort-level-group',
+ label: t('reasoningEffort.title'),
+ type: 'group' as const,
+ },
+ { type: 'divider' as const },
+ {
+ children: modeChildren,
+ key: 'effort-mode-group',
+ label: t('extendParams.reasoningMode.title'),
+ type: 'group' as const,
+ },
+ ]
+ : [...effortChildren, ...modeChildren];
+
+ // Current value shown on the collapsed row (Codex-style): effort level,
+ // plus the reasoning mode when the model exposes both.
+ const currentText = [
+ effortKey && effortValue ? t(`reasoningEffort.levels.${effortValue}`) : undefined,
+ hasReasoningMode ? t(`reasoningEffort.mode.${modeValue}`) : undefined,
+ ]
+ .filter(Boolean)
+ .join(' Β· ');
+
+ return [
+ {
+ children,
+ // Trailing chevron (replaces base-ui's default triangle submenu arrow,
+ // which is hidden via the .lobe-submenu-chevron rule in ActionDropdown).
+ extra: <Icon className="lobe-submenu-chevron" icon={ChevronRight} size={16} />,
+ icon: GaugeIcon,
+ key: 'effort',
+ label: (
+ <div className={cx(activeLabel)}>
+ <span>{t('reasoningEffort.title')}</span>
+ {currentText && <span className={cx(currentValue)}>{currentText}</span>}
+ </div>
+ ),
+ } as ActionDropdownMenuItems[number],
+ ];
+ }, [
+ config,
+ hasReasoningParams,
+ model,
+ provider,
+ reasoningParams,
+ t,
+ updateModelReasoningConfig,
+ updating,
+ ]);
+};
diff --git a/src/features/ChatInput/ActionBar/config.ts b/src/features/ChatInput/ActionBar/config.ts
index ac95b39dd8d..0e13a157df3 100644
--- a/src/features/ChatInput/ActionBar/config.ts
+++ b/src/features/ChatInput/ActionBar/config.ts
@@ -1,5 +1,6 @@
import AgentMode from './AgentMode';
import Clear from './Clear';
+import Effort from './Effort';
import History from './History';
import Memory from './Memory';
import Mention from './Mention';
@@ -18,6 +19,7 @@ export const actionMap = {
agentMode: AgentMode,
clear: Clear,
contextWindow: ContextWindow,
+ effort: Effort,
fileUpload: Upload,
plus: Plus,
history: History,
diff --git a/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts b/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts
index 054c22c33ad..ca39e892f85 100644
--- a/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts
+++ b/src/features/ChatInput/ActionBar/filterChatOnlyActions.ts
@@ -3,6 +3,8 @@ import type { ActionKey, ActionKeys } from './config';
const CHAT_ONLY_ACTIONS = new Set<ActionKey>([
'agentMode',
'clear',
+ // personal per-model reasoning preference, not resource configuration
+ 'effort',
'fileUpload',
'history',
'mention',
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index c7115c819c9..19d615f5452 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -2,6 +2,7 @@ import { useEditor } from '@lobehub/editor/react';
import { type ReactNode } from 'react';
import { memo, useRef } from 'react';
+import ReasoningConfigLoader from './ReasoningConfigLoader';
import { createStore, Provider } from './store';
import { DEFAULT_CHAT_INPUT_FEATURE } from './store/initialState';
import { type StoreUpdaterProps } from './StoreUpdater';
@@ -77,6 +78,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
onMarkdownContentChange={onMarkdownContentChange}
onSend={onSend}
/>
+ <ReasoningConfigLoader />
{children}
</Provider>
);
diff --git a/src/features/ChatInput/ReasoningConfigLoader.tsx b/src/features/ChatInput/ReasoningConfigLoader.tsx
new file mode 100644
index 00000000000..f87062702e8
--- /dev/null
+++ b/src/features/ChatInput/ReasoningConfigLoader.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { memo } from 'react';
+
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+
+import { useAgentId } from './hooks/useAgentId';
+import { useEffectiveModel } from './hooks/useEffectiveModel';
+
+const Fetcher = memo<{ model: string; provider: string }>(({ model, provider }) => {
+ const useFetchAiModelReasoningConfig = useAiInfraStore((s) => s.useFetchAiModelReasoningConfig);
+ useFetchAiModelReasoningConfig(model, provider);
+
+ return null;
+});
+
+Fetcher.displayName = 'ReasoningConfigFetcher';
+
+/**
+ * Headless loader that warms the user's model-instance reasoning config in the
+ * aiInfra store for every chat surface. The send pipeline
+ * (`resolveModelExtendParams`) reads that cache synchronously, and not every
+ * surface mounts the Effort toolbar action (e.g. Home input, PageEditor
+ * copilot), so the fetch cannot live only inside the action.
+ */
+const ReasoningConfigLoader = memo(() => {
+ const agentId = useAgentId();
+ const { model, provider } = useEffectiveModel(agentId);
+ const hasReasoningParams = useAiInfraStore(
+ aiModelSelectors.isModelHasReasoningExtendParams(model, provider),
+ );
+
+ if (!hasReasoningParams) return null;
+
+ return <Fetcher model={model} provider={provider} />;
+});
+
+ReasoningConfigLoader.displayName = 'ReasoningConfigLoader';
+
+export default ReasoningConfigLoader;
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
index 93e0db078cc..b2071e013da 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ControlsForm.tsx
@@ -4,6 +4,7 @@ import { Flexbox, Form } from '@lobehub/ui';
import { Switch } from '@lobehub/ui/base-ui';
import { Form as AntdForm } from 'antd';
import isEqual from 'fast-deep-equal';
+import { MODEL_REASONING_EXTEND_PARAMS } from 'model-bank';
import type { ReactNode } from 'react';
import { memo, useEffect, useMemo } from 'react';
import { Trans, useTranslation } from 'react-i18next';
@@ -54,6 +55,8 @@ import ThinkingLevel4Slider from './ThinkingLevel4Slider';
import ThinkingLevelSlider from './ThinkingLevelSlider';
import ThinkingSlider from './ThinkingSlider';
+const REASONING_PARAMS_SET = new Set<string>(MODEL_REASONING_EXTEND_PARAMS);
+
interface ControlsFormProps {
/**
* Override the config source. Defaults to the agent's own chatConfig; the
@@ -61,6 +64,14 @@ interface ControlsFormProps {
*/
chatConfig?: LobeAgentChatConfig;
disabled?: boolean;
+ /**
+ * Hide the reasoning-effort family + reasoningMode controls. The main-agent
+ * params panel sets this: those fields migrated to user-level model-instance
+ * settings edited via the ChatInput Effort control, so agent chatConfig
+ * writes here would be ignored at send time. The sub-agent panel keeps them
+ * as explicit per-sub-agent overrides.
+ */
+ hideReasoningParams?: boolean;
model?: string;
/**
* Override the write sink. Defaults to updating the agent's chatConfig; the
@@ -95,6 +106,7 @@ const ControlsForm = memo<ControlsFormProps>(
({
chatConfig: chatConfigProp,
disabled,
+ hideReasoningParams,
model: modelProp,
onChatConfigChange,
onUpdatingChange,
@@ -566,6 +578,7 @@ const ControlsForm = memo<ControlsFormProps>(
variant={'borderless'}
items={
(modelExtendParams || [])
+ .filter((item: any) => !(hideReasoningParams && REASONING_PARAMS_SET.has(item)))
.map((item: any) => items.find((i) => i.name === item))
.filter(Boolean) as FormItemProps[]
}
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/ReasoningModeSegmented.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/ReasoningModeSegmented.tsx
index da79a02625c..105f9a9ae9d 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/ReasoningModeSegmented.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/ReasoningModeSegmented.tsx
@@ -1,20 +1,16 @@
-import type { SegmentedOptions } from '@lobehub/ui/base-ui';
import { Segmented } from '@lobehub/ui/base-ui';
+import { MODEL_REASONING_PARAM_LEVELS } from 'model-bank';
import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
import { useUpdateAgentConfig } from '@/features/ChatInput/hooks/useUpdateAgentConfig';
import { useAgentStore } from '@/store/agent';
import { chatConfigByIdSelectors } from '@/store/agent/selectors';
-const REASONING_MODES = ['standard', 'pro'] as const;
+const REASONING_MODES = MODEL_REASONING_PARAM_LEVELS.reasoningMode;
type ReasoningMode = (typeof REASONING_MODES)[number];
-const REASONING_MODE_OPTIONS = [
- { label: 'Standard', value: 'standard' },
- { label: 'Pro', value: 'pro' },
-] satisfies SegmentedOptions<ReasoningMode>;
-
export interface ReasoningModeSegmentedProps {
defaultValue?: ReasoningMode;
disabled?: boolean;
@@ -28,18 +24,25 @@ const ReasoningModeSegmentedInner = memo<{
id?: string;
onChange: (value: ReasoningMode) => void;
value: ReasoningMode;
-}>(({ disabled, id, onChange, value }) => (
- <Segmented<ReasoningMode>
- block
- disabled={disabled}
- id={id}
- options={REASONING_MODE_OPTIONS}
- size={'small'}
- style={{ maxWidth: 240 }}
- value={value}
- onChange={onChange}
- />
-));
+}>(({ disabled, id, onChange, value }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Segmented<ReasoningMode>
+ block
+ disabled={disabled}
+ id={id}
+ size={'small'}
+ style={{ maxWidth: 240 }}
+ value={value}
+ options={REASONING_MODES.map((mode) => ({
+ label: t(`reasoningEffort.mode.${mode}`),
+ value: mode,
+ }))}
+ onChange={onChange}
+ />
+ );
+});
const ReasoningModeSegmentedWithStore = memo<{
defaultValue: ReasoningMode;
diff --git a/src/features/PageEditor/Copilot/CopilotModelSelect.tsx b/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
index da125041d31..c70082b280d 100644
--- a/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
+++ b/src/features/PageEditor/Copilot/CopilotModelSelect.tsx
@@ -49,8 +49,10 @@ const CopilotModelSelect = memo(() => {
]);
const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));
+ // Reasoning-family params are hidden below (hideReasoningParams), so gate on
+ // the non-reasoning subset to avoid an empty popover for reasoning-only models
const isModelHasExtendParams = useAiInfraStore(
- aiModelSelectors.isModelHasExtendParams(model, provider),
+ aiModelSelectors.isModelHasNonReasoningExtendParams(model, provider),
);
const displayName = enabledModel?.displayName || model;
@@ -89,7 +91,7 @@ const CopilotModelSelect = memo(() => {
</ModelSwitchPanel>
{isModelHasExtendParams && (
<ActionPopover
- content={<ControlsForm disabled={!canEdit} />}
+ content={<ControlsForm hideReasoningParams disabled={!canEdit} />}
minWidth={350}
open={settingsOpen}
placement={'topRight'}
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index e2240a78006..5f1d7c196b4 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -350,6 +350,11 @@ export const aiModelKeys = {
offset,
]),
list: def('aiModel:list', (provider: string | undefined) => ['aiModel:list', provider]),
+ reasoningConfig: def('aiModel:reasoningConfig', (provider: string, model: string) => [
+ 'aiModel:reasoningConfig',
+ provider,
+ model,
+ ]),
};
// ---- image generation ---------------------------------------------------
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
index d8caa060e57..0ac489a069e 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/index.tsx
@@ -39,6 +39,8 @@ const MainChatInput = memo(() => {
? promptTransformRightActions
: contextWindowRightActions;
+ // Reasoning effort lives inside the "+" menu (Plus β†’ ζŽ¨η†εΌΊεΊ¦) rather than as
+ // a standalone action β€” reviewer feedback on the LOBE-12599 acceptance.
const leftActions: ActionKeys[] = useMemo(() => ['model', 'plus'], []);
return (
diff --git a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
index 72669c44e71..5f589cfc905 100644
--- a/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/MainChatInput/index.tsx
@@ -10,6 +10,7 @@ import { useSendMenuItems } from './useSendMenuItems';
const leftActions: ActionKeys[] = [
'model',
+ 'effort',
'search',
'memory',
'fileUpload',
diff --git a/src/services/aiModel/index.ts b/src/services/aiModel/index.ts
index 42c76c55515..3a068cce14d 100644
--- a/src/services/aiModel/index.ts
+++ b/src/services/aiModel/index.ts
@@ -1,4 +1,5 @@
import {
+ type AiModelReasoningConfig,
type AiModelSortMap,
type AiModelType,
type AiProviderModelListItem,
@@ -42,6 +43,21 @@ export class AiModelService {
return lambdaClient.aiModel.updateAiModel.mutate({ id, providerId, value });
};
+ getAiModelReasoningConfig = async (
+ id: string,
+ providerId: string,
+ ): Promise<AiModelReasoningConfig | undefined> => {
+ return lambdaClient.aiModel.getAiModelReasoningConfig.query({ id, providerId });
+ };
+
+ updateAiModelReasoningConfig = async (
+ id: string,
+ providerId: string,
+ value: AiModelReasoningConfig,
+ ) => {
+ return lambdaClient.aiModel.updateAiModelReasoningConfig.mutate({ id, providerId, value });
+ };
+
batchUpdateAiModels = async (id: string, models: AiProviderModelListItem[]) => {
return lambdaClient.aiModel.batchUpdateAiModels.mutate({ id, models });
};
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 2eb40a048ed..5087dcef941 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -501,6 +501,11 @@ describe('ChatService', () => {
// Mock aiModelSelectors for extend params support
vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValue(() => true);
vi.spyOn(aiModelSelectors, 'modelExtendParams').mockReturnValue(() => ['reasoningEffort']);
+ // The user-level model-instance config supplies the effort; the legacy
+ // agent chatConfig value below must be ignored by the resolver
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ reasoningEffort: 'high',
+ }));
await chatService.createAssistantMessage({
messages,
@@ -508,7 +513,7 @@ describe('ChatService', () => {
provider: 'test-provider',
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'test-model', provider: 'test-provider' },
- chatConfig: { reasoningEffort: 'high' },
+ chatConfig: { reasoningEffort: 'low' },
}),
});
@@ -530,6 +535,11 @@ describe('ChatService', () => {
vi.spyOn(aiModelSelectors, 'modelExtendParams').mockReturnValue(() => [
'deepseekV4ReasoningEffort',
]);
+ // Reasoning fields are user-level model-instance settings now β€” agent
+ // chatConfig values are ignored by the resolver
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ deepseekV4ReasoningEffort: 'max',
+ }));
await chatService.createAssistantMessage({
messages,
@@ -537,7 +547,6 @@ describe('ChatService', () => {
provider: 'deepseek',
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'deepseek-v4-pro', provider: 'deepseek' },
- chatConfig: { deepseekV4ReasoningEffort: 'max' },
}),
});
@@ -562,6 +571,9 @@ describe('ChatService', () => {
vi.spyOn(aiModelSelectors, 'modelExtendParams').mockReturnValue(() => [
'deepseekV4ReasoningEffort',
]);
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ deepseekV4ReasoningEffort: 'none',
+ }));
await chatService.createAssistantMessage({
messages,
@@ -569,7 +581,6 @@ describe('ChatService', () => {
provider: 'deepseek',
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'deepseek-v4-pro', provider: 'deepseek' },
- chatConfig: { deepseekV4ReasoningEffort: 'none' },
}),
});
@@ -2075,6 +2086,11 @@ describe('ChatService private methods', () => {
// Mock aiModelSelectors for extend params support
vi.spyOn(aiModelSelectors, 'isModelHasExtendParams').mockReturnValue(() => true);
vi.spyOn(aiModelSelectors, 'modelExtendParams').mockReturnValue(() => ['reasoningEffort']);
+ // The user-level model-instance config supplies the effort; the legacy
+ // agent chatConfig value below must be ignored by the resolver
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ reasoningEffort: 'high',
+ }));
await chatService.createAssistantMessage({
messages,
@@ -2082,7 +2098,7 @@ describe('ChatService private methods', () => {
provider: 'test-provider',
resolvedAgentConfig: createMockResolvedConfig({
agentConfig: { model: 'test-model', provider: 'test-provider' },
- chatConfig: { reasoningEffort: 'high' },
+ chatConfig: { reasoningEffort: 'low' },
}),
});
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 509b8d27753..7fcc5da408b 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -33,7 +33,7 @@ import {
agentChatConfigSelectors,
agentSelectors,
} from '@/store/agent/selectors';
-import { aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
+import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
import { getChatStoreState } from '@/store/chat';
import { getToolStoreState } from '@/store/tool';
import {
@@ -322,12 +322,33 @@ class ChatService {
// ============ 3. process extend params ============ //
+ // Make sure the user's saved model-instance reasoning config is loaded
+ // before the synchronous resolution below β€” after a reload the
+ // ReasoningConfigLoader SWR fetch may still be in flight when the user
+ // sends the first message. No-op once cached; failures fall back to
+ // level defaults.
+ await getAiInfraStoreState().ensureModelReasoningConfig(payload.model, payload.provider!);
+
const extendParams = resolveModelExtendParams({
chatConfig,
model: payload.model,
provider: payload.provider!,
+ subAgentChatConfigOverride: resolvedAgentConfig.subAgentChatConfigOverride,
});
+ // For models governed by the reasoning extend-params family the user-level
+ // model-instance config is the single source of truth, so drop the legacy
+ // per-agent Advanced `params.reasoning_effort` β€” otherwise a stale agent
+ // value would leak into the payload whenever no instance value overlays it.
+ if (
+ aiModelSelectors.isModelHasReasoningExtendParams(
+ payload.model,
+ payload.provider!,
+ )(getAiInfraStoreState())
+ ) {
+ delete (params as Record<string, unknown>).reasoning_effort;
+ }
+
return {
options: { ...options, agentId: targetAgentId, topicId },
params: {
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index aba1d618555..fae78807383 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -135,6 +135,13 @@ export interface ResolvedAgentConfig {
plugins: string[];
/** The agent's slug (if builtin) */
slug?: string;
+ /**
+ * The raw sub-agent chatConfig override (`agencyConfig.subagent.chatConfig`).
+ * `chatConfig` above already has it merged in for non-migrated fields; this
+ * copy lets the model-params resolver re-apply the user's explicit sub-agent
+ * reasoning choices on top of the model-instance defaults.
+ */
+ subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
/** Pre-generated tools array (populated by internal_createAgentState, undefined means tools disabled) */
tools?: ChatCompletionTool[];
}
diff --git a/src/services/chat/mecha/modelParamsResolver.test.ts b/src/services/chat/mecha/modelParamsResolver.test.ts
index b6983a96cde..9572548abe3 100644
--- a/src/services/chat/mecha/modelParamsResolver.test.ts
+++ b/src/services/chat/mecha/modelParamsResolver.test.ts
@@ -6,6 +6,19 @@ import * as aiModelSelectors from '@/store/aiInfra/slices/aiModel/selectors';
import { resolveModelExtendParams } from './modelParamsResolver';
+/**
+ * Since the model-instance migration, effort-family fields + reasoningMode come
+ * from the user's per-model config (aiInfra store), not agent chatConfig.
+ */
+const mockModelReasoningConfig = (config: Record<string, unknown> | undefined) =>
+ vi.spyOn(aiModelSelectors.aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => config);
+
+// Reset per test so a mock from one test never leaks into the next (this file
+// only restores mocks inside the first describe block)
+beforeEach(() => {
+ mockModelReasoningConfig(undefined);
+});
+
describe('resolveModelExtendParams', () => {
const mockAiInfraStoreState = { someState: true };
const createChatConfig = (config: Partial<LobeAgentChatConfig> = {}): LobeAgentChatConfig => ({
@@ -300,10 +313,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set reasoning_effort when supported and configured', () => {
+ mockModelReasoningConfig({ reasoningEffort: 'medium' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- reasoningEffort: 'medium',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-4',
provider: 'openai',
});
@@ -333,10 +346,10 @@ describe('resolveModelExtendParams', () => {
});
it('should enable thinking and set reasoning_effort for DeepSeek when configured with a reasoning level', () => {
+ mockModelReasoningConfig({ deepseekV4ReasoningEffort: 'high' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- deepseekV4ReasoningEffort: 'high',
- } as any,
+ chatConfig: {} as any,
model: 'deepseek-v4-pro',
provider: 'deepseek',
});
@@ -350,10 +363,10 @@ describe('resolveModelExtendParams', () => {
});
it('should disable thinking and omit reasoning_effort for DeepSeek when configured as none', () => {
+ mockModelReasoningConfig({ deepseekV4ReasoningEffort: 'none' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- deepseekV4ReasoningEffort: 'none',
- } as any,
+ chatConfig: {} as any,
model: 'deepseek-v4-pro',
provider: 'deepseek',
});
@@ -377,10 +390,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set reasoning_effort for gpt5 variant', () => {
+ mockModelReasoningConfig({ gpt5ReasoningEffort: 'high' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5ReasoningEffort: 'high',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5',
provider: 'openai',
});
@@ -400,10 +413,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set reasoning_effort for gpt5.1 variant', () => {
+ mockModelReasoningConfig({ gpt5_1ReasoningEffort: 'low' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_1ReasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.1',
provider: 'openai',
});
@@ -423,10 +436,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set reasoning_effort for gpt5.2 variant', () => {
+ mockModelReasoningConfig({ gpt5_2ReasoningEffort: 'medium' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_2ReasoningEffort: 'medium',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.2',
provider: 'openai',
});
@@ -446,10 +459,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set max reasoning_effort for GPT-5.6', () => {
+ mockModelReasoningConfig({ gpt5_6ReasoningEffort: 'max' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_6ReasoningEffort: 'max',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.6-sol',
provider: 'openai',
});
@@ -469,8 +482,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set Pro mode for GPT-5.6', () => {
+ mockModelReasoningConfig({ reasoningMode: 'pro' });
+
const result = resolveModelExtendParams({
- chatConfig: { reasoningMode: 'pro' },
+ chatConfig: {},
model: 'gpt-5.6-sol',
provider: 'openai',
});
@@ -479,8 +494,10 @@ describe('resolveModelExtendParams', () => {
});
it('should omit the default Standard mode', () => {
+ mockModelReasoningConfig({ reasoningMode: 'standard' });
+
const result = resolveModelExtendParams({
- chatConfig: { reasoningMode: 'standard' },
+ chatConfig: {},
model: 'gpt-5.6-sol',
provider: 'openai',
});
@@ -500,10 +517,10 @@ describe('resolveModelExtendParams', () => {
});
it('should set reasoning_effort for gpt5.2-pro variant', () => {
+ mockModelReasoningConfig({ gpt5_2ProReasoningEffort: 'high' });
+
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_2ProReasoningEffort: 'high',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.2-pro',
provider: 'openai',
});
@@ -1049,13 +1066,13 @@ describe('multiple params combination', () => {
'urlContext',
'disableContextCaching',
]);
+ mockModelReasoningConfig({ reasoningEffort: 'high' });
const result = resolveModelExtendParams({
chatConfig: {
disableContextCaching: true,
enableReasoning: true,
reasoningBudgetToken: 3072,
- reasoningEffort: 'high',
textVerbosity: 'concise',
urlContext: true,
} as any,
@@ -1249,12 +1266,10 @@ describe('parameter precedence and conflicts', () => {
'deepseekV4ReasoningEffort',
'reasoningEffort',
]);
+ mockModelReasoningConfig({ deepseekV4ReasoningEffort: 'high', reasoningEffort: 'low' });
const result = resolveModelExtendParams({
- chatConfig: {
- deepseekV4ReasoningEffort: 'high',
- reasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'deepseek-v4-pro',
provider: 'deepseek',
});
@@ -1273,13 +1288,14 @@ describe('parameter precedence and conflicts', () => {
'reasoningEffort',
'gpt5ReasoningEffort',
]);
+ mockModelReasoningConfig({
+ deepseekV4ReasoningEffort: 'none',
+ gpt5ReasoningEffort: 'medium',
+ reasoningEffort: 'high',
+ });
const result = resolveModelExtendParams({
- chatConfig: {
- deepseekV4ReasoningEffort: 'none',
- gpt5ReasoningEffort: 'medium',
- reasoningEffort: 'high',
- } as any,
+ chatConfig: {} as any,
model: 'deepseek-v4-pro',
provider: 'deepseek',
});
@@ -1296,11 +1312,10 @@ describe('parameter precedence and conflicts', () => {
'deepseekV4ReasoningEffort',
'reasoningEffort',
]);
+ mockModelReasoningConfig({ reasoningEffort: 'low' });
const result = resolveModelExtendParams({
- chatConfig: {
- reasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'deepseek-v4-pro',
provider: 'deepseek',
});
@@ -1316,13 +1331,14 @@ describe('parameter precedence and conflicts', () => {
'gpt5ReasoningEffort',
'gpt5_1ReasoningEffort',
]);
+ mockModelReasoningConfig({
+ gpt5_1ReasoningEffort: 'high',
+ gpt5ReasoningEffort: 'medium',
+ reasoningEffort: 'low',
+ });
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_1ReasoningEffort: 'high',
- gpt5ReasoningEffort: 'medium',
- reasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.1',
provider: 'openai',
});
@@ -1338,14 +1354,15 @@ describe('parameter precedence and conflicts', () => {
'gpt5_2ReasoningEffort',
'gpt5_2ProReasoningEffort',
]);
+ mockModelReasoningConfig({
+ gpt5_2ProReasoningEffort: undefined,
+ gpt5_2ReasoningEffort: 'medium',
+ gpt5ReasoningEffort: undefined,
+ reasoningEffort: 'low',
+ });
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_2ProReasoningEffort: undefined,
- gpt5_2ReasoningEffort: 'medium',
- gpt5ReasoningEffort: undefined,
- reasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.2',
provider: 'openai',
});
@@ -1359,12 +1376,10 @@ describe('parameter precedence and conflicts', () => {
'reasoningEffort',
'gpt5_2ProReasoningEffort',
]);
+ mockModelReasoningConfig({ gpt5_2ProReasoningEffort: 'high', reasoningEffort: 'low' });
const result = resolveModelExtendParams({
- chatConfig: {
- gpt5_2ProReasoningEffort: 'high',
- reasoningEffort: 'low',
- } as any,
+ chatConfig: {} as any,
model: 'gpt-5.2-pro',
provider: 'openai',
});
@@ -1479,11 +1494,10 @@ describe('parameter precedence and conflicts', () => {
vi.spyOn(aiModelSelectors.aiModelSelectors, 'modelExtendParams').mockReturnValue(() => [
'effort',
]);
+ mockModelReasoningConfig({ effort: 'max' });
const result = resolveModelExtendParams({
- chatConfig: {
- effort: 'max',
- } as any,
+ chatConfig: {} as any,
model: 'claude-opus-4-6',
provider: 'anthropic',
});
@@ -1501,14 +1515,13 @@ describe('parameter precedence and conflicts', () => {
'disableContextCaching',
'textVerbosity',
]);
+ mockModelReasoningConfig({ gpt5ReasoningEffort: 'high', reasoningEffort: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
disableContextCaching: true,
enableReasoning: true,
- gpt5ReasoningEffort: 'high',
reasoningBudgetToken: 3000,
- reasoningEffort: 'medium',
textVerbosity: 'verbose',
} as any,
model: 'gpt-5',
@@ -1562,3 +1575,84 @@ describe('parameter precedence and conflicts', () => {
});
});
});
+
+describe('model-instance reasoning config migration', () => {
+ beforeEach(() => {
+ vi.spyOn(aiModelSelectors.aiModelSelectors, 'isModelHasExtendParams').mockReturnValue(
+ () => true,
+ );
+ vi.spyOn(aiModelSelectors.aiModelSelectors, 'modelExtendParams').mockReturnValue(() => [
+ 'reasoningEffort',
+ 'textVerbosity',
+ ]);
+ });
+
+ it('should ignore stale reasoning fields left in agent chatConfig', () => {
+ const result = resolveModelExtendParams({
+ chatConfig: {
+ reasoningEffort: 'high',
+ } as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(result.reasoning_effort).toBeUndefined();
+ });
+
+ it('should apply model-instance config over stale agent chatConfig values', () => {
+ mockModelReasoningConfig({ reasoningEffort: 'low' });
+
+ const result = resolveModelExtendParams({
+ chatConfig: {
+ reasoningEffort: 'high',
+ textVerbosity: 'concise',
+ } as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ // reasoning comes from the model-instance config; non-reasoning chatConfig
+ // fields (textVerbosity) still apply from the agent chatConfig
+ expect(result.reasoning_effort).toBe('low');
+ expect(result.verbosity).toBe('concise');
+ });
+
+ it('should let explicit sub-agent overrides win over model-instance config', () => {
+ mockModelReasoningConfig({ reasoningEffort: 'low' });
+
+ const result = resolveModelExtendParams({
+ chatConfig: {} as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ subAgentChatConfigOverride: { reasoningEffort: 'high' },
+ });
+
+ expect(result.reasoning_effort).toBe('high');
+ });
+
+ it('should apply sub-agent overrides even without model-instance config', () => {
+ const result = resolveModelExtendParams({
+ chatConfig: {} as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ subAgentChatConfigOverride: { reasoningEffort: 'medium' },
+ });
+
+ expect(result.reasoning_effort).toBe('medium');
+ });
+
+ it('should not pick non-reasoning fields from the sub-agent override', () => {
+ const result = resolveModelExtendParams({
+ chatConfig: {
+ textVerbosity: 'concise',
+ } as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ subAgentChatConfigOverride: { textVerbosity: 'verbose' } as any,
+ });
+
+ // textVerbosity is not a reasoning field, so the override is ignored here
+ // (it is merged into agent chatConfig upstream by resolveSubAgentChatConfig)
+ expect(result.verbosity).toBe('concise');
+ });
+});
diff --git a/src/services/chat/mecha/modelParamsResolver.ts b/src/services/chat/mecha/modelParamsResolver.ts
index 3f69a36f2c3..be613d648db 100644
--- a/src/services/chat/mecha/modelParamsResolver.ts
+++ b/src/services/chat/mecha/modelParamsResolver.ts
@@ -3,6 +3,7 @@ import {
type ModelExtendParams,
resolveDefaultEnableAdaptiveThinkingForModel,
resolveDefaultThinkingLevelForModel,
+ resolveEffectiveReasoningChatConfig,
} from '@lobechat/model-runtime/utils/modelExtendParams';
import type { LobeAgentChatConfig } from '@lobechat/types';
@@ -18,6 +19,11 @@ export interface ModelParamsContext {
chatConfig: LobeAgentChatConfig;
model: string;
provider: string;
+ /**
+ * Raw sub-agent chatConfig override; explicit reasoning fields set here win
+ * over the user's model-instance defaults.
+ */
+ subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
}
/**
@@ -26,9 +32,13 @@ export interface ModelParamsContext {
* Looks up the model's supported `extendParams` from the aiInfra store, then delegates the
* actual resolution to the shared `applyModelExtendParams` so the client chat service and the
* server-side agent runtime stay in sync.
+ *
+ * Reasoning fields (effort family + reasoningMode) are user-level model-instance settings:
+ * same-named agent chatConfig values are ignored and the personal-scope config from the
+ * aiInfra store applies instead β€” except explicit sub-agent overrides, which stay honored.
*/
export const resolveModelExtendParams = (ctx: ModelParamsContext): ModelExtendParams => {
- const { model, provider, chatConfig } = ctx;
+ const { model, provider, chatConfig, subAgentChatConfigOverride } = ctx;
const aiInfraStoreState = getAiInfraStoreState();
@@ -43,5 +53,15 @@ export const resolveModelExtendParams = (ctx: ModelParamsContext): ModelExtendPa
const modelExtendParams = aiModelSelectors.modelExtendParams(model, provider)(aiInfraStoreState);
- return applyModelExtendParams({ chatConfig, extendParams: modelExtendParams, model });
+ const effectiveChatConfig = resolveEffectiveReasoningChatConfig({
+ agentChatConfig: chatConfig,
+ modelReasoningConfig: aiModelSelectors.modelReasoningConfig(model, provider)(aiInfraStoreState),
+ subAgentReasoningOverrides: subAgentChatConfigOverride,
+ });
+
+ return applyModelExtendParams({
+ chatConfig: effectiveChatConfig,
+ extendParams: modelExtendParams,
+ model,
+ });
};
diff --git a/src/store/aiInfra/slices/aiModel/action.test.ts b/src/store/aiInfra/slices/aiModel/action.test.ts
index ef42e89ea2d..62809303c8f 100644
--- a/src/store/aiInfra/slices/aiModel/action.test.ts
+++ b/src/store/aiInfra/slices/aiModel/action.test.ts
@@ -11,6 +11,7 @@ import { aiModelService } from '@/services/aiModel';
import { withSWR } from '~test-utils';
import { useAiInfraStore as useStore } from '../../store';
+import { aiModelSelectors } from './selectors';
vi.mock('zustand/traditional');
@@ -23,7 +24,7 @@ vi.mock('i18next', async (importOriginal) => {
});
vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { warning: vi.fn() },
+ toast: { error: vi.fn(), warning: vi.fn() },
}));
vi.mock('@/libs/swr', async (importOriginal) => {
@@ -44,6 +45,8 @@ beforeEach(() => {
aiModelLoadingIds: [],
aiProviderModelList: [],
isAiModelListInit: false,
+ modelReasoningConfigMap: {},
+ modelReasoningConfigUpdatingKeys: [],
refreshAiProviderRuntimeState: vi.fn(),
});
});
@@ -625,6 +628,195 @@ describe('AiModelAction', () => {
});
});
+ describe('updateModelReasoningConfig', () => {
+ it('should optimistically merge the value and persist it via the service', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'updateAiModelReasoningConfig')
+ .mockResolvedValue(undefined as any);
+
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ // merged with the previous value, not replaced
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ reasoningEffort: 'low',
+ });
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
+ expect(mutate).toHaveBeenCalledWith(['aiModel:reasoningConfig', 'openai', 'gpt-5.2']);
+ });
+
+ it('should clear the updating marker before revalidating', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockResolvedValue(undefined as any);
+
+ // The fetch hook's onSuccess skips writes while the key is marked
+ // updating, so revalidating before the marker clears would discard the
+ // server-merged config (sibling fields preserved by the partial write)
+ const updatingKeysAtMutate: string[][] = [];
+ vi.mocked(mutate).mockImplementationOnce(async () => {
+ updatingKeysAtMutate.push([...useStore.getState().modelReasoningConfigUpdatingKeys]);
+ return undefined as any;
+ });
+
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ expect(updatingKeysAtMutate).toEqual([[]]);
+ });
+
+ it('should rollback the optimistic value and toast on failure', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await expect(async () => {
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+ }).rejects.toThrow('Service error');
+
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ });
+ expect(useStore.getState().modelReasoningConfigUpdatingKeys).toEqual([]);
+ expect(toast.error).toHaveBeenCalledWith(t('reasoningEffort.updateFailed', { ns: 'chat' }));
+ });
+
+ it('should drop the key on failed rollback when it was not cached before', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'updateAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await expect(async () => {
+ await act(async () => {
+ await result.current.updateModelReasoningConfig('gpt-5.2', 'openai', {
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+ }).rejects.toThrow('Service error');
+
+ // A leftover `[key]: undefined` would make ensureModelReasoningConfig
+ // treat the key as cached and never fetch the saved server value
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
+ });
+ });
+
+ describe('ensureModelReasoningConfig', () => {
+ beforeEach(() => {
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => true);
+ // Make the runtime-state warm-up a no-op so tests exercise the fetch logic
+ act(() => {
+ useStore.setState({ isInitAiProviderRuntimeState: true });
+ });
+ });
+
+ it('should skip the fetch for models without reasoning extend params', async () => {
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => false);
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-4o', 'openai');
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ });
+
+ it('should fetch and cache the config when the key is absent', async () => {
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue({ reasoningEffort: 'high' });
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).toHaveBeenCalledWith('gpt-5.2', 'openai');
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'high',
+ });
+ });
+
+ it('should keep the key for an empty config so it is not refetched', async () => {
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi
+ .spyOn(aiModelService, 'getAiModelReasoningConfig')
+ .mockResolvedValue(undefined);
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).toHaveBeenCalledTimes(1);
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(true);
+ });
+
+ it('should not fetch when the config is already cached', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { reasoningEffort: 'low' } },
+ });
+ });
+
+ const { result } = renderHook(() => useStore());
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ await act(async () => {
+ await result.current.ensureModelReasoningConfig('gpt-5.2', 'openai');
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ reasoningEffort: 'low',
+ });
+ });
+
+ it('should swallow fetch failures', async () => {
+ const { result } = renderHook(() => useStore());
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockRejectedValue(
+ new Error('Service error'),
+ );
+
+ await act(async () => {
+ await expect(
+ result.current.ensureModelReasoningConfig('gpt-5.2', 'openai'),
+ ).resolves.toBeUndefined();
+ });
+
+ expect('openai/gpt-5.2' in useStore.getState().modelReasoningConfigMap).toBe(false);
+ });
+ });
+
describe('updateAiModelsConfig', () => {
it('should update model config and refresh list', async () => {
const updateData = {
@@ -673,6 +865,63 @@ describe('AiModelAction', () => {
});
});
+ describe('useFetchAiModelReasoningConfig', () => {
+ it('should fetch the reasoning config and write it to the store map', async () => {
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
+ gpt5_2ReasoningEffort: 'high',
+ });
+
+ const { result } = renderHook(
+ () => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'),
+ { wrapper: withSWR },
+ );
+
+ await waitFor(() => {
+ expect(result.current.data).toEqual({ gpt5_2ReasoningEffort: 'high' });
+ });
+
+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalledWith('gpt-5.2', 'openai');
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+
+ it('should not fetch when model or provider is missing', () => {
+ const serviceSpy = vi.spyOn(aiModelService, 'getAiModelReasoningConfig');
+
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig(undefined, 'openai'), {
+ wrapper: withSWR,
+ });
+
+ expect(serviceSpy).not.toHaveBeenCalled();
+ });
+
+ it('should not clobber an in-flight optimistic value', async () => {
+ act(() => {
+ useStore.setState({
+ modelReasoningConfigMap: { 'openai/gpt-5.2': { gpt5_2ReasoningEffort: 'high' } },
+ modelReasoningConfigUpdatingKeys: ['openai/gpt-5.2'],
+ });
+ });
+
+ vi.spyOn(aiModelService, 'getAiModelReasoningConfig').mockResolvedValue({
+ gpt5_2ReasoningEffort: 'low',
+ });
+
+ renderHook(() => useStore.getState().useFetchAiModelReasoningConfig('gpt-5.2', 'openai'), {
+ wrapper: withSWR,
+ });
+
+ await waitFor(() => {
+ expect(aiModelService.getAiModelReasoningConfig).toHaveBeenCalled();
+ });
+
+ expect(useStore.getState().modelReasoningConfigMap['openai/gpt-5.2']).toEqual({
+ gpt5_2ReasoningEffort: 'high',
+ });
+ });
+ });
+
describe('useFetchAiProviderModels', () => {
it('should fetch provider models and update state', async () => {
const mockModels: AiProviderModelListItem[] = [
diff --git a/src/store/aiInfra/slices/aiModel/action.ts b/src/store/aiInfra/slices/aiModel/action.ts
index 5b5158ea30c..6bfc03e3075 100644
--- a/src/store/aiInfra/slices/aiModel/action.ts
+++ b/src/store/aiInfra/slices/aiModel/action.ts
@@ -2,6 +2,7 @@ import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
import type {
+ AiModelReasoningConfig,
AiModelSortMap,
AiProviderModelListItem,
CreateAiModelParams,
@@ -15,6 +16,8 @@ import { aiModelService } from '@/services/aiModel';
import type { AiInfraStore } from '@/store/aiInfra/store';
import type { StoreSetter } from '@/store/types';
+import { modelReasoningConfigKey } from './initialState';
+import { aiModelSelectors } from './selectors';
import { deduplicateRemoteModels } from './utils';
const MAX_DUPLICATE_MODEL_IDS_IN_WARNING = 3;
@@ -178,6 +181,138 @@ export class AiModelActionImpl {
this.#get().internal_toggleAiModelLoading(params.id, false);
};
+ /**
+ * Optimistically saves the user's per-model-instance reasoning defaults
+ * (personal scope, cross-workspace). Rolls the local value back and surfaces
+ * an error toast when the request fails.
+ */
+ updateModelReasoningConfig = async (
+ id: string,
+ provider: string,
+ value: AiModelReasoningConfig,
+ ): Promise<void> => {
+ const key = modelReasoningConfigKey(provider, id);
+ const previous = this.#get().modelReasoningConfigMap[key];
+
+ this.#set(
+ (state) => ({
+ modelReasoningConfigMap: {
+ ...state.modelReasoningConfigMap,
+ [key]: { ...previous, ...value },
+ },
+ modelReasoningConfigUpdatingKeys: [...state.modelReasoningConfigUpdatingKeys, key],
+ }),
+ false,
+ `updateModelReasoningConfig/optimistic/${key}`,
+ );
+
+ try {
+ await aiModelService.updateAiModelReasoningConfig(id, provider, value);
+ } catch (error) {
+ this.#set(
+ (state) => {
+ const modelReasoningConfigMap = { ...state.modelReasoningConfigMap };
+ // A leftover `[key]: undefined` would read as "cached empty" and stop
+ // ensureModelReasoningConfig from ever fetching the server value
+ if (previous === undefined) delete modelReasoningConfigMap[key];
+ else modelReasoningConfigMap[key] = previous;
+ return { modelReasoningConfigMap };
+ },
+ false,
+ `updateModelReasoningConfig/rollback/${key}`,
+ );
+
+ toast.error(t('reasoningEffort.updateFailed', { ns: 'chat' }));
+ throw error;
+ } finally {
+ this.#set(
+ (state) => ({
+ modelReasoningConfigUpdatingKeys: state.modelReasoningConfigUpdatingKeys.filter(
+ (i) => i !== key,
+ ),
+ }),
+ false,
+ `updateModelReasoningConfig/settled/${key}`,
+ );
+ }
+
+ // Revalidate only AFTER the updating marker is cleared: the server merges
+ // this partial write into previously saved fields, and the fetch hook's
+ // onSuccess skips writes while the key is marked updating β€” revalidating
+ // inside the try block would drop server-preserved sibling fields whenever
+ // the optimistic base (`previous`) had not been fetched yet.
+ await mutate(aiModelKeys.reasoningConfig(provider, id));
+ };
+
+ /**
+ * Best-effort imperative warm-up of the model-instance reasoning config for
+ * non-React callers β€” e.g. the client sub-agent executor, whose override
+ * model may never mount a ChatInput fetch hook. No-op when the key is
+ * already cached or an optimistic update is in flight; fetch failures are
+ * swallowed so the send path falls back to defaults instead of breaking.
+ */
+ ensureModelReasoningConfig = async (id: string, provider: string): Promise<void> => {
+ // Right after a reload the model metadata may still be hydrating β€” settle
+ // it first (bounded, no-op once loaded) so an unknown model isn't mistaken
+ // for "no reasoning params" and skipped.
+ await this.#get().ensureAiProviderRuntimeStateReady();
+
+ // The config only matters for models declaring reasoning-family extend
+ // params (resolveModelExtendParams ignores it otherwise) β€” skip the
+ // blocking round trip for everything else.
+ if (!aiModelSelectors.isModelHasReasoningExtendParams(id, provider)(this.#get())) return;
+
+ const key = modelReasoningConfigKey(provider, id);
+ if (key in this.#get().modelReasoningConfigMap) return;
+
+ try {
+ const data = await aiModelService.getAiModelReasoningConfig(id, provider);
+
+ const state = this.#get();
+ if (state.modelReasoningConfigUpdatingKeys.includes(key)) return;
+ if (key in state.modelReasoningConfigMap) return;
+
+ this.#set(
+ (s) => ({
+ // An empty config keeps the key (value undefined) so repeated calls
+ // don't refetch a model that simply has nothing saved yet
+ modelReasoningConfigMap: { ...s.modelReasoningConfigMap, [key]: data },
+ }),
+ false,
+ `ensureModelReasoningConfig/${key}`,
+ );
+ } catch {
+ // best-effort: resolver falls back to level defaults
+ }
+ };
+
+ useFetchAiModelReasoningConfig = (
+ id: string | undefined,
+ provider: string | undefined,
+ ): SWRResponse<AiModelReasoningConfig | undefined> => {
+ return useClientDataSWR<AiModelReasoningConfig | undefined>(
+ id && provider ? aiModelKeys.reasoningConfig(provider, id) : null,
+ ([, provider, id]) =>
+ aiModelService.getAiModelReasoningConfig(id as string, provider as string),
+ {
+ onSuccess: (data) => {
+ const key = modelReasoningConfigKey(provider!, id!);
+ // Don't clobber an in-flight optimistic value with a stale response
+ if (this.#get().modelReasoningConfigUpdatingKeys.includes(key)) return;
+ if (isEqual(data, this.#get().modelReasoningConfigMap[key])) return;
+
+ this.#set(
+ (state) => ({
+ modelReasoningConfigMap: { ...state.modelReasoningConfigMap, [key]: data },
+ }),
+ false,
+ `useFetchAiModelReasoningConfig/${key}`,
+ );
+ },
+ },
+ );
+ };
+
updateAiModelsConfig = async (
id: string,
providerId: string,
diff --git a/src/store/aiInfra/slices/aiModel/initialState.ts b/src/store/aiInfra/slices/aiModel/initialState.ts
index a786ab30264..ddf5a5a663a 100644
--- a/src/store/aiInfra/slices/aiModel/initialState.ts
+++ b/src/store/aiInfra/slices/aiModel/initialState.ts
@@ -1,10 +1,23 @@
-import { type AiProviderModelListItem, type LobeDefaultAiModelListItem } from 'model-bank';
+import {
+ type AiModelReasoningConfig,
+ type AiProviderModelListItem,
+ type LobeDefaultAiModelListItem,
+} from 'model-bank';
export interface AIModelsState {
aiModelLoadingIds: string[];
aiProviderModelList: AiProviderModelListItem[];
builtinAiModelList: LobeDefaultAiModelListItem[];
isAiModelListInit?: boolean;
+ /**
+ * The user's per-model-instance reasoning defaults, keyed by
+ * `${providerId}/${modelId}` (personal scope, cross-workspace).
+ */
+ modelReasoningConfigMap: Record<string, AiModelReasoningConfig | undefined>;
+ /**
+ * `${providerId}/${modelId}` keys with an in-flight reasoning-config save.
+ */
+ modelReasoningConfigUpdatingKeys: string[];
modelSearchKeyword: string;
}
@@ -12,5 +25,9 @@ export const initialAIModelState: AIModelsState = {
aiModelLoadingIds: [],
aiProviderModelList: [],
builtinAiModelList: [],
+ modelReasoningConfigMap: {},
+ modelReasoningConfigUpdatingKeys: [],
modelSearchKeyword: '',
};
+
+export const modelReasoningConfigKey = (provider: string, model: string) => `${provider}/${model}`;
diff --git a/src/store/aiInfra/slices/aiModel/selectors.test.ts b/src/store/aiInfra/slices/aiModel/selectors.test.ts
index 3a790c41d0c..8700a20c9fe 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.test.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.test.ts
@@ -73,6 +73,8 @@ describe('aiModelSelectors', () => {
aiProviderRuntimeConfig: {},
initAiProviderList: false,
isInitAiProviderRuntimeState: false,
+ modelReasoningConfigMap: {},
+ modelReasoningConfigUpdatingKeys: [],
};
describe('aiProviderChatModelListIds', () => {
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index 95dee1b7361..dbc9238cc0c 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -1,8 +1,12 @@
+import type { ExtendParamsType } from 'model-bank';
+import { MODEL_REASONING_EXTEND_PARAMS } from 'model-bank';
import { AiModelSourceEnum } from 'model-bank/aiModel';
import { type AIProviderStoreState } from '@/store/aiInfra/initialState';
import { ModelSearchImplement } from '@/types/search';
+import { modelReasoningConfigKey } from './initialState';
+
const aiProviderChatModelListIds = (s: AIProviderStoreState) =>
s.aiProviderModelList.filter((item) => item.type === 'chat').map((item) => item.id);
// List
@@ -107,6 +111,44 @@ const modelExtendParams = (id: string, provider: string) => (s: AIProviderStoreS
return model?.settings?.extendParams;
};
+const REASONING_EXTEND_PARAMS_SET = new Set<ExtendParamsType>(MODEL_REASONING_EXTEND_PARAMS);
+
+/**
+ * The subset of the model's extend params covered by the user-level
+ * model-instance reasoning config (effort family + reasoningMode).
+ */
+const modelReasoningExtendParams = (id: string, provider: string) => (s: AIProviderStoreState) =>
+ (modelExtendParams(id, provider)(s) ?? []).filter((param) =>
+ REASONING_EXTEND_PARAMS_SET.has(param),
+ );
+
+const isModelHasReasoningExtendParams =
+ (id: string, provider: string) => (s: AIProviderStoreState) =>
+ modelReasoningExtendParams(id, provider)(s).length > 0;
+
+/**
+ * Whether the model exposes extend params beyond the reasoning family. The
+ * reasoning family is edited through the ChatInput Effort control (user-level
+ * model-instance config), so surfaces rendering a ControlsForm with
+ * `hideReasoningParams` must gate on this instead of `isModelHasExtendParams`,
+ * otherwise a reasoning-only model shows an empty popover.
+ */
+const isModelHasNonReasoningExtendParams =
+ (id: string, provider: string) => (s: AIProviderStoreState) =>
+ (modelExtendParams(id, provider)(s) ?? []).some(
+ (param) => !REASONING_EXTEND_PARAMS_SET.has(param),
+ );
+
+/**
+ * The user's saved per-model-instance reasoning defaults (personal scope).
+ */
+const modelReasoningConfig = (id: string, provider: string) => (s: AIProviderStoreState) =>
+ s.modelReasoningConfigMap?.[modelReasoningConfigKey(provider, id)];
+
+const isModelReasoningConfigUpdating =
+ (id: string, provider: string) => (s: AIProviderStoreState) =>
+ !!s.modelReasoningConfigUpdatingKeys?.includes(modelReasoningConfigKey(provider, id));
+
const modelDisabledParams = (id: string, provider: string) => (s: AIProviderStoreState) => {
const model = getEnabledModelById(id, provider)(s);
@@ -167,7 +209,10 @@ export const aiModelSelectors = {
isModelHasBuiltinSearchConfig,
isModelHasContextWindowToken,
isModelHasExtendParams,
+ isModelHasNonReasoningExtendParams,
+ isModelHasReasoningExtendParams,
isModelLoading,
+ isModelReasoningConfigUpdating,
isModelSupportAudio,
isModelSupportFiles,
isModelSupportImageOutput,
@@ -179,5 +224,7 @@ export const aiModelSelectors = {
modelContextWindowTokens,
modelDisabledParams,
modelExtendParams,
+ modelReasoningConfig,
+ modelReasoningExtendParams,
totalAiProviderModelList,
};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index a6ccfcf7bd7..3fb007631d6 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -206,6 +206,9 @@ export class StreamingExecutorActionImpl {
chatConfig:
resolveSubAgentChatConfig(resolvedAgentConfig.chatConfig, chatConfigOverride) ??
resolvedAgentConfig.chatConfig,
+ // Keep the raw override so the model-params resolver can re-apply
+ // explicit sub-agent reasoning choices over model-instance defaults
+ subAgentChatConfigOverride: chatConfigOverride,
}
: {}),
}
@@ -1040,6 +1043,17 @@ export class StreamingExecutorActionImpl {
const parentAgentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());
const parentEffectiveModel =
topicSelectors.getTopicModelById(topicId)(this.#get()) ?? parentAgentConfig;
+ const subAgentModel = resolveSubAgentModel(
+ parentAgentConfig?.agencyConfig?.subagent,
+ parentEffectiveModel,
+ );
+ // Warm the sub-agent model's user-level reasoning config before the run:
+ // the ChatInput loader only fetches the parent's effective model, while
+ // resolveModelExtendParams reads this cache synchronously mid-run.
+ await getAiInfraStoreState().ensureModelReasoningConfig(
+ subAgentModel.model,
+ subAgentModel.provider,
+ );
const runtimeResult = await this.#get().executeClientAgent({
chatConfigOverride: getSubAgentChatConfigOverride(
parentAgentConfig?.agencyConfig?.subagent,
@@ -1047,10 +1061,7 @@ export class StreamingExecutorActionImpl {
context: subContext,
isSubAgent: true,
messages: subMessages,
- modelOverride: resolveSubAgentModel(
- parentAgentConfig?.agencyConfig?.subagent,
- parentEffectiveModel,
- ),
+ modelOverride: subAgentModel,
operationId: taskOperationId,
parentMessageId: userMessageId,
parentMessageType: 'user',