π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(chat): topic-scoped model β snapshot on create, switch within topic (#15933)
Arvin Xu1c168f7553e2
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex bedafd392b3..f5bdbbcc4b8 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -217,6 +217,8 @@ export const aiChatRouter = router({groupId: input.groupId,messages: input.newTopic!.topicMessageIds,metadata: input.newTopic!.metadata,+ model: input.newTopic!.model,+ provider: input.newTopic!.provider,sessionId,title: input.newTopic!.title,trigger: input.newTopic!.trigger,diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 62bf1832978..1093cf6d007 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -376,6 +376,10 @@ export const topicRouter = router({favorite: z.boolean().optional(),groupId: z.string().nullish(),messages: z.array(z.string()).optional(),+ // The topic's pinned model snapshot, persisted to the top-level+ // `topics.model`/`provider` columns (config source of truth).+ model: z.string().optional(),+ provider: z.string().optional(),title: z.string(),trigger: z.string().optional(),})@@ -893,12 +897,11 @@ export const topicRouter = router({favorite: z.boolean().optional(),historySummary: z.string().optional(),messages: z.array(z.string()).optional(),- metadata: z- .object({- model: z.string().optional(),- provider: z.string().optional(),- })- .optional(),+ // The topic's pinned model (top-level columns) β written when the user+ // switches model while the topic is active (see updateTopicModel).+ // Nullish to match `Partial<ChatTopic>` whose model/provider are `string | null`.+ model: z.string().nullish(),+ provider: z.string().nullish(),sessionId: z.string().optional(),status: chatTopicStatusSchema.nullish(),title: z.string().optional(),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex 45d23c7d86a..fa0be5c875a 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -111,6 +111,7 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.tsindex 37e26639e4a..1de3f6cdcd3 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts@@ -79,6 +79,7 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex b0634bc9883..ab2c424aaca 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -96,6 +96,7 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.tsindex b84a0991d2b..829d59176d5 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -77,6 +77,7 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.tsindex 844fa436898..8aaa5d5c91b 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts@@ -79,6 +79,7 @@ vi.mock('@/database/models/file', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex cc1812a78d4..fcaf565faf1 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -47,6 +47,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.tsindex 502a842b8ba..69703bc9d35 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.modelOverride.test.ts@@ -55,6 +55,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 19c1f84e3bd..1a1a6c40048 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -83,6 +83,7 @@ vi.mock('@/database/models/connectorTool', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.tsindex 980fd45f82d..e8158e40ba9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resume.test.ts@@ -59,6 +59,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex 74837104c95..6f1da731e1d 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -67,6 +67,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),updateMetadata: vi.fn(),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.tsindex 900d2f19bb2..508143061eb 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts@@ -70,6 +70,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),updateMetadata: vi.fn(),})),}));diff --git a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.tsindex f88eb26014b..031143e9918 100644--- a/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execSubAgent.test.ts@@ -54,6 +54,7 @@ vi.mock('@/database/models/plugin', () => ({vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),})),}));diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex abafa81595d..865152121da 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1592,6 +1592,16 @@ export class AiAgentService {: isFixedExecutionTargetSelection? undefined: requestedDeviceId;++ // Effective model/provider for this run. Defaults to the agent config, but a+ // topic pins its own model in the top-level `topics.model`/`provider` columns+ // (config source of truth) β snapshotted on creation, and honored below when+ // reusing a topic whose model was switched while active. Keeps the Gateway/+ // cloud path in sync with the client local path (see streamingExecutor ++ // getTopicModelById).+ let model = agentConfig.model!;+ let provider = agentConfig.provider!;+if (!topicId) {if (resume) {throw new Error('Resume mode requires the parent message to belong to a topic');@@ -1629,6 +1639,9 @@ export class AiAgentService {// must carry the groupId through too (group topic sidebar + ownership fix).groupId: appContext?.groupId,metadata,+ // Snapshot the effective model as the topic's pinned model (config).+ model,+ provider,title:title !== undefined? title@@ -1645,14 +1658,27 @@ export class AiAgentService {);} else {log('execAgent: reusing existing topic %s', topicId);++ // Honor a topic-pinned model (snapshotted on creation, updated when the+ // user switched model while the topic was active) over the agent default.+ // The pinned model lives in the top-level `topics.model`/`provider` columns+ // (config source of truth), NOT in metadata.+ const existingTopic = await this.topicModel.findById(topicId);+ const pinnedModel = existingTopic?.model;+ if (pinnedModel) {+ model = pinnedModel;+ provider = existingTopic?.provider || provider;+ log(+ 'execAgent: using topic-pinned model=%s provider=%s for topic %s',+ model,+ provider,+ topicId,+ );+ }}await throwIfExecutionAborted('topic setup');- // Extract model and provider from agent config- const model = agentConfig.model!;- const provider = agentConfig.provider!;-// Resolve device-tool access ONCE per turn, BEFORE the hetero early exit β// hetero dispatch routes the whole run to a user machine, so it must honour// the same policy as native device tools. Discord-only flows (nodiff --git a/packages/database/src/models/__tests__/topics/topic.update.test.ts b/packages/database/src/models/__tests__/topics/topic.update.test.tsindex 5692bef5e7c..ce2307e73ef 100644--- a/packages/database/src/models/__tests__/topics/topic.update.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.update.test.ts@@ -128,7 +128,16 @@ describe('TopicModel - Update', () => {describe('recomputeUsage', () => {it('rolls the topic assistant messages into the denormalized usage/cost columns', async () => {const topicId = 'usage-recompute-1';- await serverDB.insert(topics).values({ id: topicId, sessionId, userId });+ // Seed a pinned model (config). The roll-up must preserve it, not overwrite+ // it with the message's model β those columns hold the topic's config, not+ // the measured dominant model (which lives in cost.llm.byModel).+ await serverDB.insert(topics).values({+ id: topicId,+ model: 'pinned-model',+ provider: 'pinned-provider',+ sessionId,+ userId,+ });await serverDB.insert(messages).values([{id: 'usage-msg-1',@@ -153,8 +162,9 @@ describe('TopicModel - Update', () => {expect(topic.totalInputTokens).toBe(60);expect(topic.totalOutputTokens).toBe(40);expect(topic.totalCost).toBeCloseTo(0.003, 6);- expect(topic.model).toBe('gpt-4o');- expect(topic.provider).toBe('openai');+ // Pinned model (config) is preserved β roll-up does not write the message model.+ expect(topic.model).toBe('pinned-model');+ expect(topic.provider).toBe('pinned-provider');expect((topic.usage as any).llm).toEqual({apiCalls: 1,processingTimeMs: 500,diff --git a/packages/database/src/models/__tests__/topics/topicUsage.test.ts b/packages/database/src/models/__tests__/topics/topicUsage.test.tsindex 5ad301315f2..10ffe01c328 100644--- a/packages/database/src/models/__tests__/topics/topicUsage.test.ts+++ b/packages/database/src/models/__tests__/topics/topicUsage.test.ts@@ -131,7 +131,12 @@ beforeEach(async () => {// agent_operations.user_id is intentionally not a FK β clean up explicitly.await serverDB.delete(agentOperations);await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);- await serverDB.insert(topics).values({ id: topicId, userId });+ // Seed a pinned model on the topic (config). The usage roll-up must NEVER touch+ // these columns β they hold the topic's configured model, not the measured+ // dominant model (which lives in `cost.llm.byModel`).+ await serverDB+ .insert(topics)+ .values({ id: topicId, model: 'pinned-model', provider: 'pinned-provider', userId });});afterEach(async () => {@@ -162,8 +167,10 @@ describe('recomputeTopicUsage', () => {expect(topic.totalOutputTokens).toBe(50);expect(topic.totalTokens).toBe(150);expect(topic.totalCost).toBeCloseTo(0.0021, 6);- expect(topic.model).toBe('gpt-4o');- expect(topic.provider).toBe('openai');+ // Roll-up preserves the pinned model (config) β it does not write the+ // message's model into the column.+ expect(topic.model).toBe('pinned-model');+ expect(topic.provider).toBe('pinned-provider');expect(topic.usage).toEqual({humanInteraction: {@@ -242,9 +249,11 @@ describe('recomputeTopicUsage', () => {expect(usage.llm.processingTimeMs).toBe(600);expect(usage.llm.tokens).toEqual({ input: 330, output: 170, total: 500 });- // dominant model = largest token volume (claude 300 > gpt-4o 200)- expect(topic.model).toBe('claude-3-5-sonnet');- expect(topic.provider).toBe('anthropic');+ // The measured per-model breakdown lives in `cost.llm.byModel` (below); the+ // roll-up does NOT promote a dominant model into the `model` column, which+ // stays the pinned config.+ expect(topic.model).toBe('pinned-model');+ expect(topic.provider).toBe('pinned-provider');const byModel = (topic.cost as any).llm.byModel as any[];expect(byModel).toHaveLength(2);@@ -375,8 +384,9 @@ describe('recomputeTopicUsage', () => {expect(topic.totalCost).toBeNull();expect(topic.usage).toBeNull();expect(topic.cost).toBeNull();- expect(topic.model).toBeNull();- expect(topic.provider).toBeNull();+ // Usage aggregates reset to NULL, but the pinned model (config) is preserved.+ expect(topic.model).toBe('pinned-model');+ expect(topic.provider).toBe('pinned-provider');});it('short-circuits when the topic row is missing or owned by another user', async () => {@@ -518,8 +528,9 @@ describe('recomputeTopicUsage', () => {expect(topic.totalInputTokens).toBeNull();expect(topic.totalOutputTokens).toBeNull();expect(topic.totalTokens).toBeNull();- expect(topic.model).toBeNull();- expect(topic.provider).toBeNull();+ // Pinned model (config) is preserved even when usage aggregates reset.+ expect(topic.model).toBe('pinned-model');+ expect(topic.provider).toBe('pinned-provider');expect(topic.totalCost).toBeCloseTo(0.05, 6);expect((topic.usage as any).llm).toEqual({diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex fc3968f5f1e..54b02a89b93 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -64,6 +64,9 @@ export interface CreateTopicParams {groupId?: string | null;messages?: string[];metadata?: ChatTopicMetadata;+ /** Pinned model snapshot, persisted to the top-level `topics.model` column. */+ model?: string | null;+ provider?: string | null;sessionId?: string | null;/*** Initial status. Defaults to the column default (`active`). A topic created@@ -354,6 +357,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ model: topics.model,+ provider: topics.provider,status: topics.status,title: topics.title,updatedAt: topics.updatedAt,@@ -428,6 +433,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ model: topics.model,+ provider: topics.provider,status: topics.status,title: topics.title,updatedAt: topics.updatedAt,@@ -497,6 +504,8 @@ export class TopicModel {historySummary: topics.historySummary,id: topics.id,metadata: topics.metadata,+ model: topics.model,+ provider: topics.provider,sessionId: topics.sessionId,status: topics.status,title: topics.title,diff --git a/packages/database/src/models/topicUsage.ts b/packages/database/src/models/topicUsage.tsindex 8b047701ed6..78f5b7f21ba 100644--- a/packages/database/src/models/topicUsage.ts+++ b/packages/database/src/models/topicUsage.ts@@ -188,7 +188,8 @@ const aggregateOperationUsage = async (* - scalar columns : total_input_tokens / total_output_tokens / total_tokens / total_cost* - `usage` jsonb : flat aggregate { llm: { apiCalls, processingTimeMs, tokens }, tools, humanInteraction }* - `cost` jsonb : { total, currency, llm: { total, currency, byModel[] }, tools } β or NULL when nothing reported cost- * - model/provider : the dominant model by total_tokens+ * (the `model`/`provider` columns are the topic's PINNED model / config and are+ * NOT written by this roll-up; the measured per-model breakdown is `cost.llm.byModel`.)* `total_cost` / `cost.total` include tool cost on top of LLM cost.** Idempotent and non-cumulative: when neither source has measurable usage, the@@ -269,15 +270,15 @@ export const recomputeTopicUsage = async (const ops = await aggregateOperationUsage(trx, rowOwnership, topicId);// No measurable usage left in either source β reset to NULL so the columns- // reflect reality.+ // reflect reality. NOTE: `model`/`provider` are intentionally NOT touched here β+ // those columns hold the topic's PINNED model (config), not the measured+ // dominant model. The measured per-model breakdown lives in `cost.llm.byModel`.if (groups.length === 0 && !ops.hasData) {await trx.update(topics).set({accessedAt: topics.accessedAt,cost: null,- model: null,- provider: null,totalCost: null,totalInputTokens: null,totalOutputTokens: null,@@ -297,7 +298,6 @@ export const recomputeTopicUsage = async (let apiCalls = 0;let processingTimeMs = 0;const byModel: Array<Record<string, unknown>> = [];- let primary: { model: string | null; provider: string | null; tokens: number } | null = null;for (const g of groups) {const rowTotalTokens = num(g.totalTokens);@@ -313,15 +313,6 @@ export const recomputeTopicUsage = async (hasCost = true;}- // Dominant model = largest token volume.- if (!primary || rowTotalTokens > primary.tokens) {- primary = {- model: (g.model as string) ?? null,- provider: (g.provider as string) ?? null,- tokens: rowTotalTokens,- };- }-// cost.llm.byModel mirrors the operation shape: cost-bearing models only,// each carrying its merged ModelUsage breakdown.if (rowCost != null) {@@ -367,13 +358,14 @@ export const recomputeTopicUsage = async (// tokens are "not measured" (NULL), even when operations contributed tool stats.const hasLlmGroups = groups.length > 0;+ // `model`/`provider` columns are the topic's PINNED model (config) and are NOT+ // written here β the roll-up only owns usage/cost aggregates. The measured+ // per-model breakdown is preserved in `cost.llm.byModel` above.await trx.update(topics).set({accessedAt: topics.accessedAt,cost,- model: primary?.model ?? null,- provider: primary?.provider ?? null,totalCost: hasAnyCost ? totalCost + toolCostTotal : null,totalInputTokens: hasLlmGroups ? totalInputTokens : null,totalOutputTokens: hasLlmGroups ? totalOutputTokens : null,diff --git a/packages/types/src/aiChat.ts b/packages/types/src/aiChat.tsindex 8df8d9b2e36..233aa5b9e60 100644--- a/packages/types/src/aiChat.ts+++ b/packages/types/src/aiChat.ts@@ -77,6 +77,9 @@ export interface SendMessageServerParams {* post-execution metadata write which can be skipped on cancel/error.*/metadata?: ChatTopicMetadata;+ /** Pinned model snapshot for the new topic (top-level `topics.model` column). */+ model?: string;+ provider?: string;title?: string;topicMessageIds?: string[];trigger?: string;@@ -139,6 +142,8 @@ export const AiSendMessageServerSchema = z.object({newTopic: z.object({metadata: z.custom<ChatTopicMetadata>().optional(),+ model: z.string().optional(),+ provider: z.string().optional(),title: z.string().optional(),topicMessageIds: z.array(z.string()).optional(),trigger: z.string().optional(),diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex e789b682ee6..dd79a9d5e55 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -155,6 +155,12 @@ export interface ChatTopicMetadata {heteroSourceEndAt?: string;/** origin marker for imported topics, e.g. `claude-code-local` / `codex-local` */importedFrom?: string;+ /**+ * Measured dominant model by token volume, written by the usage roll-up+ * (`topicUsage.recompute`). This is an analytics projection of "what actually+ * ran", NOT the topic's configured model β the pinned/config model lives in+ * the top-level `topics.model` column (see `ChatTopic.model`).+ */model?: string;/*** Free-form feedback collected after agent onboarding completion.@@ -162,6 +168,7 @@ export interface ChatTopicMetadata {*/onboardingFeedback?: OnboardingFeedbackEntry;onboardingSession?: OnboardingSessionSnapshot;+ /** Measured dominant provider by token volume β see {@link ChatTopicMetadata.model}. */provider?: string;/*** Web (cloud) only. Ordered list of GitHub repos selected for this topic.@@ -475,6 +482,16 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {/** Total message count for the topic. */messageCount?: number | null;metadata?: ChatTopicMetadata;+ /**+ * The topic's pinned model β snapshotted from the agent default when the topic+ * is created, and overwritten when the user switches model while the topic is+ * active. Generation and ChatInput display resolve the effective model as+ * "topic model if present, else agent default" (see+ * `topicSelectors.getTopicModelById`). Distinct from the analytics+ * `metadata.model` (measured dominant model from the usage roll-up).+ */+ model?: string | null;+ provider?: string | null;sessionId?: string;/*** Sort key for the sidebar list: the topic's latest message-activity time@@ -532,6 +549,10 @@ export interface CreateTopicParams {favorite?: boolean;groupId?: string | null;messages?: string[];+ metadata?: ChatTopicMetadata;+ /** Pinned model snapshot for the new topic (see `ChatTopic.model`). */+ model?: string;+ provider?: string;sessionId?: string | null;title: string;trigger?: string;diff --git a/src/features/ChatInput/ActionBar/Model/index.tsx b/src/features/ChatInput/ActionBar/Model/index.tsxindex 9d4a9119757..b7c778fdedf 100644--- a/src/features/ChatInput/ActionBar/Model/index.tsx+++ b/src/features/ChatInput/ActionBar/Model/index.tsx@@ -6,6 +6,8 @@ import { useTranslation } from 'react-i18next';import ModelSwitchPanel from '@/features/ModelSwitchPanel';import { usePermission } from '@/hooks/usePermission';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';import { useAgentId } from '../../hooks/useAgentId';import { useAgentModelSelection } from '../../hooks/useAgentModelSelection';@@ -56,12 +58,21 @@ const ModelSwitch = memo(() => {const agentId = useAgentId();const {isPreferenceLoading,- model,- provider,+ model: agentModel,+ provider: agentProvider,selectionPolicy,selectModel,usesWorkspaceMemberSelection,} = useAgentModelSelection(agentId);+ // Topic-scoped model: a topic pins its own model (top-level `topics.model`+ // column). Display the topic's pinned model when present, else the agent+ // default; a switch pins to the active topic, otherwise updates the agent+ // (via selectModel, which honors workspace member overrides).+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const topicModel = useChatStore(topicSelectors.activeTopicModel);+ const updateTopicModel = useChatStore((s) => s.updateTopicModel);+ const model = topicModel?.model ?? agentModel;+ const provider = topicModel?.model ? topicModel.provider : agentProvider;const canSelectForAgent = usesWorkspaceMemberSelection? canUseResource && selectionPolicy === 'member': canConfigureResource;@@ -81,9 +92,10 @@ const ModelSwitch = memo(() => {async (params: { model: string; provider: string }) => {if (!canSelectModel) return;- await selectModel(params);+ if (activeTopicId) await updateTopicModel(activeTopicId, params);+ else await selectModel(params);},- [canSelectModel, selectModel],+ [activeTopicId, canSelectModel, selectModel, updateTopicModel],);const trigger = (diff --git a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx b/src/features/ChatInput/ActionBar/ModelLabel/index.tsxindex 77d1f6de9a5..a2cc13d74b3 100644--- a/src/features/ChatInput/ActionBar/ModelLabel/index.tsx+++ b/src/features/ChatInput/ActionBar/ModelLabel/index.tsx@@ -7,6 +7,8 @@ import { useTranslation } from 'react-i18next';import ModelSwitchPanel from '@/features/ModelSwitchPanel';import { usePermission } from '@/hooks/usePermission';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/slices/topic/selectors';import { useAgentId } from '../../hooks/useAgentId';import { useAgentModelSelection } from '../../hooks/useAgentModelSelection';@@ -52,12 +54,21 @@ const ModelLabel = memo(() => {const agentId = useAgentId();const {isPreferenceLoading,- model,- provider,+ model: agentModel,+ provider: agentProvider,selectionPolicy,selectModel,usesWorkspaceMemberSelection,} = useAgentModelSelection(agentId);+ // Topic-scoped model: a topic pins its own model (top-level `topics.model`+ // column). Display the topic's pinned model when present, else the agent+ // default; a switch pins to the active topic, otherwise updates the agent+ // (via selectModel, which honors workspace member overrides).+ const activeTopicId = useChatStore((s) => s.activeTopicId);+ const topicModel = useChatStore(topicSelectors.activeTopicModel);+ const updateTopicModel = useChatStore((s) => s.updateTopicModel);+ const model = topicModel?.model ?? agentModel;+ const provider = topicModel?.model ? topicModel.provider : agentProvider;const canSelectForAgent = usesWorkspaceMemberSelection? canUseResource && selectionPolicy === 'member': canConfigureResource;@@ -80,9 +91,10 @@ const ModelLabel = memo(() => {async (params: { model: string; provider: string }) => {if (!canSelectModel) return;- await selectModel(params);+ if (activeTopicId) await updateTopicModel(activeTopicId, params);+ else await selectModel(params);},- [canSelectModel, selectModel],+ [activeTopicId, canSelectModel, selectModel, updateTopicModel],);const trigger = (diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsxindex d61944c2f51..1d0ec682b9f 100644--- a/src/features/ChatInput/ActionBar/Plus/index.tsx+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx@@ -31,11 +31,7 @@ import { useIsDark } from '@/hooks/useIsDark';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';import { useVisualMediaUploadAbility } from '@/hooks/useVisualMediaUploadAbility';import { useAgentStore } from '@/store/agent';-import {- agentByIdSelectors,- agentSelectors,- chatConfigByIdSelectors,-} from '@/store/agent/selectors';+import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';import { useChatStore } from '@/store/chat';import { useFileStore } from '@/store/file';@@ -53,6 +49,7 @@ import { useGoalArmStore } from '../../../Conversation/ChatInput/VerifyTray/goalimport { openTopicGoalModal } from '../../../Conversation/ChatInput/VerifyTray/useTopicChecklist';import { useAgentId } from '../../hooks/useAgentId';import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';import { useChatInputStore } from '../../store';import { type ActionDropdownMenuItems } from '../components/ActionDropdown';@@ -313,8 +310,7 @@ const PlusAction = memo(() => {(s) => settingsSelectors.defaultAgentConfig(s).chatConfig?.disableGatewayMode,);- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));- const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));+ const { model, provider } = useEffectiveModel(agentId);const isAgentModeEnabled = useAgentStore(agentSelectors.isAgentModeEnabled);const [showRightPanel, workingSidebarTab, setWorkingSidebarTab, toggleRightPanel] =useGlobalStore((s) => [diff --git a/src/features/ChatInput/ActionBar/Search/Controls.tsx b/src/features/ChatInput/ActionBar/Search/Controls.tsxindex 38cb67b254f..927511085a6 100644--- a/src/features/ChatInput/ActionBar/Search/Controls.tsx+++ b/src/features/ChatInput/ActionBar/Search/Controls.tsx@@ -9,11 +9,12 @@ import { useTranslation } from 'react-i18next';import { usePermission } from '@/hooks/usePermission';import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';import { type SearchMode } from '@/types/search';import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';import FCSearchModel from './FCSearchModel';import ModelBuiltinSearch from './ModelBuiltinSearch';@@ -104,9 +105,8 @@ const Controls = memo(() => {const { updateAgentChatConfig } = useUpdateAgentConfig();const { allowed: canCreate } = usePermission('create_content');- const [model, provider, useModelBuiltinSearch, searchMode] = useAgentStore((s) => [- agentByIdSelectors.getAgentModelById(agentId)(s),- agentByIdSelectors.getAgentModelProviderById(agentId)(s),+ const { model, provider } = useEffectiveModel(agentId);+ const [useModelBuiltinSearch, searchMode] = useAgentStore((s) => [chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),chatConfigByIdSelectors.getChatConfigById(agentId)(s).searchMode,]);diff --git a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsxindex 054a0b7db71..2d76c930180 100644--- a/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx+++ b/src/features/ChatInput/ActionBar/Search/ModelBuiltinSearch.tsx@@ -6,10 +6,11 @@ import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';interface SearchEngineIconProps {@@ -40,11 +41,10 @@ const ModelBuiltinSearch = memo<ModelBuiltinSearchProps>(({ disabled }) => {const { t } = useTranslation('chat');const agentId = useAgentId();const { updateAgentChatConfig } = useUpdateAgentConfig();- const [model, provider, checked] = useAgentStore((s) => [- agentByIdSelectors.getAgentModelById(agentId)(s),- agentByIdSelectors.getAgentModelProviderById(agentId)(s),+ const { model, provider } = useEffectiveModel(agentId);+ const checked = useAgentStore((s) =>chatConfigByIdSelectors.getUseModelBuiltinSearchById(agentId)(s),- ]);+ );const [isLoading, setLoading] = useState(false);const modelCard = useAiInfraStore(aiModelSelectors.getEnabledModelById(model, provider));diff --git a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx b/src/features/ChatInput/ActionBar/Token/TokenTag.tsxindex 09caa234ee2..7db4c67e682 100644--- a/src/features/ChatInput/ActionBar/Token/TokenTag.tsx+++ b/src/features/ChatInput/ActionBar/Token/TokenTag.tsx@@ -23,6 +23,7 @@ import { useUserStore } from '@/store/user';import { settingsSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useChatInputStore } from '../../store';import ActionPopover from '../components/ActionPopover';import TokenProgress from './TokenProgress';@@ -42,11 +43,10 @@ const Token = memo(() => {);const agentId = useAgentId();+ const { model, provider } = useEffectiveModel(agentId);const [activeAgentId,systemRole,- model,- provider,enableAgentMode,searchMode,useModelBuiltinSearch,@@ -60,8 +60,6 @@ const Token = memo(() => {return [s.activeAgentId,agentByIdSelectors.getAgentSystemRoleById(agentId)(s),- agentByIdSelectors.getAgentModelById(agentId)(s),- agentByIdSelectors.getAgentModelProviderById(agentId)(s),chatConfig.enableAgentMode,chatConfig.searchMode,chatConfig.useModelBuiltinSearch,diff --git a/src/features/ChatInput/ActionBar/Tools/index.tsx b/src/features/ChatInput/ActionBar/Tools/index.tsxindex f5ca15e7d62..fe72eda0ca7 100644--- a/src/features/ChatInput/ActionBar/Tools/index.tsx+++ b/src/features/ChatInput/ActionBar/Tools/index.tsx@@ -4,10 +4,9 @@ import { useTranslation } from 'react-i18next';import { createSkillStoreModal } from '@/features/SkillStore';import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { ChatInputAction } from '../components/ChatInputAction';import PopoverContent from './PopoverContent';import { useControls } from './useControls';@@ -17,8 +16,7 @@ const Tools = memo(() => {const { marketItems, editPluginDrawer, pinnedCount, autoCount, isPolicyMenuOpen } = useControls();const agentId = useAgentId();- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));- const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));+ const { model, provider } = useEffectiveModel(agentId);const enableFC = useModelSupportToolUse(model, provider);diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsxindex 0c1849c8c4c..548bc3705b8 100644--- a/src/features/ChatInput/ActionBar/Upload/index.tsx+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx@@ -23,6 +23,7 @@ import { useUserStore } from '@/store/user';import { preferenceSelectors } from '@/store/user/selectors';import { useAgentId } from '../../hooks/useAgentId';+import { useEffectiveModel } from '../../hooks/useEffectiveModel';import { useChatInputStore } from '../../store';import { type ActionDropdownMenuItems } from '../components/ActionDropdown';import { ChatInputAction } from '../components/ChatInputAction';@@ -53,8 +54,7 @@ const FileUpload = memo(() => {const editor = useChatInputStore((s) => s.editor);const agentId = useAgentId();- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));- const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));+ const { model, provider } = useEffectiveModel(agentId);const { canUploadImage, canUploadVideo, canUploadAudio } = useVisualMediaUploadAbility(model,diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex 4ec3c987088..574e8369148 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -38,6 +38,7 @@ import { useAgentId } from '../hooks/useAgentId';import { useChatInputDraft } from '../hooks/useChatInputDraft';import { useChatInputHistory } from '../hooks/useChatInputHistory';import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';+import { useEffectiveModel } from '../hooks/useEffectiveModel';import { useChatInputStore, useStoreApi } from '../store';import {INSERT_ACTION_TAG_COMMAND,@@ -137,8 +138,7 @@ const InputEditor = memo<{const categories = useMentionCategories();// Get agent's model info for vision support check and handle paste upload- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));- const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));+ const { model, provider } = useEffectiveModel(agentId);const heterogeneousType = useAgentStore((s) => agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type,);diff --git a/src/features/ChatInput/hooks/useAgentEnableSearch.ts b/src/features/ChatInput/hooks/useAgentEnableSearch.tsindex 3c285ec51eb..9b5b8745e5c 100644--- a/src/features/ChatInput/hooks/useAgentEnableSearch.ts+++ b/src/features/ChatInput/hooks/useAgentEnableSearch.ts@@ -1,10 +1,11 @@'use client';import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';import { useAgentId } from './useAgentId';+import { useEffectiveModel } from './useEffectiveModel';/*** Hook to check if search is enabled for the current agent context.@@ -12,11 +13,10 @@ import { useAgentId } from './useAgentId';*/export const useAgentEnableSearch = () => {const agentId = useAgentId();- const [model, provider, agentSearchMode] = useAgentStore((s) => [- agentByIdSelectors.getAgentModelById(agentId)(s),- agentByIdSelectors.getAgentModelProviderById(agentId)(s),+ const { model, provider } = useEffectiveModel(agentId);+ const agentSearchMode = useAgentStore((s) =>chatConfigByIdSelectors.getSearchModeById(agentId)(s),- ]);+ );const searchImpl = useAiInfraStore(aiModelSelectors.modelBuiltinSearchImpl(model, provider));diff --git a/src/features/ChatInput/hooks/useEffectiveModel.ts b/src/features/ChatInput/hooks/useEffectiveModel.tsnew file mode 100644index 00000000000..6660650fdf4--- /dev/null+++ b/src/features/ChatInput/hooks/useEffectiveModel.ts@@ -0,0 +1,38 @@+'use client';++import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';+// Import from the topic slice directly (not the `@/store/chat/selectors` barrel)+// to keep this hook's import graph small β it is pulled into many ChatInput+// controls, and the barrel drags in unrelated slice selectors.+import { topicSelectors } from '@/store/chat/slices/topic/selectors';++interface ModelAndProvider {+ model: string;+ provider: string;+}++/**+ * The effective model/provider for ChatInput: the active topic's pinned model+ * when one exists, otherwise the agent default.+ *+ * Use this everywhere a capability is gated on the model that will actually run+ * (vision/upload, tool use, builtin search, context window, β¦) so the controls+ * stay in sync with the topic model after a switch β not the stale agent+ * default. The Model/ModelLabel controls resolve display + switch routing+ * against the same topic model (see `useAgentModelSelection` composition there).+ */+export const useEffectiveModel = (agentId: string): ModelAndProvider => {+ const [agentModel, agentProvider] = useAgentStore((s) => [+ agentByIdSelectors.getAgentModelById(agentId)(s),+ agentByIdSelectors.getAgentModelProviderById(agentId)(s),+ ]);++ const topicModel = useChatStore(topicSelectors.activeTopicModel);++ return {+ model: topicModel?.model || agentModel,+ provider: topicModel?.model ? topicModel.provider : agentProvider,+ };+};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 2ea41d3ea2f..c8cc24c4ed7 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -569,6 +569,60 @@ describe('ConversationLifecycle actions', () => {expect(useChatStore.getState().topicLoadingIds).not.toContain(newTopicId);});+ 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;+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ });+ });++ const sendMessageInServerSpy = vi+ .spyOn(aiChatService, 'sendMessageInServer')+ .mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: newTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ],+ topicId: newTopicId,+ topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ await act(async () => {+ await result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ expect(sendMessageInServerSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ newTopic: expect.objectContaining({+ model: expect.any(String),+ provider: expect.any(String),+ }),+ }),+ expect.any(AbortController),+ );+ });+it('should release the migrated topicLoadingIds owner after a gateway send creates the topic', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;@@ -793,6 +847,9 @@ describe('ConversationLifecycle actions', () => {// the server topic replaced it.expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]).toEqual(expect.objectContaining({+ // Pinned model is a top-level column, not metadata.+ model: expect.any(String),+ provider: expect.any(String),metadata: {repos: [selectedRepo],workingDirectory: selectedRepo,@@ -803,6 +860,8 @@ describe('ConversationLifecycle actions', () => {expect(executeGatewayAgentSpy).toHaveBeenCalledWith(expect.objectContaining({optimisticTopic: expect.objectContaining({+ model: expect.any(String),+ provider: expect.any(String),metadata: {repos: [selectedRepo],workingDirectory: selectedRepo,diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex edffd3c603c..3cb762a446e 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -77,6 +77,7 @@ import {hasRunningCompressionOperation,} from '@/store/chat/utils/compression';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { getElectronStoreState } from '@/store/electron';import { useGlobalStore } from '@/store/global';@@ -143,6 +144,9 @@ type SendMessageServerResponseMeta = SendMessageServerResponse & {interface OptimisticTopicPlaceholder {id: string;metadata?: ChatTopicMetadata;+ /** Pinned model snapshot β top-level `topics.model` column, not metadata. */+ model?: string;+ provider?: string;title: string;}@@ -678,6 +682,14 @@ export class ConversationLifecycleActionImpl {runtimeType === 'gateway' && !operationContext.topicId && operationContext.agentId? getPendingTopicRepos(operationContext.agentId): [];+ // A topic created by this send pins the model it was started with, same as+ // the manual createTopic/saveToTopic and Gateway (AiAgentService) paths. The+ // snapshot goes to the top-level `topics.model`/`provider` columns (config+ // source of truth) β generation and ChatInput display resolve from it+ // (topicSelectors.getTopicModelById).+ const newTopicModelSnapshot = !operationContext.topicId+ ? snapshotAgentModel(operationContext.agentId)+ : undefined;// Example: a pending repo topic without this metadata renders under "No directory"// until the server topic replaces `tmp_topic_*`.const optimisticTopicMetadata: ChatTopicMetadata | undefined =@@ -699,6 +711,7 @@ export class ConversationLifecycleActionImpl {? {id: `tmp_topic_${nanoid()}`,...(optimisticTopicMetadata ? { metadata: optimisticTopicMetadata } : {}),+ ...newTopicModelSnapshot,title: newTopicTitle,}: undefined;@@ -721,7 +734,7 @@ export class ConversationLifecycleActionImpl {topicId: string,title: string,action: string,- metadata?: ChatTopicMetadata,+ extra?: { metadata?: ChatTopicMetadata; model?: string; provider?: string },) => {this.#get().internal_dispatchTopic({@@ -729,7 +742,8 @@ export class ConversationLifecycleActionImpl {type: 'addTopic',value: {id: topicId,- ...(metadata ? { metadata } : {}),+ ...(extra?.metadata ? { metadata: extra.metadata } : {}),+ ...(extra?.model ? { model: extra.model, provider: extra.provider } : {}),...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),title,},@@ -744,7 +758,11 @@ export class ConversationLifecycleActionImpl {topicId,title || t('defaultTitle', { ns: 'topic' }),'sendMessage/reconcileOptimisticTopic/add',- optimisticTopic?.metadata,+ {+ metadata: optimisticTopic?.metadata,+ model: optimisticTopic?.model,+ provider: optimisticTopic?.provider,+ },);return;}@@ -755,6 +773,9 @@ export class ConversationLifecycleActionImpl {previousId: optimisticTopic.id,value: {...(optimisticTopic.metadata ? { metadata: optimisticTopic.metadata } : {}),+ ...(optimisticTopic.model+ ? { model: optimisticTopic.model, provider: optimisticTopic.provider }+ : {}),...(operationContext.groupId ? {} : { sessionId: operationContext.agentId }),title: title || t('defaultTitle', { ns: 'topic' }),},@@ -784,7 +805,11 @@ export class ConversationLifecycleActionImpl {optimisticTopic.id,optimisticTopic.title,'sendMessage/optimisticCreateTopic',- optimisticTopic.metadata,+ {+ metadata: optimisticTopic.metadata,+ model: optimisticTopic.model,+ provider: optimisticTopic.provider,+ },);this.#get().internal_updateTopicLoading(optimisticTopic.id, true);optimisticTopicActive = true;@@ -829,6 +854,7 @@ export class ConversationLifecycleActionImpl {...(workingDirectoryConfig ? { workingDirectoryConfig } : {}),}: undefined,+ ...newTopicModelSnapshot,title: newTopicTitle,topicMessageIds: messages.map((m) => m.id),}@@ -1214,6 +1240,7 @@ export class ConversationLifecycleActionImpl {: undefined,newTopic: !topicId? {+ ...newTopicModelSnapshot,topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),title: newTopicTitle,}diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.tsindex 581faed7895..4746f5182e9 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts@@ -172,16 +172,23 @@ export class StreamingExecutorActionImpl {scope, // Pass scope from operation context});- // A model/provider override resolved by the spawn site (see runClientSubAgent),- // not re-derived here: `isSubAgent` is also set for isolated group members β- // which must keep their own model β so it cannot gate this on its own.+ // Resolve the effective model/provider, in precedence order:+ // 1. `modelOverride` β forced by the spawn site (see runClientSubAgent); not+ // re-derived here because `isSubAgent` is also set for isolated group+ // members which must keep their own model, so it can't gate on its own.+ // 2. Topic-scoped model β a topic snapshots the model it was created with and+ // remembers switches made while active (top-level `topics.model`/`provider`+ // columns, read via `getTopicModelById`), overriding the agent default so+ // the whole modelβtopic chain (tools, context window, generation) uses it.// resolveAgentConfig returns an immer-frozen config, so build a new object// rather than mutating in place.+ const topicModel = topicId ? topicSelectors.getTopicModelById(topicId)(this.#get()) : undefined;+ const modelResolution = modelOverride ?? topicModel;const agentConfig: ResolvedAgentConfig =- modelOverride && resolvedAgentConfig.agentConfig+ modelResolution && resolvedAgentConfig.agentConfig? {...resolvedAgentConfig,- agentConfig: { ...resolvedAgentConfig.agentConfig, ...modelOverride },+ agentConfig: { ...resolvedAgentConfig.agentConfig, ...modelResolution },}: resolvedAgentConfig;diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex ccfd2bd9a45..8223acc20d2 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -2170,6 +2170,8 @@ describe('topic action', () => {});expect(createTopicSpy).toHaveBeenCalledWith({+ model: 'deepseek-v4-pro',+ provider: 'deepseek',sessionId: activeAgentId,messages: messages.map((m) => m.id),title: 'defaultTitle',diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex dfc990d07f1..8803fedd7b4 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -19,6 +19,7 @@ import type { TopicBatchDeleteScope } from '@/services/topic';import { topicService } from '@/services/topic';import { type ChatStore } from '@/store/chat';import { evictMessageCache } from '@/store/chat/utils/evictMessageCache';+import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';import { topicMapKey, type TopicMapScope } from '@/store/chat/utils/topicMapKey';import {canReadTopicGitTransport,@@ -190,10 +191,12 @@ export class ChatTopicActionImpl {const messages = displayMessageSelectors.activeDisplayMessages(this.#get());this.#set({ creatingTopic: true }, false, n('creatingTopic/start'));+ const targetSessionId = sessionId || activeAgentId;const topicId = await internal_createTopic({+ ...snapshotAgentModel(targetSessionId),title: t('defaultTitle', { ns: 'topic' }),messages: messages.map((m) => m.id),- sessionId: sessionId || activeAgentId,+ sessionId: targetSessionId,});this.#set({ creatingTopic: false }, false, n('creatingTopic/end'));@@ -206,12 +209,14 @@ export class ChatTopicActionImpl {if (messages.length === 0) return;const { activeAgentId, summaryTopicTitle, internal_createTopic } = this.#get();+ const targetSessionId = sessionId || activeAgentId;// 1. create topic and bind these messagesconst topicId = await internal_createTopic({+ ...snapshotAgentModel(targetSessionId),title: t('defaultTitle', { ns: 'topic' }),messages: messages.map((m) => m.id),- sessionId: sessionId || activeAgentId,+ sessionId: targetSessionId,});this.#get().internal_updateTopicLoading(topicId, true);@@ -403,6 +408,20 @@ export class ChatTopicActionImpl {await this.#get().internal_updateTopic(id, { title });};+ /**+ * Pin a model to a topic by writing the top-level `topics.model`/`provider`+ * columns (the config source of truth), NOT metadata. Called when the user+ * switches model while a topic is active so each topic keeps its own model+ * (see the Model/ModelLabel controls); generation + ChatInput display read it+ * back via `topicSelectors.getTopicModelById`.+ */+ updateTopicModel = async (+ id: string,+ { model, provider }: { model: string; provider: string },+ ): Promise<void> => {+ await this.#get().internal_updateTopic(id, { model, provider });+ };+/*** Optimistic `updateTopicStatus` writes that a topic-list refetch must not* clobber. A refetch whose server query ran BEFORE a status write can landdiff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.tsindex 2b3e999c97d..80dc568d4e2 100644--- a/src/store/chat/slices/topic/selectors.test.ts+++ b/src/store/chat/slices/topic/selectors.test.ts@@ -48,6 +48,48 @@ describe('topicSelectors', () => {});});+ describe('getTopicModelById / activeTopicModel', () => {+ const modelTopicDataMap = createTopicDataMap('test');+ modelTopicDataMap[topicMapKey({ agentId: 'test' })].items = [+ // Pinned model lives in the top-level `model`/`provider` columns, not metadata.+ { id: 'withModel', name: 'With Model', model: 'gpt-5', provider: 'openai' },+ { id: 'noModel', name: 'No Model' },+ { id: 'modelOnly', name: 'Model Only', model: 'claude-opus-4-8' },+ ] as any;++ it('returns the model/provider pinned to a topic', () => {+ const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });+ expect(topicSelectors.getTopicModelById('withModel')(state)).toEqual({+ model: 'gpt-5',+ provider: 'openai',+ });+ });++ it('defaults provider to empty string when only model is recorded', () => {+ const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });+ expect(topicSelectors.getTopicModelById('modelOnly')(state)).toEqual({+ model: 'claude-opus-4-8',+ provider: '',+ });+ });++ it('returns undefined when the topic has no model recorded', () => {+ const state = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });+ expect(topicSelectors.getTopicModelById('noModel')(state)).toBeUndefined();+ });++ it('activeTopicModel reads the active topic model, undefined when no active topic', () => {+ const base = merge(initialStore, { topicDataMap: modelTopicDataMap, activeAgentId: 'test' });+ expect(topicSelectors.activeTopicModel(base)).toBeUndefined();++ const active = merge(base, { activeTopicId: 'withModel' });+ expect(topicSelectors.activeTopicModel(active)).toEqual({+ model: 'gpt-5',+ provider: 'openai',+ });+ });+ });+describe('currentTopicLength', () => {it('should return 0 if there are no topics', () => {const length = topicSelectors.currentTopicLength(initialStore);diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex 180147e2d6a..e415171ae52 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -82,6 +82,30 @@ const currentActiveTopicSummary = (s: ChatStoreState): ChatTopicSummary | undeficonst currentTopicMetadata = (s: ChatStoreState) => currentActiveTopic(s)?.metadata;+/**+ * Get the model/provider pinned to a specific topic (snapshotted on creation,+ * updated when the user switches model while the topic is active).+ * Returns undefined when the topic has no model recorded (e.g. legacy topics),+ * in which case callers should fall back to the agent default.+ */+const getTopicModelById =+ (id: string) =>+ (s: ChatStoreState): { model: string; provider: string } | undefined => {+ const topic = getTopicById(id)(s);+ if (!topic?.model) return undefined;++ return { model: topic.model, provider: topic.provider || '' };+ };++/**+ * The model/provider pinned to the active topic, or undefined when there is no+ * active topic or it has no model recorded.+ */+const activeTopicModel = (s: ChatStoreState): { model: string; provider: string } | undefined => {+ if (!s.activeTopicId) return undefined;+ return getTopicModelById(s.activeTopicId)(s);+};+/*** Extract a topic's working directory from its metadata.* On desktop: local filesystem path.@@ -287,6 +311,7 @@ const agentTopicsViewLoadMoreError = (s: ChatStoreState): unknown =>agentTopicsViewData(s)?.loadMoreError;export const topicSelectors = {+ activeTopicModel,agentTopicsViewHasMore,agentTopicsViewIsLoadingMore,agentTopicsViewLoadMoreError,@@ -304,6 +329,7 @@ export const topicSelectors = {displayTopics,displayTopicsForSidebar,getTopicById,+ getTopicModelById,getTopicWorkingDirectory,getTopicsByAgentId,groupedTopicsForSidebar,diff --git a/src/store/chat/utils/snapshotAgentModel.ts b/src/store/chat/utils/snapshotAgentModel.tsnew file mode 100644index 00000000000..5419e0655a4--- /dev/null+++ b/src/store/chat/utils/snapshotAgentModel.ts@@ -0,0 +1,22 @@+import { getAgentStoreState } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++/**+ * Snapshot the given agent's current model/provider so a newly created topic+ * remembers which model it was started with. The snapshot is persisted to the+ * top-level `topics.model`/`provider` columns (the config source of truth) β+ * subsequent model switches while the topic is active overwrite those columns+ * (see `updateTopicModel`), and generation + ChatInput display resolve+ * from them (see `topicSelectors.getTopicModelById`).+ */+export const snapshotAgentModel = (+ agentId?: string | null,+): { model?: string; provider?: string } => {+ if (!agentId) return {};++ const agentState = getAgentStoreState();+ const model = agentByIdSelectors.getAgentModelById(agentId)(agentState);+ if (!model) return {};++ return { model, provider: agentByIdSelectors.getAgentModelProviderById(agentId)(agentState) };+};