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.

✨ feat(topic): pin reasoning effort per topic, add default effort on agent profile (#19190)

YuTengjing7cbe9fdb4d8f
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
index c4d34ef183d..621343e3363 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.test.ts
@@ -19,6 +19,18 @@ vi.mock('@/database/models/aiModel', () => ({
},
}));
+const findTopicByIdMock = vi.hoisted(() => vi.fn());
+const topicModelCtorMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: class {
+ constructor(...args: unknown[]) {
+ topicModelCtorMock(...args);
+ }
+ findById = findTopicByIdMock;
+ },
+}));
+
const createCtx = (agentConfig: any): RuntimeExecutorContext =>
({
agentConfig,
@@ -68,6 +80,158 @@ beforeEach(() => {
]);
findByIdAndProviderMock.mockResolvedValue(undefined);
getModelReasoningConfigMock.mockResolvedValue(undefined);
+ findTopicByIdMock.mockResolvedValue(undefined);
+});
+
+describe('resolveServerCallLlmContextHints - topic reasoning pin', () => {
+ const ctxWithTopic = (agentConfig: any) => ({ ...createCtx(agentConfig), topicId: 'topic-1' });
+
+ it.each([
+ ['supervisor', 'high'],
+ ['member', 'low'],
+ ])('uses group topic reasoning only for its owning agent (%s)', async (id, effort) => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+ findTopicByIdMock.mockResolvedValue({
+ agentId: 'supervisor',
+ groupId: 'group-1',
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ id, chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: effort });
+ });
+
+ it('should let the topic pin win over the model-instance config', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(findTopicByIdMock).toHaveBeenCalledWith('topic-1');
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'high' });
+ });
+
+ it('should read share-visitor topics too (they carry a senderId)', async () => {
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(topicModelCtorMock).toHaveBeenCalledWith(
+ expect.anything(),
+ 'user-1',
+ undefined,
+ undefined,
+ { includeShareVisitor: true },
+ );
+ });
+
+ it('should treat an empty topic pin as the model defaults', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: {} },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).not.toHaveBeenCalled();
+ expect(hints.resolvedExtendParams).toEqual({});
+ });
+
+ it('should ignore a topic pin taken for another model (sub-agent modelOverride)', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'other-model',
+ provider: 'openai',
+ });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(getModelReasoningConfigMock).toHaveBeenCalledWith('gpt-4', 'openai');
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'low' });
+ });
+
+ it('should fall back to the model-instance config for a legacy topic without a pin', async () => {
+ getModelReasoningConfigMock.mockResolvedValue({ reasoningEffort: 'low' });
+ findTopicByIdMock.mockResolvedValue({ metadata: {}, model: 'gpt-4', provider: 'openai' });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'low' });
+ });
+
+ it('should still let explicit sub-agent overrides win over the topic pin', async () => {
+ findTopicByIdMock.mockResolvedValue({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ const hints = await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({
+ chatConfig: {},
+ subAgentChatConfigOverride: { reasoningEffort: 'medium' },
+ }),
+ llmPayload,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(hints.resolvedExtendParams).toEqual({ reasoning_effort: 'medium' });
+ });
+
+ it('should not read the topic for models without reasoning extend params', async () => {
+ await resolveServerCallLlmContextHints({
+ ctx: ctxWithTopic({ chatConfig: {} }),
+ llmPayload,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ });
+
+ expect(findTopicByIdMock).not.toHaveBeenCalled();
+ });
});
describe('resolveServerCallLlmContextHints - model-instance reasoning config', () => {
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
index 20468aaed14..f79b16bf886 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextHints.ts
@@ -12,11 +12,13 @@ import type { LobeAgentChatConfig, UIChatMessage } from '@lobechat/types';
import {
type AiModelReasoningConfig,
type ExtendParamsType,
+ type LobeDefaultAiModelListItem,
MODEL_REASONING_EXTEND_PARAMS,
ModelProvider,
} from 'model-bank';
import { AiModelModel } from '@/database/models/aiModel';
+import { TopicModel } from '@/database/models/topic';
import type { RuntimeExecutorContext } from '../context';
import { log } from '../executorHelpers';
@@ -43,25 +45,41 @@ export interface ServerCallLlmContextHints {
shouldReplayAssistantReasoning: boolean;
}
-export const resolveServerCallLlmContextHints = async ({
- ctx,
- llmPayload,
+export interface ResolvedModelExtendParams {
+ /** Bundled card matched by id across any provider (aggregation fallback). */
+ canonicalModelCard?: LobeDefaultAiModelListItem;
+ /** Bundled card for exactly `provider`/`model`. */
+ modelCard?: LobeDefaultAiModelListItem;
+ /** Effective extend params: user row → provider card → canonical card. */
+ modelExtendParams?: string[];
+ /** True when any effort-family / reasoningMode param is among `modelExtendParams`. */
+ modelHasReasoningExtendParams: boolean;
+ userModelRow?: Awaited<ReturnType<AiModelModel['findByIdAndProvider']>>;
+}
+
+/**
+ * Resolve which extend params a model can consume for this user, matching the
+ * client's `getEnabledModels` merge. Shared by the per-attempt LLM hints and
+ * the topic-creation reasoning snapshot (`turnSetup`), so both agree on
+ * whether a model is governed by the reasoning extend-params family.
+ */
+export const resolveModelExtendParamsForUser = async ({
+ aiModelModel,
+ builtinModels: preloadedModels,
model,
provider,
-}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {
- const agentConfig = ctx.agentConfig;
- const { loadModels } = await import('@/business/client/model-bank/loadModels');
- const builtinModels = await loadModels();
-
- const preserveThinkingConfigured =
- typeof agentConfig?.chatConfig?.preserveThinking === 'boolean'
- ? agentConfig.chatConfig.preserveThinking
- : undefined;
- const preserveThinkingRequested = preserveThinkingConfigured === true;
+}: {
+ aiModelModel: AiModelModel | undefined;
+ /** Already-loaded model bank; callers on a hot path pass it to avoid a second load. */
+ builtinModels?: LobeDefaultAiModelListItem[];
+ model: string;
+ provider: string;
+}): Promise<ResolvedModelExtendParams> => {
+ const builtinModels =
+ preloadedModels ??
+ (await (await import('@/business/client/model-bank/loadModels')).loadModels());
- const readExtendParams = (
- card: (typeof builtinModels)[number] | undefined,
- ): string[] | undefined =>
+ const readExtendParams = (card: LobeDefaultAiModelListItem | undefined): string[] | undefined =>
card &&
'settings' in card &&
card.settings &&
@@ -77,17 +95,6 @@ export const resolveServerCallLlmContextHints = async ({
const canonicalModelCard = builtinModels.find(
(item) => item.id === model || item.config?.deploymentName === model,
);
- const modelKnowledgeCutoff =
- modelCard?.knowledgeCutoff ??
- (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined);
- let modelDisplayName =
- modelCard?.displayName ??
- (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);
-
- 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
@@ -102,8 +109,6 @@ export const resolveServerCallLlmContextHints = async ({
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
@@ -124,22 +129,98 @@ export const resolveServerCallLlmContextHints = async ({
}
}
- // 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),
);
+
+ return {
+ canonicalModelCard,
+ modelCard,
+ modelExtendParams,
+ modelHasReasoningExtendParams,
+ userModelRow,
+ };
+};
+
+export const resolveServerCallLlmContextHints = async ({
+ ctx,
+ llmPayload,
+ model,
+ provider,
+}: ResolveServerCallLlmContextHintsInput): Promise<ServerCallLlmContextHints> => {
+ const agentConfig = ctx.agentConfig;
+ const { loadModels } = await import('@/business/client/model-bank/loadModels');
+ const builtinModels = await loadModels();
+
+ const preserveThinkingConfigured =
+ typeof agentConfig?.chatConfig?.preserveThinking === 'boolean'
+ ? agentConfig.chatConfig.preserveThinking
+ : undefined;
+ const preserveThinkingRequested = preserveThinkingConfigured === true;
+
+ const aiModelModel =
+ ctx.serverDB && ctx.userId
+ ? new AiModelModel(ctx.serverDB, ctx.userId, ctx.workspaceId)
+ : undefined;
+
+ const {
+ canonicalModelCard,
+ modelCard,
+ modelExtendParams,
+ modelHasReasoningExtendParams,
+ userModelRow,
+ } = await resolveModelExtendParamsForUser({ aiModelModel, builtinModels, model, provider });
+
+ const modelKnowledgeCutoff =
+ modelCard?.knowledgeCutoff ??
+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.knowledgeCutoff : undefined);
+ // User-set displayName wins, matching the client list merge
+ const modelDisplayName =
+ userModelRow?.displayName ??
+ modelCard?.displayName ??
+ (provider === ModelProvider.LobeHub ? canonicalModelCard?.displayName : undefined);
+
+ // Reasoning fields (effort family + reasoningMode) resolve as: topic pin →
+ // user-level model-instance config (personal scope, cross-workspace).
+ // Same-named agent chatConfig values are ignored — except explicit sub-agent
+ // overrides, which stay honored.
+ //
+ // The topic pin (`topics.metadata.reasoningConfig`, snapshotted on creation
+ // and rewritten when the user changes effort / switches model while the
+ // topic is active) only counts when the topic's pinned model IS the model of
+ // this attempt: a sub-agent `modelOverride` or a stale snapshot must not
+ // leak another model's effort. Mirrors the client `modelParamsResolver`.
+ //
+ // Only read either source 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 reads.
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);
+ if (ctx.topicId && ctx.serverDB && ctx.userId) {
+ try {
+ // Share-visitor runs execute in the owner's context against topics that
+ // carry a `senderId`; `findById` skips those rows unless opted in, and
+ // the fallback would silently drop the visitor topic's pin.
+ const topic = await new TopicModel(ctx.serverDB, ctx.userId, ctx.workspaceId, undefined, {
+ includeShareVisitor: true,
+ }).findById(ctx.topicId);
+ if (
+ topic?.model === model &&
+ topic.provider === provider &&
+ (!topic.groupId || topic.agentId === ctx.agentConfig?.id)
+ ) {
+ modelReasoningConfig = topic.metadata?.reasoningConfig;
+ }
+ } catch (error) {
+ log('Failed to resolve topic reasoning pin for %s: %O', ctx.topicId, error);
+ }
+ }
+ if (!modelReasoningConfig) {
+ try {
+ modelReasoningConfig = await aiModelModel.getModelReasoningConfig(model, provider);
+ } catch (error) {
+ log('Failed to resolve model reasoning config for %s: %O', model, error);
+ }
}
}
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.ts
index 84a54e58e80..407009c57ee 100644
--- a/apps/server/src/routers/lambda/topic.ts
+++ b/apps/server/src/routers/lambda/topic.ts
@@ -1,6 +1,7 @@
import { PERMISSION_ACTIONS } from '@lobechat/const/rbac';
import {
canPublishAgentTopicLink,
+ chatTopicCreateMetadataSchema,
chatTopicMetadataUpdateSchema,
chatTopicStatusSchema,
type HeteroSessionImportPayload,
@@ -496,6 +497,9 @@ export const topicRouter = router({
favorite: z.boolean().optional(),
groupId: z.string().nullish(),
messages: z.array(z.string()).optional(),
+ // The pinned reasoning snapshot taken next to the pinned model
+ // (`snapshotAgentReasoning`); other metadata keys are server-owned.
+ metadata: chatTopicCreateMetadataSchema.optional(),
// The topic's pinned model snapshot, persisted to the top-level
// `topics.model`/`provider` columns (config source of truth).
model: z.string().optional(),
@@ -1069,6 +1073,28 @@ export const topicRouter = router({
return ctx.topicModel.update(input.id, { ...restValue, sessionId: resolvedSessionId });
}),
+ /**
+ * Switch the topic's pinned model and its effort pin atomically — see
+ * `TopicModel.updateModelPin`. Same co-editing rules as `updateTopic`.
+ */
+ updateTopicModel: topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .input(
+ z.object({
+ id: z.string(),
+ metadata: chatTopicCreateMetadataSchema.optional(),
+ model: z.string(),
+ provider: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+
+ const { id, ...value } = input;
+ return ctx.topicModel.updateModelPin(id, value);
+ }),
+
updateTopicMetadata: topicProcedure
.use(withScopedPermission('topic:update'))
.input(
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts
index a618fcf048f..04954656b0f 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts
@@ -1,6 +1,8 @@
import type * as ModelBankModule from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import * as modelHints from '@/server/modules/AgentRuntime/adapters/serverCallLlmContextHints';
+
import { AiAgentService } from '../index';
// Use vi.hoisted to ensure mock functions are available before vi.mock runs
@@ -32,6 +34,13 @@ vi.mock('@/database/models/message', () => ({
})),
}));
+vi.mock('@/database/models/aiModel', () => ({
+ AiModelModel: vi.fn().mockImplementation(() => ({
+ findByIdAndProvider: vi.fn().mockResolvedValue(undefined),
+ getModelReasoningConfig: vi.fn().mockResolvedValue({ reasoningEffort: 'high' }),
+ })),
+}));
+
// Mock AgentModel
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn().mockImplementation(() => ({
@@ -75,6 +84,7 @@ vi.mock('@/database/models/plugin', () => ({
// Mock TopicModel
vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn().mockImplementation(() => ({
+ armScheduledRun: vi.fn().mockResolvedValue(undefined),
create: mockTopicCreate,
findById: vi.fn().mockResolvedValue(undefined),
releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
@@ -199,6 +209,73 @@ describe('AiAgentService.execAgent - client-minted ids', () => {
mockTopicCreate.mockClear();
});
+ it.each(['scheduled', 'group'] as const)(
+ 'snapshots the model and reasoning for a precreated %s topic',
+ async (kind) => {
+ const hintsSpy = vi.spyOn(modelHints, 'resolveModelExtendParamsForUser').mockResolvedValue({
+ modelHasReasoningExtendParams: true,
+ modelExtendParams: ['reasoningEffort'],
+ });
+
+ const runSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({} as Awaited<ReturnType<AiAgentService['execAgent']>>);
+ if (kind === 'scheduled') {
+ await service.scheduleAgentRun({
+ agentId: 'agent-1',
+ prompt: 'Scheduled',
+ runAt: new Date(Date.now() + 60000).toISOString(),
+ });
+ } else {
+ await service.execGroupAgent({ agentId: 'agent-1', groupId: 'group-1', message: 'Group' });
+ }
+ expect(mockTopicCreate.mock.calls[0][0]).toMatchObject({
+ model: 'gpt-4',
+ provider: 'openai',
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ });
+ hintsSpy.mockRestore();
+ runSpy.mockRestore();
+ },
+ );
+
+ it('snapshots an explicit model override when scheduling', async () => {
+ const hintsSpy = vi.spyOn(modelHints, 'resolveModelExtendParamsForUser').mockResolvedValue({
+ modelHasReasoningExtendParams: true,
+ modelExtendParams: ['reasoningEffort'],
+ });
+ await service.scheduleAgentRun({
+ agentId: 'agent-1',
+ model: 'override-model',
+ provider: 'override-provider',
+ prompt: 'Scheduled',
+ runAt: new Date(Date.now() + 60000).toISOString(),
+ });
+ expect(mockTopicCreate.mock.calls[0][0]).toMatchObject({
+ model: 'override-model',
+ provider: 'override-provider',
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ });
+ hintsSpy.mockRestore();
+ });
+
+ it('does not recreate or snapshot an existing group topic', async () => {
+ const runSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({} as Awaited<ReturnType<AiAgentService['execAgent']>>);
+ const hintsSpy = vi.spyOn(modelHints, 'resolveModelExtendParamsForUser');
+ await service.execGroupAgent({
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ topicId: 'legacy-topic',
+ message: 'Continue',
+ });
+ expect(mockTopicCreate).not.toHaveBeenCalled();
+ expect(hintsSpy).not.toHaveBeenCalled();
+ hintsSpy.mockRestore();
+ runSpy.mockRestore();
+ });
+
it('should forward client-minted ids to topic and message creation on a fresh send', async () => {
await service.execAgent({
agentId: 'agent-1',
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
index 377857e0112..32a96e4e41a 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts
@@ -9,6 +9,7 @@ const {
mockGetAgentConfig,
mockGetPreference,
mockMessageCreate,
+ mockTopicCreate,
mockTopicFindById,
} = vi.hoisted(() => ({
mockIsResourceAuthorOrAdmin: vi.fn(),
@@ -16,6 +17,7 @@ const {
mockGetAgentConfig: vi.fn(),
mockGetPreference: vi.fn(),
mockMessageCreate: vi.fn(),
+ mockTopicCreate: vi.fn().mockResolvedValue({ id: 'topic-1' }),
mockTopicFindById: vi.fn(),
}));
@@ -29,6 +31,13 @@ vi.mock('@/libs/trusted-client', () => ({
isTrustedClientEnabled: vi.fn().mockReturnValue(false),
}));
+vi.mock('@/database/models/chatGroup', () => ({
+ ChatGroupModel: class {
+ findById = vi.fn().mockResolvedValue(undefined);
+ getGroupAgentsWithMeta = vi.fn().mockResolvedValue([]);
+ },
+}));
+
vi.mock('@/database/models/message', () => ({
MessageModel: vi.fn().mockImplementation(() => ({
create: mockMessageCreate,
@@ -85,7 +94,8 @@ vi.mock('@/database/models/topic', () => ({
TopicModel: vi.fn().mockImplementation(() => ({
releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
- create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ create: mockTopicCreate,
+ armScheduledRun: vi.fn().mockResolvedValue(undefined),
findById: mockTopicFindById,
})),
}));
@@ -200,6 +210,40 @@ describe('AiAgentService.execAgent - model/provider override', () => {
expect(callArgs.agentConfig.provider).toBe('openai');
});
+ it.each(['group', 'scheduled'])(
+ 'pins the member-selected model when precreating a %s topic',
+ async (kind) => {
+ mockGetAgentConfig.mockResolvedValue({
+ ...defaultAgentConfig,
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ userId: 'agent-author',
+ visibility: 'public',
+ workspaceId: 'workspace-1',
+ });
+ mockGetPreference.mockResolvedValue({
+ agentModelOverrides: { 'agent-1': { model: 'claude-sonnet-4-6', provider: 'anthropic' } },
+ });
+ service = new AiAgentService(mockDb, userId, { workspaceId: 'workspace-1' });
+ const runSpy = vi
+ .spyOn(service, 'execAgent')
+ .mockResolvedValue({} as Awaited<ReturnType<AiAgentService['execAgent']>>);
+ if (kind === 'group') {
+ await service.execGroupAgent({ agentId: 'agent-1', groupId: 'group-1', message: 'Group' });
+ } else {
+ await service.scheduleAgentRun({
+ agentId: 'agent-1',
+ prompt: 'Scheduled',
+ runAt: new Date(Date.now() + 60_000).toISOString(),
+ });
+ }
+ expect(mockTopicCreate.mock.calls[0][0]).toMatchObject({
+ model: 'claude-sonnet-4-6',
+ provider: 'anthropic',
+ });
+ runSpy.mockRestore();
+ },
+ );
+
it('should override model when model param is provided', async () => {
mockGetAgentConfig.mockResolvedValue({ ...defaultAgentConfig });
@@ -246,6 +290,33 @@ describe('AiAgentService.execAgent - model/provider override', () => {
expect(callArgs.agentConfig.provider).toBe('anthropic');
});
+ it('keeps group members on their own model instead of the supervisor topic pin', async () => {
+ mockGetAgentConfig.mockResolvedValue({ ...defaultAgentConfig });
+ mockTopicFindById.mockResolvedValue({
+ agentId: 'supervisor',
+ groupId: 'group-1',
+ model: 'supervisor-model',
+ provider: 'anthropic',
+ metadata: { heteroEffort: 'high' },
+ });
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ appContext: {
+ topicId: 'topic-1',
+ groupId: 'group-1',
+ orchestrationRole: 'member',
+ scope: 'group',
+ },
+ prompt: 'Hello',
+ });
+
+ expect(mockCreateOperation.mock.calls[0][0].agentConfig).toMatchObject({
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+ });
+
it('keeps an explicit model override over the topic model', async () => {
mockGetAgentConfig.mockResolvedValue({ ...defaultAgentConfig });
mockTopicFindById.mockResolvedValue({ model: 'gpt-5.6-terra', provider: 'openai' });
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index ba814910af6..14328eb4718 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -67,7 +67,7 @@ import { createHistoryMessagesLoader, prepareOperation } from './pipeline/operat
import { resolveRunAgentConfig } from './pipeline/resolveRunAgentConfig';
import { startOperation } from './pipeline/startOperation';
import { discoverTools } from './pipeline/toolDiscovery';
-import { setupTurn } from './pipeline/turnSetup';
+import { resolveNewTopicSnapshot, setupTurn } from './pipeline/turnSetup';
import { applyShareGateToAgentConfig } from './shareGate';
import type { SubAgentRunDeps } from './subAgentRuns';
import { execAgentMember, execAgentThreadRun } from './subAgentRuns';
@@ -352,6 +352,28 @@ export class AiAgentService {
return agentConfig;
}
+ /** Resolve caller model policy before a pre-created topic permanently pins its model. */
+ private async resolvePrecreatedTopicConfig(
+ identifier: string,
+ overrides?: { model?: string; provider?: string },
+ ) {
+ const { agentConfig } = await resolveRunAgentConfig(
+ {
+ db: this.db,
+ resolveAgentConfigOrThrow: (id) => this.resolveAgentConfigOrThrow(id),
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ },
+ {
+ identifier,
+ modelOverride: overrides?.model,
+ providerOverride: overrides?.provider,
+ throwIfExecutionAborted: async () => {},
+ },
+ );
+ return agentConfig;
+ }
+
/**
* Defer an agent run to a future time ("send this in 3 hours").
*
@@ -377,11 +399,20 @@ export class AiAgentService {
throw new TRPCError({ code: 'BAD_REQUEST', message: 'runAt must be in the future' });
}
- const agentConfig = await this.resolveAgentConfigOrThrow(agentId || slug!);
+ const agentConfig = await this.resolvePrecreatedTopicConfig(agentId || slug!, {
+ model,
+ provider,
+ });
const resolvedAgentId = agentConfig.id;
const titleSource = markdownToTxt(prompt);
+ const snapshot = await resolveNewTopicSnapshot(
+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },
+ agentConfig,
+ { model, provider },
+ );
const topic = await this.topicModel.create({
+ ...snapshot,
agentId: resolvedAgentId,
groupId,
// A scheduled run is still an ordinary user chat, just deferred — so it
@@ -1334,7 +1365,13 @@ export class AiAgentService {
const topicTitle =
newTopic?.title ||
fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : '');
+ const agentConfig = await this.resolvePrecreatedTopicConfig(agentId);
+ const snapshot = await resolveNewTopicSnapshot(
+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },
+ agentConfig,
+ );
const topicItem = await this.topicModel.create({
+ ...snapshot,
agentId,
groupId,
messages: newTopic?.topicMessageIds,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index fdff84f4705..939ae65cbad 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -9,7 +9,7 @@ import {
import type {
ErrorType,
ExecAgentResult,
- HeterogeneousTopicModel,
+ HeterogeneousTopicPin,
LobeAgentAgencyConfig,
RequestTrigger,
WorkingDirConfig,
@@ -182,7 +182,7 @@ export interface HeteroDispatchInput {
memberDeviceOverride?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;
operationTaskId?: string;
parentOperationId?: string;
- pinnedHeterogeneousTopicModel?: HeterogeneousTopicModel;
+ pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
requestedDeviceId?: string;
requestTrigger?: RequestTrigger;
runAttachments: { imageList?: Array<{ alt: string; id: string; url: string }> };
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 793cab669e3..12e24dd7ada 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -4,8 +4,10 @@ import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
ChatAudioItem,
ChatFileItem,
+ ChatTopicMetadata,
ChatVideoItem,
- HeterogeneousTopicModel,
+ HeterogeneousProviderConfig,
+ HeterogeneousTopicPin,
} from '@lobechat/types';
import {
ChatErrorType,
@@ -15,8 +17,10 @@ import {
import { TRPCError } from '@trpc/server';
import debug from 'debug';
+import { AiModelModel } from '@/database/models/aiModel';
import type { MessageModel } from '@/database/models/message';
import type { TopicModel } from '@/database/models/topic';
+import { resolveModelExtendParamsForUser } from '@/server/modules/AgentRuntime/adapters/serverCallLlmContextHints';
import type { AgentConfigWithId } from '@/server/services/agent';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
@@ -51,6 +55,75 @@ export interface RunAttachments {
warnings: string[];
}
+/**
+ * Build the reasoning snapshot for a topic being created — see
+ * `ChatTopicMetadata.reasoningConfig` / `heteroEffort`. Returns undefined when
+ * there is nothing to pin (non-reasoning model, hetero agent without an effort)
+ * so the caller leaves metadata untouched. Never throws: a failed lookup just
+ * means the topic follows the user-level config until the user pins one.
+ */
+const resolveTopicReasoningSnapshot = async ({
+ deps,
+ heterogeneousProvider,
+ isHeteroTopic,
+ model,
+ provider,
+}: {
+ deps: Pick<TurnSetupDeps, 'db' | 'userId' | 'workspaceId'>;
+ heterogeneousProvider: HeterogeneousProviderConfig | undefined;
+ isHeteroTopic: boolean;
+ model: string;
+ provider: string;
+}): Promise<Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'> | undefined> => {
+ if (isHeteroTopic) {
+ const effort = heterogeneousProvider?.effort;
+ return effort === undefined ? undefined : { heteroEffort: effort };
+ }
+
+ try {
+ const aiModelModel = new AiModelModel(deps.db, deps.userId, deps.workspaceId);
+ const { modelHasReasoningExtendParams } = await resolveModelExtendParamsForUser({
+ aiModelModel,
+ model,
+ provider,
+ });
+ if (!modelHasReasoningExtendParams) return undefined;
+
+ const reasoningConfig = await aiModelModel.getModelReasoningConfig(model, provider);
+ return { reasoningConfig: reasoningConfig ?? {} };
+ } catch (error) {
+ log('execAgent: failed to snapshot topic reasoning config for %s: %O', model, error);
+ return undefined;
+ }
+};
+
+/** Snapshot only newly created topics, including callers that pre-create before setupTurn. */
+export const resolveNewTopicSnapshot = async (
+ deps: Pick<TurnSetupDeps, 'db' | 'userId' | 'workspaceId'>,
+ agentConfig: AgentConfigWithId,
+ overrides?: { model?: string; provider?: string },
+) => {
+ const model = overrides?.model ?? agentConfig.model!;
+ const provider = overrides?.provider ?? agentConfig.provider!;
+ const heterogeneousProvider = agentConfig.agencyConfig?.heterogeneousProvider;
+ const heteroType =
+ heterogeneousProvider?.type ?? (isHeterogeneousAgentModelId(model) ? model : undefined);
+ const heteroModel = heterogeneousProvider
+ ? resolveHeterogeneousProviderTopicModel(heterogeneousProvider)
+ : undefined;
+ return {
+ metadata: await resolveTopicReasoningSnapshot({
+ deps,
+ heterogeneousProvider,
+ isHeteroTopic: !!heteroType,
+ model,
+ provider,
+ }),
+ model: heteroModel?.model ?? (heteroType ? undefined : model),
+ provider: heteroModel?.provider ?? heteroType ?? provider,
+ };
+};
+
/**
* Resolve a run's attachments into the lists the message + context layers
* consume. This is the single standard ingestion path shared by BOTH branches
@@ -274,7 +347,8 @@ export interface TurnSetupResult {
isHeteroAgent: boolean;
/** Effective model/provider after the topic-pinned model is applied. */
model: string;
- pinnedHeterogeneousTopicModel?: HeterogeneousTopicModel;
+ /** Topic-pinned model + reasoning effort for a heterogeneous run (reused topics only). */
+ pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
provider: string;
requestTriggerMetadata: {
agentDispatch?: { kind: 'callAgent'; visibility: 'internal' };
@@ -356,10 +430,7 @@ export const setupTurn = async (
let model = agentConfig.model!;
let provider = agentConfig.provider!;
const heterogeneousProvider = agentConfig.agencyConfig?.heterogeneousProvider;
- const heterogeneousTopicModelSnapshot = heterogeneousProvider
- ? resolveHeterogeneousProviderTopicModel(heterogeneousProvider)
- : undefined;
- let pinnedHeterogeneousTopicModel: HeterogeneousTopicModel | undefined;
+ let pinnedHeterogeneousTopicModel: HeterogeneousTopicPin | undefined;
// Share-visitor fail-closed gate — reject a heterogeneous (Claude Code /
// Codex / …) agent BEFORE any topic/message row is written. Heterogeneous
@@ -415,12 +486,9 @@ export const setupTurn = async (
: undefined;
const fallbackTitleSource = markdownToTxt(prompt);
- // Heterogeneous topics use the same snapshot rule as the client: persist
- // the selected CLI model (including `default`) or user-provider API binding.
- // Runtimes without a model selector, legacy rows, and Agent-scoped
- // server-default API configs still pin only the runtime type.
- const heteroSnapshotType =
- heterogeneousProvider?.type ?? (isHeterogeneousAgentModelId(model) ? model : undefined);
+ const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);
+ const metadataWithSnapshot: ChatTopicMetadata | undefined =
+ metadata || snapshot.metadata ? { ...metadata, ...snapshot.metadata } : undefined;
// Second argument: the id the client already rendered this topic under
// (sidebar row, message bucket). Absent → the model mints one as before.
const newTopicParams = {
@@ -433,10 +501,10 @@ export const setupTurn = async (
// that reaches execAgent without a topicId (e.g. the async/queue run)
// must carry the groupId through too (group topic sidebar + ownership fix).
groupId: appContext?.groupId,
- metadata,
+ metadata: metadataWithSnapshot,
// Snapshot the effective model as the topic's pinned model (config).
- model: heterogeneousTopicModelSnapshot?.model ?? (heteroSnapshotType ? undefined : model),
- provider: heterogeneousTopicModelSnapshot?.provider ?? heteroSnapshotType ?? provider,
+ model: snapshot.model,
+ provider: snapshot.provider,
// Share-visitor runs: the topic row belongs to the creator
// (`deps.userId`), but stamping the visitor's id here is what
// `TopicModel`'s creator-facing reads (`query`, `count`, `queryTopics`,
@@ -501,7 +569,9 @@ export const setupTurn = async (
throw new TRPCError({ code: 'NOT_FOUND', message: 'Topic not found' });
}
- const pinnedModel = existingTopic?.model;
+ /** A group topic pins its owning agent; member runs keep their own model and effort. */
+ const canUseTopicPin = !existingTopic?.groupId || existingTopic.agentId === resolvedAgentId;
+ const pinnedModel = canUseTopicPin ? existingTopic?.model : undefined;
if (pinnedModel) {
model = modelOverride || pinnedModel;
provider = providerOverride || existingTopic?.provider || provider;
@@ -513,6 +583,15 @@ export const setupTurn = async (
topicId,
);
}
+ // The heterogeneous effort pin lives in metadata and is independent of the
+ // model pin (a runtime without a model selector can still pin an effort).
+ const pinnedHeteroEffort = canUseTopicPin ? existingTopic?.metadata?.heteroEffort : undefined;
+ if (pinnedHeteroEffort !== undefined) {
+ pinnedHeterogeneousTopicModel = {
+ ...pinnedHeterogeneousTopicModel,
+ effort: pinnedHeteroEffort,
+ };
+ }
// Re-assert the share restriction after topic overrides are applied.
// Heterogeneous agents are not available for shared visitor runs.
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index e7f15075ead..e1ba5c6b369 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -865,7 +865,8 @@
"settingAgent.role.label": "Role",
"settingAgent.role.placeholder": "What it is responsible for, e.g. Health Assistant",
"settingAgent.role.unset": "No role set yet",
- "settingAgent.runtimeConfig.title": "Model & Tools",
+ "settingAgent.runtimeConfig.reasoningEffortHint": "Your default reasoning effort for this model. Shared by every agent using it; each topic keeps the effort it started with and can change it from the chat input.",
+ "settingAgent.runtimeConfig.title": "Model & Reasoning Effort",
"settingAgent.selectionPolicy.membersCanSwitch": "Can switch",
"settingAgent.selectionPolicy.membersCanSwitchWhenShared": "Can switch when shared",
"settingAgent.selectionPolicy.membersCannotSwitch": "Locked",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 1adf54b9eda..48fbcf1b454 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -865,7 +865,8 @@
"settingAgent.role.label": "角色",
"settingAgent.role.placeholder": "负责领域,例如:健康助手",
"settingAgent.role.unset": "暂未设定角色",
- "settingAgent.runtimeConfig.title": "模型与工具",
+ "settingAgent.runtimeConfig.reasoningEffortHint": "你在该模型上的默认推理强度。所有使用该模型的 Agent 共享;每个话题会记住创建时的强度,并可在输入框中单独调整。",
+ "settingAgent.runtimeConfig.title": "模型与推理强度",
"settingAgent.selectionPolicy.membersCanSwitch": "可切换",
"settingAgent.selectionPolicy.membersCanSwitchWhenShared": "公开后可切换",
"settingAgent.selectionPolicy.membersCannotSwitch": "锁定",
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index e7187d77f42..3ebdbdddbc4 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -713,6 +713,41 @@ describe('TopicModel', () => {
});
describe('update', () => {
+ it.each([{ model: 'b' }, { provider: 'other' }, { model: null }])(
+ 'clears stale reasoning on a legacy model update %j',
+ async (patch) => {
+ const topic = await topicModel.create({
+ metadata: {
+ reasoningConfig: { reasoningEffort: 'high' },
+ heteroEffort: 'low',
+ workingDirectory: '/w',
+ },
+ model: 'a',
+ provider: 'openai',
+ title: 'legacy',
+ });
+ const [updated] = await topicModel.update(topic.id, { ...patch, title: 'changed' });
+ expect(updated.metadata).toEqual({ heteroEffort: 'low', workingDirectory: '/w' });
+ expect(updated.title).toBe('changed');
+ expect(updated).toMatchObject(patch);
+ },
+ );
+
+ it.each([{ title: 'renamed' }, { model: 'a', provider: 'openai' }])(
+ 'preserves reasoning when the model does not change %j',
+ async (patch) => {
+ const metadata = { reasoningConfig: { reasoningEffort: 'high' as const } };
+ const topic = await topicModel.create({
+ metadata,
+ model: 'a',
+ provider: 'openai',
+ title: 'pin',
+ });
+ const [updated] = await topicModel.update(topic.id, patch);
+ expect(updated.metadata).toEqual(metadata);
+ },
+ );
+
it('updates status and bumps updatedAt', async () => {
const topic = await topicModel.create({ title: 'to update' });
const before = topic.updatedAt.getTime();
@@ -963,6 +998,45 @@ describe('TopicModel', () => {
});
});
+ describe('updateModelPin', () => {
+ it('switches model and replaces the reasoning pin in one write', async () => {
+ const topic = await topicModel.create({
+ metadata: { reasoningConfig: { glm5_2ReasoningEffort: 'max' }, workingDirectory: '/w' },
+ model: 'glm-5.2',
+ provider: 'lobehub',
+ title: 'pin',
+ });
+
+ const [updated] = await topicModel.updateModelPin(topic.id, {
+ metadata: { reasoningConfig: { deepseekV4GAReasoningEffort: 'low' } },
+ model: 'deepseek-v4-flash',
+ provider: 'lobehub',
+ });
+
+ expect(updated.model).toBe('deepseek-v4-flash');
+ expect(updated.metadata).toEqual({
+ reasoningConfig: { deepseekV4GAReasoningEffort: 'low' },
+ workingDirectory: '/w',
+ });
+ });
+
+ it('drops a stale reasoning pin and keeps heteroEffort when not given', async () => {
+ const topic = await topicModel.create({
+ metadata: { heteroEffort: 'high', reasoningConfig: { effort: 'max' } },
+ model: 'a',
+ provider: 'claude-code',
+ title: 'pin',
+ });
+
+ const [updated] = await topicModel.updateModelPin(topic.id, {
+ model: 'b',
+ provider: 'claude-code',
+ });
+
+ expect(updated.metadata).toEqual({ heteroEffort: 'high' });
+ });
+ });
+
describe('updateMetadata', () => {
it('merges new metadata into existing metadata', async () => {
const topic = await topicModel.create({
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 17cd001f2a3..2f0df3c68b0 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1674,9 +1674,26 @@ export class TopicModel {
// **************** Update *************** //
update = async (id: string, data: Partial<TopicItem>) => {
+ /**
+ * Older clients switch models through the general update endpoint. Clear
+ * the old model's reasoning pin in the same statement, comparing against
+ * the persisted row so partial writes and concurrent switches stay safe.
+ * Explicit metadata remains the caller's replacement snapshot.
+ */
+ const modelChanged = or(
+ data.model !== undefined ? sql`${topics.model} is distinct from ${data.model}` : undefined,
+ data.provider !== undefined
+ ? sql`${topics.provider} is distinct from ${data.provider}`
+ : undefined,
+ );
+ const metadata =
+ data.metadata === undefined && modelChanged
+ ? sql`case when ${modelChanged} then coalesce(${topics.metadata}, '{}'::jsonb) - 'reasoningConfig' else ${topics.metadata} end`
+ : data.metadata;
+
return this.db
.update(topics)
- .set({ ...data, updatedAt: new Date() })
+ .set({ ...data, metadata, updatedAt: new Date() })
.where(and(eq(topics.id, id), this.ownership()))
.returning();
};
@@ -1915,6 +1932,51 @@ export class TopicModel {
});
};
+ /**
+ * Switch a topic's pinned model together with its model-scoped effort pin
+ * (`metadata.reasoningConfig` / `metadata.heteroEffort`) in one row-locked
+ * statement, so neither a concurrent switch nor an in-flight run can observe
+ * the new model paired with the previous model's pin. `reasoningConfig` is
+ * model-keyed and therefore always replaced (dropped when not provided);
+ * `heteroEffort` is only touched when given.
+ */
+ updateModelPin = async (
+ id: string,
+ {
+ metadata,
+ model,
+ provider,
+ }: {
+ metadata?: Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>;
+ model: string;
+ provider: string;
+ },
+ ) =>
+ this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+
+ if (!existing) return [];
+
+ const { reasoningConfig: _stale, ...rest } = existing.metadata ?? {};
+ const mergedMetadata: ChatTopicMetadata = {
+ ...rest,
+ ...(metadata?.heteroEffort !== undefined && { heteroEffort: metadata.heteroEffort }),
+ ...(metadata?.reasoningConfig !== undefined && {
+ reasoningConfig: metadata.reasoningConfig,
+ }),
+ };
+
+ return tx
+ .update(topics)
+ .set({ metadata: mergedMetadata, model, provider, updatedAt: new Date() })
+ .where(and(eq(topics.id, id), this.ownership()))
+ .returning();
+ });
+
appendRunningOperationChild = async (
id: string,
parentOperationId: string,
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index abefb422475..f65925edc30 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1002,7 +1002,9 @@ export default {
'settingAgent.modelPolicy.fixedTip':
'The model is fixed in Agent Profile and cannot be switched while chatting.',
'settingAgent.modelPolicy.title': 'Model',
- 'settingAgent.runtimeConfig.title': 'Model & Tools',
+ 'settingAgent.runtimeConfig.reasoningEffortHint':
+ 'Your default reasoning effort for this model. Shared by every agent using it; each topic keeps the effort it started with and can change it from the chat input.',
+ 'settingAgent.runtimeConfig.title': 'Model & Reasoning Effort',
'settingAgent.selectionPolicy.membersCannotSwitch': 'Locked',
'settingAgent.selectionPolicy.membersCannotSwitchWhenShared': 'Locked when shared',
'settingAgent.selectionPolicy.membersCanSwitch': 'Can switch',
diff --git a/packages/model-bank/src/types/aiModel.test.ts b/packages/model-bank/src/types/aiModel.test.ts
index 2a27e2c89a4..e81799b075a 100644
--- a/packages/model-bank/src/types/aiModel.test.ts
+++ b/packages/model-bank/src/types/aiModel.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { CreateAiModelSchema, UpdateAiModelSchema } from './aiModel';
+import { AiModelReasoningConfigSchema, CreateAiModelSchema, UpdateAiModelSchema } from './aiModel';
describe('AI model mutation schemas', () => {
it('strips deployment-owned compatibility metadata from user mutations', () => {
@@ -19,3 +19,21 @@ describe('AI model mutation schemas', () => {
expect(UpdateAiModelSchema.parse({ agentCompatibility })).toEqual({});
});
});
+
+describe('Gemini reasoning config persistence', () => {
+ it('preserves supported thinking levels and rejects invalid levels', () => {
+ const config = {
+ thinkingLevel: 'minimal',
+ thinkingLevel2: 'low',
+ thinkingLevel3: 'medium',
+ thinkingLevel4: 'high',
+ };
+ expect(AiModelReasoningConfigSchema.parse(config)).toEqual(config);
+ expect(AiModelReasoningConfigSchema.safeParse({ thinkingLevel3: 'minimal' }).success).toBe(
+ false,
+ );
+ expect(AiModelReasoningConfigSchema.safeParse({ thinkingLevel4: 'medium' }).success).toBe(
+ false,
+ );
+ });
+});
diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.ts
index 871bc61313f..9dc1962472e 100644
--- a/packages/model-bank/src/types/aiModel.ts
+++ b/packages/model-bank/src/types/aiModel.ts
@@ -333,8 +333,8 @@ export const isAiModelVisible = (model: { visible?: boolean }) => model.visible
*
* 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.
+ * the reasoning-effort family, Gemini thinking levels, and `reasoningMode`.
+ * Numeric thinking budgets and other extend params remain agent-scoped.
*/
export interface AiModelReasoningConfig {
codexMaxReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';
@@ -360,6 +360,10 @@ export interface AiModelReasoningConfig {
reasoningMode?: 'standard' | 'pro';
ring2_6ReasoningEffort?: 'high' | 'xhigh';
step3_5ReasoningEffort?: 'low' | 'high';
+ thinkingLevel?: 'minimal' | 'low' | 'medium' | 'high';
+ thinkingLevel2?: 'low' | 'high';
+ thinkingLevel3?: 'low' | 'medium' | 'high';
+ thinkingLevel4?: 'minimal' | 'high';
}
export const AiModelReasoningConfigSchema = z.object({
@@ -386,6 +390,10 @@ export const AiModelReasoningConfigSchema = z.object({
reasoningMode: z.enum(['standard', 'pro']).optional(),
ring2_6ReasoningEffort: z.enum(['high', 'xhigh']).optional(),
step3_5ReasoningEffort: z.enum(['low', 'high']).optional(),
+ thinkingLevel: z.enum(['minimal', 'low', 'medium', 'high']).optional(),
+ thinkingLevel2: z.enum(['low', 'high']).optional(),
+ thinkingLevel3: z.enum(['low', 'medium', 'high']).optional(),
+ thinkingLevel4: z.enum(['minimal', 'high']).optional(),
});
/**
@@ -428,6 +436,10 @@ export const MODEL_REASONING_PARAM_LEVELS: {
reasoningMode: ['standard', 'pro'],
ring2_6ReasoningEffort: ['high', 'xhigh'],
step3_5ReasoningEffort: ['low', 'high'],
+ thinkingLevel: ['minimal', 'low', 'medium', 'high'],
+ thinkingLevel2: ['low', 'high'],
+ thinkingLevel3: ['low', 'medium', 'high'],
+ thinkingLevel4: ['minimal', 'high'],
};
/**
@@ -461,6 +473,10 @@ export const MODEL_REASONING_PARAM_DEFAULTS: {
reasoningMode: 'standard',
ring2_6ReasoningEffort: 'high',
step3_5ReasoningEffort: 'low',
+ thinkingLevel: 'high',
+ thinkingLevel2: 'high',
+ thinkingLevel3: 'high',
+ thinkingLevel4: 'minimal',
};
export interface AiModelConfig {
diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.ts
index cf55aa2fa47..be8af52881e 100644
--- a/packages/types/src/agent/agencyConfig.test.ts
+++ b/packages/types/src/agent/agencyConfig.test.ts
@@ -1099,3 +1099,87 @@ describe('canPublishAgentTopicLink', () => {
);
});
});
+
+describe('applyTopicModelToHeterogeneousProvider - effort pin', () => {
+ it.each(['server-default', 'user-provider'] as const)(
+ 'drops an unsupported effort when an API binding rejects the old model pin (%s)',
+ (source) => {
+ const effective = applyTopicModelToHeterogeneousProvider(
+ {
+ type: 'codex',
+ authMode: 'api',
+ apiConfig:
+ source === 'server-default'
+ ? { source, model: 'deepseek-v4-pro' }
+ : { providerId: 'deepseek', model: 'deepseek-v4-pro' },
+ args: ['-c', 'model_reasoning_effort="ultra"'],
+ },
+ { model: 'gpt-5.6-sol', provider: 'codex', effort: 'ultra' },
+ );
+ expect(effective.apiConfig?.model).toBe('deepseek-v4-pro');
+ expect(effective.effort).toBe('default');
+ expect(buildHeteroExecArgs(effective)?.join(' ') ?? '').not.toContain('ultra');
+ },
+ );
+
+ it('validates effort after applying a supported model pin', () => {
+ const effective = applyTopicModelToHeterogeneousProvider(
+ { type: 'codex', model: 'gpt-5.4' },
+ { model: 'gpt-5.6-sol', provider: 'codex', effort: 'ultra' },
+ );
+ expect(effective.effort).toBe('ultra');
+ expect(buildHeteroExecArgs(effective)?.join(' ')).toContain('ultra');
+ });
+
+ it('applies a topic effort pin without a model pin', () => {
+ const effective = applyTopicModelToHeterogeneousProvider(
+ { command: 'claude', effort: 'low', type: 'claude-code' },
+ { effort: 'high' },
+ );
+
+ expect(effective).toEqual({ command: 'claude', effort: 'high', type: 'claude-code' });
+ expect(buildHeteroSpawnArgs(effective)).toEqual(['--effort', 'high']);
+ });
+
+ it('applies the model pin and the effort pin together', () => {
+ const effective = applyTopicModelToHeterogeneousProvider(
+ { args: ['--effort', 'low'], model: 'global-model', type: 'claude-code' },
+ { effort: 'max', model: 'topic-model', provider: 'claude-code' },
+ );
+
+ expect(effective).toEqual({
+ args: [],
+ effort: 'max',
+ model: 'topic-model',
+ type: 'claude-code',
+ });
+ });
+
+ it("treats 'default' as a real pin that drops the agent effort flag", () => {
+ const effective = applyTopicModelToHeterogeneousProvider(
+ { command: 'claude', effort: 'high', type: 'claude-code' },
+ { effort: 'default' },
+ );
+
+ expect(effective.effort).toBe('default');
+ // no extra args and the agent declared none, so `provider.args` (undefined) comes back
+ expect(buildHeteroSpawnArgs(effective)).toBeUndefined();
+ });
+
+ it('keeps the agent effort when the topic pins none', () => {
+ const config = { command: 'claude', effort: 'high', type: 'claude-code' } as const;
+
+ expect(applyTopicModelToHeterogeneousProvider(config, undefined)).toBe(config);
+ expect(
+ applyTopicModelToHeterogeneousProvider(config, { model: 'default', provider: 'claude-code' }),
+ ).toMatchObject({
+ effort: 'high',
+ });
+ });
+
+ it('ignores an effort pin for runtimes without an effort selector', () => {
+ const config = { model: 'global-model', type: 'cursor' } as const;
+
+ expect(applyTopicModelToHeterogeneousProvider(config, { effort: 'high' })).toBe(config);
+ });
+});
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index d98e0209c01..d23fb215f5a 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -248,6 +248,17 @@ export interface HeterogeneousTopicModel {
provider: string;
}
+/**
+ * Everything a topic pins for a heterogeneous run: the model/provider pair from
+ * the top-level `topics.model`/`provider` columns plus the reasoning effort
+ * from `topics.metadata.heteroEffort`. Each part is optional — a topic may pin
+ * an effort without a model (runtimes without a model selector) or the other
+ * way round.
+ */
+export interface HeterogeneousTopicPin extends Partial<HeterogeneousTopicModel> {
+ effort?: HeterogeneousReasoningEffort;
+}
+
/**
* Resolve the topic-level model snapshot for a heterogeneous provider.
*
@@ -268,9 +279,9 @@ export const resolveHeterogeneousProviderTopicModel = (
return model ? { model, provider: config.type } : undefined;
};
-export const applyTopicModelToHeterogeneousProvider = (
+const applyTopicModelPin = (
config: HeterogeneousProviderConfig,
- topicModel: HeterogeneousTopicModel | undefined,
+ topicModel: HeterogeneousTopicPin | undefined,
): HeterogeneousProviderConfig => {
if (!topicModel?.model) return config;
@@ -299,6 +310,37 @@ export const applyTopicModelToHeterogeneousProvider = (
};
};
+/**
+ * Overlay a topic's pins (model/provider + reasoning effort) on the agent's
+ * heterogeneous provider config. The model pin follows the auth-mode rules of
+ * {@link applyTopicModelPin}; the effort pin is a plain CLI-level override, so
+ * it applies when supported by the effective model — independent of whether
+ * a model was pinned. `'default'` is a real pin (it means "drop the
+ * agent's effort flag for this topic"), only `undefined` keeps the agent value.
+ */
+export const applyTopicModelToHeterogeneousProvider = (
+ config: HeterogeneousProviderConfig,
+ topicModel: HeterogeneousTopicPin | undefined,
+): HeterogeneousProviderConfig => {
+ const withModel = applyTopicModelPin(config, topicModel);
+ let effort = topicModel?.effort;
+ if (effort === undefined) return withModel;
+ const capability = getHeteroSelectorCapability(withModel.type);
+ if (!capability?.effort) return withModel;
+ const model =
+ withModel.authMode === 'api'
+ ? withModel.apiConfig?.model
+ : capability.model?.resolve(withModel);
+ /** Auth-mode changes can reject the topic model while leaving its old effort behind. */
+ if (effort !== 'default' && !capability.effort.levels(model ?? 'default').includes(effort)) {
+ effort = 'default';
+ }
+ return {
+ ...withModel,
+ ...applyHeteroSelection(withModel, { effort }),
+ };
+};
+
const HETEROGENEOUS_AGENT_TYPES = new Set<string>([
...HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
...REMOTE_HETEROGENEOUS_AGENT_CONFIGS.map(({ type }) => type),
diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.ts
index 5f67b1c7bf9..153cc6d7f69 100644
--- a/packages/types/src/topic/topic.test.ts
+++ b/packages/types/src/topic/topic.test.ts
@@ -1,6 +1,27 @@
import { describe, expect, it } from 'vitest';
-import { chatTopicMetadataUpdateSchema, parseTopicScheduledRun } from './topic';
+import {
+ chatTopicCreateMetadataSchema,
+ chatTopicMetadataUpdateSchema,
+ parseTopicScheduledRun,
+} from './topic';
+
+describe.each([chatTopicCreateMetadataSchema, chatTopicMetadataUpdateSchema])(
+ 'reasoning metadata validation',
+ (schema) => {
+ it('rejects invalid known reasoning enum values', () => {
+ expect(
+ schema.safeParse({ reasoningConfig: { gpt5ReasoningEffort: 'invalid' } }).success,
+ ).toBe(false);
+ expect(schema.safeParse({ reasoningConfig: { reasoningMode: 'fast' } }).success).toBe(false);
+ });
+ it('accepts valid values and an explicit default pin', () => {
+ for (const reasoningConfig of [{}, { gpt5ReasoningEffort: 'high', reasoningMode: 'pro' }]) {
+ expect(schema.parse({ reasoningConfig })).toEqual({ reasoningConfig });
+ }
+ });
+ },
+);
describe('chatTopicMetadataUpdateSchema', () => {
it('parses a scheduled heterogeneous continuation patch', () => {
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 17db3b6f399..6169345a9d2 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -1,5 +1,8 @@
+import type { AiModelReasoningConfig } from 'model-bank';
+import { AiModelReasoningConfigSchema } from 'model-bank/aiModel';
import { z } from 'zod';
+import type { HeterogeneousReasoningEffort } from '../agent/heteroSelectorCapabilities';
import type { SerializedAgentHook } from '../agentHook';
import { serializedAgentHookSchema } from '../agentHook';
import type { WorkingDirConfig } from '../device';
@@ -153,6 +156,15 @@ export interface ChatTopicMetadata {
* Updated on every step boundary.
*/
heteroCurrentMsgId?: { msgId: string; operationId: string };
+ /**
+ * Topic-pinned reasoning effort for a heterogeneous agent (Claude Code /
+ * Codex / …). Snapshotted from `agencyConfig.heterogeneousProvider.effort`
+ * when the topic is created and overwritten when the user picks an effort
+ * while the topic is active, so a single session can run at a higher effort
+ * without retuning the agent. Resolved as "topic effort if present, else the
+ * agent's effort" by `applyTopicModelToHeterogeneousProvider`.
+ */
+ heteroEffort?: HeterogeneousReasoningEffort;
/**
* Secret-free identity of the provider/auth binding that created
* `heteroSessionId`. Resume is allowed only when this identity still matches.
@@ -216,6 +228,18 @@ export interface ChatTopicMetadata {
onboardingSession?: OnboardingSessionSnapshot;
/** Measured dominant provider by token volume — see {@link ChatTopicMetadata.model}. */
provider?: string;
+ /**
+ * Topic-pinned reasoning effort / mode for the pinned API model
+ * (`ChatTopic.model`). Mirrors the model pin: snapshotted from the user's
+ * model-instance reasoning config when the topic is created, re-snapshotted
+ * for the new model when the user switches model while the topic is active,
+ * and overwritten when the user picks an effort while the topic is active.
+ * Generation resolves "topic config if present (and its pinned model matches
+ * the run model), else the user-level model-instance config" — see
+ * `resolveEffectiveReasoningChatConfig`. An empty object is a valid snapshot:
+ * it pins the topic to the model's own defaults.
+ */
+ reasoningConfig?: AiModelReasoningConfig;
/**
* Web (cloud) only. Ordered list of GitHub repos selected for this topic.
* Each repo will be cloned into the Gateway sandbox before execution.
@@ -471,9 +495,11 @@ export const parseTopicScheduledRun = (raw: unknown): TopicScheduledRun | null =
};
};
-/** Metadata patch accepted by the topic update API. */
export const chatTopicMetadataUpdateSchema = z.object({
boundDeviceId: z.string().optional(),
+ heteroEffort: z
+ .custom<HeterogeneousReasoningEffort>((value) => typeof value === 'string')
+ .optional(),
heteroSessionBindingKey: z.string().optional(),
heteroSessionBindingKeyByWorkingDirectory: z.record(z.string(), z.string()).optional(),
heteroSessionId: z.string().optional(),
@@ -513,6 +539,7 @@ export const chatTopicMetadataUpdateSchema = z.object({
.optional(),
provider: z.string().optional(),
lastSettledOperationId: z.string().optional(),
+ reasoningConfig: AiModelReasoningConfigSchema.optional(),
repos: z.array(z.string()).optional(),
runningOperation: z
.object({
@@ -557,6 +584,15 @@ export const chatTopicMetadataUpdateSchema = z.object({
workingDirectoryConfig: workingDirConfigSchema.optional(),
});
+/**
+ * Metadata a client may seed when creating a topic: the pinned reasoning
+ * snapshot taken alongside the pinned model (see `snapshotAgentModel`).
+ */
+export const chatTopicCreateMetadataSchema = chatTopicMetadataUpdateSchema.pick({
+ heteroEffort: true,
+ reasoningConfig: true,
+});
+
export interface ChatTopicSummary {
content: string;
model: string;
diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsx
index f5cd9d01648..584862d3326 100644
--- a/src/features/ChatInput/ActionBar/Model/index.tsx
+++ b/src/features/ChatInput/ActionBar/Model/index.tsx
@@ -40,9 +40,10 @@ const ModelSwitch = memo(() => {
const enabledModel = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));
const displayName = enabledModel?.displayName || model;
const lockTooltip = useModelLockTooltip(displayName, selectionLockReason);
- // Reasoning effort is a per-model user preference, so it rides along with the
- // model trigger instead of claiming a second action slot.
- const effort = useReasoningEffortControl(model, provider);
+ // Reasoning effort rides along with the model trigger instead of claiming a
+ // second action slot. Like the model, it pins to the active topic when there
+ // is one and edits the user's per-model default otherwise.
+ const effort = useReasoningEffortControl(model, provider, activeTopicId ?? undefined);
// A pinned model still opens the menu when there is an effort to pick there.
const interactive = canSelectModel || effort.hasReasoningParams;
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/index.tsx b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
index 456780d64fc..ff845575cb3 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
+++ b/src/features/ChatInput/ControlBar/HeteroModel/index.tsx
@@ -30,9 +30,10 @@ const HeteroModel = memo(() => {
const { canConfigureResource } = useChatInputResourceAccess();
const enabled = canCreateContent && canConfigureResource;
const patch = useHeteroProviderPatch({ agentId, enabled, provider });
- const topicModel = useChatStore(topicSelectors.activeTopicModel);
+ // Model AND effort pins: both follow the active topic once one exists.
+ const topicPin = useChatStore(topicSelectors.activeTopicHeteroPin, isEqual);
const effectiveProvider = provider
- ? applyTopicModelToHeterogeneousProvider(provider, topicModel)
+ ? applyTopicModelToHeterogeneousProvider(provider, topicPin)
: undefined;
const shape = resolveSelectorShape(effectiveProvider, enabled);
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
index c7ac7d645d0..f58adacddc5 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.test.ts
@@ -7,7 +7,7 @@ const state = vi.hoisted(() => ({
agent: { updateAgentConfigById: vi.fn() },
chat: {
activeTopicId: 'topic-a' as string | null,
- updateTopicModel: vi.fn(),
+ updateTopicHeteroPin: vi.fn(),
},
}));
@@ -23,7 +23,7 @@ describe('useHeteroProviderPatch', () => {
beforeEach(() => {
state.agent.updateAgentConfigById.mockReset();
state.chat.activeTopicId = 'topic-a';
- state.chat.updateTopicModel.mockReset();
+ state.chat.updateTopicHeteroPin.mockReset();
});
it('writes a model selection to the active topic without changing the Agent default', async () => {
@@ -37,14 +37,15 @@ describe('useHeteroProviderPatch', () => {
await act(() => result.current({ model: 'topic-model' }));
- expect(state.chat.updateTopicModel).toHaveBeenCalledWith('topic-a', {
+ expect(state.chat.updateTopicHeteroPin).toHaveBeenCalledWith('topic-a', {
+ effort: undefined,
model: 'topic-model',
provider: 'cursor',
});
expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();
});
- it('keeps non-model compatibility resets global when selecting a topic model', async () => {
+ it('writes model and effort selections to the active topic, never the Agent default', async () => {
const { result } = renderHook(() =>
useHeteroProviderPatch({
agentId: 'agent-a',
@@ -55,10 +56,50 @@ describe('useHeteroProviderPatch', () => {
await act(() => result.current({ effort: 'default', model: 'topic-model' }));
- expect(state.chat.updateTopicModel).toHaveBeenCalledWith('topic-a', {
+ expect(state.chat.updateTopicHeteroPin).toHaveBeenCalledWith('topic-a', {
+ effort: 'default',
model: 'topic-model',
provider: 'codex',
});
+ expect(state.agent.updateAgentConfigById).not.toHaveBeenCalled();
+ });
+
+ it('keeps the remaining dimensions global when selecting a topic effort', async () => {
+ const { result } = renderHook(() =>
+ useHeteroProviderPatch({
+ agentId: 'agent-a',
+ enabled: true,
+ provider: { effort: 'high', model: 'global-model', type: 'codex' },
+ }),
+ );
+
+ await act(() => result.current({ effort: 'medium', speed: 'fast' }));
+
+ expect(state.chat.updateTopicHeteroPin).toHaveBeenCalledWith('topic-a', {
+ effort: 'medium',
+ model: undefined,
+ provider: 'codex',
+ });
+ expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-a', {
+ agencyConfig: {
+ heterogeneousProvider: { args: undefined, speed: 'fast' },
+ },
+ });
+ });
+
+ it('writes the effort to the Agent default when there is no active topic', async () => {
+ state.chat.activeTopicId = null;
+ const { result } = renderHook(() =>
+ useHeteroProviderPatch({
+ agentId: 'agent-a',
+ enabled: true,
+ provider: { effort: 'high', model: 'global-model', type: 'codex' },
+ }),
+ );
+
+ await act(() => result.current({ effort: 'default' }));
+
+ expect(state.chat.updateTopicHeteroPin).not.toHaveBeenCalled();
expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-a', {
agencyConfig: {
heterogeneousProvider: { args: undefined, effort: 'default' },
@@ -78,7 +119,7 @@ describe('useHeteroProviderPatch', () => {
await act(() => result.current({ model: 'next-default' }));
- expect(state.chat.updateTopicModel).not.toHaveBeenCalled();
+ expect(state.chat.updateTopicHeteroPin).not.toHaveBeenCalled();
expect(state.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-a', {
agencyConfig: {
heterogeneousProvider: { args: undefined, model: 'next-default' },
diff --git a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
index d2e7389c360..50076341f37 100644
--- a/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
+++ b/src/features/ChatInput/ControlBar/HeteroModel/useHeteroProviderPatch.ts
@@ -16,15 +16,20 @@ export const useHeteroProviderPatch = ({
}) => {
const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);
const activeTopicId = useChatStore((s) => s.activeTopicId);
- const updateTopicModel = useChatStore((s) => s.updateTopicModel);
+ const updateTopicHeteroPin = useChatStore((s) => s.updateTopicHeteroPin);
return useCallback(
async (selection: HeteroSelection) => {
if (!enabled || !agentId || !provider) return;
- const { model, ...agentSelection } = selection;
- if (activeTopicId && model !== undefined) {
- await updateTopicModel(activeTopicId, { model, provider: provider.type });
+ // Model and effort are topic-scoped once a topic exists (the topic keeps
+ // its own pins, see `ChatTopic.model` / `ChatTopicMetadata.heteroEffort`);
+ // the remaining dimensions (mode, speed) still write the shared agent config.
+ const { effort, model, ...agentSelection } = selection;
+ if (activeTopicId) {
+ if (model !== undefined || effort !== undefined) {
+ await updateTopicHeteroPin(activeTopicId, { effort, model, provider: provider.type });
+ }
if (Object.keys(agentSelection).length === 0) return;
}
await updateAgentConfigById(agentId, {
@@ -36,6 +41,6 @@ export const useHeteroProviderPatch = ({
},
});
},
- [activeTopicId, agentId, enabled, provider, updateAgentConfigById, updateTopicModel],
+ [activeTopicId, agentId, enabled, provider, updateAgentConfigById, updateTopicHeteroPin],
);
};
diff --git a/src/features/ChatInput/hooks/useReasoningEffortControl.test.ts b/src/features/ChatInput/hooks/useReasoningEffortControl.test.ts
index d7fb608b068..1a2e490b594 100644
--- a/src/features/ChatInput/hooks/useReasoningEffortControl.test.ts
+++ b/src/features/ChatInput/hooks/useReasoningEffortControl.test.ts
@@ -11,6 +11,24 @@ const testState = vi.hoisted(() => ({
updateModelReasoningConfig: vi.fn(() => Promise.resolve()),
updating: false,
},
+ chat: {
+ topicEffortUpdatingIds: [] as string[],
+ /** keyed by `${topicId}/${provider}/${model}` — mirrors getTopicReasoningConfigForModel */
+ topicConfigs: {} as Record<string, AiModelReasoningConfig | undefined>,
+ updateTopicReasoningConfig: vi.fn(() => Promise.resolve()),
+ },
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: <T>(selector: (state: typeof testState.chat) => T) => selector(testState.chat),
+}));
+
+vi.mock('@/store/chat/slices/topic/selectors', () => ({
+ topicSelectors: {
+ getTopicReasoningConfigForModel:
+ (topicId: string, model: string, provider: string) => (state: typeof testState.chat) =>
+ state.topicConfigs[`${topicId}/${provider}/${model}`],
+ },
}));
vi.mock('@/store/aiInfra', () => ({
@@ -29,6 +47,9 @@ beforeEach(() => {
testState.ai.reasoningParams = [];
testState.ai.updating = false;
testState.ai.updateModelReasoningConfig.mockClear();
+ testState.chat.topicConfigs = {};
+ testState.chat.topicEffortUpdatingIds = [];
+ testState.chat.updateTopicReasoningConfig.mockClear();
});
describe('useReasoningEffortControl', () => {
@@ -62,6 +83,19 @@ describe('useReasoningEffortControl', () => {
expect(other.current.effortValue).toBe('none');
});
+ it.each([
+ ['thinkingLevel', 'gemini-3-flash-preview', ['minimal', 'low', 'medium', 'high'], 'high'],
+ ['thinkingLevel2', 'gemini-3-pro-preview', ['low', 'high'], 'high'],
+ ['thinkingLevel3', 'gemini-3.7-flash', ['low', 'medium', 'high'], 'medium'],
+ ['thinkingLevel4', 'gemini-3.1-flash-image', ['minimal', 'high'], 'minimal'],
+ ['thinkingLevel', 'gemini-3.1-flash-lite', ['minimal', 'low', 'medium', 'high'], 'minimal'],
+ ])('exposes %s choices and the runtime default for %s', (key, model, levels, fallback) => {
+ testState.ai.reasoningParams = [key as string];
+ const { result } = renderHook(() => useReasoningEffortControl(model as string, 'google'));
+ expect(result.current.effortLevels).toEqual(levels);
+ expect(result.current.effortValue).toBe(fallback);
+ });
+
it('keeps the reasoning mode separate from the effort level', () => {
testState.ai.reasoningParams = ['effort', 'reasoningMode'];
testState.ai.config = { reasoningMode: 'pro' };
@@ -90,4 +124,61 @@ describe('useReasoningEffortControl', () => {
expect(testState.ai.updateModelReasoningConfig).toHaveBeenCalledTimes(1);
});
+
+ describe('topic scope', () => {
+ it('uses the topic in-flight state rather than the shared default mutation', () => {
+ testState.ai.updating = true;
+ const { result, rerender } = renderHook(() =>
+ useReasoningEffortControl('claude', 'anthropic', 'topic-1'),
+ );
+ expect(result.current.updating).toBe(false);
+ testState.chat.topicEffortUpdatingIds = ['topic-1'];
+ rerender();
+ expect(result.current.updating).toBe(true);
+ result.current.select({ effort: 'high' });
+ expect(testState.chat.updateTopicReasoningConfig).not.toHaveBeenCalled();
+ });
+
+ it('shows the topic pin over the user-level config when pinned for this model', () => {
+ testState.ai.reasoningParams = ['effort', 'reasoningMode'];
+ testState.ai.config = { effort: 'low', reasoningMode: 'pro' };
+ testState.chat.topicConfigs['topic-1/anthropic/claude'] = { effort: 'max' };
+
+ const { result } = renderHook(() =>
+ useReasoningEffortControl('claude', 'anthropic', 'topic-1'),
+ );
+
+ expect(result.current.effortValue).toBe('max');
+ // the pin replaces the whole config: an unset mode falls back to the param default
+ expect(result.current.modeValue).toBe('standard');
+ });
+
+ it('falls back to the user-level config when the topic has no pin for this model', () => {
+ testState.ai.reasoningParams = ['effort'];
+ testState.ai.config = { effort: 'low' };
+
+ const { result } = renderHook(() =>
+ useReasoningEffortControl('claude', 'anthropic', 'topic-1'),
+ );
+
+ expect(result.current.effortValue).toBe('low');
+ });
+
+ it('writes the topic pin (seeded from the user-level config) instead of the user config', () => {
+ testState.ai.reasoningParams = ['effort', 'reasoningMode'];
+ testState.ai.config = { effort: 'low', reasoningMode: 'pro' };
+
+ const { result } = renderHook(() =>
+ useReasoningEffortControl('claude', 'anthropic', 'topic-1'),
+ );
+ result.current.select({ effort: 'max' });
+
+ expect(testState.chat.updateTopicReasoningConfig).toHaveBeenCalledWith(
+ 'topic-1',
+ { effort: 'max' },
+ { effort: 'low', reasoningMode: 'pro' },
+ );
+ expect(testState.ai.updateModelReasoningConfig).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/src/features/ChatInput/hooks/useReasoningEffortControl.ts b/src/features/ChatInput/hooks/useReasoningEffortControl.ts
index 9c0184a25d4..a92d2e9972b 100644
--- a/src/features/ChatInput/hooks/useReasoningEffortControl.ts
+++ b/src/features/ChatInput/hooks/useReasoningEffortControl.ts
@@ -1,11 +1,14 @@
'use client';
+import { resolveDefaultThinkingLevelForModel } from '@lobechat/model-runtime/utils/modelExtendParams';
import isEqual from 'fast-deep-equal';
import type { AiModelReasoningConfig } from 'model-bank';
import { MODEL_REASONING_PARAM_DEFAULTS, MODEL_REASONING_PARAM_LEVELS } from 'model-bank';
import { useCallback } from 'react';
import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/slices/topic/selectors';
type EffortKey = Exclude<keyof AiModelReasoningConfig, 'reasoningMode'>;
/** Every level any effort-family param can take — all have a `reasoningEffort.levels.*` label. */
@@ -27,18 +30,28 @@ export interface ReasoningEffortControl {
}
/**
- * Reasoning effort / mode for one model instance, as a user-level setting
- * (userId + providerId + modelId, personal scope) — not part of the agent's
- * chatConfig, so it follows the user across agents and stays writable for
- * chat-only members.
+ * Reasoning effort / mode for one model instance.
*
- * The saved defaults are fetched by ReasoningConfigLoader (mounted in
- * ChatInputProvider), so every control built on this hook and the send pipeline
- * (modelParamsResolver) read the same store value.
+ * Two scopes, mirroring the model pin (`ChatTopic.model`):
+ * - With `topicId` (chat input while a topic is active): reads and writes the
+ * topic's own pin (`ChatTopicMetadata.reasoningConfig`), so one session can
+ * run at a higher effort without retuning anything else. The pin only
+ * applies when it was taken for this very model; otherwise the user-level
+ * value shows and the first pick seeds a pin from it.
+ * - Without `topicId` (new conversation, agent profile): the user-level
+ * model-instance setting (userId + providerId + modelId, personal scope) —
+ * not part of the agent's chatConfig, so it follows the user across agents
+ * and stays writable for chat-only members. It is also what a new topic
+ * snapshots.
+ *
+ * The saved user-level defaults are fetched by ReasoningConfigLoader (mounted
+ * in ChatInputProvider), so every control built on this hook and the send
+ * pipeline (modelParamsResolver) read the same store value.
*/
export const useReasoningEffortControl = (
model: string,
provider: string,
+ topicId?: string,
): ReasoningEffortControl => {
const hasReasoningParams = useAiInfraStore(
aiModelSelectors.isModelHasReasoningExtendParams(model, provider),
@@ -47,19 +60,49 @@ export const useReasoningEffortControl = (
aiModelSelectors.modelReasoningExtendParams(model, provider),
isEqual,
);
- const config = useAiInfraStore(aiModelSelectors.modelReasoningConfig(model, provider), isEqual);
- const updating = useAiInfraStore(
+ const userConfig = useAiInfraStore(
+ aiModelSelectors.modelReasoningConfig(model, provider),
+ isEqual,
+ );
+ const topicConfig = useChatStore(
+ (s) =>
+ topicId
+ ? topicSelectors.getTopicReasoningConfigForModel(topicId, model, provider)(s)
+ : undefined,
+ isEqual,
+ );
+ const config = topicConfig ?? userConfig;
+ const modelUpdating = useAiInfraStore(
aiModelSelectors.isModelReasoningConfigUpdating(model, provider),
);
+ const topicUpdating = useChatStore(
+ (s) => !!topicId && s.topicEffortUpdatingIds.includes(topicId),
+ );
+ const updating = topicId ? topicUpdating : modelUpdating;
const updateModelReasoningConfig = useAiInfraStore((s) => s.updateModelReasoningConfig);
+ const updateTopicReasoningConfig = useChatStore((s) => s.updateTopicReasoningConfig);
const select = useCallback(
(patch: AiModelReasoningConfig) => {
if (updating) return;
+ if (topicId) {
+ // Seed a first-time pin from the user-level config so the topic keeps
+ // e.g. the user's reasoning mode when only the effort was changed.
+ void updateTopicReasoningConfig(topicId, patch, userConfig).catch(() => {});
+ return;
+ }
// failure already rolls back and toasts inside the store action
void updateModelReasoningConfig(model, provider, patch).catch(() => {});
},
- [model, provider, updateModelReasoningConfig, updating],
+ [
+ model,
+ provider,
+ topicId,
+ updateModelReasoningConfig,
+ updateTopicReasoningConfig,
+ updating,
+ userConfig,
+ ],
);
// modelReasoningExtendParams only returns MODEL_REASONING_EXTEND_PARAMS
@@ -72,7 +115,12 @@ export const useReasoningEffortControl = (
const effortDefault = effortKey
? effortKey === 'gpt5_2ReasoningEffort' && model === 'gpt-5.5'
? 'medium'
- : MODEL_REASONING_PARAM_DEFAULTS[effortKey]
+ : effortKey === 'thinkingLevel' ||
+ effortKey === 'thinkingLevel2' ||
+ effortKey === 'thinkingLevel3' ||
+ effortKey === 'thinkingLevel4'
+ ? resolveDefaultThinkingLevelForModel(model, effortKey)
+ : MODEL_REASONING_PARAM_DEFAULTS[effortKey]
: undefined;
return {
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 8058750caa4..e864995df59 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -248,12 +248,12 @@ const runHeterogeneousFromExistingMessage = async (
else if (reason === 'binding_changed')
toast.info(t('heteroAgent.resumeReset.bindingChanged', { ns: 'chat' }));
- const topicModel = context.topicId
- ? topicSelectors.getTopicModelById(context.topicId)(chatStore)
+ const topicPin = context.topicId
+ ? topicSelectors.getTopicHeteroPinById(context.topicId)(chatStore)
: undefined;
const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
heterogeneousProvider,
- topicModel,
+ topicPin,
);
const assistantMsg = await messageService.createMessage({
diff --git a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
index 9075540e384..2c13eb1825d 100644
--- a/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
+++ b/src/features/Conversation/store/slices/generation/continueHeteroAfterError.test.ts
@@ -95,6 +95,8 @@ vi.mock('@/store/agent/selectors', () => ({
vi.mock('@/store/chat/selectors', () => ({
topicSelectors: {
getTopicById: () => () => mockTopic,
+ getTopicHeteroPinById: () => () =>
+ mockTopic?.model ? { model: mockTopic.model, provider: mockTopic.provider || '' } : undefined,
getTopicModelById: () => () =>
mockTopic?.model ? { model: mockTopic.model, provider: mockTopic.provider || '' } : undefined,
},
diff --git a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
index 1ee031ad6c5..42f5ebe4a21 100644
--- a/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
+++ b/src/features/Conversation/store/slices/generation/regenerateHeteroImages.test.ts
@@ -70,6 +70,7 @@ vi.mock('@/store/agent/selectors', () => ({
vi.mock('@/store/chat/selectors', () => ({
topicSelectors: {
getTopicById: () => () => undefined,
+ getTopicHeteroPinById: () => () => undefined,
getTopicModelById: () => () => undefined,
},
}));
diff --git a/src/features/ModelSelect/ReasoningEffortSelect.tsx b/src/features/ModelSelect/ReasoningEffortSelect.tsx
new file mode 100644
index 00000000000..76e297b054e
--- /dev/null
+++ b/src/features/ModelSelect/ReasoningEffortSelect.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import { Tooltip } from '@lobehub/ui';
+import { Select } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useReasoningEffortControl } from '@/features/ChatInput/hooks/useReasoningEffortControl';
+import { useAiInfraStore } from '@/store/aiInfra';
+
+interface ReasoningEffortSelectProps {
+ disabled?: boolean;
+ model: string;
+ provider: string;
+}
+
+/**
+ * Default reasoning effort / mode for the agent's model, shown next to the
+ * model picker on the Agent Profile page.
+ *
+ * Deliberately NOT an agent-level setting: the value is the user's per-model
+ * default (`useReasoningEffortControl` without a topic), the same one the chat
+ * input edits for a new conversation and that every new topic snapshots. The
+ * profile page is simply the natural place to see "what effort will a new
+ * topic with this agent start at", so the hint spells out the shared scope.
+ */
+const ReasoningEffortSelect = memo<ReasoningEffortSelectProps>(({ disabled, model, provider }) => {
+ const { t } = useTranslation(['setting', 'chat']);
+ // The chat input warms this config through ReasoningConfigLoader; the
+ // profile page has no ChatInputProvider, so fetch it here.
+ const useFetchAiModelReasoningConfig = useAiInfraStore((s) => s.useFetchAiModelReasoningConfig);
+ useFetchAiModelReasoningConfig(model, provider);
+
+ const {
+ effortKey,
+ effortLevels,
+ effortValue,
+ hasReasoningMode,
+ hasReasoningParams,
+ modeLevels,
+ modeValue,
+ select,
+ updating,
+ } = useReasoningEffortControl(model, provider);
+
+ if (!hasReasoningParams) return null;
+
+ return (
+ <Tooltip title={t('settingAgent.runtimeConfig.reasoningEffortHint', { ns: 'setting' })}>
+ <div style={{ display: 'flex', gap: 8 }}>
+ {effortKey && (
+ <Select
+ disabled={disabled || updating}
+ placeholder={t('reasoningEffort.title', { ns: 'chat' })}
+ popupMatchSelectWidth={false}
+ value={effortValue}
+ options={effortLevels.map((level) => ({
+ label: t(`reasoningEffort.levels.${level}`, { ns: 'chat' }),
+ value: level,
+ }))}
+ onChange={(value) => {
+ if (typeof value === 'string') select({ [effortKey]: value });
+ }}
+ />
+ )}
+ {hasReasoningMode && (
+ <Select
+ disabled={disabled || updating}
+ popupMatchSelectWidth={false}
+ value={modeValue}
+ options={modeLevels.map((mode) => ({
+ label: t(`reasoningEffort.mode.${mode}`, { ns: 'chat' }),
+ value: mode,
+ }))}
+ onChange={(value) => {
+ if (typeof value === 'string') select({ reasoningMode: value as typeof modeValue });
+ }}
+ />
+ )}
+ </div>
+ </Tooltip>
+ );
+});
+
+ReasoningEffortSelect.displayName = 'ReasoningEffortSelect';
+
+export default ReasoningEffortSelect;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
index e395356a4f5..99055870521 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ApiModeModelBar.tsx
@@ -5,6 +5,7 @@ import type { HeterogeneousApiConfig } from '@lobechat/types';
import { applyTopicModelToHeterogeneousProvider } from '@lobechat/types';
import { TooltipGroup } from '@lobehub/ui';
import { Select } from '@lobehub/ui/base-ui';
+import isEqual from 'fast-deep-equal';
import { memo, useMemo } from 'react';
import { useProviderBindingCompatibleProviders } from '@/features/HeterogeneousAgent/hooks/useProviderBinding';
@@ -35,7 +36,7 @@ const ApiModeModelBar = memo<ApiModeModelBarProps>(({ agentId }) => {
const updateAgentConfigById = useAgentStore((state) => state.updateAgentConfigById);
const heterogeneousProvider = agencyConfig?.heterogeneousProvider;
const activeTopicId = useChatStore((state) => state.activeTopicId);
- const topicModel = useChatStore(topicSelectors.activeTopicModel);
+ const topicModel = useChatStore(topicSelectors.activeTopicHeteroPin, isEqual);
const updateTopicModel = useChatStore((state) => state.updateTopicModel);
const { providers } = useProviderBindingCompatibleProviders(heterogeneousProvider?.type);
const providerIds = useMemo(() => providers.map(({ id }) => id), [providers]);
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
index aa6cfabbdf5..3dfe6dcd8dc 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx
@@ -18,6 +18,7 @@ import { useTranslation } from 'react-i18next';
import { resolveServerDefaultAgentModels } from '@/features/HeterogeneousAgent/modelPicker';
import ModelSelect from '@/features/ModelSelect';
+import ReasoningEffortSelect from '@/features/ModelSelect/ReasoningEffortSelect';
import RunPriorityHint from '@/features/ProfileEditor/AgentUserTools/RunPriorityHint';
import { resolveExecutionTarget } from '@/helpers/executionTarget';
import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';
@@ -270,6 +271,13 @@ const ProfileEditor = memo(() => {
void updateAgentConfigById(agentId, value);
}}
/>
+ {config?.model && config.provider && (
+ <ReasoningEffortSelect
+ disabled={!canEdit}
+ model={config.model}
+ provider={config.provider}
+ />
+ )}
</Flexbox>
<AgentTool />
</Flexbox>
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 8e11377c6a2..6b57e8bcab4 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -35,6 +35,7 @@ import {
} from '@/store/agent/selectors';
import { aiModelSelectors, aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
import { getChatStoreState } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import { getToolStoreState } from '@/store/tool';
import {
builtinToolSelectors,
@@ -340,6 +341,15 @@ class ChatService {
model: payload.model,
provider: payload.provider!,
subAgentChatConfigOverride: resolvedAgentConfig.subAgentChatConfigOverride,
+ // The topic's own effort pin (only when pinned for this very model — a
+ // sub-agent modelOverride must not inherit the parent topic's effort).
+ topicReasoningConfig: topicId
+ ? topicSelectors.getTopicReasoningConfigForModel(
+ topicId,
+ payload.model,
+ payload.provider!,
+ )(getChatStoreState())
+ : undefined,
});
// For models governed by the reasoning extend-params family the user-level
diff --git a/src/services/chat/mecha/modelParamsResolver.test.ts b/src/services/chat/mecha/modelParamsResolver.test.ts
index a7e41585766..eab590c2224 100644
--- a/src/services/chat/mecha/modelParamsResolver.test.ts
+++ b/src/services/chat/mecha/modelParamsResolver.test.ts
@@ -771,6 +771,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel when supported and configured', () => {
+ mockModelReasoningConfig({ thinkingLevel: 'high' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel: 'high',
@@ -793,6 +794,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel from thinkingLevel config key for gemini-3.5-flash', () => {
+ mockModelReasoningConfig({ thinkingLevel: 'low' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel: 'low',
@@ -817,6 +819,7 @@ describe('thinking configuration', () => {
it.each(['minimal', 'low', 'medium', 'high'] as const)(
'should forward the %s thinkingLevel for Gemini 3.6 Flash',
(thinkingLevel) => {
+ mockModelReasoningConfig({ thinkingLevel });
const result = resolveModelExtendParams({
chatConfig: { thinkingLevel } as any,
model: 'gemini-3.6-flash',
@@ -852,6 +855,7 @@ describe('thinking configuration', () => {
});
it('should reuse thinkingLevel for Gemini 3.1 Flash-Lite models', () => {
+ mockModelReasoningConfig({ thinkingLevel: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel: 'medium',
@@ -864,6 +868,7 @@ describe('thinking configuration', () => {
});
it('should reuse thinkingLevel for Gemini 3.5 Flash-Lite', () => {
+ mockModelReasoningConfig({ thinkingLevel: 'high' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel: 'high',
@@ -907,6 +912,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel from thinkingLevel2 config key', () => {
+ mockModelReasoningConfig({ thinkingLevel2: 'low' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel2: 'low',
@@ -940,6 +946,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel from thinkingLevel3 config key', () => {
+ mockModelReasoningConfig({ thinkingLevel3: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel3: 'medium',
@@ -962,6 +969,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel from thinkingLevel3 config key for gemini-3.7-flash', () => {
+ mockModelReasoningConfig({ thinkingLevel3: 'high' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel3: 'high',
@@ -995,6 +1003,7 @@ describe('thinking configuration', () => {
});
it('should set thinkingLevel from thinkingLevel4 config key', () => {
+ mockModelReasoningConfig({ thinkingLevel4: 'minimal' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel4: 'minimal',
@@ -1027,6 +1036,7 @@ describe('thinking configuration', () => {
'thinkingLevel3',
]);
+ mockModelReasoningConfig({ thinkingLevel: 'high', thinkingLevel3: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel: 'high',
@@ -1048,6 +1058,7 @@ describe('thinking configuration', () => {
'thinkingLevel3',
]);
+ mockModelReasoningConfig({ thinkingLevel3: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
thinkingLevel3: 'medium',
@@ -1290,11 +1301,12 @@ describe('multiple params combination', () => {
'thinkingLevel',
]);
+ mockModelReasoningConfig({ thinkingLevel: 'high' });
const result = resolveModelExtendParams({
chatConfig: {
thinking: 'enabled',
thinkingBudget: 8000,
- thinkingLevel: 'expert',
+ thinkingLevel: 'high',
} as any,
model: 'deepseek',
provider: 'deepseek',
@@ -1305,7 +1317,7 @@ describe('multiple params combination', () => {
type: 'enabled',
},
thinkingBudget: 8000,
- thinkingLevel: 'expert',
+ thinkingLevel: 'high',
});
});
});
@@ -1605,11 +1617,12 @@ describe('parameter precedence and conflicts', () => {
'thinkingLevel',
]);
+ mockModelReasoningConfig({ thinkingLevel: 'medium' });
const result = resolveModelExtendParams({
chatConfig: {
thinking: 'enabled',
thinkingBudget: 5000,
- thinkingLevel: 'advanced',
+ thinkingLevel: 'medium',
} as any,
model: 'model',
provider: 'provider',
@@ -1618,7 +1631,7 @@ describe('parameter precedence and conflicts', () => {
// These are independent params and should all be set
expect(result.thinking).toEqual({ type: 'enabled' });
expect(result.thinkingBudget).toBe(5000);
- expect(result.thinkingLevel).toBe('advanced');
+ expect(result.thinkingLevel).toBe('medium');
});
});
@@ -1782,6 +1795,44 @@ describe('model-instance reasoning config migration', () => {
expect(result.verbosity).toBe('concise');
});
+ it('should let the topic pin win over the model-instance config', () => {
+ mockModelReasoningConfig({ reasoningEffort: 'low' });
+
+ const result = resolveModelExtendParams({
+ chatConfig: { reasoningEffort: 'medium' } as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ topicReasoningConfig: { reasoningEffort: 'high' },
+ });
+
+ expect(result.reasoning_effort).toBe('high');
+ });
+
+ it('should treat an empty topic pin as "model defaults", not as a missing pin', () => {
+ mockModelReasoningConfig({ reasoningEffort: 'low' });
+
+ const result = resolveModelExtendParams({
+ chatConfig: {} as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ topicReasoningConfig: {},
+ });
+
+ expect(result.reasoning_effort).toBeUndefined();
+ });
+
+ it('should let explicit sub-agent overrides win over the topic pin', () => {
+ const result = resolveModelExtendParams({
+ chatConfig: {} as any,
+ model: 'gpt-4',
+ provider: 'openai',
+ subAgentChatConfigOverride: { reasoningEffort: 'medium' },
+ topicReasoningConfig: { reasoningEffort: 'high' },
+ });
+
+ expect(result.reasoning_effort).toBe('medium');
+ });
+
it('should let explicit sub-agent overrides win over model-instance config', () => {
mockModelReasoningConfig({ reasoningEffort: 'low' });
@@ -1821,3 +1872,35 @@ describe('model-instance reasoning config migration', () => {
expect(result.verbosity).toBe('concise');
});
});
+
+describe('Gemini topic thinking levels', () => {
+ it('uses the saved user level, then the topic pin, and ignores legacy agent values', () => {
+ vi.spyOn(aiInfraStore, 'getAiInfraStoreState').mockReturnValue(
+ {} as ReturnType<typeof aiInfraStore.getAiInfraStoreState>,
+ );
+ vi.spyOn(aiModelSelectors.aiModelSelectors, 'isModelHasExtendParams').mockReturnValue(
+ () => true,
+ );
+ vi.spyOn(aiModelSelectors.aiModelSelectors, 'modelExtendParams').mockReturnValue(() => [
+ 'thinkingLevel3',
+ ]);
+ mockModelReasoningConfig({ thinkingLevel3: 'low' });
+ const context = {
+ chatConfig: { thinkingLevel3: 'medium' as const },
+ model: 'gemini-3.1-pro-preview',
+ provider: 'google',
+ };
+ expect(resolveModelExtendParams(context).thinkingLevel).toBe('low');
+ expect(
+ resolveModelExtendParams({ ...context, topicReasoningConfig: { thinkingLevel3: 'high' } })
+ .thinkingLevel,
+ ).toBe('high');
+ expect(
+ resolveModelExtendParams({
+ ...context,
+ topicReasoningConfig: {},
+ subAgentChatConfigOverride: { thinkingLevel3: 'medium' },
+ }).thinkingLevel,
+ ).toBe('medium');
+ });
+});
diff --git a/src/services/chat/mecha/modelParamsResolver.ts b/src/services/chat/mecha/modelParamsResolver.ts
index be613d648db..70ea11269b5 100644
--- a/src/services/chat/mecha/modelParamsResolver.ts
+++ b/src/services/chat/mecha/modelParamsResolver.ts
@@ -6,6 +6,7 @@ import {
resolveEffectiveReasoningChatConfig,
} from '@lobechat/model-runtime/utils/modelExtendParams';
import type { LobeAgentChatConfig } from '@lobechat/types';
+import type { AiModelReasoningConfig } from 'model-bank';
import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';
@@ -24,6 +25,12 @@ export interface ModelParamsContext {
* over the user's model-instance defaults.
*/
subAgentChatConfigOverride?: Partial<LobeAgentChatConfig>;
+ /**
+ * Reasoning config pinned to the topic for exactly this model
+ * (`topicSelectors.getTopicReasoningConfigForModel`). Wins over the
+ * user-level model-instance config; absent → user-level applies.
+ */
+ topicReasoningConfig?: AiModelReasoningConfig;
}
/**
@@ -33,12 +40,13 @@ export interface ModelParamsContext {
* 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.
+ * Reasoning fields (effort family + reasoningMode) resolve as topic pin → user-level
+ * model-instance setting: same-named agent chatConfig values are ignored and the topic's
+ * pinned config (or, without one, 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, subAgentChatConfigOverride } = ctx;
+ const { model, provider, chatConfig, subAgentChatConfigOverride, topicReasoningConfig } = ctx;
const aiInfraStoreState = getAiInfraStoreState();
@@ -55,7 +63,9 @@ export const resolveModelExtendParams = (ctx: ModelParamsContext): ModelExtendPa
const effectiveChatConfig = resolveEffectiveReasoningChatConfig({
agentChatConfig: chatConfig,
- modelReasoningConfig: aiModelSelectors.modelReasoningConfig(model, provider)(aiInfraStoreState),
+ modelReasoningConfig:
+ topicReasoningConfig ??
+ aiModelSelectors.modelReasoningConfig(model, provider)(aiInfraStoreState),
subAgentReasoningOverrides: subAgentChatConfigOverride,
});
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index e7b028a4086..f16c6d61bba 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -155,6 +155,17 @@ export class TopicService {
return lambdaClient.topic.updateTopic.mutate({ id, value: data });
};
+ updateTopicModel = (
+ id: string,
+ value: {
+ metadata?: Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>;
+ model: string;
+ provider: string;
+ },
+ ) => {
+ return lambdaClient.topic.updateTopicModel.mutate({ id, ...value });
+ };
+
updateTopicMetadata = (id: string, metadata: UpdateTopicMetadataInput) => {
return lambdaClient.topic.updateTopicMetadata.mutate({ id, metadata });
};
diff --git a/src/store/aiInfra/slices/aiModel/selectors.ts b/src/store/aiInfra/slices/aiModel/selectors.ts
index dbc9238cc0c..3ef0bc071de 100644
--- a/src/store/aiInfra/slices/aiModel/selectors.ts
+++ b/src/store/aiInfra/slices/aiModel/selectors.ts
@@ -145,6 +145,15 @@ const isModelHasNonReasoningExtendParams =
const modelReasoningConfig = (id: string, provider: string) => (s: AIProviderStoreState) =>
s.modelReasoningConfigMap?.[modelReasoningConfigKey(provider, id)];
+/**
+ * Whether `ensureModelReasoningConfig` / the SWR loader has settled the saved
+ * config for this model (the key is kept even when nothing is saved). Topic
+ * snapshots must not pin "model defaults" while the real value is still in
+ * flight, so they skip pinning until this is true.
+ */
+const isModelReasoningConfigLoaded = (id: string, provider: string) => (s: AIProviderStoreState) =>
+ modelReasoningConfigKey(provider, id) in (s.modelReasoningConfigMap ?? {});
+
const isModelReasoningConfigUpdating =
(id: string, provider: string) => (s: AIProviderStoreState) =>
!!s.modelReasoningConfigUpdatingKeys?.includes(modelReasoningConfigKey(provider, id));
@@ -212,6 +221,7 @@ export const aiModelSelectors = {
isModelHasNonReasoningExtendParams,
isModelHasReasoningExtendParams,
isModelLoading,
+ isModelReasoningConfigLoaded,
isModelReasoningConfigUpdating,
isModelSupportAudio,
isModelSupportFiles,
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 536e663464a..12a64f08722 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -10,6 +10,8 @@ import { chatService } from '@/services/chat';
import * as skillPreload from '@/services/chat/mecha/skillPreload';
import { messageService } from '@/services/message';
import * as agentGroupStore from '@/store/agentGroup';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';
import { setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import type {
@@ -1517,6 +1519,18 @@ describe('ConversationLifecycle actions', () => {
it('should snapshot the agent model onto the newTopic (top-level) when the send creates the topic', async () => {
const { result } = renderHook(() => useChatStore());
const agentId = TEST_IDS.SESSION_ID;
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => true);
+ let loaded = false;
+ vi.spyOn(aiModelSelectors, 'isModelReasoningConfigLoaded').mockReturnValue(() => loaded);
+ vi.spyOn(useAiInfraStore.getState(), 'ensureModelReasoningConfig').mockImplementation(
+ async () => {
+ await Promise.resolve();
+ loaded = true;
+ },
+ );
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ reasoningEffort: 'high',
+ }));
const newTopicId = TEST_IDS.NEW_TOPIC_ID;
act(() => {
@@ -1560,6 +1574,7 @@ describe('ConversationLifecycle actions', () => {
expect(sendMessageInServerSpy).toHaveBeenCalledWith(
expect.objectContaining({
newTopic: expect.objectContaining({
+ metadata: expect.objectContaining({ reasoningConfig: { reasoningEffort: 'high' } }),
model: expect.any(String),
provider: expect.any(String),
}),
@@ -2207,6 +2222,16 @@ describe('ConversationLifecycle actions', () => {
window.__LOBE_GLOBAL_AGENT_CONTEXT__ = { desktopPath: DESKTOP_PATH };
});
+ it('snapshots the heterogeneous effort into the first-send topic', async () => {
+ const sendSpy = setupHeteroRun({
+ heterogeneousProvider: { command: 'codex', effort: 'high', type: 'codex' },
+ });
+ await sendHeteroMessage();
+ expect(sendSpy.mock.calls[0][0].newTopic?.metadata).toMatchObject({
+ heteroEffort: 'high',
+ });
+ });
+
it('prefers the bound device defaultCwd over the desktop fallback', async () => {
const sendMessageInServerSpy = setupHeteroRun();
act(() => {
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 4de4bc48ba6..9e6da72c749 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -80,6 +80,7 @@ import {
} from '@/store/chat/slices/operation/types';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';
+import { resolveTopicHeteroPin } from '@/store/chat/slices/topic/selectors';
import { type ChatStore } from '@/store/chat/store';
import {
mergeAgentRuntimeInitialContexts,
@@ -92,7 +93,7 @@ import {
} from '@/store/chat/utils/compression';
import { isLocalOnlyMessage } from '@/store/chat/utils/localMessages';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';
+import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { deviceSelectors, getDeviceStoreState } from '@/store/device';
import { getElectronStoreState } from '@/store/electron';
@@ -1193,7 +1194,10 @@ export class ConversationLifecycleActionImpl {
: [];
// Example: a pending repo topic without this metadata renders under "No
// directory" until the server row lands.
- const optimisticTopicMetadata: ChatTopicMetadata | undefined =
+ const newTopicReasoningSnapshot = newTopicModelSnapshot
+ ? await snapshotAgentReasoning(operationContext.agentId, newTopicModelSnapshot)
+ : undefined;
+ const workingDirectoryMetadata: ChatTopicMetadata | undefined =
pendingTopicRepos.length > 0
? {
repos: pendingTopicRepos,
@@ -1206,6 +1210,10 @@ export class ConversationLifecycleActionImpl {
...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),
}
: undefined;
+ /** First-send persistence bypasses turnSetup, so both runtime paths must carry the effort snapshot. */
+ const optimisticTopicMetadata = newTopicReasoningSnapshot
+ ? { ...workingDirectoryMetadata, ...newTopicReasoningSnapshot }
+ : workingDirectoryMetadata;
// The sidebar row was already inserted (title + model) before the awaits
// above; the cwd/repos metadata only resolves here, so patch it on now.
@@ -1364,12 +1372,7 @@ export class ConversationLifecycleActionImpl {
? {
// Same id the optimistic sidebar row already uses.
id: optimisticTopic?.id,
- metadata: workingDirectory
- ? {
- workingDirectory,
- ...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),
- }
- : undefined,
+ metadata: optimisticTopicMetadata,
...newTopicModelSnapshot,
title: newTopicTitle,
topicMessageIds: messages.map((m) => m.id),
@@ -1617,7 +1620,7 @@ export class ConversationLifecycleActionImpl {
}
const effectiveHeterogeneousProvider = applyTopicModelToHeterogeneousProvider(
heterogeneousProvider,
- topic?.model ? { model: topic.model, provider: topic.provider || '' } : undefined,
+ resolveTopicHeteroPin(topic),
);
await executeHeterogeneousAgent(() => this.#get(), {
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 106c4e870bc..cb040abaeec 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -1,6 +1,7 @@
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';
import { TOPIC_TITLE_JSON_SCHEMA } from '@lobechat/prompts';
import type { LobeUser, UIChatMessage } from '@lobechat/types';
+import { toast } from '@lobehub/ui/base-ui';
import { act, renderHook, waitFor } from '@testing-library/react';
import { type Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -12,6 +13,8 @@ import { chatService } from '@/services/chat';
import { messageService } from '@/services/message';
import { topicService } from '@/services/topic';
import { useAgentStore } from '@/store/agent';
+import { useAiInfraStore } from '@/store/aiInfra';
+import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';
import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
@@ -21,6 +24,11 @@ import { type ChatTopic } from '@/types/topic';
import { useChatStore } from '../../store';
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = await importOriginal<{ toast: Record<string, unknown> }>();
+ return { ...actual, toast: { ...actual.toast, error: vi.fn() } };
+});
+
// Mock @/libs/swr mutate
vi.mock('@/libs/swr', async () => {
const actual = await vi.importActual('@/libs/swr');
@@ -42,6 +50,7 @@ vi.mock('@/services/topic', () => ({
createTopic: vi.fn(),
updateTopicFavorite: vi.fn(),
updateTopicMetadata: vi.fn(),
+ updateTopicModel: vi.fn(),
updateTopicTitle: vi.fn(),
updateTopic: vi.fn(),
batchRemoveTopics: vi.fn(),
@@ -337,7 +346,7 @@ describe('topic action', () => {
it('applies the switch to the bucket that owns the topic', async () => {
const { result } = renderHook(() => useChatStore());
- vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);
+ vi.spyOn(topicService, 'updateTopicModel').mockResolvedValue(undefined as any);
seedBuilderTopic();
await act(async () => {
@@ -355,7 +364,7 @@ describe('topic action', () => {
it('revalidates the owning bucket instead of the active agent bucket', async () => {
const { result } = renderHook(() => useChatStore());
- vi.spyOn(topicService, 'updateTopic').mockResolvedValue(undefined as any);
+ vi.spyOn(topicService, 'updateTopicModel').mockResolvedValue(undefined as any);
(mutate as Mock).mockClear();
seedBuilderTopic();
@@ -370,6 +379,399 @@ describe('topic action', () => {
expect(matcherFn(['topic:list', BUILDER_KEY, { pageSize: 20 }])).toBe(true);
expect(matcherFn(['topic:list', topicMapKey({ agentId: 'edited-agent' }), {}])).toBe(false);
});
+
+ it('writes model and the re-pinned reasoning config in one request', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const spy = vi.spyOn(topicService, 'updateTopicModel').mockResolvedValue(undefined as any);
+ seedBuilderTopic();
+ act(() => {
+ useChatStore.setState({
+ internal_resolveTopicReasoningSnapshot: vi
+ .fn()
+ .mockResolvedValue({ deepseekV4GAReasoningEffort: 'high' }),
+ });
+ });
+
+ await act(async () => {
+ await result.current.updateTopicModel('builder-topic', {
+ model: 'deepseek-v4-flash',
+ provider: 'lobehub',
+ });
+ });
+
+ expect(spy).toHaveBeenCalledWith('builder-topic', {
+ metadata: { reasoningConfig: { deepseekV4GAReasoningEffort: 'high' } },
+ model: 'deepseek-v4-flash',
+ provider: 'lobehub',
+ });
+ expect(useChatStore.getState().topicDataMap[BUILDER_KEY].items[0]).toMatchObject({
+ metadata: { reasoningConfig: { deepseekV4GAReasoningEffort: 'high' } },
+ model: 'deepseek-v4-flash',
+ });
+ });
+
+ it('drops the previous pin when the new model has no reasoning params', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const spy = vi.spyOn(topicService, 'updateTopicModel').mockResolvedValue(undefined as any);
+ seedBuilderTopic();
+ act(() => {
+ const key = BUILDER_KEY;
+ const state = useChatStore.getState();
+ useChatStore.setState({
+ internal_resolveTopicReasoningSnapshot: vi.fn().mockResolvedValue(undefined),
+ topicDataMap: {
+ [key]: {
+ ...state.topicDataMap[key],
+ items: [
+ {
+ ...state.topicDataMap[key].items[0],
+ metadata: {
+ reasoningConfig: { glm5_2ReasoningEffort: 'max' },
+ workingDirectory: '/w',
+ },
+ },
+ ],
+ },
+ },
+ });
+ });
+
+ await act(async () => {
+ await result.current.updateTopicModel('builder-topic', {
+ model: 'plain-model',
+ provider: 'lobehub',
+ });
+ });
+
+ expect(spy).toHaveBeenCalledWith('builder-topic', {
+ metadata: undefined,
+ model: 'plain-model',
+ provider: 'lobehub',
+ });
+ expect(useChatStore.getState().topicDataMap[BUILDER_KEY].items[0].metadata).toEqual({
+ workingDirectory: '/w',
+ });
+ });
+ });
+
+ describe('updateTopicHeteroPin', () => {
+ const KEY = topicMapKey({ agentId: 'hetero-agent' });
+ const seed = () => {
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'hetero-agent',
+ activeTopicId: 'hetero-topic',
+ topicDataMap: {
+ [KEY]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [
+ {
+ id: 'hetero-topic',
+ metadata: { heteroEffort: 'high' },
+ model: 'old-model',
+ provider: 'codex',
+ title: 'Hetero',
+ } as ChatTopic,
+ ],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+ };
+
+ it('writes model and effort reset in one request', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const spy = vi.spyOn(topicService, 'updateTopicModel').mockResolvedValue(undefined as any);
+ seed();
+
+ await act(async () => {
+ await result.current.updateTopicHeteroPin('hetero-topic', {
+ effort: 'default',
+ model: 'new-model',
+ provider: 'codex',
+ });
+ });
+
+ expect(spy).toHaveBeenCalledWith('hetero-topic', {
+ metadata: { heteroEffort: 'default' },
+ model: 'new-model',
+ provider: 'codex',
+ });
+ });
+
+ it.each(['heterogeneous', 'api'] as const)(
+ 'preserves the latest effort when a %s model write finishes later',
+ async (kind) => {
+ seed();
+ let finishModel!: () => void;
+ const modelPending = new Promise<void>((resolve) => {
+ finishModel = resolve;
+ });
+ let persistedEffort = 'high';
+ const modelSpy = vi.spyOn(topicService, 'updateTopicModel').mockImplementation(async () => {
+ await modelPending;
+ persistedEffort = 'default';
+ return [];
+ });
+ vi.spyOn(topicService, 'updateTopicMetadata').mockImplementation(async () => {
+ persistedEffort = 'low';
+ return [];
+ });
+ vi.spyOn(
+ useChatStore.getState(),
+ 'internal_resolveTopicReasoningSnapshot',
+ ).mockResolvedValue({ reasoningEffort: 'high' });
+ let modelWrite!: Promise<void>;
+ act(() => {
+ modelWrite =
+ kind === 'heterogeneous'
+ ? useChatStore.getState().updateTopicHeteroPin('hetero-topic', {
+ model: 'new-model',
+ provider: 'codex',
+ effort: 'default',
+ })
+ : useChatStore
+ .getState()
+ .updateTopicModel('hetero-topic', { model: 'new-model', provider: 'openai' });
+ });
+ await waitFor(() => expect(modelSpy).toHaveBeenCalledTimes(1));
+ let effortWrite!: Promise<void>;
+ act(() => {
+ effortWrite =
+ kind === 'heterogeneous'
+ ? useChatStore.getState().updateTopicHeteroEffort('hetero-topic', 'low')
+ : useChatStore
+ .getState()
+ .updateTopicReasoningConfig('hetero-topic', { reasoningEffort: 'low' });
+ });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ await act(async () => {
+ finishModel();
+ await Promise.all([modelWrite, effortWrite]);
+ });
+ expect(persistedEffort).toBe('low');
+ expect(useChatStore.getState().topicEffortUpdatingIds).not.toContain('hetero-topic');
+ },
+ );
+
+ it('restores the persisted topic after a model pin fails', async () => {
+ seed();
+ const saved = useChatStore.getState().topicDataMap[KEY];
+ vi.spyOn(topicService, 'updateTopicModel').mockRejectedValue(new Error('offline'));
+ const refresh = vi
+ .spyOn(useChatStore.getState(), 'refreshTopic')
+ .mockImplementation(async () => {
+ useChatStore.setState({ topicDataMap: { [KEY]: saved } });
+ });
+ await act(async () => {
+ await expect(
+ useChatStore.getState().updateTopicHeteroPin('hetero-topic', {
+ model: 'new-model',
+ provider: 'codex',
+ effort: 'low',
+ }),
+ ).rejects.toThrow('offline');
+ });
+ expect(refresh).toHaveBeenCalledWith(KEY);
+ expect(useChatStore.getState().topicDataMap[KEY]?.items[0].model).toBe('old-model');
+ expect(toast.error).toHaveBeenCalled();
+ });
+
+ it.each(['model', 'effort'])(
+ 'rolls back a failed %s pin even when revalidation fails',
+ async (kind) => {
+ seed();
+ const previous = useChatStore.getState().topicDataMap[KEY]?.items[0];
+ vi.spyOn(topicService, 'updateTopicModel').mockRejectedValue(new Error('write failed'));
+ vi.spyOn(topicService, 'updateTopicMetadata').mockRejectedValue(new Error('write failed'));
+ vi.spyOn(useChatStore.getState(), 'refreshTopic').mockRejectedValue(
+ new Error('refresh failed'),
+ );
+ await act(async () => {
+ await expect(
+ useChatStore.getState().updateTopicHeteroPin('hetero-topic', {
+ ...(kind === 'model' ? { model: 'new-model' } : {}),
+ provider: 'codex',
+ effort: 'low',
+ }),
+ ).rejects.toThrow('write failed');
+ });
+ const restored = useChatStore.getState().topicDataMap[KEY]?.items[0];
+ expect(restored?.model).toEqual(previous?.model);
+ expect(restored?.metadata).toEqual(previous?.metadata);
+ expect(toast.error).toHaveBeenCalled();
+ },
+ );
+
+ it('writes only the effort when no model is selected', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const updateTopicSpy = vi
+ .spyOn(topicService, 'updateTopic')
+ .mockResolvedValue(undefined as any);
+ const metadataSpy = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockResolvedValue(undefined as any);
+ seed();
+
+ await act(async () => {
+ await result.current.updateTopicHeteroPin('hetero-topic', {
+ effort: 'low',
+ provider: 'codex',
+ });
+ });
+
+ expect(updateTopicSpy).not.toHaveBeenCalled();
+ expect(metadataSpy).toHaveBeenCalledWith('hetero-topic', { heteroEffort: 'low' });
+ });
+ });
+
+ describe('updateTopicReasoningConfig', () => {
+ const KEY = topicMapKey({ agentId: 'agent-1' });
+ const seedTopic = () => {
+ const timestamp = Date.now();
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: 'agent-1',
+ activeTopicId: 'topic-1',
+ topicDataMap: {
+ [KEY]: {
+ currentPage: 0,
+ hasMore: false,
+ items: [
+ {
+ id: 'topic-1',
+ metadata: {
+ reasoningConfig: { reasoningEffort: 'low', reasoningMode: 'standard' },
+ },
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ title: 'Topic',
+ } satisfies ChatTopic,
+ ],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ });
+ });
+ };
+
+ it('keeps a persisted effort when only the follow-up refresh fails', async () => {
+ seedTopic();
+ vi.spyOn(topicService, 'updateTopicMetadata').mockResolvedValue([]);
+ vi.spyOn(useChatStore.getState(), 'refreshTopic').mockRejectedValue(
+ new Error('refresh failed'),
+ );
+ await act(async () => {
+ await expect(
+ useChatStore
+ .getState()
+ .updateTopicReasoningConfig('topic-1', { reasoningEffort: 'high' }),
+ ).rejects.toThrow('refresh failed');
+ });
+ expect(useChatStore.getState().topicDataMap[KEY]?.items[0].metadata?.reasoningConfig).toEqual(
+ {
+ reasoningEffort: 'high',
+ reasoningMode: 'standard',
+ },
+ );
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('serializes consecutive selections through persistence and refresh', async () => {
+ seedTopic();
+ let finishFirst!: () => void;
+ const firstWrite = new Promise<void>((resolve) => {
+ finishFirst = resolve;
+ });
+ const spy = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockImplementationOnce(async () => {
+ await firstWrite;
+ return [];
+ })
+ .mockResolvedValue([]);
+ let first!: Promise<void>;
+ let second!: Promise<void>;
+ act(() => {
+ first = useChatStore
+ .getState()
+ .updateTopicReasoningConfig('topic-1', { reasoningEffort: 'high' });
+ second = useChatStore
+ .getState()
+ .updateTopicReasoningConfig('topic-1', { reasoningMode: 'pro' });
+ });
+ await waitFor(() => expect(spy).toHaveBeenCalledTimes(1));
+ expect(useChatStore.getState().topicEffortUpdatingIds).toContain('topic-1');
+ await act(async () => {
+ finishFirst();
+ await Promise.all([first, second]);
+ });
+ expect(spy).toHaveBeenCalledTimes(2);
+ expect(spy).toHaveBeenLastCalledWith('topic-1', {
+ reasoningConfig: { reasoningEffort: 'high', reasoningMode: 'pro' },
+ });
+ expect(useChatStore.getState().topicEffortUpdatingIds).not.toContain('topic-1');
+ });
+
+ it('releases the updating state after failure and accepts another selection', async () => {
+ seedTopic();
+ const spy = vi
+ .spyOn(topicService, 'updateTopicMetadata')
+ .mockRejectedValueOnce(new Error('failed'))
+ .mockResolvedValue([]);
+ await act(async () => {
+ await expect(
+ useChatStore
+ .getState()
+ .updateTopicReasoningConfig('topic-1', { reasoningEffort: 'high' }),
+ ).rejects.toThrow('failed');
+ });
+ expect(useChatStore.getState().topicEffortUpdatingIds).not.toContain('topic-1');
+ await act(async () => {
+ await useChatStore
+ .getState()
+ .updateTopicReasoningConfig('topic-1', { reasoningEffort: 'medium' });
+ });
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+
+ it('merges the patch over the current topic pin', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const spy = vi.spyOn(topicService, 'updateTopicMetadata').mockResolvedValue(undefined as any);
+ seedTopic();
+
+ await act(async () => {
+ await result.current.updateTopicReasoningConfig('topic-1', { reasoningEffort: 'high' });
+ });
+
+ expect(spy).toHaveBeenCalledWith('topic-1', {
+ reasoningConfig: { reasoningEffort: 'high', reasoningMode: 'standard' },
+ });
+ });
+
+ it('revalidates and toasts when the pin cannot be saved', async () => {
+ const { result } = renderHook(() => useChatStore());
+ vi.spyOn(topicService, 'updateTopicMetadata').mockRejectedValue(new Error('offline'));
+ seedTopic();
+ const refreshTopic = vi.fn();
+ act(() => {
+ useChatStore.setState({ refreshTopic });
+ });
+
+ await expect(
+ result.current.updateTopicReasoningConfig('topic-1', { reasoningEffort: 'high' }),
+ ).rejects.toThrow('offline');
+
+ expect(refreshTopic).toHaveBeenCalledWith(KEY);
+ expect(toast.error).toHaveBeenCalled();
+ });
});
describe('favoriteTopic', () => {
@@ -2734,6 +3136,52 @@ describe('topic action', () => {
});
});
describe('createTopic', () => {
+ it.each(['createTopic', 'saveToTopic'] as const)(
+ '%s waits for saved reasoning before persisting',
+ async (method) => {
+ const agentId = 'test-session-id';
+ useChatStore.setState({
+ activeAgentId: agentId,
+ messagesMap: { [messageMapKey({ agentId })]: [{ id: 'message-1' } as UIChatMessage] },
+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),
+ });
+ let loaded = false;
+ let finishLoad!: () => void;
+ vi.spyOn(aiModelSelectors, 'isModelHasReasoningExtendParams').mockReturnValue(() => true);
+ vi.spyOn(aiModelSelectors, 'isModelReasoningConfigLoaded').mockReturnValue(() => loaded);
+ vi.spyOn(aiModelSelectors, 'modelReasoningConfig').mockReturnValue(() => ({
+ reasoningEffort: 'high',
+ }));
+ const ensure = vi
+ .spyOn(useAiInfraStore.getState(), 'ensureModelReasoningConfig')
+ .mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ finishLoad = () => {
+ loaded = true;
+ resolve();
+ };
+ }),
+ );
+ const persist = vi.spyOn(topicService, 'createTopic').mockResolvedValue('loaded-topic');
+ let pending!: Promise<string | undefined>;
+ act(() => {
+ pending = useChatStore.getState()[method]();
+ });
+ await waitFor(() => expect(ensure).toHaveBeenCalled());
+ expect(persist).not.toHaveBeenCalled();
+ await act(async () => {
+ finishLoad();
+ await pending;
+ });
+ expect(persist).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ }),
+ );
+ },
+ );
+
it('should create a new topic and update the store', async () => {
const { result } = renderHook(() => useChatStore());
const activeAgentId = 'test-session-id';
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 882bc8d1d48..4c810247fa2 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -6,10 +6,16 @@ import {
TOPIC_TITLE_JSON_SCHEMA,
TOPIC_TITLE_PROMPT_VERSION,
} from '@lobechat/prompts';
-import { type ChatTopicMetadata, type MessageMapScope, type UIChatMessage } from '@lobechat/types';
+import {
+ type ChatTopicMetadata,
+ type HeterogeneousReasoningEffort,
+ type MessageMapScope,
+ type UIChatMessage,
+} from '@lobechat/types';
import { toast } from '@lobehub/ui/base-ui';
import isEqual from 'fast-deep-equal';
import { t } from 'i18next';
+import type { AiModelReasoningConfig } from 'model-bank';
import { type SWRResponse } from 'swr';
import useSWR from 'swr';
@@ -21,9 +27,11 @@ import { type GitLinkedPRSummary, gitService } from '@/services/git';
import { messageService } from '@/services/message';
import type { TopicBatchDeleteScope } from '@/services/topic';
import { topicService } from '@/services/topic';
+import { getAiInfraStoreState } from '@/store/aiInfra';
+import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';
import { type ChatStore } from '@/store/chat';
import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';
-import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';
+import { snapshotAgentModel, snapshotAgentReasoning } from '@/store/chat/utils/snapshotAgentModel';
import { topicMapKey, type TopicMapScope } from '@/store/chat/utils/topicMapKey';
import {
canReadTopicGitTransport,
@@ -202,8 +210,11 @@ export class ChatTopicActionImpl {
this.#set({ creatingTopic: true }, false, n('creatingTopic/start'));
const targetSessionId = sessionId || activeAgentId;
+ const modelSnapshot = snapshotAgentModel(targetSessionId);
+ const reasoningSnapshot = await snapshotAgentReasoning(targetSessionId, modelSnapshot);
const topicId = await internal_createTopic({
- ...snapshotAgentModel(targetSessionId),
+ ...modelSnapshot,
+ ...(reasoningSnapshot ? { metadata: reasoningSnapshot } : {}),
title: t('defaultTitle', { ns: 'topic' }),
messages: messages.map((m) => m.id),
sessionId: targetSessionId,
@@ -222,8 +233,11 @@ export class ChatTopicActionImpl {
const targetSessionId = sessionId || activeAgentId;
// 1. create topic and bind these messages
+ const modelSnapshot = snapshotAgentModel(targetSessionId);
+ const reasoningSnapshot = await snapshotAgentReasoning(targetSessionId, modelSnapshot);
const topicId = await internal_createTopic({
- ...snapshotAgentModel(targetSessionId),
+ ...modelSnapshot,
+ ...(reasoningSnapshot ? { metadata: reasoningSnapshot } : {}),
title: t('defaultTitle', { ns: 'topic' }),
messages: messages.map((m) => m.id),
sessionId: targetSessionId,
@@ -417,7 +431,225 @@ export class ChatTopicActionImpl {
id: string,
{ model, provider }: { model: string; provider: string },
): Promise<void> => {
- await this.#get().internal_updateTopic(id, { model, provider });
+ await this.#enqueueTopicEffortWrite(id, async () => {
+ // The effort pin belongs to the model it was taken for (the param names
+ // are model-specific), so switching model re-snapshots it from the user's
+ // config for the new model — same "remembers what it started with" rule.
+ const reasoningConfig = await this.#get().internal_resolveTopicReasoningSnapshot({
+ model,
+ provider,
+ });
+ await this.#writeTopicModelPin(id, {
+ metadata: reasoningConfig ? { reasoningConfig } : undefined,
+ model,
+ provider,
+ });
+ });
+ };
+
+ /**
+ * Model + pin land in one server write (`topic.updateTopicModel`) so a run or
+ * a concurrent switch can never see the new model with the old model's pin.
+ * Optimistically mirrors the server merge: `reasoningConfig` is replaced,
+ * `heteroEffort` only when given.
+ */
+ #writeTopicModelPin = async (
+ id: string,
+ value: {
+ metadata?: Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>;
+ model: string;
+ provider: string;
+ },
+ ): Promise<void> => {
+ const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());
+ const previous = topicSelectors.getTopicById(id)(this.#get());
+ const { reasoningConfig: _stale, ...rest } = previous?.metadata ?? {};
+ this.#get().internal_dispatchTopic({
+ containerKey,
+ id,
+ type: 'updateTopic',
+ value: {
+ metadata: { ...rest, ...value.metadata },
+ model: value.model,
+ provider: value.provider,
+ },
+ });
+
+ try {
+ await topicService.updateTopicModel(id, value);
+ } catch (error) {
+ if (previous) {
+ this.#get().internal_dispatchTopic({
+ containerKey,
+ id,
+ type: 'updateTopic',
+ value: {
+ model: previous.model,
+ provider: previous.provider,
+ metadata: previous.metadata,
+ },
+ });
+ }
+ await this.#recoverTopicPinWrite(containerKey, error);
+ }
+ await this.#get().refreshTopic(containerKey);
+ };
+
+ /**
+ * Resolve the user-level reasoning config to pin for `model`, fetching it when
+ * not cached yet. Returns `undefined` for models without reasoning extend
+ * params (nothing to pin).
+ */
+ internal_resolveTopicReasoningSnapshot = async ({
+ model,
+ provider,
+ }: {
+ model: string;
+ provider: string;
+ }): Promise<AiModelReasoningConfig | undefined> => {
+ const aiInfraStore = getAiInfraStoreState();
+ if (!aiModelSelectors.isModelHasReasoningExtendParams(model, provider)(aiInfraStore)) return;
+
+ await aiInfraStore.ensureModelReasoningConfig(model, provider);
+ return aiModelSelectors.modelReasoningConfig(model, provider)(getAiInfraStoreState()) ?? {};
+ };
+
+ /**
+ * Change the reasoning effort / mode of one topic without touching the
+ * user-level model-instance config. The patch is merged over the topic's
+ * current pin (seeded with `base` — normally the user-level config — when the
+ * topic has no pin yet), so a topic that only ever changed its effort still
+ * keeps the user's reasoning mode.
+ */
+ updateTopicReasoningConfig = async (
+ id: string,
+ patch: AiModelReasoningConfig,
+ base?: AiModelReasoningConfig,
+ ): Promise<void> => {
+ await this.#enqueueTopicEffortWrite(id, async () => {
+ const current = topicSelectors.getTopicById(id)(this.#get())?.metadata?.reasoningConfig;
+ await this.#writeTopicEffortPin(id, {
+ reasoningConfig: { ...(current ?? base), ...patch },
+ });
+ });
+ };
+
+ /** Pin a heterogeneous agent's reasoning effort to one topic (`metadata.heteroEffort`). */
+ updateTopicHeteroEffort = async (
+ id: string,
+ effort: HeterogeneousReasoningEffort,
+ ): Promise<void> => {
+ await this.#enqueueTopicEffortWrite(id, () =>
+ this.#writeTopicEffortPin(id, { heteroEffort: effort }),
+ );
+ };
+
+ /**
+ * Apply a heterogeneous (Claude Code / Codex) model + effort selection to one
+ * topic. When the selector pairs a model switch with an effort reset (the new
+ * model does not support the current effort) both land in the same write, so
+ * the topic never carries a model with an effort it cannot run.
+ */
+ updateTopicHeteroPin = async (
+ id: string,
+ {
+ effort,
+ model,
+ provider,
+ }: { effort?: HeterogeneousReasoningEffort; model?: string; provider: string },
+ ): Promise<void> => {
+ if (model === undefined) {
+ if (effort !== undefined) await this.#get().updateTopicHeteroEffort(id, effort);
+ return;
+ }
+ /** Model resets and later effort selections must share one persistence order. */
+ await this.#enqueueTopicEffortWrite(id, () =>
+ this.#writeTopicModelPin(id, {
+ metadata: effort === undefined ? undefined : { heteroEffort: effort },
+ model,
+ provider,
+ }),
+ );
+ };
+
+ #topicEffortWrites = new Map<string, Promise<void>>();
+
+ /** Serialize the full optimistic write/RPC/refresh cycle so earlier selections cannot land last. */
+ #enqueueTopicEffortWrite = async (id: string, write: () => Promise<void>): Promise<void> => {
+ const previous = this.#topicEffortWrites.get(id);
+ /** Failures already revalidate and toast; a rejected write must not poison the next selection. */
+ const pending = (previous ? previous.catch(() => {}) : Promise.resolve()).then(write);
+ this.#topicEffortWrites.set(id, pending);
+ this.#set(
+ (s) => ({
+ topicEffortUpdatingIds: s.topicEffortUpdatingIds.includes(id)
+ ? s.topicEffortUpdatingIds
+ : [...s.topicEffortUpdatingIds, id],
+ }),
+ false,
+ n('topicEffort/start'),
+ );
+ try {
+ await pending;
+ } finally {
+ if (this.#topicEffortWrites.get(id) === pending) {
+ this.#topicEffortWrites.delete(id);
+ this.#set(
+ (s) => ({ topicEffortUpdatingIds: s.topicEffortUpdatingIds.filter((key) => key !== id) }),
+ false,
+ n('topicEffort/end'),
+ );
+ }
+ }
+ };
+
+ /**
+ * `updateTopicMetadata` shows the new value optimistically and has no
+ * rollback, so a failed effort write would leave the picker (and client-side
+ * generation) on a value that was never persisted. Revalidate and tell the
+ * user, mirroring `updateModelReasoningConfig` for the user-level default.
+ */
+ #writeTopicEffortPin = async (
+ id: string,
+ metadata: Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>,
+ ): Promise<void> => {
+ const containerKey = topicSelectors.getTopicContainerKeyById(id)(this.#get());
+ const previous = topicSelectors.getTopicById(id)(this.#get());
+ if (!previous) return;
+ this.#get().internal_dispatchTopic({
+ containerKey,
+ id,
+ type: 'updateTopic',
+ value: { metadata: { ...previous.metadata, ...metadata } },
+ });
+ try {
+ await topicService.updateTopicMetadata(id, metadata);
+ } catch (error) {
+ if (previous) {
+ this.#get().internal_dispatchTopic({
+ containerKey,
+ id,
+ type: 'updateTopic',
+ value: { metadata: previous.metadata },
+ });
+ }
+ await this.#recoverTopicPinWrite(containerKey, error);
+ }
+ await this.#get().refreshTopic(containerKey);
+ };
+
+ /** Local rollback must survive an offline refresh and preserve the original write failure. */
+ #recoverTopicPinWrite = async (
+ containerKey: string | undefined,
+ error: unknown,
+ ): Promise<never> => {
+ toast.error(t('reasoningEffort.updateFailed', { ns: 'chat' }));
+ try {
+ await this.#get().refreshTopic(containerKey);
+ } catch (refreshError) {
+ console.error('[topicPin] Failed to revalidate after rollback:', refreshError);
+ }
+ throw error;
};
/**
diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.ts
index 97c65c6c681..49ecced7f51 100644
--- a/src/store/chat/slices/topic/initialState.ts
+++ b/src/store/chat/slices/topic/initialState.ts
@@ -77,6 +77,8 @@ export interface ChatTopicState {
* keeps the real title instead of degrading to the "new topic" placeholder.
*/
topicDetailMap: Record<string, ChatTopic>;
+ /** Topics with effort selections queued or being persisted. */
+ topicEffortUpdatingIds: string[];
/**
* Internal ref-count for topic loading owners. A topic can be loading because
* the agent is running and because title-summary is streaming at the same time.
@@ -99,5 +101,6 @@ export const initialTopicState: ChatTopicState = {
topicDetailMap: {},
topicLoadingIdCounts: {},
topicLoadingIds: [],
+ topicEffortUpdatingIds: [],
topicSearchKeywords: '',
};
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 6981acfa74d..4bdd7d787db 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -48,6 +48,81 @@ describe('topicSelectors', () => {
});
});
+ describe('reasoning + hetero pins', () => {
+ const pinTopicDataMap = createTopicDataMap('test');
+ pinTopicDataMap[topicMapKey({ agentId: 'test' })].items = [
+ {
+ id: 'pinned',
+ metadata: { reasoningConfig: { reasoningEffort: 'high' } },
+ model: 'gpt-5',
+ name: 'Pinned',
+ provider: 'openai',
+ },
+ { id: 'legacy', model: 'gpt-5', name: 'Legacy', provider: 'openai' },
+ { id: 'noModel', metadata: { reasoningConfig: {} }, name: 'No Model' },
+ {
+ id: 'heteroBoth',
+ metadata: { heteroEffort: 'max' },
+ model: 'opus',
+ name: 'Hetero',
+ provider: 'claude-code',
+ },
+ { id: 'heteroEffortOnly', metadata: { heteroEffort: 'default' }, name: 'Hetero effort' },
+ { id: 'heteroNone', name: 'Hetero none' },
+ ] as any;
+ const state = merge(initialStore, { topicDataMap: pinTopicDataMap, activeAgentId: 'test' });
+
+ it('getTopicReasoningPinById returns the pinned model with its reasoning config', () => {
+ expect(topicSelectors.getTopicReasoningPinById('pinned')(state)).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ reasoningConfig: { reasoningEffort: 'high' },
+ });
+ expect(topicSelectors.getTopicReasoningPinById('legacy')(state)).toEqual({
+ model: 'gpt-5',
+ provider: 'openai',
+ reasoningConfig: undefined,
+ });
+ expect(topicSelectors.getTopicReasoningPinById('noModel')(state)).toBeUndefined();
+ });
+
+ it('getTopicReasoningConfigForModel only honors a pin taken for the same model', () => {
+ expect(
+ topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-5', 'openai')(state),
+ ).toEqual({ reasoningEffort: 'high' });
+ // a sub-agent modelOverride must not inherit the parent topic's effort
+ expect(
+ topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-4', 'openai')(state),
+ ).toBeUndefined();
+ expect(
+ topicSelectors.getTopicReasoningConfigForModel('pinned', 'gpt-5', 'azure')(state),
+ ).toBeUndefined();
+ expect(
+ topicSelectors.getTopicReasoningConfigForModel('legacy', 'gpt-5', 'openai')(state),
+ ).toBeUndefined();
+ });
+
+ it('getTopicHeteroPinById combines the model columns with the effort pin', () => {
+ expect(topicSelectors.getTopicHeteroPinById('heteroBoth')(state)).toEqual({
+ effort: 'max',
+ model: 'opus',
+ provider: 'claude-code',
+ });
+ expect(topicSelectors.getTopicHeteroPinById('heteroEffortOnly')(state)).toEqual({
+ effort: 'default',
+ });
+ expect(topicSelectors.getTopicHeteroPinById('heteroNone')(state)).toBeUndefined();
+ expect(topicSelectors.getTopicHeteroPinById('missing')(state)).toBeUndefined();
+ });
+
+ it('activeTopicHeteroPin follows the active topic', () => {
+ expect(topicSelectors.activeTopicHeteroPin(state)).toBeUndefined();
+ expect(
+ topicSelectors.activeTopicHeteroPin(merge(state, { activeTopicId: 'heteroBoth' })),
+ ).toEqual({ effort: 'max', model: 'opus', provider: 'claude-code' });
+ });
+ });
+
describe('getTopicModelById / activeTopicModel', () => {
const modelTopicDataMap = createTopicDataMap('test');
modelTopicDataMap[topicMapKey({ agentId: 'test' })].items = [
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index b8b13cba649..67395180ea4 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -1,6 +1,8 @@
import { isDesktop } from '@lobechat/const';
+import type { HeterogeneousTopicPin } from '@lobechat/types';
import { getWorkingDirEffectivePath } from '@lobechat/types';
import { t } from 'i18next';
+import type { AiModelReasoningConfig } from 'model-bank';
import { MAIN_SIDEBAR_EXCLUDE_TRIGGERS } from '@/const/topic';
import {
@@ -156,6 +158,74 @@ const activeTopicModel = (s: ChatStoreState): { model: string; provider: string
return getTopicModelById(s.activeTopicId)(s);
};
+export interface TopicReasoningPin {
+ model: string;
+ provider: string;
+ /** Absent on legacy topics and topics created before the config was loaded. */
+ reasoningConfig?: AiModelReasoningConfig;
+}
+
+/**
+ * The reasoning effort pinned to a topic together with the model it was pinned
+ * for (`ChatTopicMetadata.reasoningConfig` + `ChatTopic.model`). Consumers must
+ * only honor `reasoningConfig` when the pinned model matches the model they are
+ * about to run — a sub-agent `modelOverride` or a stale snapshot must not leak
+ * another model's effort — and fall back to the user-level model-instance
+ * config otherwise. Undefined when the topic has no model pinned at all.
+ */
+const getTopicReasoningPinById =
+ (id: string) =>
+ (s: ChatStoreState): TopicReasoningPin | undefined => {
+ const topic = getTopicById(id)(s);
+ if (!topic?.model) return undefined;
+
+ return {
+ model: topic.model,
+ provider: topic.provider || '',
+ reasoningConfig: topic.metadata?.reasoningConfig,
+ };
+ };
+
+/**
+ * The reasoning config pinned to `id` for exactly `model`/`provider`, else
+ * undefined (no pin, legacy topic, or pinned for another model).
+ */
+const getTopicReasoningConfigForModel =
+ (id: string, model: string, provider: string) =>
+ (s: ChatStoreState): AiModelReasoningConfig | undefined => {
+ const pin = getTopicReasoningPinById(id)(s);
+ if (!pin || pin.model !== model || pin.provider !== provider) return undefined;
+ return pin.reasoningConfig;
+ };
+
+/**
+ * Everything a topic pins for a heterogeneous run — the model/provider columns
+ * plus `metadata.heteroEffort`. Undefined when nothing is pinned, so callers
+ * can pass it straight to `applyTopicModelToHeterogeneousProvider`.
+ */
+export const resolveTopicHeteroPin = (
+ topic: Pick<ChatTopic, 'metadata' | 'model' | 'provider'> | undefined,
+): HeterogeneousTopicPin | undefined => {
+ if (!topic) return undefined;
+ const effort = topic.metadata?.heteroEffort;
+ if (!topic.model && effort === undefined) return undefined;
+
+ return {
+ ...(topic.model ? { model: topic.model, provider: topic.provider || '' } : {}),
+ ...(effort === undefined ? {} : { effort }),
+ };
+};
+
+const getTopicHeteroPinById =
+ (id: string) =>
+ (s: ChatStoreState): HeterogeneousTopicPin | undefined =>
+ resolveTopicHeteroPin(getTopicById(id)(s));
+
+const activeTopicHeteroPin = (s: ChatStoreState): HeterogeneousTopicPin | undefined => {
+ if (!s.activeTopicId) return undefined;
+ return getTopicHeteroPinById(s.activeTopicId)(s);
+};
+
/**
* Extract a topic's working directory from its metadata.
* On desktop: local filesystem path.
@@ -391,6 +461,7 @@ const agentTopicsViewLoadMoreError = (s: ChatStoreState): unknown =>
agentTopicsViewData(s)?.loadMoreError;
export const topicSelectors = {
+ activeTopicHeteroPin,
activeTopicModel,
agentTopicsViewHasMore,
agentTopicsViewIsLoadingMore,
@@ -410,7 +481,10 @@ export const topicSelectors = {
displayTopicsForSidebar,
getTopicById,
getTopicContainerKeyById,
+ getTopicHeteroPinById,
getTopicModelById,
+ getTopicReasoningConfigForModel,
+ getTopicReasoningPinById,
getTopicWorkingDirectory,
getTopicsByAgentId,
groupedTopicsForSidebar,
diff --git a/src/store/chat/utils/snapshotAgentModel.test.ts b/src/store/chat/utils/snapshotAgentModel.test.ts
index 2dd1403013e..a933ce6d9bd 100644
--- a/src/store/chat/utils/snapshotAgentModel.test.ts
+++ b/src/store/chat/utils/snapshotAgentModel.test.ts
@@ -1,13 +1,32 @@
import { DEFAULT_PROVIDER } from '@lobechat/business-const';
import { DEFAULT_MODEL } from '@lobechat/const';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { snapshotAgentModel } from './snapshotAgentModel';
+import { snapshotAgentModel, snapshotAgentReasoning } from './snapshotAgentModel';
const agentMap: Record<string, any> = {};
vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({ agentMap }) }));
+const aiInfra = vi.hoisted(() => ({
+ state: {
+ loaded: false,
+ reasoningConfig: undefined as Record<string, string> | undefined,
+ reasoningParams: false,
+ },
+}));
+
+vi.mock('@/store/aiInfra', () => ({
+ getAiInfraStoreState: () => ({ ...aiInfra.state, ensureModelReasoningConfig: () => {} }),
+}));
+vi.mock('@/store/aiInfra/slices/aiModel/selectors', () => ({
+ aiModelSelectors: {
+ isModelHasReasoningExtendParams: () => (s: typeof aiInfra.state) => s.reasoningParams,
+ isModelReasoningConfigLoaded: () => (s: typeof aiInfra.state) => s.loaded,
+ modelReasoningConfig: () => (s: typeof aiInfra.state) => s.reasoningConfig,
+ },
+}));
+
const seedAgent = (id: string, config: Record<string, any>) => {
agentMap[id] = config;
return id;
@@ -105,3 +124,55 @@ describe('snapshotAgentModel', () => {
expect(snapshotAgentModel(id)).toEqual({});
});
});
+
+describe('snapshotAgentReasoning', () => {
+ const modelSnapshot = { model: 'gpt-5.5', provider: 'openai' };
+
+ beforeEach(() => {
+ aiInfra.state = { loaded: false, reasoningConfig: undefined, reasoningParams: false };
+ });
+
+ it('returns nothing without an agent', async () => {
+ expect(await snapshotAgentReasoning(undefined, modelSnapshot)).toBeUndefined();
+ });
+
+ it("pins a heterogeneous agent's effort, and nothing when it has none", async () => {
+ const withEffort = seedAgent('hetero-effort', {
+ agencyConfig: { heterogeneousProvider: { effort: 'high', type: 'claude-code' } },
+ });
+ const without = seedAgent('hetero-plain', {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ });
+
+ expect(await snapshotAgentReasoning(withEffort, {})).toEqual({ heteroEffort: 'high' });
+ expect(await snapshotAgentReasoning(without, {})).toBeUndefined();
+ });
+
+ it('skips models without reasoning extend params', async () => {
+ const id = seedAgent('plain', { model: 'gpt-4o', provider: 'openai' });
+
+ expect(await snapshotAgentReasoning(id, modelSnapshot)).toBeUndefined();
+ });
+
+ it('pins the loaded user-level config, an empty object when nothing is saved', async () => {
+ const id = seedAgent('reasoning', { model: 'gpt-5.5', provider: 'openai' });
+ aiInfra.state = {
+ loaded: true,
+ reasoningConfig: { gpt5_2ReasoningEffort: 'high' },
+ reasoningParams: true,
+ };
+ expect(await snapshotAgentReasoning(id, modelSnapshot)).toEqual({
+ reasoningConfig: { gpt5_2ReasoningEffort: 'high' },
+ });
+
+ aiInfra.state = { loaded: true, reasoningConfig: undefined, reasoningParams: true };
+ expect(await snapshotAgentReasoning(id, modelSnapshot)).toEqual({ reasoningConfig: {} });
+ });
+
+ it('retains fallback when the user-level config could not be loaded', async () => {
+ const id = seedAgent('loading', { model: 'gpt-5.5', provider: 'openai' });
+ aiInfra.state = { loaded: false, reasoningConfig: undefined, reasoningParams: true };
+
+ expect(await snapshotAgentReasoning(id, modelSnapshot)).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/utils/snapshotAgentModel.ts b/src/store/chat/utils/snapshotAgentModel.ts
index 6ddc0de9c23..adba9a175f2 100644
--- a/src/store/chat/utils/snapshotAgentModel.ts
+++ b/src/store/chat/utils/snapshotAgentModel.ts
@@ -1,7 +1,10 @@
+import type { ChatTopicMetadata } from '@lobechat/types';
import { resolveHeterogeneousProviderTopicModel } from '@lobechat/types';
import { getAgentStoreState } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import { getAiInfraStoreState } from '@/store/aiInfra';
+import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';
/**
* Snapshot the given agent's current model/provider so a newly created topic
@@ -38,3 +41,47 @@ export const snapshotAgentModel = (
provider: agentByIdSelectors.getAgentModelProviderById(agentId)(agentState),
};
};
+
+export type TopicReasoningSnapshot = Pick<ChatTopicMetadata, 'heteroEffort' | 'reasoningConfig'>;
+
+/**
+ * Snapshot the reasoning effort that goes with {@link snapshotAgentModel} so a
+ * new topic also remembers the effort it was started with (persisted to
+ * `topics.metadata.reasoningConfig` / `heteroEffort`, see `ChatTopicMetadata`).
+ *
+ * - Heterogeneous agents pin the agent's `heterogeneousProvider.effort`.
+ * - API models pin the user's model-instance reasoning config for the
+ * snapshotted model — an empty object when nothing is saved, which pins the
+ * topic to the model's own defaults. Wait for the saved config before
+ * snapshotting; if loading fails, retain the generation fallback instead
+ * of freezing an unverified default.
+ *
+ * Returns undefined when there is nothing to pin, so callers can spread it
+ * into `metadata` without leaving empty keys behind.
+ */
+export const snapshotAgentReasoning = async (
+ agentId: string | null | undefined,
+ modelSnapshot: { model?: string; provider?: string },
+): Promise<TopicReasoningSnapshot | undefined> => {
+ if (!agentId) return undefined;
+
+ const heterogeneousProvider =
+ agentByIdSelectors.getAgencyConfigById(agentId)(getAgentStoreState())?.heterogeneousProvider;
+ if (heterogeneousProvider) {
+ const effort = heterogeneousProvider.effort;
+ return effort === undefined ? undefined : { heteroEffort: effort };
+ }
+
+ const { model, provider } = modelSnapshot;
+ if (!model || !provider) return undefined;
+
+ /** Creation must settle the saved config before persistence, including a first send after reload. */
+ await getAiInfraStoreState().ensureModelReasoningConfig(model, provider);
+ const aiInfraState = getAiInfraStoreState();
+ if (!aiModelSelectors.isModelHasReasoningExtendParams(model, provider)(aiInfraState)) return;
+ if (!aiModelSelectors.isModelReasoningConfigLoaded(model, provider)(aiInfraState)) return;
+
+ return {
+ reasoningConfig: aiModelSelectors.modelReasoningConfig(model, provider)(aiInfraState) ?? {},
+ };
+};