🤯 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(settings): redesign Service Model settings page (#21480)
CanisMinor1d601f8b160f
diff --git a/apps/server/src/services/expertise/modelConfig.test.ts b/apps/server/src/services/expertise/modelConfig.test.tsindex 0814b550bcb..8c7dd6e7ff3 100644--- a/apps/server/src/services/expertise/modelConfig.test.ts+++ b/apps/server/src/services/expertise/modelConfig.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import { DEFAULT_SYSTEM_AGENT_ITEM } from '@lobechat/const';import { beforeEach, describe, expect, it, vi } from 'vitest';import { resolveExpertiseModelConfig } from './modelConfig';@@ -14,12 +15,12 @@ vi.mock('@/database/models/user', () => ({describe('resolveExpertiseModelConfig', () => {beforeEach(() => vi.clearAllMocks());- it('defaults to GPT-5.6 Luna instead of the target agent model', async () => {+ it('defaults to the main service model instead of the target agent model', async () => {getUserSettings.mockResolvedValue(undefined);await expect(resolveExpertiseModelConfig({} as never, 'user_1')).resolves.toEqual({- model: 'gpt-5.6-luna',- provider: 'openai',+ model: DEFAULT_SYSTEM_AGENT_ITEM.model,+ provider: DEFAULT_SYSTEM_AGENT_ITEM.provider,});});diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex f81999b3060..cc9d53b5893 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1219,10 +1219,33 @@"plugin.settings.title": "{{id}} Skill Configuration","plugin.settings.tooltip": "Skill Configuration","plugin.store": "Skill Store",+ "serviceModel.advanced.collapse": "Collapse",+ "serviceModel.advanced.expand": "Expand",+ "serviceModel.advanced.restoreAll": "Restore all",+ "serviceModel.advanced.summary.custom": "{{count}} customized",+ "serviceModel.advanced.summary.off": "{{count}} off",+ "serviceModel.advanced.summary.rest": "the rest follow the settings above",+ "serviceModel.advanced.summary.separator": ", ",+ "serviceModel.advanced.summary.total": "{{count}} tasks",+ "serviceModel.advanced.title": "Advanced","serviceModel.contextLimit.placeholder": "Context limit",- "serviceModel.memoryModels.title": "Memory",- "serviceModel.modelAssignments.title": "General",- "serviceModel.optionalFeatures.title": "Optional Features",+ "serviceModel.customModel": "Choose a model",+ "serviceModel.desc": "Models LobeHub uses for background tasks. They follow the system recommendation by default and upgrade automatically when new models arrive.",+ "serviceModel.group.agent": "Agents & Goals",+ "serviceModel.group.content": "Content Processing",+ "serviceModel.group.memory": "Memory",+ "serviceModel.group.suggestion": "Suggestions",+ "serviceModel.group.topic": "Topic Naming & Summaries",+ "serviceModel.group.voice": "Voice",+ "serviceModel.off": "Off",+ "serviceModel.systemRecommended": "System recommended",+ "serviceModel.tier.embedding.desc": "Memory retrieval",+ "serviceModel.tier.embedding.title": "Embedding Model",+ "serviceModel.tier.flash.desc": "Frequent tasks such as naming, translation, compression and memory",+ "serviceModel.tier.flash.title": "Flash Model",+ "serviceModel.tier.main.desc": "Quality-sensitive tasks such as writing and reasoning",+ "serviceModel.tier.main.title": "Main Model",+ "serviceModel.title": "Service Model","serviceModel.topicAutoSummary.desc": "Summarizes topics created in the rolling 24-hour window after one hour without message activity.","settingAgent.agentTools.add": "Add Tool","settingAgent.agentTools.agentEmpty": "No agent-exclusive tools yet",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex eaefb15d4e2..7cbb956dd65 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1219,10 +1219,33 @@"plugin.settings.title": "{{id}} 技能配置","plugin.settings.tooltip": "技能配置","plugin.store": "技能商店",+ "serviceModel.advanced.collapse": "收起",+ "serviceModel.advanced.expand": "展开",+ "serviceModel.advanced.restoreAll": "全部恢复",+ "serviceModel.advanced.summary.custom": "{{count}} 项自定",+ "serviceModel.advanced.summary.off": "{{count}} 项不启用",+ "serviceModel.advanced.summary.rest": "其余跟随上面的设置",+ "serviceModel.advanced.summary.separator": ",",+ "serviceModel.advanced.summary.total": "{{count}} 项任务",+ "serviceModel.advanced.title": "高级","serviceModel.contextLimit.placeholder": "上下文限制",- "serviceModel.memoryModels.title": "记忆",- "serviceModel.modelAssignments.title": "通用",- "serviceModel.optionalFeatures.title": "可选功能",+ "serviceModel.customModel": "指定模型",+ "serviceModel.desc": "LobeHub 后台任务用的模型。默认跟随系统推荐,有新模型时自动升级。",+ "serviceModel.group.agent": "助理与目标",+ "serviceModel.group.content": "内容处理",+ "serviceModel.group.memory": "记忆",+ "serviceModel.group.suggestion": "建议",+ "serviceModel.group.topic": "话题命名与总结",+ "serviceModel.group.voice": "语音",+ "serviceModel.off": "不启用",+ "serviceModel.systemRecommended": "系统推荐",+ "serviceModel.tier.embedding.desc": "记忆检索",+ "serviceModel.tier.embedding.title": "向量化模型",+ "serviceModel.tier.flash.desc": "命名、翻译、压缩、记忆等高频任务",+ "serviceModel.tier.flash.title": "Flash 模型",+ "serviceModel.tier.main.desc": "创作、推理等看重质量的任务",+ "serviceModel.tier.main.title": "主模型",+ "serviceModel.title": "服务模型","serviceModel.topicAutoSummary.desc": "针对滚动 24 小时内创建、消息已停止更新一小时的话题自动生成摘要。","settingAgent.agentTools.add": "添加工具","settingAgent.agentTools.agentEmpty": "还没有 Agent 专属工具",diff --git a/packages/const/src/settings/systemAgent.ts b/packages/const/src/settings/systemAgent.tsindex be6c66b4b30..af811159e9e 100644--- a/packages/const/src/settings/systemAgent.ts+++ b/packages/const/src/settings/systemAgent.ts@@ -7,8 +7,10 @@ import {} from '@lobechat/business-const';import type {PromptRewriteSystemAgent,+ ServiceModelTier,SystemAgentItem,UserServiceModelConfig,+ UserServiceModelConfigKey,} from '@lobechat/types';import { DEFAULT_EMBEDDING_MODEL, DEFAULT_MINI_MODEL, DEFAULT_MODEL } from './llm';@@ -67,11 +69,11 @@ export const DEFAULT_SYSTEM_AGENT_CONFIG: UserServiceModelConfig = {agentMeta: DEFAULT_SYSTEM_AGENT_ITEM,asr: DEFAULT_ASR_SYSTEM_AGENT_ITEM,channelRouting: { enabled: false, model: 'jev-1.14.0', provider: 'typesafe' },- expertise: DEFAULT_MINI_SYSTEM_AGENT_ITEM,+ expertise: DEFAULT_SYSTEM_AGENT_ITEM,followUpAction: DEFAULT_FOLLOW_UP_ACTION_SYSTEM_AGENT_ITEM,generationTopic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,- goal: DEFAULT_MINI_SYSTEM_AGENT_ITEM,- historyCompress: DEFAULT_SYSTEM_AGENT_ITEM,+ goal: DEFAULT_SYSTEM_AGENT_ITEM,+ historyCompress: DEFAULT_MINI_SYSTEM_AGENT_ITEM,inputCompletion: DEFAULT_INPUT_COMPLETION_SYSTEM_AGENT_ITEM,memoryAnalysisAgentConfig: DEFAULT_MINI_SYSTEM_AGENT_ITEM,onboardingTaskRecommender: DEFAULT_MINI_SYSTEM_AGENT_ITEM,@@ -79,8 +81,32 @@ export const DEFAULT_SYSTEM_AGENT_CONFIG: UserServiceModelConfig = {userMemoryEmbedding: DEFAULT_USER_MEMORY_EMBEDDING_SYSTEM_AGENT_ITEM,userMemoryPersonaWriter: DEFAULT_MINI_SYSTEM_AGENT_ITEM,promptRewrite: DEFAULT_PROMPT_REWRITE_SYSTEM_AGENT_ITEM,- thread: DEFAULT_SYSTEM_AGENT_ITEM,+ thread: DEFAULT_MINI_SYSTEM_AGENT_ITEM,topic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,topicAutoSummary: DEFAULT_TOPIC_AUTO_SUMMARY_SYSTEM_AGENT_ITEM,translation: DEFAULT_MINI_SYSTEM_AGENT_ITEM,};++/**+ * Which top-level Service Model tier each task slot follows. A slot's default+ * above is its tier's default, so a slot that follows an unset tier runs the+ * same system-recommended model the tier shows. The first slot of a tier+ * stands for the tier's own recommendation. Slots left out (`asr`,+ * `channelRouting`, onboarding) keep their own system default and ignore tier changes.+ */+export const SERVICE_MODEL_TIER_SLOTS: Record<ServiceModelTier, UserServiceModelConfigKey[]> = {+ embedding: ['userMemoryEmbedding'],+ flash: [+ 'topic',+ 'thread',+ 'generationTopic',+ 'promptRewrite',+ 'historyCompress',+ 'memoryAnalysisAgentConfig',+ 'userMemoryPersonaWriter',+ 'translation',+ 'inputCompletion',+ 'followUpAction',+ ],+ main: ['agentMeta', 'expertise', 'goal', 'topicAutoSummary'],+};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 1dea0edae03..a2d86a21396 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1527,10 +1527,35 @@ export default {'settingSystem.oauth.signout.confirm': 'Confirm sign out?','settingSystem.oauth.signout.success': 'Sign out successful','settingSystem.title': 'System Settings',- 'serviceModel.modelAssignments.title': 'General',+ 'serviceModel.advanced.collapse': 'Collapse',+ 'serviceModel.advanced.expand': 'Expand',+ 'serviceModel.advanced.restoreAll': 'Restore all',+ 'serviceModel.advanced.summary.custom': '{{count}} customized',+ 'serviceModel.advanced.summary.off': '{{count}} off',+ 'serviceModel.advanced.summary.rest': 'the rest follow the settings above',+ 'serviceModel.advanced.summary.separator': ', ',+ 'serviceModel.advanced.summary.total': '{{count}} tasks',+ 'serviceModel.advanced.title': 'Advanced','serviceModel.contextLimit.placeholder': 'Context limit',- 'serviceModel.memoryModels.title': 'Memory',- 'serviceModel.optionalFeatures.title': 'Optional Features',+ 'serviceModel.customModel': 'Choose a model',+ 'serviceModel.desc':+ 'Models LobeHub uses for background tasks. They follow the system recommendation by default and upgrade automatically when new models arrive.',+ 'serviceModel.group.agent': 'Agents & Goals',+ 'serviceModel.group.content': 'Content Processing',+ 'serviceModel.group.memory': 'Memory',+ 'serviceModel.group.suggestion': 'Suggestions',+ 'serviceModel.group.topic': 'Topic Naming & Summaries',+ 'serviceModel.group.voice': 'Voice',+ 'serviceModel.off': 'Off',+ 'serviceModel.systemRecommended': 'System recommended',+ 'serviceModel.title': 'Service Model',+ 'serviceModel.tier.embedding.desc': 'Memory retrieval',+ 'serviceModel.tier.embedding.title': 'Embedding Model',+ 'serviceModel.tier.flash.desc':+ 'Frequent tasks such as naming, translation, compression and memory',+ 'serviceModel.tier.flash.title': 'Flash Model',+ 'serviceModel.tier.main.desc': 'Quality-sensitive tasks such as writing and reasoning',+ 'serviceModel.tier.main.title': 'Main Model','serviceModel.topicAutoSummary.desc':'Summarizes topics created in the rolling 24-hour window after one hour without message activity.','settingSystemTools.appEnvironment.chromium.desc': 'Chromium browser engine version',diff --git a/packages/types/src/user/settings/index.ts b/packages/types/src/user/settings/index.tsindex a2a5f4070ab..c1a0b390f84 100644--- a/packages/types/src/user/settings/index.ts+++ b/packages/types/src/user/settings/index.ts@@ -9,7 +9,7 @@ import type { MarketAuthTokens } from './market';import type { UserMemorySettings } from './memory';import type { UserModelProviderConfig } from './modelProvider';import type { NotificationSettings } from './notification';-import type { UserServiceModelConfig } from './systemAgent';+import type { ServiceModelTierConfig, UserServiceModelConfig } from './systemAgent';import type { UserToolConfig } from './tool';import type { UserTTSConfig } from './tts';@@ -42,7 +42,7 @@ export interface UserSettings {market?: MarketAuthTokens;memory?: UserMemorySettings;notification?: NotificationSettings;- systemAgent: UserServiceModelConfig;+ systemAgent: UserServiceModelConfig & { tiers?: ServiceModelTierConfig };tool: UserToolConfig;tts: UserTTSConfig;}diff --git a/packages/types/src/user/settings/systemAgent.ts b/packages/types/src/user/settings/systemAgent.tsindex 06a0ba28c00..72cee21e197 100644--- a/packages/types/src/user/settings/systemAgent.ts+++ b/packages/types/src/user/settings/systemAgent.ts@@ -49,6 +49,26 @@ export interface UserMemoryServiceModelConfig {export interface UserServiceModelConfigextends UserSystemAgentConfig, UserMemoryServiceModelConfig {}+/**+ * The three models a user picks at the top of Service Model settings. Every+ * task slot follows one of them (see `SERVICE_MODEL_TIER_SLOTS`) unless the+ * user pins that slot to its own model.+ */+export type ServiceModelTier = 'embedding' | 'flash' | 'main';++export interface ServiceModelTierItem {+ model: string;+ provider: string;+}++/**+ * Tier choices stored next to the task slots in the `systemAgent` column. An+ * absent tier follows the system recommendation. A chosen tier is also written+ * into each slot that follows it, so every runtime that reads a slot directly+ * gets the tier model without knowing tiers exist.+ */+export type ServiceModelTierConfig = Partial<Record<ServiceModelTier, ServiceModelTierItem>>;+export type UserSystemAgentConfigKey = keyof UserSystemAgentConfig;export type UserMemoryServiceModelConfigKey = keyof UserMemoryServiceModelConfig;export type UserServiceModelConfigKey = keyof UserServiceModelConfig;diff --git a/src/features/ServiceModel/ChatAssistForm.tsx b/src/features/ServiceModel/ChatAssistForm.tsxindex 2bc04c6d550..6f4540a7adf 100644--- a/src/features/ServiceModel/ChatAssistForm.tsx+++ b/src/features/ServiceModel/ChatAssistForm.tsx@@ -72,7 +72,7 @@ ChatAssistControl.displayName = 'ChatAssistControl';/*** The chat-assist entries of the service-model settings that stay personal* inside a workspace (follow-up chips, input completion). Unlike- * `ModelAssignmentsForm`, nothing here is gated on workspace permissions:+ * `ServiceModelForm`, nothing here is gated on workspace permissions:* every member configures their own.*/const ChatAssistForm = memo(() => {diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsxdeleted file mode 100644index 786785bde8c..00000000000--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx+++ /dev/null@@ -1,387 +0,0 @@-'use client';--import { Flexbox, InputNumber, Switch, TextArea, Tooltip } from '@lobehub/ui';-import { Form, type FormFieldProps, type FormGroupItem, useForm } from '@lobehub/ui/form';-import isEqual from 'fast-deep-equal';-import { memo, useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';--import AsyncError from '@/components/AsyncError';-import AutoSaveHint from '@/components/Editor/AutoSaveHint';-import { RouteLoading } from '@/components/Skeleton/RouteSegment';-import { FORM_STYLE } from '@/const/layoutTokens';-import ModelSelect from '@/features/ModelSelect';-import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';-import { usePermission } from '@/hooks/usePermission';-import { useSaveState } from '@/hooks/useSaveState';-import { useUserStore } from '@/store/user';-import { settingsSelectors } from '@/store/user/selectors';-import {- PERSONAL_SYSTEM_AGENT_KEYS,- type SystemAgentItem,- type UserServiceModelConfigKey,-} from '@/types/user/settings';--type ModelAssignmentItemKey = Exclude<- UserServiceModelConfigKey,- 'asr' | 'channelRouting' | 'onboardingTaskRecommender' | 'onboardingUnderstanding'->;--interface SystemAgentModelItem {- contextLimit?: boolean;- key: ModelAssignmentItemKey;- modelType?: 'chat' | 'embedding';-}--type LoadingKey = 'defaultAgent' | UserServiceModelConfigKey;--type SavingGroup = 'assignments' | 'memory' | 'optional';--const SYSTEM_AGENT_MODEL_ITEMS: SystemAgentModelItem[] = [- { key: 'expertise' },- { key: 'goal' },- { key: 'topic' },- { key: 'generationTopic' },- { key: 'translation' },- { key: 'historyCompress' },- { key: 'agentMeta' },-];--const OPTIONAL_FEATURE_ITEMS: SystemAgentModelItem[] = [- { key: 'topicAutoSummary' },- { key: 'followUpAction' },- { key: 'inputCompletion' },- { key: 'promptRewrite' },-];--const MEMORY_MODEL_ITEMS: SystemAgentModelItem[] = [- { contextLimit: true, key: 'memoryAnalysisAgentConfig' },- { contextLimit: true, key: 'userMemoryPersonaWriter' },- { contextLimit: true, key: 'userMemoryEmbedding', modelType: 'embedding' },-];--interface ModelAssignmentsFormProps {- /**- * Drop the personal chat-assist rows (follow-up, input completion). The- * workspace surface edits them on its own Chat Preferences tab instead.- */- hidePersonalPreferences?: boolean;-}--const ModelAssignmentsForm = memo<ModelAssignmentsFormProps>(({ hidePersonalPreferences }) => {- const { t } = useTranslation('setting');- const { allowed: canManageServiceModel, reason } = usePermission('manage_settings');- const [defaultAgent, systemAgentSettings] = useUserStore(- (s) => [settingsSelectors.defaultAgent(s), settingsSelectors.currentSystemAgent(s)],- isEqual,- );- const [- updateDefaultAgent,- updateSystemAgent,- isUserStateInit,- isUserStateInitError,- refreshUserState,- ] = useUserStore((s) => [- s.updateDefaultAgent,- s.updateSystemAgent,- s.isUserStateInit,- s.isUserStateInitError,- s.refreshUserState,- ]);- const [loadingKey, setLoadingKey] = useState<LoadingKey>();- // Track which group last saved so its AutoSaveHint (and only its) reflects the- // shared save-state — the write-side counterpart to the read-side AsyncError above.- const [savingGroup, setSavingGroup] = useState<SavingGroup>();- const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();- const form = useForm();-- useEffect(() => {- if (loadingKey === 'defaultAgent') setLoadingKey(undefined);- }, [defaultAgent.config.model, defaultAgent.config.provider, loadingKey]);-- const groupOfKey = (key: UserServiceModelConfigKey): SavingGroup => {- if (MEMORY_MODEL_ITEMS.some((item) => item.key === key)) return 'memory';- if (key === 'asr' || OPTIONAL_FEATURE_ITEMS.some((item) => item.key === key)) return 'optional';- return 'assignments';- };-- if (!isUserStateInit) {- // A failed user-state init must show error + Retry, not a permanent skeleton- if (isUserStateInitError)- return (- <AsyncError- error={isUserStateInitError}- variant={'block'}- onRetry={() => refreshUserState()}- />- );- return <RouteLoading />;- }-- const updateDefaultAgentModel = async ({- model,- provider,- }: {- model: string;- provider: string;- }) => {- if (!canManageServiceModel) return;-- setSavingGroup('assignments');- setLoadingKey('defaultAgent');- try {- await save(() => updateDefaultAgent({ config: { model, provider } }));- } finally {- setLoadingKey(undefined);- }- };-- const updateSystemAgentModel = async (- key: UserServiceModelConfigKey,- value: Partial<SystemAgentItem>,- ) => {- if (!canManageServiceModel) return;-- setSavingGroup(groupOfKey(key));- setLoadingKey(key);- try {- await save(() => updateSystemAgent(key, value));- } finally {- setLoadingKey(undefined);- }- };-- const defaultAgentItem: FormFieldProps = {- children: (- <Tooltip title={reason}>- <Flexbox- align="center"- direction="horizontal"- gap={12}- style={{ width: 'min(100%, 448px)' }}- >- <ModelSelect- disabled={!canManageServiceModel}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- value={defaultAgent.config}- onChange={updateDefaultAgentModel}- />- </Flexbox>- </Tooltip>- ),- // No `desc` here or on the rows below: in Model Assignments the label plus- // the picker already say what the row does, and a line of prose per row- // just pushes the list apart. The other groups keep theirs.- label: t('defaultAgent.title'),- };-- const systemModelItems: FormFieldProps[] = SYSTEM_AGENT_MODEL_ITEMS.map(({ key }) => {- const value = systemAgentSettings[key];-- return {- children: (- <Tooltip title={reason}>- <Flexbox- align="center"- direction="horizontal"- gap={12}- style={{ width: 'min(100%, 448px)' }}- >- <ModelSelect- disabled={!canManageServiceModel}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- value={value}- onChange={(props) => updateSystemAgentModel(key, props)}- />- </Flexbox>- </Tooltip>- ),- label: t(`systemAgent.${key}.title`),- } satisfies FormFieldProps;- });-- const memoryModelItems: FormFieldProps[] = MEMORY_MODEL_ITEMS.map(- ({ contextLimit, key, modelType }) => {- const value = systemAgentSettings[key];-- return {- children: (- <Flexbox- align="center"- direction="horizontal"- gap={12}- style={{ width: 'min(100%, 448px)' }}- >- <ModelSelect- modelType={modelType}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- value={value}- onChange={(props) => updateSystemAgentModel(key, props)}- />- {contextLimit && (- <InputNumber- min={1}- placeholder={t('serviceModel.contextLimit.placeholder')}- // Sits beside the picker, so it keeps the picker's height and- // holds its width while the picker takes the slack.- style={{ flex: 'none', width: 140 }}- value={value.contextLimit}- onChange={(contextLimit) =>- updateSystemAgentModel(key, {- contextLimit: typeof contextLimit === 'number' ? contextLimit : undefined,- })- }- />- )}- </Flexbox>- ),- desc: t(`systemAgent.${key}.modelDesc`),- label: t(`systemAgent.${key}.title`),- } satisfies FormFieldProps;- },- );-- const optionalFeatureItems: FormFieldProps[] = OPTIONAL_FEATURE_ITEMS.filter(- ({ key }) =>- !hidePersonalPreferences || !(PERSONAL_SYSTEM_AGENT_KEYS as readonly string[]).includes(key),- ).map(({ key }) => {- const value = systemAgentSettings[key];- const featureDisabled = value.enabled === false;-- return {- children: (- <Tooltip title={reason}>- <Flexbox gap={12} style={{ width: 'min(100%, 448px)' }}>- <Flexbox align="center" direction="horizontal" gap={12} justify="flex-end">- {/* Which model runs a feature is only worth asking once the feature- itself is on — off, the picker is a dead control, so the switch- stands alone until it's flipped back. */}- {!featureDisabled && (- <ModelSelect- disabled={!canManageServiceModel}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- value={value}- onChange={(props) => updateSystemAgentModel(key, props)}- />- )}- <Flexbox align="center" direction="horizontal" gap={8}>- <Switch- aria-label={t(`systemAgent.${key}.title`)}- checked={value.enabled}- disabled={!canManageServiceModel}- loading={loadingKey === key}- onChange={(enabled) => updateSystemAgentModel(key, { enabled })}- />- </Flexbox>- </Flexbox>- {key === 'topicAutoSummary' && !featureDisabled && (- <TextArea- autoSize={{ maxRows: 8, minRows: 3 }}- defaultValue={value.customPrompt}- disabled={!canManageServiceModel}- placeholder={t('systemAgent.topicAutoSummary.promptPlaceholder')}- onBlur={(event) =>- updateSystemAgentModel(key, { customPrompt: event.currentTarget.value.trim() })- }- />- )}- </Flexbox>- </Tooltip>- ),- desc: t(`systemAgent.${key}.modelDesc`),- label: (- <span- style={{- opacity: featureDisabled || !canManageServiceModel ? 0.45 : 1,- }}- >- {t(`systemAgent.${key}.title`)}- </span>- ),- } satisfies FormFieldProps;- });-- const asrValue = systemAgentSettings.asr;- const asrItem: FormFieldProps = {- children: (- <Tooltip title={reason}>- <Flexbox- align="center"- direction="horizontal"- gap={12}- style={{ width: 'min(100%, 448px)' }}- >- <ModelSelect- allowClear- disabled={!canManageServiceModel}- modelType={'asr'}- placeholder={t('systemAgent.asr.placeholder')}- showAbility={false}- style={{ minWidth: 0, width: '100%' }}- // Empty means unconfigured: render the placeholder rather than a blank selection.- value={asrValue.model && asrValue.provider ? asrValue : undefined}- onChange={(props) => updateSystemAgentModel('asr', props)}- onClear={() => updateSystemAgentModel('asr', { model: '', provider: '' })}- />- </Flexbox>- </Tooltip>- ),- desc: t('systemAgent.asr.modelDesc'),- label: t('systemAgent.asr.title'),- };-- const renderSaveHint = (group: SavingGroup) =>- savingGroup === group && (- <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />- );-- const modelAssignments: FormGroupItem = {- children: [defaultAgentItem, ...systemModelItems],- extra: renderSaveHint('assignments'),- title: (- <SettingsSearchAnchor id={'service-model-assignments'}>- {t('serviceModel.modelAssignments.title')}- </SettingsSearchAnchor>- ),- };-- const optionalFeatures: FormGroupItem = {- children: [...optionalFeatureItems, asrItem],- extra: renderSaveHint('optional'),- title: (- <SettingsSearchAnchor id={'service-model-optional-features'}>- {t('serviceModel.optionalFeatures.title')}- </SettingsSearchAnchor>- ),- };-- const memoryModels: FormGroupItem = {- children: memoryModelItems,- extra: renderSaveHint('memory'),- title: (- <SettingsSearchAnchor id={'service-model-memory'}>- {t('serviceModel.memoryModels.title')}- </SettingsSearchAnchor>- ),- };-- return (- <Form- collapsible={false}- form={form}- items={[modelAssignments, memoryModels, optionalFeatures]}- itemsType={'group'}- variant={'filled'}- {...FORM_STYLE}- itemMinWidth={undefined}- />- );-});--ModelAssignmentsForm.displayName = 'ModelAssignmentsForm';--export default ModelAssignmentsForm;diff --git a/src/features/ServiceModel/ServiceModelForm/ModelLabel.tsx b/src/features/ServiceModel/ServiceModelForm/ModelLabel.tsxnew file mode 100644index 00000000000..3c2487710c1--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/ModelLabel.tsx@@ -0,0 +1,37 @@+import { Flexbox, Text } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';++import { ModelIcon } from '@/components/LobeIcons';++import { styles } from './styles';++interface ModelLabelProps {+ /** Gray text on the right, e.g. 「系统推荐」 in a tier picker. */+ hint?: string;+ model: string;+ name: string;+}++/** Icon + model name; with a hint it fills the trigger so the hint sits at the right edge. */+const ModelLabel = ({ hint, model, name }: ModelLabelProps) => (+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ justify={'space-between'}+ // Without a hint it keeps its own width so the parent decides the alignment.+ style={+ hint+ ? { minWidth: 0, width: '100%' }+ : { flex: 'none', maxWidth: '100%', minWidth: 0, width: 'auto' }+ }+ >+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <ModelIcon model={model} size={16} type={'avatar'} />+ <Text ellipsis>{name}</Text>+ </Flexbox>+ {hint && <span {...stylex.props(styles.hint)}>{hint}</span>}+ </Flexbox>+);++export default ModelLabel;diff --git a/src/features/ServiceModel/ServiceModelForm/SlotRow.tsx b/src/features/ServiceModel/ServiceModelForm/SlotRow.tsxnew file mode 100644index 00000000000..c74f3a57c52--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/SlotRow.tsx@@ -0,0 +1,111 @@+import { Select, type SelectOptions } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import { type ModelRef, type SlotChoice } from '../serviceModelState';+import ModelLabel from './ModelLabel';+import { PICKER_WIDTH, styles } from './styles';+import { type ModelKind, toOptionValue, useModelName, useModelOptions } from './useModelCatalog';++const FOLLOW_VALUE = '__follow__';+const OFF_VALUE = '__off__';++/** What a task row shows: the follow target, 「不启用」, or its own model. */+export type RowState = { kind: 'custom'; value: ModelRef } | { kind: 'follow' } | { kind: 'off' };++interface SlotRowProps {+ canDisable: boolean;+ disabled?: boolean;+ /** Who the row follows: 主模型 / Flash 模型 / 向量化模型 / 系统推荐. */+ followLabel: string;+ /** The model the row runs when it follows, shown next to the follow item. */+ followModel?: ModelRef;+ modelKind: ModelKind;+ onChange: (choice: SlotChoice) => void;+ state: RowState;+ /** The picker's accessible name; the row shows the same text as its label. */+ title: string;+}++/**+ * One task's picker: borderless, in the shared 280px right column. Following+ * and off rows read as gray text; only a pinned row shows an icon and a model+ * name. Picking the first item (the follow target) restores a single row.+ */+const SlotRow = ({+ canDisable,+ disabled,+ followLabel,+ followModel,+ modelKind,+ onChange,+ state,+ title,+}: SlotRowProps) => {+ const { t } = useTranslation('setting');+ const { groups, parseValue } = useModelOptions(modelKind);+ const getModelName = useModelName();++ const value =+ state.kind === 'custom'+ ? toOptionValue(state.value)+ : state.kind === 'off'+ ? OFF_VALUE+ : FOLLOW_VALUE;++ const options: SelectOptions = [+ {+ label: (+ <span style={{ display: 'flex', gap: 8, justifyContent: 'space-between', width: '100%' }}>+ <span>{followLabel}</span>+ {followModel && <span {...stylex.props(styles.hint)}>{getModelName(followModel)}</span>}+ </span>+ ),+ title: followLabel,+ value: FOLLOW_VALUE,+ },+ ...groups,+ ...(canDisable+ ? [+ {+ className: stylex.props(styles.offOption).className,+ label: t('serviceModel.off'),+ title: t('serviceModel.off'),+ value: OFF_VALUE,+ },+ ]+ : []),+ ];++ return (+ <Select+ aria-label={title}+ classNames={{ value: stylex.props(styles.triggerValue).className }}+ disabled={disabled}+ options={options}+ // borderless sits 1px further right than a filled trigger; keep the arrows in one line+ style={{ flex: 'none', marginInlineEnd: 1, width: PICKER_WIDTH }}+ value={value}+ variant={'borderless'}+ labelRender={() =>+ state.kind === 'custom' ? (+ <span {...stylex.props(styles.valueEnd)}>+ <ModelLabel model={state.value.model} name={getModelName(state.value)} />+ </span>+ ) : (+ <span {...stylex.props(styles.valueMuted)}>+ {state.kind === 'off' ? t('serviceModel.off') : followLabel}+ </span>+ )+ }+ onChange={(next) => {+ if (typeof next !== 'string' || next === value) return;+ if (next === FOLLOW_VALUE) onChange({ kind: 'follow' });+ else if (next === OFF_VALUE) onChange({ kind: 'off' });+ else onChange({ kind: 'custom', value: parseValue(next) });+ }}+ />+ );+};++export default SlotRow;diff --git a/src/features/ServiceModel/ServiceModelForm/TierRow.tsx b/src/features/ServiceModel/ServiceModelForm/TierRow.tsxnew file mode 100644index 00000000000..895588da6ad--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/TierRow.tsx@@ -0,0 +1,83 @@+import { Flexbox, Select, type SelectOptions } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import { type ModelRef } from '../serviceModelState';+import ModelLabel from './ModelLabel';+import { styles } from './styles';+import { type ModelKind, toOptionValue, useModelName, useModelOptions } from './useModelCatalog';++const SYSTEM_VALUE = '__system__';++interface TierRowProps {+ disabled?: boolean;+ modelKind: ModelKind;+ onChange: (value: ModelRef | undefined) => void;+ /** The model the system recommends for this tier right now. */+ recommended: ModelRef;+ /** The picker's accessible name; the form row shows the same text as its label. */+ title: string;+ /** The user's pick; `undefined` follows the system recommendation. */+ value?: ModelRef;+}++/**+ * A top-level model picker. `Form.Field` supplies the label and the scope text;+ * this renders only the control. 「系统推荐」 is said once, next to the model it+ * currently means.+ */+const TierRow = ({ disabled, modelKind, onChange, recommended, title, value }: TierRowProps) => {+ const { t } = useTranslation('setting');+ const { groups, parseValue } = useModelOptions(modelKind);+ const getModelName = useModelName();+ const systemLabel = t('serviceModel.systemRecommended');++ const selected = value ? toOptionValue(value) : SYSTEM_VALUE;+ const options: SelectOptions = [+ {+ label: (+ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ justify={'space-between'}+ style={{ width: '100%' }}+ >+ <span>{systemLabel}</span>+ <span {...stylex.props(styles.hint)}>{getModelName(recommended)}</span>+ </Flexbox>+ ),+ title: systemLabel,+ value: SYSTEM_VALUE,+ },+ ...groups,+ ];++ return (+ <Select+ aria-label={title}+ classNames={{ value: stylex.props(styles.triggerValue).className }}+ disabled={disabled}+ options={options}+ style={{ width: '100%' }}+ value={selected}+ variant={'filled'}+ labelRender={() => {+ const current = value ?? recommended;+ return (+ <ModelLabel+ hint={value ? undefined : systemLabel}+ model={current.model}+ name={getModelName(current)}+ />+ );+ }}+ onChange={(next) => {+ if (typeof next !== 'string' || next === selected) return;+ onChange(next === SYSTEM_VALUE ? undefined : parseValue(next));+ }}+ />+ );+};++export default TierRow;diff --git a/src/features/ServiceModel/ServiceModelForm/index.tsx b/src/features/ServiceModel/ServiceModelForm/index.tsxnew file mode 100644index 00000000000..f2e837b79e3--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/index.tsx@@ -0,0 +1,427 @@+'use client';++import { SERVICE_MODEL_TIER_SLOTS } from '@lobechat/const';+import { Button, Flexbox, Icon, InputNumber, TextArea } from '@lobehub/ui';+import { Form, type FormGroupItem, useForm } from '@lobehub/ui/form';+import * as stylex from '@stylexjs/stylex';+import isEqual from 'fast-deep-equal';+import { ChevronDown, ChevronUp } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useLocation } from 'react-router';++import AsyncError from '@/components/AsyncError';+import AutoSaveHint from '@/components/Editor/AutoSaveHint';+import { RouteLoading } from '@/components/Skeleton/RouteSegment';+import { FORM_STYLE } from '@/const/layoutTokens';+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';+import { usePermission } from '@/hooks/usePermission';+import { useSaveState } from '@/hooks/useSaveState';+import { useUserStore } from '@/store/user';+import {+ PERSONAL_SYSTEM_AGENT_KEYS,+ type ServiceModelTier,+ type SystemAgentItem,+ type UserServiceModelConfigKey,+} from '@/types/user/settings';++import {+ applySlotChoice,+ applyTierChoice,+ canDisableSlot,+ getTierItem,+ type ModelRef,+ resolveFollowModel,+ resolveSlotState,+ restoreAllSlots,+ type SlotChoice,+ type StoredSystemAgent,+} from '../serviceModelState';+import SlotRow, { type RowState } from './SlotRow';+import { PICKER_WIDTH, styles } from './styles';+import TierRow from './TierRow';+import { type ModelKind } from './useModelCatalog';++/** The model new agents start with; it lives in `defaultAgent`, not in `systemAgent`. */+const DEFAULT_AGENT_ROW = 'defaultAgent';++const ADVANCED_ANCHOR = 'service-model-advanced';++/** Onboarding and channel-routing slots are internal and not shown. */+type DisplaySlot = Exclude<+ UserServiceModelConfigKey,+ 'channelRouting' | 'onboardingTaskRecommender' | 'onboardingUnderstanding'+>;++type RowKey = typeof DEFAULT_AGENT_ROW | DisplaySlot;++// lobe-design-ignore DETAIL-NO-EMPTY: the groups and rows are a fixed list; a group left empty (personal rows hidden in a workspace) is filtered out+/** 「高级」 is grouped by what the task is for, not by the model it follows. */+const GROUPS: { key: string; rows: RowKey[] }[] = [+ { key: 'agent', rows: [DEFAULT_AGENT_ROW, 'agentMeta', 'expertise', 'goal'] },+ { key: 'topic', rows: ['topic', 'thread', 'generationTopic', 'topicAutoSummary'] },+ { key: 'content', rows: ['translation', 'historyCompress', 'promptRewrite'] },+ {+ key: 'memory',+ rows: ['memoryAnalysisAgentConfig', 'userMemoryPersonaWriter', 'userMemoryEmbedding'],+ },+ { key: 'suggestion', rows: ['inputCompletion', 'followUpAction'] },+ { key: 'voice', rows: ['asr'] },+];++const TIERS: { key: ServiceModelTier; modelKind: ModelKind }[] = [+ { key: 'main', modelKind: 'chat' },+ { key: 'flash', modelKind: 'chat' },+ { key: 'embedding', modelKind: 'embedding' },+];++const MEMORY_CONTEXT_LIMIT_SLOTS = new Set<RowKey>([+ 'memoryAnalysisAgentConfig',+ 'userMemoryEmbedding',+ 'userMemoryPersonaWriter',+]);++const modelKindOf = (row: RowKey): ModelKind =>+ row === 'userMemoryEmbedding' ? 'embedding' : row === 'asr' ? 'asr' : 'chat';++const PERSONAL_SLOTS = new Set<UserServiceModelConfigKey>(PERSONAL_SYSTEM_AGENT_KEYS);+const NO_SLOTS = new Set<UserServiceModelConfigKey>();++interface ServiceModelFormProps {+ /**+ * Drop the personal chat-assist rows (follow-up, input completion). The+ * workspace surface edits them on its own Chat Preferences tab instead.+ */+ hidePersonalPreferences?: boolean;+}++const ServiceModelForm = ({ hidePersonalPreferences }: ServiceModelFormProps) => {+ const { t } = useTranslation('setting');+ const { allowed: canManage, reason } = usePermission('manage_settings');+ const [storedSystemAgent, storedDefaultAgent, defaults, defaultAgentDefaults] = useUserStore(+ (s) => [+ s.settings.systemAgent as StoredSystemAgent | undefined,+ s.settings.defaultAgent,+ s.defaultSettings.systemAgent,+ s.defaultSettings.defaultAgent?.config,+ ],+ isEqual,+ );+ const [replaceServiceModelSettings, isUserStateInit, isUserStateInitError, refreshUserState] =+ useUserStore((s) => [+ s.replaceServiceModelSettings,+ s.isUserStateInit,+ s.isUserStateInitError,+ s.refreshUserState,+ ]);+ // A settings-search deep link to 「高级」 lands on it opened.+ const { hash } = useLocation();+ const [expanded, setExpanded] = useState(() => hash === `#${ADVANCED_ANCHOR}`);+ const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();+ const form = useForm();++ if (!isUserStateInit) {+ // A failed user-state init must show error + Retry, not a permanent skeleton+ if (isUserStateInitError)+ return (+ <AsyncError+ error={isUserStateInitError}+ variant={'block'}+ onRetry={() => refreshUserState()}+ />+ );+ return <RouteLoading />;+ }++ const skipSlots = hidePersonalPreferences ? PERSONAL_SLOTS : NO_SLOTS;+ const groups = GROUPS.map((group) => ({+ ...group,+ rows: group.rows.filter(+ (row) => row === DEFAULT_AGENT_ROW || !skipSlots.has(row as UserServiceModelConfigKey),+ ),+ })).filter((group) => group.rows.length > 0);+ const slotRows = groups+ .flatMap((group) => group.rows)+ .filter((row): row is DisplaySlot => row !== DEFAULT_AGENT_ROW);+ const rows: RowKey[] = [DEFAULT_AGENT_ROW, ...slotRows];++ const pinnedDefaultAgent: ModelRef | undefined =+ storedDefaultAgent?.config?.model && storedDefaultAgent.config.provider+ ? { model: storedDefaultAgent.config.model, provider: storedDefaultAgent.config.provider }+ : undefined;++ const rowState = (row: RowKey): RowState => {+ if (row === DEFAULT_AGENT_ROW)+ return pinnedDefaultAgent+ ? { kind: 'custom', value: pinnedDefaultAgent }+ : { kind: 'follow' };++ const state = resolveSlotState(storedSystemAgent, defaults, row);+ return state.kind === 'custom' ? state : { kind: state.kind };+ };++ const states = rows.map(rowState);+ const customCount = states.filter((state) => state.kind === 'custom').length;+ const offCount = states.filter((state) => state.kind === 'off').length;++ const write = (columns: Parameters<typeof replaceServiceModelSettings>[0]) =>+ save(() => replaceServiceModelSettings(columns));++ const writeSlot = (row: RowKey, choice: SlotChoice) => {+ if (row !== DEFAULT_AGENT_ROW) {+ write({ systemAgent: applySlotChoice(storedSystemAgent, row, choice, { skipSlots }) });+ return;+ }++ // Following drops the pin, so new agents pick up the system default again.+ const config = { ...storedDefaultAgent?.config };+ delete config.model;+ delete config.provider;+ if (choice.kind === 'custom') Object.assign(config, choice.value);+ write({ defaultAgent: { ...storedDefaultAgent, config } });+ };++ const writeSlotField = (slot: UserServiceModelConfigKey, patch: Partial<SystemAgentItem>) =>+ write({+ systemAgent: {+ ...storedSystemAgent,+ [slot]: { ...(storedSystemAgent?.[slot] as Partial<SystemAgentItem>), ...patch },+ },+ });++ const restoreAll = () => {+ const columns: Parameters<typeof replaceServiceModelSettings>[0] = {+ systemAgent: restoreAllSlots(storedSystemAgent, defaults, slotRows, {+ skipSlots,+ }),+ };+ if (pinnedDefaultAgent) {+ const config = { ...storedDefaultAgent?.config };+ delete config.model;+ delete config.provider;+ columns.defaultAgent = { ...storedDefaultAgent, config };+ }+ write(columns);+ };++ const followLabelOf = (row: RowKey) => {+ if (row === DEFAULT_AGENT_ROW || row === 'asr') return t('serviceModel.systemRecommended');+ const tier = TIERS.find(({ key }) => SERVICE_MODEL_TIER_SLOTS[key].includes(row));+ return tier ? t(`serviceModel.tier.${tier.key}.title`) : t('serviceModel.systemRecommended');+ };++ const followModelOf = (row: RowKey): ModelRef | undefined => {+ if (row !== DEFAULT_AGENT_ROW) return resolveFollowModel(storedSystemAgent, defaults, row);+ return defaultAgentDefaults?.model && defaultAgentDefaults.provider+ ? { model: defaultAgentDefaults.model, provider: defaultAgentDefaults.provider }+ : undefined;+ };++ /** Row-level controls that only exist for some rows (a custom prompt, a context limit). */+ const renderExtra = (row: RowKey, state: RowState) => {+ if (row === 'topicAutoSummary' && state.kind !== 'off') {+ const value = storedSystemAgent?.topicAutoSummary?.customPrompt;+ return (+ <TextArea+ autoSize={{ maxRows: 8, minRows: 3 }}+ defaultValue={value}+ disabled={!canManage}+ placeholder={t('systemAgent.topicAutoSummary.promptPlaceholder')}+ style={{ marginBlockEnd: 8, width: '100%' }}+ onBlur={(event) => {+ const customPrompt = event.currentTarget.value.trim();+ if (customPrompt !== (value ?? ''))+ writeSlotField('topicAutoSummary', { customPrompt });+ }}+ />+ );+ }++ // A context limit only matters for a model the user picked; the system+ // default brings its own. Keep showing a limit that is already set.+ const contextLimit = (+ storedSystemAgent?.[row as UserServiceModelConfigKey] as Partial<SystemAgentItem> | undefined+ )?.contextLimit;+ if (MEMORY_CONTEXT_LIMIT_SLOTS.has(row) && (state.kind === 'custom' || contextLimit)) {+ return (+ <Flexbox+ horizontal+ align={'center'}+ gap={24}+ justify={'space-between'}+ style={{ minHeight: 40 }}+ >+ <span {...stylex.props(styles.taskNameOff)}>+ {t('serviceModel.contextLimit.placeholder')}+ </span>+ <InputNumber+ aria-label={t('serviceModel.contextLimit.placeholder')}+ disabled={!canManage}+ min={1}+ style={{ flex: 'none', width: PICKER_WIDTH }}+ value={contextLimit}+ variant={'filled'}+ onChange={(next) =>+ writeSlotField(row as UserServiceModelConfigKey, {+ contextLimit: typeof next === 'number' ? next : undefined,+ })+ }+ />+ </Flexbox>+ );+ }+ };++ const summary = [+ t('serviceModel.advanced.summary.total', { count: states.length }),+ customCount > 0 && t('serviceModel.advanced.summary.custom', { count: customCount }),+ offCount > 0 && t('serviceModel.advanced.summary.off', { count: offCount }),+ t('serviceModel.advanced.summary.rest'),+ ]+ .filter(Boolean)+ .join(t('serviceModel.advanced.summary.separator'));++ // One settings group per page. The tiers are form rows; 「高级」 stays a+ // lighter sub-section inside the same card — small type, compact 40px rows —+ // so it reads as a detail of 服务模型 rather than a second group.+ const group: FormGroupItem = {+ children: (+ <>+ {TIERS.map(({ key, modelKind }, index) => {+ const title = t(`serviceModel.tier.${key}.title`);+ return (+ <Form.Field+ desc={t(`serviceModel.tier.${key}.desc`)}+ divider={index > 0}+ key={key}+ label={+ <SettingsSearchAnchor+ id={index === 0 ? 'service-model-assignments' : `service-model-${key}`}+ >+ {title}+ </SettingsSearchAnchor>+ }+ >+ <TierRow+ disabled={!canManage}+ modelKind={modelKind}+ recommended={resolveFollowModel({}, defaults, SERVICE_MODEL_TIER_SLOTS[key][0])!}+ title={title}+ value={getTierItem(storedSystemAgent, key)}+ onChange={(value) =>+ write({+ systemAgent: applyTierChoice(storedSystemAgent, key, value, { skipSlots }),+ })+ }+ />+ </Form.Field>+ );+ })}++ <Form.Divider />++ <Flexbox style={{ paddingBlock: 16 }}>+ <Flexbox horizontal align={'center'} gap={24} justify={'space-between'}>+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ <SettingsSearchAnchor id={ADVANCED_ANCHOR}>+ <span {...stylex.props(styles.sectionTitle)}>+ {t('serviceModel.advanced.title')}+ </span>+ </SettingsSearchAnchor>+ <span {...stylex.props(styles.sectionDesc)}>{summary}</span>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4} style={{ flex: 'none' }}>+ {customCount > 0 && (+ <Button disabled={!canManage} size={'small'} type={'text'} onClick={restoreAll}>+ {t('serviceModel.advanced.restoreAll')}+ </Button>+ )}+ <Button+ aria-expanded={expanded}+ icon={<Icon icon={expanded ? ChevronUp : ChevronDown} />}+ iconPosition={'end'}+ size={'small'}+ type={'text'}+ onClick={() => setExpanded(!expanded)}+ >+ {expanded ? t('serviceModel.advanced.collapse') : t('serviceModel.advanced.expand')}+ </Button>+ </Flexbox>+ </Flexbox>++ {expanded && (+ <Flexbox gap={20} style={{ paddingBlockStart: 16 }}>+ {groups.map((purpose) => (+ <Flexbox gap={4} key={purpose.key}>+ <span {...stylex.props(styles.groupTitle)}>+ {t(`serviceModel.group.${purpose.key}` as 'serviceModel.group.agent')}+ </span>+ <Flexbox>+ {purpose.rows.map((row) => {+ const state = rowState(row);+ const title =+ row === DEFAULT_AGENT_ROW+ ? t('defaultAgent.title')+ : t(`systemAgent.${row}.title`);++ return (+ <Flexbox key={row}>+ <Flexbox+ horizontal+ align={'center'}+ gap={24}+ justify={'space-between'}+ {...stylex.props(styles.row)}+ >+ <span+ {...stylex.props(+ state.kind === 'off' ? styles.taskNameOff : styles.taskName,+ )}+ >+ {title}+ </span>+ <SlotRow+ canDisable={row !== DEFAULT_AGENT_ROW && canDisableSlot(row)}+ disabled={!canManage}+ followLabel={followLabelOf(row)}+ followModel={followModelOf(row)}+ modelKind={modelKindOf(row)}+ state={state}+ title={title}+ onChange={(choice) => writeSlot(row, choice)}+ />+ </Flexbox>+ {renderExtra(row, state)}+ </Flexbox>+ );+ })}+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+ )}+ </Flexbox>+ </>+ ),+ collapsible: false,+ desc: `${t('serviceModel.desc')}${!canManage && reason ? ` ${reason}` : ''}`,+ extra:+ saveStatus === 'idle' ? undefined : (+ <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />+ ),+ title: t('serviceModel.title'),+ };++ return (+ <Form+ collapsible={false}+ form={form}+ items={[group]}+ itemsType={'group'}+ variant={'filled'}+ {...FORM_STYLE}+ />+ );+};++export default ServiceModelForm;diff --git a/src/features/ServiceModel/ServiceModelForm/styles.ts b/src/features/ServiceModel/ServiceModelForm/styles.tsnew file mode 100644index 00000000000..7d65580a765--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/styles.ts@@ -0,0 +1,87 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++/** The advanced rows' picker column; every task picker ends on the same right edge. */+export const PICKER_WIDTH = 280;++export const styles = stylex.create({+ /** 「高级」 and the summary under it: a section inside the card, not a group title. */+ sectionTitle: {+ color: cssVar.colorText,+ fontSize: cssVar.fontSize,+ fontWeight: 500,+ lineHeight: 1.5,+ },+ sectionDesc: {+ color: cssVar.colorTextTertiary,+ fontSize: cssVar.fontSizeSM,+ lineHeight: 1.5,+ },+ /** Purpose headings inside 高级: one step quieter than a task name. */+ groupTitle: {+ color: cssVar.colorTextSecondary,+ fontSize: cssVar.fontSizeSM,+ fontWeight: 500,+ lineHeight: 1.5,+ },+ /** Compact rows: the picker is 32px, so 40 leaves 4px above and below. */+ row: {+ minHeight: 40,+ },+ taskName: {+ color: cssVar.colorText,+ fontSize: cssVar.fontSize,+ lineHeight: 1.5,+ },+ /** An off task's name drops to secondary, matching its gray value. */+ taskNameOff: {+ color: cssVar.colorTextSecondary,+ fontSize: cssVar.fontSize,+ lineHeight: 1.5,+ },+ /** The model a follow item currently means, next to it in the menu. */+ hint: {+ color: cssVar.colorTextTertiary,+ flexShrink: 0,+ fontSize: cssVar.fontSizeSM,+ },+ /** 「不启用」 sits under a divider; Select options have no divider item, so the option draws it. */+ offOption: {+ 'marginBlockStart': 9,+ 'overflow': 'visible',+ 'position': 'relative',+ '::before': {+ backgroundColor: cssVar.colorBorderSecondary,+ content: '""',+ height: 1,+ insetBlockStart: -5,+ insetInlineEnd: 0,+ insetInlineStart: 0,+ position: 'absolute',+ },+ },+ /**+ * The picker wraps the rendered value in a content-sized span; as a grid item+ * that span stretches over the trigger, so values and hints can align to its+ * right edge.+ */+ triggerValue: {+ display: 'grid',+ flex: '1',+ gridTemplateColumns: 'minmax(0, 1fr)',+ minWidth: 0,+ },+ /** A follow / off value: gray, no icon, right-aligned against the arrow. */+ valueMuted: {+ color: cssVar.colorTextTertiary,+ display: 'block',+ fontSize: cssVar.fontSize,+ textAlign: 'end',+ },+ /** A pinned model keeps the same right edge as the muted values. */+ valueEnd: {+ display: 'flex',+ justifyContent: 'flex-end',+ minWidth: 0,+ },+});diff --git a/src/features/ServiceModel/ServiceModelForm/useModelCatalog.tsx b/src/features/ServiceModel/ServiceModelForm/useModelCatalog.tsxnew file mode 100644index 00000000000..1c63f718e09--- /dev/null+++ b/src/features/ServiceModel/ServiceModelForm/useModelCatalog.tsx@@ -0,0 +1,70 @@+import { type SelectOptions } from '@lobehub/ui';+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';++import { type ModelRef } from '../serviceModelState';+import ModelLabel from './ModelLabel';++export type ModelKind = 'asr' | 'chat' | 'embedding';++// lobe-design-ignore DETAIL-NO-EMPTY: with no enabled model the picker still offers its follow item, so the list is never empty+export const toOptionValue = ({ model, provider }: ModelRef) => `${provider}/${model}`;++/**+ * The enabled models of one kind as Select option groups, plus a resolver from+ * `{ provider, model }` to the option value it was rendered with.+ */+export const useModelOptions = (kind: ModelKind) => {+ const { t } = useTranslation('setting');+ const providers = useAiInfraStore((s) =>+ kind === 'embedding'+ ? aiProviderSelectors.enabledEmbeddingModelList(s)+ : kind === 'asr'+ ? aiProviderSelectors.enabledAsrModelList(s)+ : s.enabledChatModelList || [],+ );++ const groups = useMemo<SelectOptions>(() => {+ const withModels = providers.filter((provider) => provider.children.length > 0);++ return withModels.map((provider) => ({+ // With one provider the group is just 「指定模型」; otherwise the provider+ // name tells apart the same model served by different providers.+ label: withModels.length === 1 ? t('serviceModel.customModel') : provider.name,+ options: provider.children.map((model) => ({+ label: <ModelLabel model={model.id} name={model.displayName || model.id} />,+ title: model.displayName || model.id,+ value: toOptionValue({ model: model.id, provider: provider.id }),+ })),+ }));+ }, [providers, t]);++ /** Option value → model ref; the model id may itself contain slashes. */+ const parseValue = useCallback((value: string): ModelRef => {+ const [provider, ...rest] = value.split('/');+ return { model: rest.join('/'), provider };+ }, []);++ return { groups, parseValue };+};++/** Display name of any model, enabled or not, falling back to its id. */+export const useModelName = () => {+ const chat = useAiInfraStore((s) => s.enabledChatModelList);+ const embedding = useAiInfraStore(aiProviderSelectors.enabledEmbeddingModelList);+ const asr = useAiInfraStore(aiProviderSelectors.enabledAsrModelList);+ const builtin = useAiInfraStore((s) => s.builtinAiModelList);++ const names = useMemo(() => {+ const map = new Map<string, string>();+ for (const model of builtin) if (model.displayName) map.set(model.id, model.displayName);+ for (const provider of [...(chat || []), ...embedding, ...asr])+ for (const model of provider.children)+ if (model.displayName) map.set(model.id, model.displayName);+ return map;+ }, [asr, builtin, chat, embedding]);++ return useCallback((ref?: ModelRef) => (ref ? names.get(ref.model) || ref.model : ''), [names]);+};diff --git a/src/features/ServiceModel/index.ts b/src/features/ServiceModel/index.tsindex 55f4a492524..ed929fafec7 100644--- a/src/features/ServiceModel/index.ts+++ b/src/features/ServiceModel/index.ts@@ -1,2 +1,2 @@export { default as ChatAssistForm } from './ChatAssistForm';-export { default as ModelAssignmentsForm } from './ModelAssignmentsForm';+export { default as ServiceModelForm } from './ServiceModelForm';diff --git a/src/features/ServiceModel/serviceModelState.test.ts b/src/features/ServiceModel/serviceModelState.test.tsnew file mode 100644index 00000000000..caa7759511f--- /dev/null+++ b/src/features/ServiceModel/serviceModelState.test.ts@@ -0,0 +1,171 @@+import { DEFAULT_SYSTEM_AGENT_CONFIG } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import {+ applySlotChoice,+ applyTierChoice,+ canDisableSlot,+ resolveSlotState,+ restoreAllSlots,+ type StoredSystemAgent,+} from './serviceModelState';++const defaults = DEFAULT_SYSTEM_AGENT_CONFIG;+const FLASH = { model: 'flash-x', provider: 'acme' };+const OTHER = { model: 'other-y', provider: 'acme' };++describe('resolveSlotState', () => {+ it('follows the system recommendation when nothing is stored', () => {+ expect(resolveSlotState({}, defaults, 'topic')).toEqual({+ kind: 'follow',+ tier: 'flash',+ value: { model: defaults.topic.model, provider: defaults.topic.provider },+ });+ });++ it('reads the system defaults of opt-in tasks as off', () => {+ expect(resolveSlotState({}, defaults, 'topicAutoSummary').kind).toBe('off');+ expect(resolveSlotState({}, defaults, 'inputCompletion').kind).toBe('off');+ expect(resolveSlotState({}, defaults, 'followUpAction').kind).toBe('off');+ expect(resolveSlotState({}, defaults, 'promptRewrite').kind).toBe('follow');+ });++ it('reads a slot pinned to its tier model as following', () => {+ const stored: StoredSystemAgent = { tiers: { flash: FLASH }, topic: FLASH };+ expect(resolveSlotState(stored, defaults, 'topic')).toEqual({+ kind: 'follow',+ tier: 'flash',+ value: FLASH,+ });+ });++ it('reads any other pinned model as custom', () => {+ const stored: StoredSystemAgent = { tiers: { flash: FLASH }, topic: OTHER };+ expect(resolveSlotState(stored, defaults, 'topic')).toEqual({ kind: 'custom', value: OTHER });+ });++ it('treats an empty speech-to-text model as off', () => {+ expect(resolveSlotState({ asr: { model: '', provider: '' } }, defaults, 'asr').kind).toBe(+ 'off',+ );+ });+});++describe('applyTierChoice', () => {+ it('writes the tier model into following slots and keeps custom ones', () => {+ const next = applyTierChoice({ translation: OTHER }, 'flash', FLASH);++ expect(next.tiers).toEqual({ flash: FLASH });+ expect(next.topic).toEqual(FLASH);+ expect(next.thread).toEqual(FLASH);+ expect(next.translation).toEqual(OTHER);+ // other tiers are untouched+ expect(next.agentMeta).toBeUndefined();+ });++ it('moves slots that followed the old tier value to the new one', () => {+ const before = applyTierChoice({}, 'flash', FLASH);+ const next = applyTierChoice(before, 'flash', OTHER);++ expect(next.topic).toEqual(OTHER);+ expect(resolveSlotState(next, defaults, 'topic').kind).toBe('follow');+ });++ it('drops the pins when the tier goes back to the system recommendation', () => {+ const before = applyTierChoice({ translation: OTHER }, 'flash', FLASH);+ const next = applyTierChoice(before, 'flash', undefined);++ expect(next.tiers).toBeUndefined();+ expect(next.topic).toBeUndefined();+ expect(next.translation).toEqual(OTHER);+ });++ it('keeps the enabled flag of a disabled task while updating its model', () => {+ const next = applyTierChoice({}, 'flash', FLASH);++ expect(next.inputCompletion).toEqual({ ...FLASH });+ expect(resolveSlotState(next, defaults, 'inputCompletion').kind).toBe('off');+ });++ it('leaves skipped slots alone', () => {+ const next = applyTierChoice({}, 'flash', FLASH, {+ skipSlots: new Set(['followUpAction', 'inputCompletion']),+ });++ expect(next.followUpAction).toBeUndefined();+ expect(next.inputCompletion).toBeUndefined();+ });+});++describe('applySlotChoice', () => {+ it('pins a custom model', () => {+ const next = applySlotChoice({}, 'translation', { kind: 'custom', value: OTHER });+ expect(resolveSlotState(next, defaults, 'translation')).toEqual({+ kind: 'custom',+ value: OTHER,+ });+ });++ it('restores a custom slot to the system recommendation by removing the pin', () => {+ const next = applySlotChoice({ translation: OTHER }, 'translation', { kind: 'follow' });+ expect(next.translation).toBeUndefined();+ });++ it('restores a custom slot to its tier model when the tier is set', () => {+ const stored = applyTierChoice({ translation: OTHER }, 'flash', FLASH);+ const next = applySlotChoice(stored, 'translation', { kind: 'follow' });++ expect(next.translation).toEqual(FLASH);+ expect(resolveSlotState(next, defaults, 'translation').kind).toBe('follow');+ });++ it('turns an opt-in task on when its follow item is picked, and off again', () => {+ const on = applySlotChoice({}, 'topicAutoSummary', { kind: 'follow' });+ expect(on.topicAutoSummary).toEqual({ enabled: true });+ expect(resolveSlotState(on, defaults, 'topicAutoSummary').kind).toBe('follow');++ const off = applySlotChoice(on, 'topicAutoSummary', { kind: 'off' });+ expect(resolveSlotState(off, defaults, 'topicAutoSummary').kind).toBe('off');+ });++ it('turns speech-to-text off with an empty model and back on by following', () => {+ const off = applySlotChoice({}, 'asr', { kind: 'off' });+ expect(off.asr).toEqual({ model: '', provider: '' });++ const on = applySlotChoice(off, 'asr', { kind: 'follow' });+ expect(on.asr).toBeUndefined();+ });++ it('keeps other stored fields of a slot', () => {+ const next = applySlotChoice(+ { userMemoryEmbedding: { ...OTHER, contextLimit: 512 } },+ 'userMemoryEmbedding',+ { kind: 'follow' },+ );+ expect(next.userMemoryEmbedding).toEqual({ contextLimit: 512 });+ });+});++describe('restoreAllSlots', () => {+ it('unpins custom slots and keeps disabled tasks disabled', () => {+ const stored: StoredSystemAgent = {+ followUpAction: { enabled: false },+ tiers: { flash: FLASH },+ topic: FLASH,+ translation: OTHER,+ };+ const next = restoreAllSlots(stored, defaults, ['translation', 'topic', 'followUpAction']);++ expect(next.translation).toEqual(FLASH);+ expect(resolveSlotState(next, defaults, 'followUpAction').kind).toBe('off');+ });+});++describe('canDisableSlot', () => {+ it('only offers 不启用 where the runtime honours it', () => {+ expect(canDisableSlot('topicAutoSummary')).toBe(true);+ expect(canDisableSlot('asr')).toBe(true);+ expect(canDisableSlot('userMemoryEmbedding')).toBe(false);+ expect(canDisableSlot('topic')).toBe(false);+ });+});diff --git a/src/features/ServiceModel/serviceModelState.ts b/src/features/ServiceModel/serviceModelState.tsnew file mode 100644index 00000000000..2e617dd41b4--- /dev/null+++ b/src/features/ServiceModel/serviceModelState.ts@@ -0,0 +1,209 @@+import { SERVICE_MODEL_TIER_SLOTS } from '@lobechat/const';+import type { PartialDeep } from 'type-fest';++import type {+ ServiceModelTier,+ ServiceModelTierItem,+ SystemAgentItem,+ UserServiceModelConfig,+ UserServiceModelConfigKey,+ UserSettings,+} from '@/types/user/settings';++/** The raw `systemAgent` column as stored for the user (only what they changed). */+export type StoredSystemAgent = PartialDeep<UserSettings['systemAgent']>;++export interface ModelRef {+ model: string;+ provider: string;+}++/**+ * Slots whose runtime honours `enabled: false`, so 「不启用」 really turns the+ * feature off. Other slots have no off switch at runtime and get no such option.+ */+const ENABLED_FLAG_SLOTS = new Set<UserServiceModelConfigKey>([+ 'followUpAction',+ 'inputCompletion',+ 'promptRewrite',+ 'topicAutoSummary',+]);++/** Speech-to-text treats an empty model as unconfigured, which hides voice input. */+const EMPTY_MODEL_OFF_SLOTS = new Set<UserServiceModelConfigKey>(['asr']);++export const canDisableSlot = (slot: UserServiceModelConfigKey) =>+ ENABLED_FLAG_SLOTS.has(slot) || EMPTY_MODEL_OFF_SLOTS.has(slot);++export const tierOfSlot = (slot: UserServiceModelConfigKey): ServiceModelTier | undefined =>+ (Object.keys(SERVICE_MODEL_TIER_SLOTS) as ServiceModelTier[]).find((tier) =>+ SERVICE_MODEL_TIER_SLOTS[tier].includes(slot),+ );++export type SlotState =+ | { kind: 'custom'; value: ModelRef }+ /** `value` is the model the slot actually runs. */+ | { kind: 'follow'; tier?: ServiceModelTier; value?: ModelRef }+ | { kind: 'off'; tier?: ServiceModelTier };++export type SlotChoice = { kind: 'follow' } | { kind: 'off' } | { kind: 'custom'; value: ModelRef };++const toRef = (item?: Partial<SystemAgentItem> | ServiceModelTierItem): ModelRef | undefined =>+ item?.model && item.provider ? { model: item.model, provider: item.provider } : undefined;++export const isSameModel = (a?: ModelRef, b?: ModelRef) =>+ !!a && !!b && a.model === b.model && a.provider === b.provider;++/** A slot pinned to exactly its tier's model is following that tier (the tier wrote it there). */+const isFollowing = (pinned: ModelRef | undefined, tierItem: ModelRef | undefined) =>+ !pinned || isSameModel(pinned, tierItem);++export const getTierItem = (stored: StoredSystemAgent | undefined, tier: ServiceModelTier) =>+ toRef(stored?.tiers?.[tier]);++/** The model a slot runs while it follows: its tier's pick, else the system recommendation. */+export const resolveFollowModel = (+ stored: StoredSystemAgent | undefined,+ defaults: UserServiceModelConfig,+ slot: UserServiceModelConfigKey,+): ModelRef | undefined => {+ const tier = tierOfSlot(slot);+ return (tier ? getTierItem(stored, tier) : undefined) ?? toRef(defaults[slot]);+};++/**+ * @param defaults the system-recommended config (code defaults plus the+ * deployment's `SYSTEM_AGENT` overrides), i.e. `defaultSettings.systemAgent`+ */+export const resolveSlotState = (+ stored: StoredSystemAgent | undefined,+ defaults: UserServiceModelConfig,+ slot: UserServiceModelConfigKey,+): SlotState => {+ const storedItem = stored?.[slot] as Partial<SystemAgentItem> | undefined;+ const tier = tierOfSlot(slot);++ if (EMPTY_MODEL_OFF_SLOTS.has(slot)) {+ const model = storedItem?.model ?? defaults[slot].model;+ const provider = storedItem?.provider ?? defaults[slot].provider;+ if (!model || !provider) return { kind: 'off', tier };+ }++ if (ENABLED_FLAG_SLOTS.has(slot) && (storedItem?.enabled ?? defaults[slot].enabled) === false)+ return { kind: 'off', tier };++ const pinned = toRef(storedItem);+ const tierItem = tier ? getTierItem(stored, tier) : undefined;++ if (isFollowing(pinned, tierItem))+ return { kind: 'follow', tier, value: resolveFollowModel(stored, defaults, slot) };++ return { kind: 'custom', value: pinned! };+};++const cloneStored = (stored: StoredSystemAgent | undefined): Record<string, any> =>+ structuredClone((stored ?? {}) as Record<string, any>);++const clearPin = (next: Record<string, any>, slot: string) => {+ const item = next[slot];+ if (!item || typeof item !== 'object') return;+ delete item.model;+ delete item.provider;+ if (Object.keys(item).length === 0) delete next[slot];+};++/**+ * Write each set tier's model into the slots that follow it. Runtimes read a+ * slot's own model and know nothing about tiers, so following must be stored.+ */+const syncTierPins = (+ next: Record<string, any>,+ skipSlots: ReadonlySet<UserServiceModelConfigKey>,+) => {+ for (const tier of Object.keys(SERVICE_MODEL_TIER_SLOTS) as ServiceModelTier[]) {+ const tierItem = toRef(next.tiers?.[tier]);+ if (!tierItem) continue;++ for (const slot of SERVICE_MODEL_TIER_SLOTS[tier]) {+ if (skipSlots.has(slot) || toRef(next[slot])) continue;+ next[slot] = { ...next[slot], ...tierItem };+ }+ }+ return next as StoredSystemAgent;+};++export interface ApplyOptions {+ /** Slots this surface does not manage (e.g. personal chat-assist rows inside a workspace). */+ skipSlots?: ReadonlySet<UserServiceModelConfigKey>;+}++const NO_SKIP: ReadonlySet<UserServiceModelConfigKey> = new Set();++export const applyTierChoice = (+ stored: StoredSystemAgent | undefined,+ tier: ServiceModelTier,+ value: ModelRef | undefined,+ { skipSlots = NO_SKIP }: ApplyOptions = {},+): StoredSystemAgent => {+ const next = cloneStored(stored);+ const prevTierItem = getTierItem(stored, tier);++ // Slots that followed the old tier value follow the new one; pinned slots stay.+ for (const slot of SERVICE_MODEL_TIER_SLOTS[tier]) {+ if (skipSlots.has(slot)) continue;+ if (isFollowing(toRef(next[slot]), prevTierItem)) clearPin(next, slot);+ }++ const tiers = { ...next.tiers };+ if (value) tiers[tier] = { model: value.model, provider: value.provider };+ else delete tiers[tier];+ if (Object.keys(tiers).length > 0) next.tiers = tiers;+ else delete next.tiers;++ return syncTierPins(next, skipSlots);+};++export const applySlotChoice = (+ stored: StoredSystemAgent | undefined,+ slot: UserServiceModelConfigKey,+ choice: SlotChoice,+ { skipSlots = NO_SKIP }: ApplyOptions = {},+): StoredSystemAgent => {+ const next = cloneStored(stored);+ const item: Record<string, unknown> = { ...next[slot] };++ if (choice.kind === 'off') {+ if (EMPTY_MODEL_OFF_SLOTS.has(slot)) Object.assign(item, { model: '', provider: '' });+ else item.enabled = false;+ next[slot] = item;+ return syncTierPins(next, skipSlots);+ }++ if (choice.kind === 'custom') Object.assign(item, choice.value);+ else {+ delete item.model;+ delete item.provider;+ }+ // Picking a model (or the follow item) is how a disabled task comes back on.+ if (ENABLED_FLAG_SLOTS.has(slot)) item.enabled = true;++ if (Object.keys(item).length > 0) next[slot] = item;+ else delete next[slot];++ return syncTierPins(next, skipSlots);+};++/** 「全部恢复」: every pinned slot follows again; disabled tasks stay disabled. */+export const restoreAllSlots = (+ stored: StoredSystemAgent | undefined,+ defaults: UserServiceModelConfig,+ slots: UserServiceModelConfigKey[],+ options: ApplyOptions = {},+): StoredSystemAgent => {+ let next = stored;+ for (const slot of slots) {+ if (resolveSlotState(next, defaults, slot).kind === 'custom')+ next = applySlotChoice(next, slot, { kind: 'follow' }, options);+ }+ return next ?? {};+};diff --git a/src/features/Settings/service-model/index.tsx b/src/features/Settings/service-model/index.tsxindex a1a8b2ddbd2..c9450db342f 100644--- a/src/features/Settings/service-model/index.tsx+++ b/src/features/Settings/service-model/index.tsx@@ -2,7 +2,7 @@import { useTranslation } from 'react-i18next';-import { ModelAssignmentsForm } from '@/features/ServiceModel';+import { ServiceModelForm } from '@/features/ServiceModel';import SettingHeader from '@/features/Settings/features/SettingHeader';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';@@ -19,7 +19,7 @@ const Page = ({ hidePersonalPreferences, showSettingHeader = true }: PageProps)return (<>{showSettingHeader && <SettingHeader title={t('tab.serviceModel')} />}- <ModelAssignmentsForm hidePersonalPreferences={hidePersonalPreferences} />+ <ServiceModelForm hidePersonalPreferences={hidePersonalPreferences} />{showAiImage && <Image />}</>);diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex 74d2d52cbeb..b3ad3b9e7db 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -468,24 +468,30 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [// Service Model{anchor: 'service-model-assignments',- keywords: ['model assignment', 'topic naming', 'translation', 'default model'],- labelKey: 'serviceModel.modelAssignments.title',+ descKey: 'serviceModel.desc',+ keywords: ['main model', 'flash model', 'embedding', 'default model', 'system recommended'],+ labelKey: 'serviceModel.tier.main.title',tab: SettingsTabs.ServiceModel,},{- anchor: 'service-model-memory',- keywords: ['memory', 'embedding', 'vector'],- labelKey: 'serviceModel.memoryModels.title',- tab: SettingsTabs.ServiceModel,- },- {- anchor: 'service-model-optional-features',- keywords: ['follow up', 'input completion', 'prompt rewrite', 'suggestion'],- labelKey: 'serviceModel.optionalFeatures.title',+ // Follow-up / input completion stay out of the keywords: inside a workspace+ // they live on Chat Preferences, not here.+ anchor: 'service-model-advanced',+ keywords: [+ 'model assignment',+ 'topic naming',+ 'translation',+ 'memory',+ 'prompt rewrite',+ 'history compress',+ 'voice',+ 'transcription',+ ],+ labelKey: 'serviceModel.advanced.title',tab: SettingsTabs.ServiceModel,},// Chat Preferences (workspace only — the personal sidebar keeps these rows in- // Service Model › Optional Features)+ // Service Model › Advanced){anchor: 'chat-preference-followUpAction',descKey: 'systemAgent.followUpAction.modelDesc',diff --git a/src/features/WorkspaceSetting/hooks/useSettingsSearchScope.test.ts b/src/features/WorkspaceSetting/hooks/useSettingsSearchScope.test.tsindex 6ee8e04da63..62343e1507f 100644--- a/src/features/WorkspaceSetting/hooks/useSettingsSearchScope.test.ts+++ b/src/features/WorkspaceSetting/hooks/useSettingsSearchScope.test.ts@@ -87,7 +87,7 @@ describe('workspace settings search scope', () => {it('keeps admin-only tabs searchable for admins', () => {const urls = search('prompt rewrite', adminGroups).map((result) => result.url);- expect(urls).toContain('/acme/settings/service-model#service-model-optional-features');+ expect(urls).toContain('/acme/settings/service-model#service-model-advanced');expect(search('openai', adminGroups).map((result) => result.url)).toContain('/acme/settings/provider/openai',);diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.tsindex 5434fc3effe..2fbdb00e9d4 100644--- a/src/store/user/slices/settings/action.ts+++ b/src/store/user/slices/settings/action.ts@@ -45,6 +45,8 @@ export class UserSettingsActionImpl {* requests could commit out of order and leave an older list in the DB.*/#toolChannelsWrite: Promise<unknown> = Promise.resolve();+ /** Tail of the in-flight `replaceServiceModelSettings` writes, kept in call order. */+ #serviceModelWrite: Promise<unknown> = Promise.resolve();/** Latest queued write per personal system-agent entry; see updatePersonalSystemAgent. */readonly #personalSystemAgentWrites = new Map<PersonalSystemAgentKey, Promise<unknown>>();@@ -107,6 +109,43 @@ export class UserSettingsActionImpl {return newSignal;};+ /**+ * Replace the Service Model columns with exactly the given stored values.+ * Unlike `setSettings`, which can only merge, this can drop keys: removing a+ * slot's model is how a slot goes back to following its tier or the system+ * recommendation. The server replaces these jsonb columns wholesale.+ */+ replaceServiceModelSettings = async (+ columns: Pick<PartialDeep<UserSettings>, 'defaultAgent' | 'systemAgent'>,+ ): Promise<void> => {+ this.#set(+ { settings: { ...this.#get().settings, ...columns } },+ false,+ 'optimistic_replaceServiceModelSettings',+ );++ // A failed earlier write must not block later ones; its caller still+ // receives the rejection through its own `write` promise.+ const write = this.#serviceModelWrite+ .catch(() => {})+ .then(() => userService.updateUserSettings(columns));+ this.#serviceModelWrite = write;++ try {+ await write;+ } catch (error) {+ // Drop the unsaved optimistic value; the caller keeps the rejection for retry.+ await this.#get()+ .refreshUserState()+ .catch(() => {});+ throw error;+ }+ for (const key of Object.keys(columns)) this.#pendingSettingKeys.delete(key);+ // Only the latest write refreshes: an intermediate refresh would pull a+ // value that a queued write is about to replace.+ if (this.#serviceModelWrite === write) await this.#get().refreshUserState();+ };+resetSettings = async (): Promise<void> => {await userService.resetUserSettings();await this.#get().refreshUserState();diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snapindex 45f428eb864..a12bc2a650b 100644--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap@@ -61,8 +61,8 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG},"enableAutoReply": true,"expertise": {- "model": "gpt-5.6-luna",- "provider": "openai",+ "model": "deepseek-v4-flash",+ "provider": "deepseek",},"followUpAction": {"enabled": false,@@ -74,13 +74,13 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG"provider": "openai",},"goal": {- "model": "gpt-5.6-luna",- "provider": "openai",- },- "historyCompress": {"model": "deepseek-v4-flash","provider": "deepseek",},+ "historyCompress": {+ "model": "gpt-5.6-luna",+ "provider": "openai",+ },"inputCompletion": {"enabled": false,"model": "gpt-5.6-luna",@@ -105,8 +105,8 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG},"replyMessage": "Custom auto reply","thread": {- "model": "deepseek-v4-flash",- "provider": "deepseek",+ "model": "gpt-5.6-luna",+ "provider": "openai",},"topic": {"model": "gpt-5.6-luna",