Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(models): add system admin model catalog console (#3662)
lyingbug967ed097062c
diff --git a/cmd/server/main.go b/cmd/server/main.goindex 9f008d682..021a8bd25 100644--- a/cmd/server/main.go+++ b/cmd/server/main.go@@ -32,6 +32,7 @@ import ("github.com/gin-gonic/gin"+ "github.com/Tencent/WeKnora/internal/application/service""github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/container""github.com/Tencent/WeKnora/internal/logger"@@ -67,6 +68,7 @@ func main() {router *gin.Engine,resourceCleaner interfaces.ResourceCleaner,systemSettingSvc interfaces.SystemSettingService,+ modelCatalogSvc *service.ModelCatalogService,) error {// Create HTTP serverserver := &http.Server{@@ -80,6 +82,7 @@ func main() {}ctx, done := context.WithCancel(context.Background())+ modelCatalogSvc.Start(ctx)// Start the system_settings pubsub subscriber. Runs in its own// goroutine and exits when ctx is cancelled at shutdown. Best-diff --git a/frontend/src/api/system/modelCatalog.ts b/frontend/src/api/system/modelCatalog.tsnew file mode 100644index 000000000..733bade27--- /dev/null+++ b/frontend/src/api/system/modelCatalog.ts@@ -0,0 +1,44 @@+import { get, post, put } from '@/utils/request'++export interface CatalogModel {+ id: string+ type?: string+ match?: string+ name?: string+ context_window?: number+ max_output_tokens?: number+ reasoning?: boolean+ deprecated?: boolean+ [key: string]: unknown+}+export interface CatalogProvider {+ id: string+ name: string+ api: string+ model_types: string[]+ settings?: Record<string, unknown>+ models: CatalogModel[] | null+ // Levels each chat model offers once thinking is on, resolved server-side.+ model_thinking_levels?: Record<string, string[]>+ vendor_thinking_levels?: string[]+}+export interface CatalogOverlay { providers: Record<string, Record<string, any>> }+export interface CatalogState {+ version: number+ baseline: string+ overlay: CatalogOverlay+ history: Array<{ version: number; overlay: CatalogOverlay; updated_by: string; updated_at: string }>+ builtin: CatalogProvider[]+ deployment: CatalogProvider[]+ effective: CatalogProvider[]+ deployment_error?: string+ sync_error?: string+ applied_version: number+}+// A check returns only the candidate; history and the lower layers are omitted.+export type CatalogPreview = Omit<CatalogState, 'history' | 'builtin' | 'deployment'>+export interface CatalogUpdate { version: number; baseline: string; overlay: CatalogOverlay }+const root = '/api/v1/system/admin/model-catalog'+export const getModelCatalog = () => get(root) as unknown as Promise<CatalogState>+export const previewModelCatalog = (request: CatalogUpdate) => post(`${root}/preview`, request) as unknown as Promise<CatalogPreview>+export const publishModelCatalog = (request: CatalogUpdate) => put(root, request) as unknown as Promise<CatalogState>diff --git a/frontend/src/components/ModelEditorDialog.vue b/frontend/src/components/ModelEditorDialog.vueindex e86e6747c..8992c1549 100644--- a/frontend/src/components/ModelEditorDialog.vue+++ b/frontend/src/components/ModelEditorDialog.vue@@ -753,9 +753,9 @@ const modelTypeChoices = computed(() => ([// 厂商列表完全来自后端目录(store 按模型类型缓存);前端不再维护任何厂商表。const loadingProviders = computed(() => providersStore.isLoading(activeModelType.value))-const loadProviders = async () => {+const loadProviders = async (force = false) => {try {- await providersStore.ensureLoaded(activeModelType.value)+ await providersStore.ensureLoaded(activeModelType.value, force)} catch (error) {console.error('Failed to load providers from API', error)}@@ -1459,8 +1459,10 @@ watch(() => props.visible, (val) => {// 检查Ollama服务状态checkOllamaServiceStatus()- // 从 API 加载 Model Provider 列表(编辑已有行时顺便补齐额外字段默认值)- loadProviders().then(() => {+ // 从 API 加载 Model Provider 列表(编辑已有行时顺便补齐额外字段默认值)。+ // Catalogs can be published by another administrator while this page is+ // open, so refresh this type without dropping other types' cached lists.+ loadProviders(true).then(() => {if (props.visible && !isEdit.value) applyExtraFieldDefaults()})advancedOpen.value = falsediff --git a/frontend/src/components/modelEditorFlow.test.ts b/frontend/src/components/modelEditorFlow.test.tsindex bb6c16795..46ea698e0 100644--- a/frontend/src/components/modelEditorFlow.test.ts+++ b/frontend/src/components/modelEditorFlow.test.ts@@ -38,8 +38,9 @@ async function fixture(options: {const saves: any[] = []const resolves: any[] = []const providers: any[] = options.providers || []+ const catalogEvents: string[] = []const providersStore = {- ensureLoaded: async () => providers,+ ensureLoaded: async (_type?: string, force?: boolean) => { catalogEvents.push(force ? 'refresh' : 'load'); return providers },providersFor: () => providers,isLoading: () => false,providerById: (id: string) => providers.find((p) => p.value === id),@@ -113,7 +114,7 @@ async function fixture(options: {Object.assign(vm.formData, { modelName: 'draft-model', baseUrl: 'https://example.com/v1', apiKey: options.edit ? '' : 'draft-key' })vm.formRef = { validate: async () => true }await nextTick()- return { vm, props, requests, saves, toasts, visibility, resolves, close: () => app.unmount() }+ return { vm, props, requests, saves, toasts, visibility, resolves, catalogEvents, close: () => app.unmount() }}for (const type of ['chat', 'embedding', 'rerank', 'vllm', 'asr']) {@@ -957,3 +958,16 @@ test('capability preview includes the same edited spec as connection tests', asyassert.deepEqual(plain(f.resolves.at(-1).spec), { api: 'openai-completions', compat: { supports_temperature: false } })} finally { f.close() }})++test('opening the model editor refreshes its catalog candidates', async () => {+ const f = await fixture()+ try {+ assert.equal(f.catalogEvents[0], 'refresh')+ f.props.visible = false+ await nextTick()+ f.catalogEvents.length = 0+ f.props.visible = true+ await nextTick()+ assert.equal(f.catalogEvents[0], 'refresh')+ } finally { f.close() }+})diff --git a/frontend/src/config/settingsAccess.test.ts b/frontend/src/config/settingsAccess.test.tsindex b2da7ac76..dbe44dc90 100644--- a/frontend/src/config/settingsAccess.test.ts+++ b/frontend/src/config/settingsAccess.test.ts@@ -34,6 +34,6 @@ test('personal skill environment variables are visible to every member', () => {test('system administration settings stay explicitly system-admin-only', () => {assert.deepEqual([...SYSTEM_ADMIN_SETTINGS_SECTIONS],- ['system-global', 'runtime-queues', 'platform-api-keys', 'system-audit-log'],+ ['system-global', 'model-catalog', 'runtime-queues', 'platform-api-keys', 'system-audit-log'],)})diff --git a/frontend/src/config/settingsAccess.ts b/frontend/src/config/settingsAccess.tsindex cdc6dad50..5950c7c5c 100644--- a/frontend/src/config/settingsAccess.ts+++ b/frontend/src/config/settingsAccess.ts@@ -45,6 +45,7 @@ export const SETTINGS_MANAGEMENT_SHORTCUT_MIN_ROLE = {export const SYSTEM_ADMIN_SETTINGS_SECTIONS = new Set(['system-global',+ 'model-catalog','runtime-queues','platform-api-keys','system-audit-log',diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 800fa93ff..3bbf9c199 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -1,4 +1,129 @@export default {+ modelCatalog: {+ "title": "Model catalog",+ "description": "The model catalog defines which models are offered when adding a model, along with defaults such as context window and reasoning support. Changes here apply to all workspaces immediately.",+ "howItWorks": "How settings are resolved",+ "layers": {+ "builtin": "Built-in catalog: the default model list shipped with each release.",+ "deployment": "Deployment file: models.json on the server, which overrides the built-in catalog.",+ "console": "Administrator changes: edits made on this page, which take precedence over both.",+ "explicit": "Values a workspace sets in model settings always win; catalog changes never rewrite saved models.",+ },+ "add": "Add model",+ "more": "More",+ "jsonEditor": "Edit JSON",+ "history": "Version history",+ "import": "Import JSON",+ "export": "Export changes",+ "search": "Search model ID or name",+ "allProviders": "All providers",+ "allTypes": "All types",+ "onlyModified": "Modified only",+ "summary": "{count} models · version {version}",+ "columns": {+ "model": "Model",+ "provider": "Provider",+ "type": "Type",+ "tokens": "Context / output",+ "capabilities": "Capabilities",+ "source": "Source",+ },+ "capability": {+ "reasoning": "Reasoning",+ "image": "Image",+ "audio": "Audio",+ "video": "Video",+ },+ "source": {+ "builtin": "Built-in",+ "deployment": "Deployment",+ "console": "Admin change",+ },+ "rule": "Pattern",+ "ruleTip": "Matches a family of models by name and supplies defaults. Patterns are not offered in the model picker.",+ "hidden": "Hidden",+ "edit": "Edit",+ "view": "View",+ "empty": "No matching models",+ "editDescription": "{provider} · {type}",+ "ruleNotice": "This pattern supplies defaults to models whose names match it. To change it, use More → Edit JSON.",+ "fieldsSection": "Defaults",+ "nameDesc": "Name shown in the model picker.",+ "dimension": "Vector dimension",+ "dimensionDesc": "Prefilled when this embedding model is added; must match what the model actually returns.",+ "inputDesc": "Input types the model accepts. Models with image input can be used as vision models.",+ "thinkingLevels": "Thinking levels",+ "thinkingLevelsDesc": "Reasoning intensities offered in chat. Without Off, the model always thinks.",+ "levelsNeedReasoning": "Turn on Reasoning to set levels.",+ "levelsUnsupported": "This provider's API does not support graded thinking.",+ "textOnly": "Text only",+ "noLevels": "None",+ "sourceLink": "Provider docs",+ "customHint": "An administrator added this model on this page; all of its values come from here.",+ "fieldsHint": "Values a workspace sets in model settings still take precedence. Clear a field to restore its default.",+ "context": "Context window",+ "contextDesc": "Maximum tokens the model can process at once.",+ "output": "Max output",+ "outputDesc": "Maximum tokens generated in one response.",+ "reasoning": "Reasoning",+ "reasoningDesc": "Whether the model can output its reasoning.",+ "hide": "Hide from picker",+ "hideDesc": "Hidden models are no longer offered when adding a model. Existing models are unaffected.",+ "inputModes": "Input modalities",+ "inherited": "Default: {value}",+ "notSet": "Not set",+ "optional": "Optional",+ "yes": "Yes",+ "no": "No",+ "modified": "Modified",+ "layersSection": "Values by layer",+ "layerField": "Setting",+ "layerBuiltin": "Built-in",+ "layerDeployment": "Deployment",+ "layerEffective": "Effective",+ "save": "Save and apply",+ "restore": "Restore defaults",+ "restoreConfirm": "Remove all administrator changes for this model and apply immediately?",+ "restored": "Restored. Other instances sync within about 5 seconds.",+ "remove": "Delete model",+ "removeConfirm": "Delete this administrator-added model from the catalog and apply immediately?",+ "removed": "Deleted. Other instances sync within about 5 seconds.",+ "published": "Applied. Other instances sync within about 5 seconds.",+ "conflict": "Another administrator updated the catalog. The page has been refreshed; please try again.",+ "loadFailed": "Failed to load the model catalog",+ "deploymentError": "Failed to load the deployment models.json; only the built-in catalog is in use: {error}",+ "syncError": "Failed to sync the latest version; this page may not show the configuration in effect: {error}",+ "addDescription": "Add a model the catalog does not list yet. It can then be selected directly in model settings.",+ "modelId": "Model ID",+ "modelIdPlaceholder": "The model name used by the provider API, e.g. gpt-5-mini",+ "displayName": "Display name",+ "required": "Select a provider and enter a model ID",+ "exists": "This model is already in the catalog; edit it instead",+ "jsonDescription": "Edit all administrator changes as models.json. Useful for bulk changes or migration.",+ "jsonHint": "Include only the fields you want to change; remove a field to restore its default. Manage credentials, headers and environment references in model settings or deployment files. Icons must be inline SVG. Maximum 1 MiB.",+ "jsonClear": "Clear all changes",+ "jsonCheck": "Check changes",+ "jsonPublish": "Publish {count} changes",+ "jsonUnchanged": "Matches the configuration in effect; nothing to publish.",+ "changesTitle": "Changes to apply",+ "change": {+ "added": "Added",+ "removed": "Removed",+ "updated": "Changed",+ "provider": "Provider",+ },+ "publishHint": "Takes effect on this instance immediately; other instances sync within about 5 seconds.",+ "invalid": "Enter a models.json document containing a providers object.",+ "tooLarge": "The file must not exceed 1 MiB.",+ "historyDescription": "The last 20 versions are kept. Restoring a version applies it immediately.",+ "historyVersion": "Version {version}",+ "historyCurrent": "Current",+ "historyRestore": "Restore",+ "historyRestoreConfirm": "Restore version {version} and apply it to all workspaces immediately?",+ "historyEmpty": "No earlier versions",+ "historyModels": "{count} models changed",+ "historyNoOverrides": "No administrator changes",+ },toolbox: {"title": "Toolbox","description": "Manage skills, external tools, and browser connections for your agents.",diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 8e03c1974..ff5b59439 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -1,4 +1,129 @@export default {+ modelCatalog: {+ "title": "モデルカタログ",+ "description": "モデルカタログは、モデル追加時に選べるモデル一覧と、コンテキスト長や思考対応などの既定値を定義します。ここでの変更はすべてのワークスペースに即時反映されます。",+ "howItWorks": "設定の適用順序",+ "layers": {+ "builtin": "組み込みカタログ:リリースに同梱される既定のモデル一覧。",+ "deployment": "デプロイファイル:サーバー上の models.json。組み込みカタログを上書きします。",+ "console": "管理者による変更:このページでの変更。上記の両方より優先されます。",+ "explicit": "各ワークスペースのモデル設定で指定した値が常に優先され、保存済みモデルは書き換えられません。",+ },+ "add": "モデルを追加",+ "more": "その他",+ "jsonEditor": "JSON 編集",+ "history": "バージョン履歴",+ "import": "JSON をインポート",+ "export": "変更をエクスポート",+ "search": "モデル ID または名前で検索",+ "allProviders": "すべてのプロバイダー",+ "allTypes": "すべての種類",+ "onlyModified": "変更済みのみ",+ "summary": "{count} 件のモデル · バージョン {version}",+ "columns": {+ "model": "モデル",+ "provider": "プロバイダー",+ "type": "種類",+ "tokens": "コンテキスト / 出力",+ "capabilities": "機能",+ "source": "ソース",+ },+ "capability": {+ "reasoning": "思考",+ "image": "画像",+ "audio": "音声",+ "video": "動画",+ },+ "source": {+ "builtin": "組み込み",+ "deployment": "デプロイ",+ "console": "管理者変更",+ },+ "rule": "パターン",+ "ruleTip": "名前のパターンで一群のモデルに既定値を提供します。候補一覧には表示されません。",+ "hidden": "非表示",+ "edit": "編集",+ "view": "表示",+ "empty": "一致するモデルはありません",+ "editDescription": "{provider} · {type}",+ "ruleNotice": "このパターンは名前が一致するモデルに既定値を提供します。変更するには「その他 → JSON 編集」を使用してください。",+ "fieldsSection": "既定値",+ "nameDesc": "モデル選択一覧に表示する名前。",+ "dimension": "ベクトル次元",+ "dimensionDesc": "この埋め込みモデルを追加するときに事前入力される次元。モデルの実際の出力と一致させてください。",+ "inputDesc": "モデルが受け付ける入力の種類。画像を選ぶとビジョンモデルとして使用できます。",+ "thinkingLevels": "思考レベル",+ "thinkingLevelsDesc": "チャットで選べる思考の強さ。「オフ」を選ばない場合、モデルは常に思考します。",+ "levelsNeedReasoning": "「思考対応」をオンにすると設定できます。",+ "levelsUnsupported": "このプロバイダーの API は段階的な思考に対応していません。",+ "textOnly": "テキストのみ",+ "noLevels": "なし",+ "sourceLink": "プロバイダーのドキュメント",+ "customHint": "このモデルは管理者がこのページで追加したもので、すべての値はここでの設定です。",+ "fieldsHint": "各ワークスペースのモデル設定で指定した値が引き続き優先されます。入力を空にすると既定値に戻ります。",+ "context": "コンテキストウィンドウ",+ "contextDesc": "モデルが一度に処理できる最大トークン数。",+ "output": "最大出力",+ "outputDesc": "1 回の応答で生成される最大トークン数。",+ "reasoning": "思考対応",+ "reasoningDesc": "モデルが思考過程を出力できるかどうか。",+ "hide": "候補から非表示",+ "hideDesc": "非表示にするとモデル追加時に表示されません。設定済みのモデルには影響しません。",+ "inputModes": "入力モダリティ",+ "inherited": "既定:{value}",+ "notSet": "未設定",+ "optional": "任意",+ "yes": "はい",+ "no": "いいえ",+ "modified": "変更済み",+ "layersSection": "レイヤーごとの値",+ "layerField": "項目",+ "layerBuiltin": "組み込み",+ "layerDeployment": "デプロイ",+ "layerEffective": "適用中",+ "save": "保存して適用",+ "restore": "既定に戻す",+ "restoreConfirm": "このモデルに対する管理者の変更をすべて削除し、即時に適用しますか?",+ "restored": "戻しました。他のインスタンスには約 5 秒で同期されます。",+ "remove": "モデルを削除",+ "removeConfirm": "管理者が追加したこのモデルをカタログから削除し、即時に適用しますか?",+ "removed": "削除しました。他のインスタンスには約 5 秒で同期されます。",+ "published": "適用しました。他のインスタンスには約 5 秒で同期されます。",+ "conflict": "別の管理者がカタログを更新しました。最新の状態に更新したので、もう一度操作してください。",+ "loadFailed": "モデルカタログを読み込めませんでした",+ "deploymentError": "デプロイファイル models.json を読み込めなかったため、組み込みカタログのみを使用しています:{error}",+ "syncError": "最新バージョンの同期に失敗しました。表示内容が現在の設定と異なる可能性があります:{error}",+ "addDescription": "カタログにないモデルを追加します。追加後はモデル設定で直接選択できます。",+ "modelId": "モデル ID",+ "modelIdPlaceholder": "プロバイダー API のモデル名(例:gpt-5-mini)",+ "displayName": "表示名",+ "required": "プロバイダーを選択し、モデル ID を入力してください",+ "exists": "このモデルはすでにカタログにあります。編集してください",+ "jsonDescription": "管理者の変更全体を models.json 形式で直接編集します。一括変更や移行に便利です。",+ "jsonHint": "変更するフィールドのみ記述し、フィールドを削除すると既定値に戻ります。認証情報、ヘッダー、環境変数の参照はモデル設定またはデプロイファイルで管理してください。アイコンはインライン SVG のみ、最大 1 MiB です。",+ "jsonClear": "すべての変更をクリア",+ "jsonCheck": "変更を確認",+ "jsonPublish": "{count} 件の変更を公開",+ "jsonUnchanged": "現在の設定と同じため、公開は不要です。",+ "changesTitle": "適用される変更",+ "change": {+ "added": "追加",+ "removed": "削除",+ "updated": "変更",+ "provider": "プロバイダー",+ },+ "publishHint": "このインスタンスには即時に反映され、他のインスタンスには約 5 秒で同期されます。",+ "invalid": "providers オブジェクトを含む models.json を入力してください。",+ "tooLarge": "ファイルは 1 MiB 以下にしてください。",+ "historyDescription": "直近 20 バージョンを保持します。復元すると即時に適用されます。",+ "historyVersion": "バージョン {version}",+ "historyCurrent": "現在",+ "historyRestore": "復元",+ "historyRestoreConfirm": "バージョン {version} の設定に戻し、すべてのワークスペースに即時適用しますか?",+ "historyEmpty": "過去のバージョンはありません",+ "historyModels": "{count} 件のモデルを変更",+ "historyNoOverrides": "管理者の変更なし",+ },toolbox: {"title": "ツールボックス","description": "エージェントのスキル、外部ツール、ブラウザー接続を管理します。",diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 4a9d5ba49..4d496c196 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -1,4 +1,129 @@export default {+ modelCatalog: {+ "title": "모델 카탈로그",+ "description": "모델 카탈로그는 모델 추가 시 선택할 수 있는 모델 목록과 컨텍스트 창, 추론 지원 여부 같은 기본값을 정의합니다. 여기서 변경하면 모든 워크스페이스에 즉시 적용됩니다.",+ "howItWorks": "설정 적용 순서",+ "layers": {+ "builtin": "내장 카탈로그: 릴리스에 포함된 기본 모델 목록.",+ "deployment": "배포 파일: 서버의 models.json으로, 내장 카탈로그를 덮어씁니다.",+ "console": "관리자 변경: 이 페이지에서 한 변경으로, 위 두 가지보다 우선합니다.",+ "explicit": "워크스페이스에서 모델 설정에 입력한 값이 항상 우선하며, 저장된 모델은 다시 쓰이지 않습니다.",+ },+ "add": "모델 추가",+ "more": "더보기",+ "jsonEditor": "JSON 편집",+ "history": "버전 기록",+ "import": "JSON 가져오기",+ "export": "변경 내보내기",+ "search": "모델 ID 또는 이름 검색",+ "allProviders": "모든 공급자",+ "allTypes": "모든 유형",+ "onlyModified": "변경된 항목만",+ "summary": "모델 {count}개 · 버전 {version}",+ "columns": {+ "model": "모델",+ "provider": "공급자",+ "type": "유형",+ "tokens": "컨텍스트 / 출력",+ "capabilities": "기능",+ "source": "출처",+ },+ "capability": {+ "reasoning": "추론",+ "image": "이미지",+ "audio": "오디오",+ "video": "비디오",+ },+ "source": {+ "builtin": "내장",+ "deployment": "배포 파일",+ "console": "관리자 변경",+ },+ "rule": "패턴",+ "ruleTip": "이름 패턴으로 모델 계열에 기본값을 제공합니다. 모델 선택 목록에는 표시되지 않습니다.",+ "hidden": "숨김",+ "edit": "편집",+ "view": "보기",+ "empty": "일치하는 모델이 없습니다",+ "editDescription": "{provider} · {type}",+ "ruleNotice": "이 패턴은 이름이 일치하는 모델에 기본값을 제공합니다. 변경하려면 더보기 → JSON 편집을 사용하세요.",+ "fieldsSection": "기본값",+ "nameDesc": "모델 선택 목록에 표시되는 이름입니다.",+ "dimension": "벡터 차원",+ "dimensionDesc": "이 임베딩 모델을 추가할 때 미리 채워지는 차원으로, 모델의 실제 출력과 같아야 합니다.",+ "inputDesc": "모델이 받을 수 있는 입력 유형입니다. 이미지를 선택하면 비전 모델로 사용할 수 있습니다.",+ "thinkingLevels": "추론 수준",+ "thinkingLevelsDesc": "채팅에서 선택할 수 있는 추론 강도입니다. '끄기'를 선택하지 않으면 모델이 항상 추론합니다.",+ "levelsNeedReasoning": "'추론 지원'을 켜면 설정할 수 있습니다.",+ "levelsUnsupported": "이 공급자의 API는 단계별 추론을 지원하지 않습니다.",+ "textOnly": "텍스트만",+ "noLevels": "없음",+ "sourceLink": "공급자 문서",+ "customHint": "관리자가 이 페이지에서 추가한 모델이며, 모든 값은 여기서 설정한 것입니다.",+ "fieldsHint": "워크스페이스에서 모델 설정에 입력한 값이 계속 우선합니다. 입력란을 비우면 기본값으로 돌아갑니다.",+ "context": "컨텍스트 창",+ "contextDesc": "모델이 한 번에 처리할 수 있는 최대 토큰 수.",+ "output": "최대 출력",+ "outputDesc": "한 번의 응답에서 생성하는 최대 토큰 수.",+ "reasoning": "추론 지원",+ "reasoningDesc": "모델이 추론 과정을 출력할 수 있는지 여부.",+ "hide": "선택 목록에서 숨기기",+ "hideDesc": "숨기면 모델 추가 시 표시되지 않습니다. 이미 설정된 모델에는 영향이 없습니다.",+ "inputModes": "입력 모달리티",+ "inherited": "기본값: {value}",+ "notSet": "설정 안 됨",+ "optional": "선택 사항",+ "yes": "예",+ "no": "아니요",+ "modified": "변경됨",+ "layersSection": "계층별 값",+ "layerField": "항목",+ "layerBuiltin": "내장",+ "layerDeployment": "배포 파일",+ "layerEffective": "적용 중",+ "save": "저장 후 적용",+ "restore": "기본값 복원",+ "restoreConfirm": "이 모델에 대한 관리자 변경을 모두 제거하고 즉시 적용할까요?",+ "restored": "복원했습니다. 다른 인스턴스는 약 5초 내에 동기화됩니다.",+ "remove": "모델 삭제",+ "removeConfirm": "관리자가 추가한 이 모델을 카탈로그에서 삭제하고 즉시 적용할까요?",+ "removed": "삭제했습니다. 다른 인스턴스는 약 5초 내에 동기화됩니다.",+ "published": "적용했습니다. 다른 인스턴스는 약 5초 내에 동기화됩니다.",+ "conflict": "다른 관리자가 카탈로그를 업데이트했습니다. 최신 상태로 새로 고쳤으니 다시 시도하세요.",+ "loadFailed": "모델 카탈로그를 불러오지 못했습니다",+ "deploymentError": "배포 파일 models.json을 불러오지 못해 내장 카탈로그만 사용 중입니다: {error}",+ "syncError": "최신 버전 동기화에 실패했습니다. 페이지에 현재 적용 중인 설정이 표시되지 않을 수 있습니다: {error}",+ "addDescription": "카탈로그에 없는 모델을 추가합니다. 추가 후 모델 설정에서 바로 선택할 수 있습니다.",+ "modelId": "모델 ID",+ "modelIdPlaceholder": "공급자 API의 모델 이름(예: gpt-5-mini)",+ "displayName": "표시 이름",+ "required": "공급자를 선택하고 모델 ID를 입력하세요",+ "exists": "이미 카탈로그에 있는 모델입니다. 편집해 주세요",+ "jsonDescription": "모든 관리자 변경을 models.json 형식으로 직접 편집합니다. 일괄 변경이나 마이그레이션에 유용합니다.",+ "jsonHint": "변경할 필드만 입력하고, 필드를 삭제하면 기본값으로 돌아갑니다. 자격 증명, 헤더, 환경 변수 참조는 모델 설정이나 배포 파일에서 관리하세요. 아이콘은 인라인 SVG만 지원하며 최대 1 MiB입니다.",+ "jsonClear": "모든 변경 지우기",+ "jsonCheck": "변경 사항 확인",+ "jsonPublish": "변경 {count}개 게시",+ "jsonUnchanged": "현재 적용 중인 설정과 같아 게시할 필요가 없습니다.",+ "changesTitle": "적용될 변경 사항",+ "change": {+ "added": "추가",+ "removed": "제거",+ "updated": "변경",+ "provider": "공급자",+ },+ "publishHint": "이 인스턴스에는 즉시 적용되고, 다른 인스턴스는 약 5초 내에 동기화됩니다.",+ "invalid": "providers 객체가 포함된 models.json을 입력하세요.",+ "tooLarge": "파일은 1 MiB를 넘을 수 없습니다.",+ "historyDescription": "최근 20개 버전을 보관합니다. 복원하면 즉시 적용됩니다.",+ "historyVersion": "버전 {version}",+ "historyCurrent": "현재",+ "historyRestore": "복원",+ "historyRestoreConfirm": "버전 {version}의 설정으로 복원하고 모든 워크스페이스에 즉시 적용할까요?",+ "historyEmpty": "이전 버전이 없습니다",+ "historyModels": "모델 {count}개 변경",+ "historyNoOverrides": "관리자 변경 없음",+ },toolbox: {"title": "도구함","description": "에이전트의 스킬, 외부 도구 및 브라우저 연결을 관리합니다.",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 27557a858..a1c7f885c 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -1,4 +1,129 @@export default {+ modelCatalog: {+ "title": "Каталог моделей",+ "description": "Каталог моделей определяет, какие модели предлагаются при добавлении модели, и значения по умолчанию, например контекстное окно и поддержку рассуждений. Изменения здесь сразу применяются ко всем рабочим пространствам.",+ "howItWorks": "Порядок применения настроек",+ "layers": {+ "builtin": "Встроенный каталог: список моделей по умолчанию, поставляемый с релизом.",+ "deployment": "Файл развёртывания: models.json на сервере, переопределяет встроенный каталог.",+ "console": "Изменения администратора: правки на этой странице, имеют приоритет над обоими.",+ "explicit": "Значения, заданные в рабочем пространстве в настройках модели, всегда важнее; изменения каталога не перезаписывают сохранённые модели.",+ },+ "add": "Добавить модель",+ "more": "Ещё",+ "jsonEditor": "Редактировать JSON",+ "history": "История версий",+ "import": "Импорт JSON",+ "export": "Экспорт изменений",+ "search": "Поиск по ID или названию модели",+ "allProviders": "Все провайдеры",+ "allTypes": "Все типы",+ "onlyModified": "Только изменённые",+ "summary": "Моделей: {count} · версия {version}",+ "columns": {+ "model": "Модель",+ "provider": "Провайдер",+ "type": "Тип",+ "tokens": "Контекст / вывод",+ "capabilities": "Возможности",+ "source": "Источник",+ },+ "capability": {+ "reasoning": "Рассуждения",+ "image": "Изображения",+ "audio": "Аудио",+ "video": "Видео",+ },+ "source": {+ "builtin": "Встроенный",+ "deployment": "Развёртывание",+ "console": "Изменено админом",+ },+ "rule": "Шаблон",+ "ruleTip": "Задаёт значения по умолчанию для семейства моделей по шаблону имени. Шаблоны не показываются в списке выбора.",+ "hidden": "Скрыта",+ "edit": "Изменить",+ "view": "Просмотр",+ "empty": "Подходящих моделей нет",+ "editDescription": "{provider} · {type}",+ "ruleNotice": "Этот шаблон задаёт значения по умолчанию для моделей с подходящими именами. Чтобы изменить его, используйте «Ещё → Редактировать JSON».",+ "fieldsSection": "Значения по умолчанию",+ "nameDesc": "Название в списке выбора моделей.",+ "dimension": "Размерность векторов",+ "dimensionDesc": "Подставляется при добавлении этой модели эмбеддингов; должна совпадать с фактическим выводом модели.",+ "inputDesc": "Типы входных данных модели. С изображениями модель можно использовать как визуальную.",+ "thinkingLevels": "Уровни рассуждений",+ "thinkingLevelsDesc": "Интенсивность рассуждений, доступная в чате. Без «Выкл» модель рассуждает всегда.",+ "levelsNeedReasoning": "Включите «Рассуждения», чтобы настроить уровни.",+ "levelsUnsupported": "API этого провайдера не поддерживает уровни рассуждений.",+ "textOnly": "Только текст",+ "noLevels": "Нет",+ "sourceLink": "Документация провайдера",+ "customHint": "Эту модель добавил администратор на этой странице; все её значения заданы здесь.",+ "fieldsHint": "Значения, заданные в рабочем пространстве в настройках модели, по-прежнему важнее. Очистите поле, чтобы вернуть значение по умолчанию.",+ "context": "Контекстное окно",+ "contextDesc": "Максимальное число токенов, которое модель обрабатывает за раз.",+ "output": "Макс. вывод",+ "outputDesc": "Максимальное число токенов в одном ответе.",+ "reasoning": "Рассуждения",+ "reasoningDesc": "Может ли модель выводить ход рассуждений.",+ "hide": "Скрыть из списка выбора",+ "hideDesc": "Скрытая модель не предлагается при добавлении. Уже настроенные модели не затрагиваются.",+ "inputModes": "Типы входных данных",+ "inherited": "По умолчанию: {value}",+ "notSet": "Не задано",+ "optional": "Необязательно",+ "yes": "Да",+ "no": "Нет",+ "modified": "Изменено",+ "layersSection": "Значения по уровням",+ "layerField": "Параметр",+ "layerBuiltin": "Встроенный",+ "layerDeployment": "Развёртывание",+ "layerEffective": "Действующее",+ "save": "Сохранить и применить",+ "restore": "Восстановить по умолчанию",+ "restoreConfirm": "Удалить все изменения администратора для этой модели и сразу применить?",+ "restored": "Восстановлено. Другие экземпляры синхронизируются примерно за 5 секунд.",+ "remove": "Удалить модель",+ "removeConfirm": "Удалить эту добавленную администратором модель из каталога и сразу применить?",+ "removed": "Удалено. Другие экземпляры синхронизируются примерно за 5 секунд.",+ "published": "Применено. Другие экземпляры синхронизируются примерно за 5 секунд.",+ "conflict": "Другой администратор обновил каталог. Страница обновлена, повторите действие.",+ "loadFailed": "Не удалось загрузить каталог моделей",+ "deploymentError": "Не удалось загрузить файл развёртывания models.json, используется только встроенный каталог: {error}",+ "syncError": "Не удалось синхронизировать последнюю версию; страница может показывать не действующую конфигурацию: {error}",+ "addDescription": "Добавьте модель, которой ещё нет в каталоге. После этого её можно сразу выбрать в настройках моделей.",+ "modelId": "ID модели",+ "modelIdPlaceholder": "Имя модели в API провайдера, например gpt-5-mini",+ "displayName": "Отображаемое имя",+ "required": "Выберите провайдера и укажите ID модели",+ "exists": "Эта модель уже есть в каталоге — отредактируйте её",+ "jsonDescription": "Редактирование всех изменений администратора в формате models.json. Удобно для массовых правок и миграции.",+ "jsonHint": "Указывайте только изменяемые поля; удалите поле, чтобы вернуть значение по умолчанию. Учётные данные, заголовки и ссылки на переменные окружения храните в настройках моделей или файлах развёртывания. Значки — только встроенный SVG. Не более 1 МиБ.",+ "jsonClear": "Очистить все изменения",+ "jsonCheck": "Проверить изменения",+ "jsonPublish": "Опубликовать изменения ({count})",+ "jsonUnchanged": "Совпадает с действующей конфигурацией — публиковать нечего.",+ "changesTitle": "Изменения к применению",+ "change": {+ "added": "Добавлено",+ "removed": "Удалено",+ "updated": "Изменено",+ "provider": "Провайдер",+ },+ "publishHint": "На этом экземпляре применяется сразу, другие синхронизируются примерно за 5 секунд.",+ "invalid": "Введите models.json с объектом providers.",+ "tooLarge": "Файл не должен превышать 1 МиБ.",+ "historyDescription": "Хранятся последние 20 версий. Восстановленная версия применяется сразу.",+ "historyVersion": "Версия {version}",+ "historyCurrent": "Текущая",+ "historyRestore": "Восстановить",+ "historyRestoreConfirm": "Восстановить версию {version} и сразу применить её ко всем рабочим пространствам?",+ "historyEmpty": "Предыдущих версий нет",+ "historyModels": "Изменено моделей: {count}",+ "historyNoOverrides": "Нет изменений администратора",+ },toolbox: {"title": "Инструменты","description": "Управляйте навыками, внешними инструментами и подключением браузера для агентов.",diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex b60af1376..dc5bac94e 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -1,4 +1,129 @@export default {+ modelCatalog: {+ "title": "模型目录",+ "description": "模型目录决定添加模型时可选的模型列表,以及上下文窗口、是否支持思考等默认参数。在这里修改后,所有空间立即生效。",+ "howItWorks": "配置如何生效",+ "layers": {+ "builtin": "内置目录:随版本发布的默认模型清单。",+ "deployment": "部署文件:服务器上的 models.json,可覆盖内置目录。",+ "console": "管理员修改:在本页所做的修改,优先于以上两者。",+ "explicit": "各空间在模型配置中填写的参数始终优先;修改目录不会改写已保存的模型。",+ },+ "add": "添加模型",+ "more": "更多",+ "jsonEditor": "JSON 编辑",+ "history": "版本历史",+ "import": "导入 JSON",+ "export": "导出修改",+ "search": "搜索模型 ID 或名称",+ "allProviders": "全部厂商",+ "allTypes": "全部类型",+ "onlyModified": "只看已修改",+ "summary": "{count} 个模型 · 版本 {version}",+ "columns": {+ "model": "模型",+ "provider": "厂商",+ "type": "类型",+ "tokens": "上下文 / 输出",+ "capabilities": "能力",+ "source": "来源",+ },+ "capability": {+ "reasoning": "思考",+ "image": "图像",+ "audio": "音频",+ "video": "视频",+ },+ "source": {+ "builtin": "内置",+ "deployment": "部署文件",+ "console": "管理员修改",+ },+ "rule": "匹配规则",+ "ruleTip": "按名称模式匹配一组模型,只提供默认参数,不会出现在候选列表中。",+ "hidden": "已隐藏",+ "edit": "编辑",+ "view": "查看",+ "empty": "没有匹配的模型",+ "editDescription": "{provider} · {type}",+ "ruleNotice": "这是一条匹配规则,为名称符合该模式的模型提供默认参数。如需修改,请使用「更多 → JSON 编辑」。",+ "fieldsSection": "默认参数",+ "nameDesc": "在模型选择列表中显示的名称。",+ "dimension": "向量维度",+ "dimensionDesc": "添加该向量模型时预填的维度,需与模型实际输出一致。",+ "inputDesc": "模型可接收的输入类型;勾选图像后可作为视觉模型使用。",+ "thinkingLevels": "思考等级",+ "thinkingLevelsDesc": "对话中可选的思考强度。未勾选「关闭」表示该模型始终思考。",+ "levelsNeedReasoning": "开启「支持思考」后可设置。",+ "levelsUnsupported": "该厂商接口不支持分级思考。",+ "textOnly": "仅文本",+ "noLevels": "无",+ "sourceLink": "厂商文档",+ "customHint": "这是管理员在本页添加的模型,参数均来自这里的配置。",+ "fieldsHint": "各空间在模型配置中填写的参数仍然优先。输入框留空即恢复默认值。",+ "context": "上下文窗口",+ "contextDesc": "模型一次可处理的最大 token 数。",+ "output": "最大输出",+ "outputDesc": "单次回复最多生成的 token 数。",+ "reasoning": "支持思考",+ "reasoningDesc": "模型能否输出思考过程。",+ "hide": "在候选列表中隐藏",+ "hideDesc": "隐藏后添加模型时不再出现,已配置的模型不受影响。",+ "inputModes": "输入模态",+ "inherited": "默认:{value}",+ "notSet": "未设置",+ "optional": "可选",+ "yes": "是",+ "no": "否",+ "modified": "已修改",+ "layersSection": "各层取值",+ "layerField": "参数",+ "layerBuiltin": "内置目录",+ "layerDeployment": "部署文件",+ "layerEffective": "当前生效",+ "save": "保存并生效",+ "restore": "恢复默认",+ "restoreConfirm": "移除对该模型的全部管理员修改,并立即生效?",+ "restored": "已恢复,其他实例约 5 秒内同步",+ "remove": "删除模型",+ "removeConfirm": "从目录中删除这个由管理员添加的模型,并立即生效?",+ "removed": "已删除,其他实例约 5 秒内同步",+ "published": "已生效,其他实例约 5 秒内同步",+ "conflict": "目录已被其他管理员更新,已刷新到最新版本,请重新操作。",+ "loadFailed": "模型目录加载失败",+ "deploymentError": "部署文件 models.json 加载失败,当前只使用内置目录:{error}",+ "syncError": "最新版本同步失败,页面显示的可能不是当前生效的配置:{error}",+ "addDescription": "为厂商补充目录中没有的模型,添加后可在模型配置中直接选择。",+ "modelId": "模型 ID",+ "modelIdPlaceholder": "与厂商 API 中的模型名一致,如 gpt-5-mini",+ "displayName": "显示名称",+ "required": "请选择厂商并填写模型 ID",+ "exists": "该模型已在目录中,请直接编辑",+ "jsonDescription": "用 models.json 格式直接编辑全部管理员修改,适合批量调整或迁移。",+ "jsonHint": "只写需要修改的字段,删除字段即恢复默认。凭据、请求头和环境变量引用请在模型配置或部署文件中维护;图标仅支持内联 SVG;最大 1 MiB。",+ "jsonClear": "清空全部修改",+ "jsonCheck": "检查变更",+ "jsonPublish": "发布 {count} 项变更",+ "jsonUnchanged": "与当前生效的配置一致,无需发布。",+ "changesTitle": "将要生效的变更",+ "change": {+ "added": "新增",+ "removed": "移除",+ "updated": "修改",+ "provider": "厂商",+ },+ "publishHint": "发布后本实例立即生效,其他实例约 5 秒内同步。",+ "invalid": "请输入包含 providers 对象的 models.json。",+ "tooLarge": "文件不能超过 1 MiB。",+ "historyDescription": "保留最近 20 个版本,恢复后立即生效。",+ "historyVersion": "版本 {version}",+ "historyCurrent": "当前",+ "historyRestore": "恢复",+ "historyRestoreConfirm": "恢复到版本 {version} 的配置,并立即对所有空间生效?",+ "historyEmpty": "暂无历史版本",+ "historyModels": "修改了 {count} 个模型",+ "historyNoOverrides": "无管理员修改",+ },toolbox: {"title": "工具箱","description": "管理智能体可用的技能、外部工具和浏览器连接。",diff --git a/frontend/src/stores/modelProviders.ts b/frontend/src/stores/modelProviders.tsindex f82be5761..5d5a4cd2c 100644--- a/frontend/src/stores/modelProviders.ts+++ b/frontend/src/stores/modelProviders.ts@@ -24,6 +24,8 @@ export const useModelProvidersStore = defineStore('modelProviders', () => {const byType = ref<Record<string, ModelProviderOption[]>>({})const byId = ref<Record<string, ModelProviderOption>>({})const loadingByType = ref<Record<string, boolean>>({})+ let generation = 0+ const requestTokens = new Map<string, symbol>()const pending = new Map<string, Promise<ModelProviderOption[]>>()const currentLocale = computed(() => String(i18n.global.locale.value || ''))@@ -42,16 +44,23 @@ export const useModelProvidersStore = defineStore('modelProviders', () => {const inflight = pending.get(key)if (inflight && !force) return inflight+ const requestGeneration = generation+ const token = Symbol(key)+ requestTokens.set(key, token)const request = (async () => {loadingByType.value = { ...loadingByType.value, [key]: true }try {const { providers, cacheable } = await loadProvidersForType(listModelProviders, key)- if (!cacheable) return providers+ if (!cacheable || requestGeneration !== generation || requestTokens.get(key) !== token) return providersbyType.value = { ...byType.value, [key]: providers }- byId.value = mergeProviderIndex(byId.value, providers)+ // The freshest list is merged first so its metadata wins over older types.+ byId.value = [providers, ...Object.entries(byType.value).filter(([type]) => type !== key).map(([, entries]) => entries)]+ .reduce((index, entries) => mergeProviderIndex(index, entries), {} as Record<string, ModelProviderOption>)return providers} finally {- loadingByType.value = { ...loadingByType.value, [key]: false }+ if (requestGeneration === generation && requestTokens.get(key) === token) {+ loadingByType.value = { ...loadingByType.value, [key]: false }+ }}})()pending.set(key, request)@@ -83,6 +92,8 @@ export const useModelProvidersStore = defineStore('modelProviders', () => {providerDescription(providerById(id), locale ?? currentLocale.value)const reset = () => {+ generation+++ requestTokens.clear()byType.value = {}byId.value = {}loadingByType.value = {}diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vueindex 83cc5e1b3..d48c7bb26 100644--- a/frontend/src/views/settings/ModelSettings.vue+++ b/frontend/src/views/settings/ModelSettings.vue@@ -6,18 +6,32 @@<h2>{{ $t('modelSettings.title') }}</h2><p class="section-description">{{ $t('modelSettings.description') }}</p></div>- <t-button- v-if="authStore.hasRole('admin')"- type="button"- theme="primary"- variant="text"- size="medium"- class="model-test-trigger"- @click="showDebugDrawer = true"- >- <template #icon><play-circle-icon /></template>- {{ $t('modelSettings.actions.debugModel') }}- </t-button>+ <div class="model-header-actions">+ <t-button+ v-if="authStore.isSystemAdmin"+ type="button"+ theme="primary"+ variant="text"+ size="medium"+ class="model-test-trigger"+ @click="uiStore.openSettings('model-catalog')"+ >+ <template #icon><t-icon name="control-platform" /></template>+ {{ $t('modelCatalog.title') }}+ </t-button>+ <t-button+ v-if="authStore.hasRole('admin')"+ type="button"+ theme="primary"+ variant="text"+ size="medium"+ class="model-test-trigger"+ @click="showDebugDrawer = true"+ >+ <template #icon><play-circle-icon /></template>+ {{ $t('modelSettings.actions.debugModel') }}+ </t-button>+ </div></div><div class="builtin-models-hint" role="note">@@ -892,6 +906,13 @@ onMounted(() => {.settings-section-header();}+.model-header-actions {+ display: flex;+ align-items: center;+ gap: 20px;+ flex-shrink: 0;+}+.model-test-trigger {--td-bg-color-container-hover: transparent;flex-shrink: 0;diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vueindex c2e9ac615..11fb045e4 100644--- a/frontend/src/views/settings/Settings.vue+++ b/frontend/src/views/settings/Settings.vue@@ -148,6 +148,10 @@<SystemSettings /></div>+ <div v-if="currentSection === 'model-catalog'" class="section">+ <ModelCatalog />+ </div>+<!-- 系统管理员可见的任务队列运行状态 --><div v-if="currentSection === 'runtime-queues'" class="section"><RuntimeQueues />@@ -202,6 +206,7 @@ import TenantInfo from './TenantInfo.vue'import UserProfile from './UserProfile.vue'import GeneralSettings from './GeneralSettings.vue'import ModelSettings from './ModelSettings.vue'+import ModelCatalog from '../system/ModelCatalog.vue'import OllamaSettings from './OllamaSettings.vue'import WebSearchSettings from './WebSearchSettings.vue'import ChatHistorySettings from './ChatHistorySettings.vue'@@ -345,6 +350,7 @@ const navItems = computed(() => {{ key: 'sandbox', icon: 'code', label: t('settings.sandbox.title') },{ key: 'system', icon: 'info-circle', label: t('settings.versionInfo') },{ key: 'system-global', icon: 'server', label: t('settings.system') },+ { key: 'model-catalog', icon: 'control-platform', label: t('modelCatalog.title') },{ key: 'runtime-queues', icon: 'queue', label: t('settings.taskQueue') },{ key: 'platform-api-keys', icon: 'secured', label: t('platformApiKeys.title') },{ key: 'system-audit-log', icon: 'history', label: t('system.globalSettings.audit.tabLabel') },@@ -406,7 +412,7 @@ const navGroups = computed<NavGroup[]>(() => {{key: 'system_administration',label: t('settings.navGroups.systemAdministration'),- items: pickItems(['system-global', 'runtime-queues', 'platform-api-keys', 'system-audit-log']),+ items: pickItems(['system-global', 'model-catalog', 'runtime-queues', 'platform-api-keys', 'system-audit-log']),},{key: 'platform',@@ -466,7 +472,7 @@ const handleClose = () => {// 如果当前路由是设置页,返回上一页if (route.path === '/platform/settings') {const sec = route.query.section- if (sec === 'system-global' || sec === 'runtime-queues' || sec === 'platform-api-keys' || sec === 'system-audit-log') {+ if (sec === 'model-catalog' || sec === 'system-global' || sec === 'runtime-queues' || sec === 'platform-api-keys' || sec === 'system-audit-log') {router.push('/platform/knowledge-bases')} else {router.back()diff --git a/frontend/src/views/system/ModelCatalog.vue b/frontend/src/views/system/ModelCatalog.vuenew file mode 100644index 000000000..cad8ca822--- /dev/null+++ b/frontend/src/views/system/ModelCatalog.vue@@ -0,0 +1,1272 @@+<template>+ <div class="model-catalog">+ <header class="section-header">+ <div class="section-header__top">+ <div class="section-header__main">+ <div class="section-header__titlewrap">+ <h2>{{ t('modelCatalog.title') }}</h2>+ <t-popup placement="bottom-start" trigger="hover" :overlay-inner-style="{ maxWidth: '420px' }">+ <button type="button" class="hint-trigger" :aria-label="t('modelCatalog.howItWorks')">+ <t-icon name="info-circle" size="16px" />+ </button>+ <template #content>+ <div class="hint-popover">+ <p class="hint-popover__title">{{ t('modelCatalog.howItWorks') }}</p>+ <ol class="hint-popover__list">+ <li>{{ t('modelCatalog.layers.builtin') }}</li>+ <li>{{ t('modelCatalog.layers.deployment') }}</li>+ <li>{{ t('modelCatalog.layers.console') }}</li>+ <li>{{ t('modelCatalog.layers.explicit') }}</li>+ </ol>+ </div>+ </template>+ </t-popup>+ </div>+ <p class="section-description">{{ t('modelCatalog.description') }}</p>+ </div>+ <div class="section-header__actions">+ <t-button theme="primary" variant="text" class="header-action" :disabled="!state" @click="openAdd">+ <template #icon><t-icon name="add" /></template>+ {{ t('modelCatalog.add') }}+ </t-button>+ <t-dropdown :options="moreOptions" placement="bottom-right" attach="body" trigger="click" :disabled="!state"+ @click="onMore">+ <t-button variant="text" class="header-action header-action--muted" :disabled="!state">+ {{ t('modelCatalog.more') }}+ <template #suffix><t-icon name="chevron-down" /></template>+ </t-button>+ </t-dropdown>+ <input ref="fileInput" type="file" accept=".json,application/json" hidden @change="importOverlay" />+ </div>+ </div>+ </header>++ <t-alert v-if="state?.deployment_error" theme="warning" class="catalog-alert"+ :message="t('modelCatalog.deploymentError', { error: state.deployment_error })" />+ <t-alert v-if="state?.sync_error" theme="warning" class="catalog-alert"+ :message="t('modelCatalog.syncError', { error: state.sync_error })" />++ <div v-if="loadError && !state" class="catalog-state">+ <t-alert theme="error" :message="loadError">+ <template #operation>+ <t-button size="small" @click="load">{{ t('common.retry') }}</t-button>+ </template>+ </t-alert>+ </div>++ <div v-else-if="!state" class="catalog-state catalog-state--loading">+ <t-loading size="small" />+ </div>++ <template v-else>+ <div class="catalog-toolbar">+ <t-input v-model="search" clearable class="catalog-toolbar__search" :placeholder="t('modelCatalog.search')">+ <template #prefix-icon><t-icon name="search" /></template>+ </t-input>+ <t-select v-model="providerFilter" clearable filterable class="catalog-toolbar__select"+ :placeholder="t('modelCatalog.allProviders')" :options="providerOptions" />+ <t-select v-model="typeFilter" clearable class="catalog-toolbar__select catalog-toolbar__select--type"+ :placeholder="t('modelCatalog.allTypes')" :options="typeOptions" />+ <t-checkbox v-model="onlyModified" class="catalog-toolbar__check">+ {{ t('modelCatalog.onlyModified') }}<span v-if="modifiedCount" class="catalog-toolbar__count">{{ modifiedCount }}</span>+ </t-checkbox>+ <div class="catalog-toolbar__meta">+ <span>{{ t('modelCatalog.summary', { count: filteredRows.length, version: state.version }) }}</span>+ <button type="button" class="catalog-refresh" :disabled="loading" :title="t('common.refresh')"+ :aria-label="t('common.refresh')" @click="load">+ <t-icon :name="loading ? 'loading' : 'refresh'" :class="{ 'catalog-refresh--spin': loading }" />+ </button>+ </div>+ </div>++ <div class="data-table-shell catalog-table-shell"+ :class="{ 'catalog-table-shell--single-page': filteredRows.length <= PAGE_SIZE }">+ <t-table row-key="key" :data="pageRows" :columns="columns" :pagination="pagination" disable-data-page+ size="medium" hover+ :row-class-name="rowClassName" @row-click="({ row }: { row: CatalogRow }) => openEdit(row)"+ @page-change="(info: { current: number }) => { page = info.current }">+ <template #model="{ row }">+ <div class="catalog-model">+ <div class="catalog-model__id">+ <code>{{ row.model.id || row.model.match }}</code>+ <t-tooltip v-if="!row.model.id" :content="t('modelCatalog.ruleTip')">+ <t-tag size="small" variant="light">{{ t('modelCatalog.rule') }}</t-tag>+ </t-tooltip>+ <t-tag v-if="row.model.deprecated" size="small" variant="light">{{ t('modelCatalog.hidden') }}</t-tag>+ </div>+ <span class="catalog-model__name">+ {{ providerLabel(row.provider) }}<template v-if="row.model.name && row.model.name !== row.model.id"> · {{ row.model.name }}</template>+ </span>+ </div>+ </template>+ <template #type="{ row }">+ <span class="catalog-cell-text">{{ typeLabel(row.model.type) }}</span>+ </template>+ <template #tokens="{ row }">+ <span class="catalog-num"+ :title="`${row.model.context_window?.toLocaleString() || '—'} / ${row.model.max_output_tokens?.toLocaleString() || '—'}`">+ {{ formatTokens(row.model.context_window) || '—' }}<span class="catalog-muted"> / </span>{{ formatTokens(row.model.max_output_tokens) || '—' }}+ </span>+ </template>+ <template #capabilities="{ row }">+ <div class="catalog-caps">+ <span v-for="cap in capabilities(row.model)" :key="cap" class="catalog-cap">+ {{ t(`modelCatalog.capability.${cap}`) }}+ </span>+ <span v-if="capabilities(row.model).length === 0" class="catalog-muted">—</span>+ </div>+ </template>+ <template #source="{ row }">+ <t-tag v-if="sourceOf(row) !== 'builtin'" size="small" variant="light"+ :theme="sourceOf(row) === 'console' ? 'primary' : 'warning'">+ {{ t(`modelCatalog.source.${sourceOf(row)}`) }}+ </t-tag>+ <span v-else class="catalog-muted">{{ t('modelCatalog.source.builtin') }}</span>+ </template>+ <template #actions="{ row }">+ <t-button variant="text" theme="primary" size="small" @click.stop="openEdit(row)">+ {{ row.model.id ? t('modelCatalog.edit') : t('modelCatalog.view') }}+ </t-button>+ </template>+ <template #empty>+ <t-empty :description="t('modelCatalog.empty')" />+ </template>+ </t-table>+ </div>+ </template>++ <!-- 编辑单个模型:保存即发布 -->+ <SettingDrawer :visible="editVisible" :title="selected ? (selected.model.id || selected.model.match || '') : ''"+ :description="selected ? t('modelCatalog.editDescription', { provider: providerLabel(selected.provider), type: typeLabel(selected.model.type) }) : ''"+ icon="layers" width="560px" storage-key="setting-drawer:width:model-catalog-edit"+ :hide-footer="!selected?.model.id" :confirm-text="t('modelCatalog.save')" :confirm-loading="saving"+ :confirm-disabled="!editDirty" @update:visible="editVisible = $event" @confirm="saveEdit">+ <template v-if="selected">+ <section v-if="!selected.model.id" class="setting-drawer__section">+ <t-alert theme="info" :message="t('modelCatalog.ruleNotice')" />+ </section>++ <section v-else class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ t('modelCatalog.fieldsSection') }}</h4>+ <p class="drawer-hint">+ {{ t(selectedInherited ? 'modelCatalog.fieldsHint' : 'modelCatalog.customHint') }}+ <a v-if="selected.model.source" :href="String(selected.model.source)" target="_blank" rel="noopener noreferrer"+ class="drawer-link">{{ t('modelCatalog.sourceLink') }}<t-icon name="jump" /></a>+ </p>+ <div v-for="field in editFields" :key="field.key" class="drawer-row"+ :class="{ 'drawer-row--stacked': field.kind === 'levels' }">+ <div class="drawer-row__info">+ <div class="drawer-row__label">+ {{ field.label }}+ <t-tag v-if="selectedInherited && isOverridden(field.key)" size="small" theme="primary" variant="light">+ {{ t('modelCatalog.modified') }}+ </t-tag>+ </div>+ <p class="drawer-row__desc">{{ field.desc }}</p>+ <p v-if="selectedInherited && field.kind !== 'levels'" class="drawer-row__inherited">+ {{ t('modelCatalog.inherited', { value: displayField(field.kind, fieldValue('deployment', selected, field.key)) }) }}+ </p>+ </div>+ <div class="drawer-row__control">+ <template v-if="field.kind === 'levels'">+ <p v-if="!form.reasoning" class="drawer-row__inherited">{{ t('modelCatalog.levelsNeedReasoning') }}</p>+ <p v-else-if="!levelsAvailable" class="drawer-row__inherited">{{ t('modelCatalog.levelsUnsupported') }}</p>+ <template v-else>+ <t-checkbox-group v-model="form.thinking_levels" :options="levelOptions" class="drawer-levels" />+ <p v-if="selectedInherited" class="drawer-row__inherited">+ {{ t('modelCatalog.inherited', { value: displayField('levels', fieldValue('deployment', selected, 'thinking_levels')) }) }}+ </p>+ </template>+ </template>+ <FieldControl v-else :kind="field.kind" :model-value="form[field.key]"+ :placeholder="t('modelCatalog.notSet')" @update:model-value="form[field.key] = $event" />+ </div>+ </div>+ </section>++ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ t('modelCatalog.layersSection') }}</h4>+ <table class="layer-table">+ <thead>+ <tr>+ <th>{{ t('modelCatalog.layerField') }}</th>+ <th>{{ t('modelCatalog.layerBuiltin') }}</th>+ <th>{{ t('modelCatalog.layerDeployment') }}</th>+ <th>{{ t('modelCatalog.layerEffective') }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="field in editFields" :key="field.key">+ <td>{{ field.label }}</td>+ <td v-for="layer in (['builtin', 'deployment', 'effective'] as const)" :key="layer"+ :class="{ 'layer-table__changed': layer !== 'builtin' && layerValue(layer, field) !== layerValue(layer === 'effective' ? 'deployment' : 'builtin', field) }">+ {{ layerValue(layer, field) }}+ </td>+ </tr>+ </tbody>+ </table>+ </section>+ </template>+ <template #footer-left>+ <t-popconfirm v-if="selected && hasModelOverride(state?.overlay, selected.provider, selected.model)"+ :content="t(selectedInherited ? 'modelCatalog.restoreConfirm' : 'modelCatalog.removeConfirm')"+ :confirm-btn="{ content: t(selectedInherited ? 'modelCatalog.restore' : 'common.delete'), theme: 'danger' }"+ :cancel-btn="{ content: t('common.cancel') }" placement="top-left" @confirm="restoreSelected">+ <t-button variant="text" theme="danger" :disabled="saving">+ {{ t(selectedInherited ? 'modelCatalog.restore' : 'modelCatalog.remove') }}+ </t-button>+ </t-popconfirm>+ </template>+ </SettingDrawer>++ <!-- 添加目录模型 -->+ <SettingDrawer :visible="addVisible" :title="t('modelCatalog.add')" :description="t('modelCatalog.addDescription')"+ icon="add" width="520px" storage-key="setting-drawer:width:model-catalog-add" :close-on-overlay-click="false"+ :confirm-text="t('modelCatalog.save')" :confirm-loading="saving" @update:visible="addVisible = $event"+ @confirm="saveAdd">+ <section class="setting-drawer__section">+ <div class="drawer-field">+ <label>{{ t('modelCatalog.columns.provider') }}</label>+ <t-select v-model="addForm.provider" filterable :options="providerOptions" />+ </div>+ <div class="drawer-field">+ <label>{{ t('modelCatalog.columns.type') }}</label>+ <t-select v-model="addForm.type" :options="addTypeOptions" />+ </div>+ <div class="drawer-field">+ <label>{{ t('modelCatalog.modelId') }}</label>+ <t-input v-model="addForm.id" :placeholder="t('modelCatalog.modelIdPlaceholder')" />+ </div>+ </section>+ <section class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">{{ t('modelCatalog.fieldsSection') }}</h4>+ <div v-for="field in addFields" :key="field.key" class="drawer-row">+ <div class="drawer-row__info">+ <div class="drawer-row__label">{{ field.label }}</div>+ <p class="drawer-row__desc">{{ field.desc }}</p>+ </div>+ <div class="drawer-row__control">+ <FieldControl :kind="field.kind" :model-value="addForm[field.key]" :placeholder="t('modelCatalog.optional')"+ @update:model-value="addForm[field.key] = $event" />+ </div>+ </div>+ </section>+ </SettingDrawer>++ <!-- 高级:直接编辑管理员修改(models.json 格式) -->+ <SettingDrawer :visible="jsonVisible" :title="t('modelCatalog.jsonEditor')"+ :description="t('modelCatalog.jsonDescription')" icon="code" width="720px" :max-width="1200" maximizable+ storage-key="setting-drawer:width:model-catalog-json" :close-on-overlay-click="false"+ :confirm-text="jsonPreview ? t('modelCatalog.jsonPublish', { count: jsonChanges.length }) : t('modelCatalog.jsonCheck')"+ :confirm-loading="saving" :confirm-disabled="!!jsonPreview && jsonChanges.length === 0"+ @update:visible="jsonVisible = $event" @confirm="confirmJson">+ <section class="setting-drawer__section">+ <p class="drawer-hint">{{ t('modelCatalog.jsonHint') }}</p>+ <t-textarea v-model="draft" class="json-editor" :autosize="{ minRows: 16, maxRows: 40 }" spellcheck="false"+ :status="jsonError ? 'error' : 'default'" :tips="jsonError" />+ </section>+ <section v-if="jsonPreview" class="setting-drawer__section">+ <h4 class="setting-drawer__section-title">+ {{ t('modelCatalog.changesTitle') }}+ <span class="catalog-muted">{{ jsonChanges.length }}</span>+ </h4>+ <p v-if="jsonChanges.length === 0" class="drawer-hint">{{ t('modelCatalog.jsonUnchanged') }}</p>+ <template v-else>+ <p class="drawer-hint">{{ t('modelCatalog.publishHint') }}</p>+ <ul class="change-list">+ <li v-for="change in jsonChanges" :key="change.key" class="change-list__item">+ <t-tag size="small" variant="light" :theme="changeTheme(change.kind)">+ {{ t(`modelCatalog.change.${change.kind}`) }}+ </t-tag>+ <span class="change-list__target">+ <span class="catalog-muted">{{ providerLabel(change.provider) }}</span>+ <code v-if="change.kind !== 'provider'">{{ change.target }}</code>+ </span>+ <span v-if="change.fields.length" class="change-list__fields">+ {{ change.fields.map(fieldLabel).join('、') }}+ </span>+ </li>+ </ul>+ </template>+ </section>+ <template #footer-left>+ <t-button variant="text" :disabled="saving" @click="fileInput?.click()">{{ t('modelCatalog.import') }}</t-button>+ <t-button variant="text" :disabled="saving" @click="draft = emptyOverlay">{{ t('modelCatalog.jsonClear') }}</t-button>+ </template>+ </SettingDrawer>++ <!-- 版本历史:恢复即发布 -->+ <SettingDrawer :visible="historyVisible" :title="t('modelCatalog.history')"+ :description="t('modelCatalog.historyDescription')" icon="history" width="560px"+ storage-key="setting-drawer:width:model-catalog-history" hide-footer @update:visible="historyVisible = $event">+ <section v-if="state" class="setting-drawer__section">+ <div class="history-row">+ <div class="history-row__main">+ <span class="history-row__version">{{ t('modelCatalog.historyVersion', { version: state.version }) }}</span>+ <t-tag size="small" theme="success" variant="light">{{ t('modelCatalog.historyCurrent') }}</t-tag>+ <span class="history-row__meta">{{ overrideSummary(state.overlay) }}</span>+ </div>+ </div>+ <div v-for="revision in state.history" :key="revision.version" class="history-row">+ <div class="history-row__main">+ <span class="history-row__version">{{ t('modelCatalog.historyVersion', { version: revision.version }) }}</span>+ <span class="history-row__meta">{{ overrideSummary(revision.overlay) }}</span>+ </div>+ <div class="history-row__side">+ <span class="history-row__meta">{{ revision.updated_by || '—' }} · {{ formatDate(revision.updated_at) }}</span>+ <t-popconfirm :content="t('modelCatalog.historyRestoreConfirm', { version: revision.version })"+ :confirm-btn="{ content: t('modelCatalog.historyRestore'), theme: 'primary' }"+ :cancel-btn="{ content: t('common.cancel') }" placement="bottom-right"+ @confirm="restoreRevision(revision.overlay)">+ <t-button variant="text" theme="primary" size="small" :disabled="saving">+ {{ t('modelCatalog.historyRestore') }}+ </t-button>+ </t-popconfirm>+ </div>+ </div>+ <p v-if="state.history.length === 0" class="drawer-hint">{{ t('modelCatalog.historyEmpty') }}</p>+ </section>+ </SettingDrawer>+ </div>+</template>++<script setup lang="ts">+import { computed, onMounted, reactive, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { MessagePlugin, type TableProps } from 'tdesign-vue-next'+import SettingDrawer from '@/components/settings/SettingDrawer.vue'+import { levelLabelKey } from '@/utils/reasoningEffort'+import FieldControl from './ModelCatalogFieldControl.vue'+import { getModelCatalog, previewModelCatalog, publishModelCatalog, type CatalogModel, type CatalogOverlay, type CatalogPreview, type CatalogState } from '@/api/system/modelCatalog'+import { useModelProvidersStore } from '@/stores/modelProviders'+import { useChatResourcesStore } from '@/stores/chatResources'+import {+ EDITABLE_INPUTS, THINKING_LEVELS, catalogChanges, catalogRows, catalogSource, composeInput, formatTokens,+ hasModelOverride, patchCatalogModel, removeCatalogModelOverride, sameMembers, stableJSON, summarizeChanges,+ thinkingLevelsPatch, type CatalogChangeSummary, type CatalogRow, type FieldKind,+} from './modelCatalogState'++type Layer = 'builtin' | 'deployment' | 'effective'+type FieldKey = 'name' | 'context_window' | 'max_output_tokens' | 'dimension' | 'input' | 'reasoning' | 'thinking_levels' | 'deprecated'+// `types` limits a field to the model types that use it; omitted means all.+interface FieldDef { key: FieldKey; kind: FieldKind; label: string; desc: string; types?: string[] }++const PAGE_SIZE = 20+const TYPE_LABEL_KEYS: Record<string, string> = {+ KnowledgeQA: 'chat', Embedding: 'embedding', Rerank: 'rerank', VLLM: 'vllm', ASR: 'asr',+}++const { t, locale } = useI18n()+const providersStore = useModelProvidersStore()+const chatResources = useChatResourcesStore()+const emptyOverlay = '{\n "providers": {}\n}'++const state = ref<CatalogState>()+const loading = ref(false)+const loadError = ref('')+const saving = ref(false)+const fileInput = ref<HTMLInputElement>()++const search = ref('')+const providerFilter = ref<string>()+const typeFilter = ref<string>()+const onlyModified = ref(false)+const page = ref(1)++// ---------- 目录列表 ----------++const layerIndexes = computed(() => Object.fromEntries((['builtin', 'deployment', 'effective'] as const).map(layer => [+ layer, new Map(catalogRows(state.value?.[layer] || []).map(row => [row.key, row.model])),+])) as Record<Layer, Map<string, CatalogModel>>)+// Concrete models first within each provider; patterns only supply defaults.+const allRows = computed(() => catalogRows(state.value?.effective || [])+ .map((row, index) => ({ row, index }))+ .sort((a, b) => a.row.provider.localeCompare(b.row.provider) || Number(!a.row.model.id) - Number(!b.row.model.id) || a.index - b.index)+ .map(({ row }) => row))+const sources = computed(() => new Map(allRows.value.map(row => [row.key, catalogSource(+ state.value?.overlay, row, layerIndexes.value.deployment.get(row.key), layerIndexes.value.builtin.get(row.key),+)])))+const sourceOf = (row: CatalogRow) => sources.value.get(row.key) || 'builtin'+const modifiedCount = computed(() => allRows.value.filter(row => sourceOf(row) === 'console').length)++const filteredRows = computed(() => {+ const keyword = search.value.trim().toLowerCase()+ return allRows.value.filter(row => (!providerFilter.value || row.provider === providerFilter.value)+ && (!typeFilter.value || (row.model.type || 'KnowledgeQA') === typeFilter.value)+ && (!onlyModified.value || sourceOf(row) === 'console')+ && (!keyword || `${row.model.id} ${row.model.match || ''} ${row.model.name || ''}`.toLowerCase().includes(keyword)))+})+watch([search, providerFilter, typeFilter, onlyModified], () => { page.value = 1 })+// Slice pages here instead of relying on t-table's local paging, which keeps+// showing stale rows when the pagination prop toggles off after filtering.+const pageRows = computed(() => filteredRows.value.slice((page.value - 1) * PAGE_SIZE, page.value * PAGE_SIZE))+const pagination = computed(() => ({ current: page.value, pageSize: PAGE_SIZE, total: filteredRows.value.length, showPageSize: false }))++const providerLabel = (id: string) => {+ const provider = state.value?.effective.find(p => p.id === id)+ const names = provider?.settings?.names as Record<string, string> | undefined+ return names?.[String(locale.value)] || provider?.name || id+}+const typeLabel = (type?: string) => {+ const key = TYPE_LABEL_KEYS[type || 'KnowledgeQA']+ return key ? t(`modelSettings.typeShort.${key}`) : type || ''+}+const providerOptions = computed(() => (state.value?.effective || []).map(p => ({ label: providerLabel(p.id), value: p.id })))+const typeOptions = computed(() => [...new Set(allRows.value.map(row => row.model.type || 'KnowledgeQA'))]+ .map(type => ({ label: typeLabel(type), value: type })))++const capabilities = (model: CatalogModel) => [+ ...(model.reasoning ? ['reasoning'] : []),+ ...((model.input as string[] | undefined) || []).filter(kind => ['image', 'audio', 'video'].includes(kind)),+]+const rowClassName = ({ row }: { row: CatalogRow }) => (row.model.deprecated ? 'catalog-row--hidden' : '')++const columns = computed<TableProps['columns']>(() => [+ { colKey: 'model', title: t('modelCatalog.columns.model') },+ { colKey: 'type', title: t('modelCatalog.columns.type'), width: 100 },+ { colKey: 'tokens', title: t('modelCatalog.columns.tokens'), width: 124, align: 'right' },+ { colKey: 'capabilities', title: t('modelCatalog.columns.capabilities'), width: 148 },+ { colKey: 'source', title: t('modelCatalog.columns.source'), width: 108 },+ { colKey: 'actions', title: '', width: 64, align: 'right' },+])++// ---------- 加载与发布 ----------++async function load() {+ loading.value = true+ try {+ state.value = await getModelCatalog()+ loadError.value = ''+ } catch (e: any) {+ loadError.value = e?.message || t('modelCatalog.loadFailed')+ if (state.value) MessagePlugin.error(loadError.value)+ } finally {+ loading.value = false+ }+}++async function handleError(e: any) {+ if (e?.status === 409) {+ MessagePlugin.warning(t('modelCatalog.conflict'))+ await load()+ return+ }+ MessagePlugin.error(e?.message || String(e))+}++// Every edit publishes a whole overlay against the version it was based on;+// a concurrent publish returns 409 and the page reloads instead of merging.+async function commit(overlay: CatalogOverlay, message = t('modelCatalog.published')) {+ if (!state.value) return false+ saving.value = true+ try {+ state.value = await publishModelCatalog({ version: state.value.version, baseline: state.value.baseline, overlay })+ providersStore.reset()+ // Model responses contain resolved catalog capabilities as well.+ chatResources.invalidate('models')+ MessagePlugin.success(message)+ return true+ } catch (e: any) {+ await handleError(e)+ return false+ } finally {+ saving.value = false+ }+}++// ---------- 编辑单个模型 ----------++const CHAT = ['KnowledgeQA']+const fieldDefs = computed<FieldDef[]>(() => [+ { key: 'name', kind: 'text', label: t('modelCatalog.displayName'), desc: t('modelCatalog.nameDesc') },+ { key: 'context_window', kind: 'tokens', label: t('modelCatalog.context'), desc: t('modelCatalog.contextDesc') },+ { key: 'max_output_tokens', kind: 'tokens', label: t('modelCatalog.output'), desc: t('modelCatalog.outputDesc'), types: CHAT },+ { key: 'dimension', kind: 'number', label: t('modelCatalog.dimension'), desc: t('modelCatalog.dimensionDesc'), types: ['Embedding'] },+ { key: 'input', kind: 'modalities', label: t('modelCatalog.inputModes'), desc: t('modelCatalog.inputDesc'), types: CHAT },+ { key: 'reasoning', kind: 'bool', label: t('modelCatalog.reasoning'), desc: t('modelCatalog.reasoningDesc'), types: CHAT },+ { key: 'thinking_levels', kind: 'levels', label: t('modelCatalog.thinkingLevels'), desc: t('modelCatalog.thinkingLevelsDesc'), types: CHAT },+ { key: 'deprecated', kind: 'bool', label: t('modelCatalog.hide'), desc: t('modelCatalog.hideDesc') },+])+const fieldsFor = (type?: string) => fieldDefs.value.filter(field => !field.types || field.types.includes(type || 'KnowledgeQA'))+const editFields = computed(() => fieldsFor(selected.value?.model.type))+const levelOptions = computed(() => THINKING_LEVELS.map(level => ({ label: t(levelLabelKey(level)), value: level })))++const editVisible = ref(false)+const selected = ref<CatalogRow>()+const form = reactive<Record<FieldKey, any>>({+ name: '', context_window: undefined, max_output_tokens: undefined, dimension: undefined,+ input: [], reasoning: false, thinking_levels: [], deprecated: false,+})++// Values the model falls back to without an administrator override. Models+// added from this page have no lower layer, so there is nothing to restore.+const selectedInherited = computed(() => selected.value ? layerIndexes.value.deployment.get(selected.value.key) : undefined)+const selectedOverride = computed(() => {+ const row = selected.value, p = row && state.value?.overlay.providers[row.provider]+ if (!row || !p) return {}+ const id = row.model.id.toLowerCase(), type = row.model.type || 'KnowledgeQA'+ const entry = (p.models || []).find((m: CatalogModel) => m.id?.toLowerCase() === id && (!m.type || m.type === type))+ const extra = Object.entries(p.model_overrides || {}).find(([key]) => key.toLowerCase() === id)?.[1]+ return { ...(extra as object || {}), ...(entry || {}) } as Record<string, unknown>+})+const isOverridden = (key: FieldKey) => selectedOverride.value[key] !== undefined++const providerIn = (layer: Layer, id: string) => state.value?.[layer].find(p => p.id === id)+const kindOf = (key: FieldKey) => fieldDefs.value.find(f => f.key === key)!.kind+function normalize(kind: FieldKind, value: unknown) {+ if (kind === 'bool') return !!value+ if (kind === 'text') return String(value ?? '').trim() || undefined+ if (kind === 'modalities' || kind === 'levels') return [...(value as string[] | undefined || [])]+ return value || undefined+}+const sameValue = (kind: FieldKind, a: unknown, b: unknown) => (kind === 'modalities' || kind === 'levels')+ ? sameMembers(a as string[], b as string[]) : a === b++// Reads a field from one catalog layer in the shape the form edits. Thinking+// levels come from the server's resolution, since they merge the vendor map.+function fieldValue(layer: Layer, row: CatalogRow, key: FieldKey) {+ const model = layerIndexes.value[layer].get(row.key)+ if (!model) return undefined+ if (key === 'thinking_levels') return [...(providerIn(layer, row.provider)?.model_thinking_levels?.[row.model.id] || [])]+ if (key === 'input') return ((model.input as string[] | undefined) || []).filter(m => (EDITABLE_INPUTS as readonly string[]).includes(m))+ return normalize(kindOf(key), model[key])+}++const levelsAvailable = computed(() => {+ const row = selected.value+ if (!row) return false+ return ((fieldValue('effective', row, 'thinking_levels') as string[] | undefined)?.length || 0) > 0+ || (providerIn('effective', row.provider)?.vendor_thinking_levels?.length || 0) > 0+})++const editDirty = computed(() => {+ const row = selected.value+ return !!row && editFields.value.some(({ key, kind }) =>+ !sameValue(kind, normalize(kind, form[key]), fieldValue('effective', row, key)))+})++function openEdit(row: CatalogRow) {+ selected.value = row+ for (const { key, kind } of fieldDefs.value) form[key] = fieldValue('effective', row, key) ?? normalize(kind, undefined)+ form.name = form.name || ''+ editVisible.value = true+}++async function saveEdit() {+ const row = selected.value+ if (!row || !state.value || !editDirty.value) return+ const inherited = !!selectedInherited.value+ const vendor = providerIn('effective', row.provider)+ const patch: Record<string, unknown> = {}+ for (const { key, kind } of editFields.value) {+ const value = normalize(kind, form[key])+ if (sameValue(kind, value, fieldValue('effective', row, key))) continue+ if (key === 'thinking_levels') {+ // Levels only matter while reasoning is on; leave them alone otherwise.+ if (!form.reasoning) continue+ const base = inherited ? fieldValue('deployment', row, key) as string[] : vendor?.vendor_thinking_levels || []+ patch[key] = thinkingLevelsPatch(value as string[], base,+ selectedOverride.value.thinking_levels as Record<string, string | null> | undefined,+ vendor?.settings?.thinking_levels as Record<string, string | null> | undefined)+ continue+ }+ // Choosing the inherited value again drops the override instead of pinning it.+ if (inherited && sameValue(kind, value, fieldValue('deployment', row, key))) {+ patch[key] = undefined+ continue+ }+ patch[key] = key === 'input' ? composeInput(row.model.input as string[] | undefined, value as string[]) : value+ }+ if (await commit(patchCatalogModel(state.value.overlay, row.provider, row.model, patch))) editVisible.value = false+}++async function restoreSelected() {+ const row = selected.value+ if (!row || !state.value) return+ const message = t(selectedInherited.value ? 'modelCatalog.restored' : 'modelCatalog.removed')+ if (await commit(removeCatalogModelOverride(state.value.overlay, row.provider, row.model), message)) editVisible.value = false+}++function displayField(kind: FieldKind, value: unknown) {+ if (kind === 'modalities') {+ const extras = value as string[] | undefined+ return extras?.length ? extras.map(m => t(`modelCatalog.capability.${m}`)).join('、') : t('modelCatalog.textOnly')+ }+ if (kind === 'levels') {+ const levels = value as string[] | undefined+ return levels?.length ? levels.map(level => t(levelLabelKey(level))).join('、') : t('modelCatalog.noLevels')+ }+ if (value === undefined || value === null || value === '') return t('modelCatalog.notSet')+ if (kind === 'bool') return t(value ? 'modelCatalog.yes' : 'modelCatalog.no')+ if (kind === 'tokens') return formatTokens(value as number)+ return String(value)+}+function layerValue(layer: Layer, field: FieldDef) {+ if (!selected.value || !layerIndexes.value[layer].get(selected.value.key)) return '—'+ return displayField(field.kind, fieldValue(layer, selected.value, field.key))+}++// ---------- 添加模型 ----------++const addVisible = ref(false)+const emptyAddForm = () => ({+ provider: providerFilter.value || '', type: typeFilter.value || 'KnowledgeQA', id: '', name: '',+ context_window: undefined, max_output_tokens: undefined, dimension: undefined, input: [] as string[], reasoning: false,+})+const addForm = reactive<Record<string, any>>(emptyAddForm())+// Levels start from the vendor defaults and are tuned after the model exists.+const addFields = computed(() => fieldsFor(addForm.type).filter(field => field.key !== 'deprecated' && field.key !== 'thinking_levels'))+// VLM eligibility is derived from a chat model's input modalities, so the+// catalog has no separate VLLM entries to add.+const addTypeOptions = computed(() => {+ const provider = state.value?.effective.find(p => p.id === addForm.provider)+ if (!provider) return typeOptions.value+ return provider.model_types.filter(kind => kind !== 'VLLM').map(kind => ({ label: typeLabel(kind), value: kind }))+})+watch(() => addForm.provider, () => {+ if (!addTypeOptions.value.some(option => option.value === addForm.type)) addForm.type = addTypeOptions.value[0]?.value || 'KnowledgeQA'+})++function openAdd() {+ Object.assign(addForm, emptyAddForm())+ addVisible.value = true+}++async function saveAdd() {+ const id = addForm.id.trim()+ if (!state.value || !addForm.provider || !id) {+ MessagePlugin.warning(t('modelCatalog.required'))+ return+ }+ const key = `${addForm.provider}:${addForm.type}:`+ if (allRows.value.some(row => row.key.toLowerCase() === (key + id).toLowerCase())) {+ MessagePlugin.warning(t('modelCatalog.exists'))+ return+ }+ const fields: Record<string, unknown> = { deprecated: false }+ for (const { key, kind } of addFields.value) {+ const value = normalize(kind, addForm[key])+ fields[key] = key === 'input' ? ((value as string[]).length ? composeInput(undefined, value as string[]) : undefined) : value+ }+ const overlay = patchCatalogModel(state.value.overlay, addForm.provider, { id, type: addForm.type }, fields)+ if (await commit(overlay)) {+ addVisible.value = false+ providerFilter.value = addForm.provider+ search.value = id+ }+}++// ---------- JSON 编辑 ----------++const jsonVisible = ref(false)+const draft = ref(emptyOverlay)+const jsonError = ref('')+const jsonPreview = ref<CatalogPreview>()+const jsonChanges = computed<CatalogChangeSummary[]>(() => jsonPreview.value+ ? summarizeChanges(catalogChanges(state.value?.effective || [], jsonPreview.value.effective)) : [])+watch(draft, () => { jsonPreview.value = undefined; jsonError.value = '' })++function openJson(text?: string) {+ draft.value = text ?? stableJSON(state.value?.overlay || { providers: {} })+ jsonVisible.value = true+}++function parseDraft(): CatalogOverlay {+ const value = JSON.parse(draft.value)+ if (!value || typeof value !== 'object' || !value.providers || typeof value.providers !== 'object' || Array.isArray(value.providers)) {+ throw new Error(t('modelCatalog.invalid'))+ }+ return value+}++// First click validates on the server and lists the resulting changes; the+// second click publishes exactly the overlay that was checked.+async function confirmJson() {+ if (!state.value) return+ if (jsonPreview.value) {+ if (await commit(jsonPreview.value.overlay)) jsonVisible.value = false+ return+ }+ let overlay: CatalogOverlay+ try {+ overlay = parseDraft()+ } catch (e: any) {+ jsonError.value = e?.message || String(e)+ return+ }+ const text = draft.value+ saving.value = true+ try {+ const candidate = await previewModelCatalog({ version: state.value.version, baseline: state.value.baseline, overlay })+ if (draft.value === text) jsonPreview.value = candidate+ } catch (e: any) {+ if (e?.status === 409) await handleError(e)+ else jsonError.value = e?.message || String(e)+ } finally {+ saving.value = false+ }+}++const changeTheme = (kind: CatalogChangeSummary['kind']) => (+ { added: 'success', removed: 'danger', updated: 'primary', provider: 'warning' } as const)[kind]+const fieldLabel = (field: string) => {+ const def = fieldDefs.value.find(f => f.key === field)+ return def ? def.label : field+}++async function importOverlay(event: Event) {+ const input = event.target as HTMLInputElement+ const file = input.files?.[0]+ input.value = ''+ if (!file) return+ if (file.size > 1024 * 1024) {+ MessagePlugin.warning(t('modelCatalog.tooLarge'))+ return+ }+ try {+ openJson(stableJSON(JSON.parse(await file.text())))+ } catch (e: any) {+ MessagePlugin.error(e?.message || String(e))+ }+}++function exportOverlay() {+ const url = URL.createObjectURL(new Blob([stableJSON(state.value?.overlay || { providers: {} }) + '\n'], { type: 'application/json' }))+ const a = document.createElement('a')+ a.href = url+ a.download = 'models.json'+ a.click()+ URL.revokeObjectURL(url)+}++// ---------- 版本历史 ----------++const historyVisible = ref(false)++const overrideSummary = (overlay: CatalogOverlay) => {+ const count = Object.values(overlay?.providers || {}).reduce((sum, p: any) =>+ sum + (p.models?.length || 0) + Object.keys(p.model_overrides || {}).length, 0)+ return count ? t('modelCatalog.historyModels', { count }) : t('modelCatalog.historyNoOverrides')+}++function formatDate(value?: string) {+ if (!value) return '—'+ const date = new Date(value)+ const pad = (part: number) => String(part).padStart(2, '0')+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`+}++async function restoreRevision(overlay: CatalogOverlay) {+ if (await commit(overlay, t('modelCatalog.restored'))) historyVisible.value = false+}++// ---------- 更多菜单 ----------++const moreOptions = computed(() => [+ { content: t('modelCatalog.jsonEditor'), value: 'json' },+ { content: t('modelCatalog.history'), value: 'history', divider: true },+ { content: t('modelCatalog.import'), value: 'import' },+ { content: t('modelCatalog.export'), value: 'export' },+])++function onMore(data: { value?: string | number }) {+ if (data.value === 'json') openJson()+ else if (data.value === 'history') historyVisible.value = true+ else if (data.value === 'import') fileInput.value?.click()+ else if (data.value === 'export') exportOverlay()+}++onMounted(load)+</script>++<style lang="less" scoped>+@import (reference) '@/components/css/settings-section.less';++.model-catalog {+ width: 100%;+}++.section-header {+ .settings-section-header();+}++.section-header__main {+ min-width: 0;+}++.section-header__titlewrap {+ display: flex;+ align-items: center;+ gap: 6px;++ h2 {+ margin-bottom: 0;+ }+}++.section-header__titlewrap + .section-description {+ margin-top: 8px;+}++.section-header__actions {+ display: flex;+ align-items: center;+ gap: 16px;+ flex-shrink: 0;+}++.header-action {+ --td-bg-color-container-hover: transparent;+ padding-left: 0;+ padding-right: 0;+ font-weight: 600;+}++.header-action--muted {+ color: var(--td-text-color-secondary);++ &:hover:not(:disabled) {+ color: var(--td-brand-color);+ }+}++.hint-trigger {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 2px;+ border: none;+ border-radius: var(--app-radius-xs);+ background: transparent;+ color: var(--td-text-color-placeholder);+ cursor: help;+ line-height: 1;++ &:hover,+ &:focus-visible {+ color: var(--td-brand-color);+ }+}++.hint-popover {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.hint-popover__title {+ margin: 0;+ color: var(--td-text-color-primary);+ font-size: var(--app-text-md);+ font-weight: 600;+}++.hint-popover__list {+ margin: 0;+ padding: 0 0 0 18px;+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-sm);+ line-height: 1.6;++ li + li {+ margin-top: 4px;+ }+}++.catalog-alert {+ margin-bottom: 16px;+}++.catalog-state {+ min-height: 160px;+}++.catalog-state--loading {+ display: flex;+ align-items: center;+ justify-content: center;+}++.catalog-toolbar {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 12px;+ margin-bottom: 16px;+}++.catalog-toolbar__search {+ width: 200px;+}++.catalog-toolbar__select {+ width: 160px;+}++.catalog-toolbar__select--type {+ width: 116px;+}++.catalog-toolbar__count {+ margin-left: 4px;+ color: var(--td-brand-color);+ font-weight: 600;+}++.catalog-toolbar__meta {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin-left: auto;+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ white-space: nowrap;+}++.catalog-refresh {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ padding: 0;+ border: none;+ border-radius: var(--app-radius-sm);+ background: transparent;+ color: var(--td-text-color-placeholder);+ cursor: pointer;+ transition: color var(--app-motion-base) ease, background var(--app-motion-base) ease;++ &:hover:not(:disabled) {+ color: var(--td-brand-color);+ background: var(--td-bg-color-secondarycontainer);+ }++ &:disabled {+ cursor: default;+ opacity: 0.7;+ }+}++.catalog-refresh--spin {+ animation: wk-spin 0.8s linear infinite;+}++.data-table-shell {+ overflow-x: auto;+ border: 1px solid var(--td-component-stroke);+ border-radius: var(--app-radius-lg);+ background-color: var(--td-bg-color-container);++ &:deep(thead th) {+ background-color: var(--td-bg-color-secondarycontainer);+ font-size: var(--app-text-md);+ font-weight: 600;+ }++ &:deep(.t-table td),+ &:deep(.t-table th) {+ padding-top: 12px;+ padding-bottom: 12px;+ vertical-align: middle;+ }++ &:deep(.t-table__pagination) {+ padding: 12px 16px;+ }+}++.catalog-table-shell {+ &:deep(.t-table tbody tr) {+ cursor: pointer;+ }++ &--single-page :deep(.t-table__pagination) {+ display: none;+ }++ &:deep(.catalog-row--hidden td) {+ color: var(--td-text-color-placeholder);+ }+}++.catalog-model {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.catalog-model__id {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ min-width: 0;++ code {+ color: var(--td-text-color-primary);+ font-family: var(--app-font-family-mono);+ font-size: var(--app-text-md);+ font-weight: 500;+ overflow-wrap: anywhere;+ }+}++.catalog-row--hidden .catalog-model__id code {+ color: var(--td-text-color-placeholder);+}++.catalog-model__name {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ line-height: 1.4;+}++.catalog-cell-text {+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-md);+}++.catalog-num {+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-md);+ font-variant-numeric: tabular-nums;+}++.catalog-caps {+ display: flex;+ flex-wrap: wrap;+ gap: 4px;+}++.catalog-cap {+ display: inline-flex;+ align-items: center;+ height: 20px;+ padding: 0 6px;+ border-radius: var(--app-radius-xs);+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-xs);+ line-height: 20px;+ white-space: nowrap;+}++.catalog-muted {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ font-weight: 400;+}++// ---------- 抽屉内容 ----------++.drawer-hint {+ margin: 0;+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ line-height: 1.5;+}++.drawer-row {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ padding: 12px 0;+ border-top: 1px solid var(--td-component-stroke);+}++.drawer-row__info {+ flex: 1;+ min-width: 0;+}++.drawer-row__label {+ display: flex;+ align-items: center;+ gap: 6px;+ color: var(--td-text-color-primary);+ font-size: var(--app-text-base);+ font-weight: 500;+ line-height: 1.4;+}++.drawer-row__desc,+.drawer-row__inherited {+ margin: 2px 0 0;+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-sm);+ line-height: 1.5;+}++.drawer-row__inherited {+ color: var(--td-text-color-placeholder);+}++.drawer-row__control {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ flex-shrink: 0;+ min-height: 32px;+}++.drawer-row--stacked {+ flex-direction: column;+ gap: 10px;++ .drawer-row__control {+ justify-content: flex-start;+ flex-direction: column;+ align-items: flex-start;+ gap: 6px;+ }+}++.drawer-levels {+ flex-wrap: wrap;+ row-gap: 8px;+}++.drawer-link {+ display: inline-flex;+ align-items: center;+ gap: 2px;+ margin-left: 4px;+ color: var(--td-brand-color);+ text-decoration: none;++ &:hover {+ color: var(--td-brand-color-hover);+ }+}++.drawer-field {+ display: flex;+ flex-direction: column;+ gap: 8px;++ label {+ color: var(--td-text-color-primary);+ font-size: var(--app-text-base);+ font-weight: 500;+ }+}++.layer-table {+ width: 100%;+ border-collapse: collapse;+ font-size: var(--app-text-sm);++ th,+ td {+ padding: 8px 10px;+ border-bottom: 1px solid var(--td-component-stroke);+ text-align: left;+ overflow-wrap: anywhere;+ }++ th {+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-text-color-secondary);+ font-weight: 500;+ }++ td {+ color: var(--td-text-color-secondary);+ }++ td:first-child {+ color: var(--td-text-color-primary);+ }++ td.layer-table__changed {+ color: var(--td-brand-color);+ font-weight: 500;+ }+}++.json-editor :deep(textarea) {+ font-family: var(--app-font-family-mono);+ font-size: var(--app-text-sm);+ line-height: 1.6;+}++.change-list {+ display: flex;+ flex-direction: column;+ margin: 0;+ padding: 0;+ list-style: none;+ border: 1px solid var(--td-component-stroke);+ border-radius: var(--app-radius-md);+}++.change-list__item {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 8px;+ padding: 8px 12px;+ font-size: var(--app-text-sm);++ & + & {+ border-top: 1px solid var(--td-component-stroke);+ }+}++.change-list__target {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;++ code {+ color: var(--td-text-color-primary);+ font-family: var(--app-font-family-mono);+ overflow-wrap: anywhere;+ }+}++.change-list__fields {+ color: var(--td-text-color-secondary);+}++.history-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 10px 0;+ border-top: 1px solid var(--td-component-stroke);++ &:first-child {+ border-top: none;+ padding-top: 0;+ }+}++.history-row__main,+.history-row__side {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+}++.history-row__main {+ flex-wrap: wrap;+}++.history-row__version {+ color: var(--td-text-color-primary);+ font-size: var(--app-text-md);+ font-weight: 500;+}++.history-row__meta {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+}+</style>diff --git a/frontend/src/views/system/ModelCatalogFieldControl.vue b/frontend/src/views/system/ModelCatalogFieldControl.vuenew file mode 100644index 000000000..9fa12bf58--- /dev/null+++ b/frontend/src/views/system/ModelCatalogFieldControl.vue@@ -0,0 +1,30 @@+<template>+ <t-input v-if="kind === 'text'" :model-value="modelValue" :placeholder="placeholder" class="field-control--text"+ @update:model-value="emit('update:modelValue', $event)" />+ <t-input-number v-else-if="kind === 'tokens' || kind === 'number'" :model-value="modelValue" theme="normal" :min="0"+ :placeholder="placeholder" class="field-control--number" @update:model-value="emit('update:modelValue', $event)" />+ <t-switch v-else-if="kind === 'bool'" :model-value="modelValue" @update:model-value="emit('update:modelValue', $event)" />+ <t-checkbox-group v-else-if="kind === 'modalities'" :model-value="modelValue" :options="modalityOptions"+ @update:model-value="emit('update:modelValue', $event)" />+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { EDITABLE_INPUTS, type FieldKind } from './modelCatalogState'++defineProps<{ kind: FieldKind; modelValue: any; placeholder?: string }>()+const emit = defineEmits<{ 'update:modelValue': [value: any] }>()+const { t } = useI18n()+const modalityOptions = computed(() => EDITABLE_INPUTS.map(value => ({ label: t(`modelCatalog.capability.${value}`), value })))+</script>++<style lang="less" scoped>+.field-control--text {+ width: 200px;+}++.field-control--number {+ width: 160px;+}+</style>diff --git a/frontend/src/views/system/modelCatalogState.test.ts b/frontend/src/views/system/modelCatalogState.test.tsnew file mode 100644index 000000000..2394afe9e--- /dev/null+++ b/frontend/src/views/system/modelCatalogState.test.ts@@ -0,0 +1,75 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { reactive } from 'vue'+import { catalogChanges, catalogRows, catalogSource, composeInput, formatTokens, hasModelOverride, patchCatalogModel, removeCatalogModelOverride, sameMembers, summarizeChanges, thinkingLevelsPatch } from './modelCatalogState'+import type { CatalogOverlay, CatalogProvider } from '@/api/system/modelCatalog'++test('form edits remove higher-precedence fields without losing unrelated overrides', () => {+ const overlay: CatalogOverlay = { providers: { openai: {+ models: [{ id: 'shared', type: 'KnowledgeQA', reasoning: true }, { id: 'shared', type: 'Embedding', dimension: 1024 }],+ model_overrides: { shared: { context_window: 123, compat: { supports_temperature: false } } },+ } } }+ const next = patchCatalogModel(overlay, 'openai', { id: 'shared', type: 'KnowledgeQA' }, { context_window: 456 })+ assert.equal(next.providers.openai.models[0].context_window, 456)+ assert.equal(next.providers.openai.models[0].reasoning, true)+ assert.equal(next.providers.openai.models[1].dimension, 1024)+ assert.deepEqual(next.providers.openai.model_overrides.shared, { compat: { supports_temperature: false } })+ assert.equal(overlay.providers.openai.model_overrides.shared.context_window, 123)+})+test('restore removes only the selected type and preserves unrelated models', () => {+ const overlay: CatalogOverlay = { providers: { openai: { models: [+ { id: 'same', type: 'KnowledgeQA', reasoning: false }, { id: 'same', type: 'Embedding', dimension: 1024 },+ ] } } }+ const next = removeCatalogModelOverride(overlay, 'openai', { id: 'same', type: 'KnowledgeQA' })+ assert.deepEqual(next.providers.openai.models, [{ id: 'same', type: 'Embedding', dimension: 1024 }])+})+test('diff identifies removed models, changed fields, and provider changes', () => {+ const before: CatalogProvider[] = [{ id: 'lab', name: 'Lab', api: 'openai-completions', model_types: ['KnowledgeQA'], models: [+ { id: 'first', context_window: 100 }, { id: 'removed' },+ ] }]+ const after = structuredClone(before)+ after[0]!.api = 'openai-responses'+ after[0]!.models = [{ id: 'first', context_window: 200 }]+ assert.deepEqual(catalogChanges(before, after).map(c => c.key), ['lab', 'lab:KnowledgeQA:first', 'lab:KnowledgeQA:removed'])+ assert.equal(catalogRows(before).length, 2)+})+test('source prefers administrator overrides, then deployment differences', () => {+ const row = { key: 'p:KnowledgeQA:m', provider: 'p', model: { id: 'm', context_window: 2 } }+ const overlay: CatalogOverlay = { providers: { p: { models: [{ id: 'M', context_window: 2 }] } } }+ assert.equal(catalogSource(overlay, row, { id: 'm', context_window: 1 }, { id: 'm', context_window: 1 }), 'console')+ assert.equal(catalogSource({ providers: {} }, row, { id: 'm', context_window: 2 }, { id: 'm', context_window: 1 }), 'deployment')+ assert.equal(catalogSource({ providers: {} }, row, { id: 'm', context_window: 2 }, { id: 'm', context_window: 2 }), 'builtin')+ assert.equal(hasModelOverride(overlay, 'p', { id: 'm', type: 'Embedding' }), true)+ assert.equal(hasModelOverride(overlay, 'p', { id: 'other' }), false)+})+test('token counts use vendor-style units', () => {+ assert.deepEqual([131072, 128000, 1048576, 1000000, 32769, undefined].map(formatTokens), ['128K', '128K', '1M', '1M', '32,769', ''])+})+test('change summaries name the model and the fields that changed', () => {+ assert.deepEqual(summarizeChanges([+ { key: 'lab', before: { api: 'a' }, after: { api: 'b' } },+ { key: 'lab:KnowledgeQA:org/x:1', before: { id: 'org/x:1', reasoning: false }, after: { id: 'org/x:1', reasoning: true } },+ { key: 'lab:Embedding:new', before: undefined, after: { id: 'new' } },+ ]), [+ { key: 'lab', provider: 'lab', target: 'lab', kind: 'provider', fields: ['api'] },+ { key: 'lab:KnowledgeQA:org/x:1', provider: 'lab', target: 'org/x:1', kind: 'updated', fields: ['reasoning'] },+ { key: 'lab:Embedding:new', provider: 'lab', target: 'new', kind: 'added', fields: [] },+ ])+})+test('edits accept the reactive overlay held by the page', () => {+ const overlay = reactive<CatalogOverlay>({ providers: { p: { models: [{ id: 'm', reasoning: true }] } } })+ assert.equal(patchCatalogModel(overlay, 'p', { id: 'm' }, { context_window: 1 }).providers.p.models[0].context_window, 1)+ assert.deepEqual(removeCatalogModelOverride(overlay, 'p', { id: 'm' }).providers.p.models, [])+})+test('input edits keep text and unknown modalities', () => {+ assert.deepEqual(composeInput(undefined, ['image']), ['text', 'image'])+ assert.deepEqual(composeInput(['text', 'image', 'pdf'], ['video']), ['text', 'pdf', 'video'])+ assert.equal(sameMembers(['a', 'b'], ['b', 'a']), true)+})+test('thinking level patches only record differences from the inherited levels', () => {+ const inherited = ['off', 'auto', 'minimal', 'low', 'medium', 'high']+ assert.equal(thinkingLevelsPatch(inherited, inherited, undefined, undefined), undefined)+ assert.deepEqual(thinkingLevelsPatch(['auto', 'low', 'medium', 'high', 'max'], inherited, undefined, { max: 'xhigh' }),+ { off: null, minimal: null, max: 'xhigh' })+ assert.deepEqual(thinkingLevelsPatch(inherited, inherited, { high: 'deep', low: null }, undefined), { high: 'deep' })+})diff --git a/frontend/src/views/system/modelCatalogState.ts b/frontend/src/views/system/modelCatalogState.tsnew file mode 100644index 000000000..0190faa1d--- /dev/null+++ b/frontend/src/views/system/modelCatalogState.ts@@ -0,0 +1,128 @@+import type { CatalogModel, CatalogOverlay, CatalogProvider } from '@/api/system/modelCatalog'++export const modelIdentity = (model: CatalogModel) => `${model.type || 'KnowledgeQA'}:${model.id || model.match || ''}`+export interface CatalogRow { key: string; provider: string; model: CatalogModel }+export function catalogRows(providers: CatalogProvider[]): CatalogRow[] {+ return providers.flatMap(provider => (provider.models || []).map(model => ({+ key: `${provider.id}:${modelIdentity(model)}`, provider: provider.id, model,+ })))+}+export function stableJSON(value: unknown): string {+ return JSON.stringify(value, (_, v) => v && typeof v === 'object' && !Array.isArray(v)+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b))) : v, 2)+}+export function catalogChanges(before: CatalogProvider[], after: CatalogProvider[]) {+ const flatten = (providers: CatalogProvider[]) => new Map<string, unknown>(providers.flatMap(p => [+ [p.id, { name: p.name, api: p.api, model_types: p.model_types, settings: p.settings }] as const,+ ...catalogRows([p]).map(row => [row.key, row.model] as const),+ ]))+ const old = flatten(before), next = flatten(after)+ return [...new Set([...old.keys(), ...next.keys()])].sort().flatMap(key => {+ const a = old.get(key), b = next.get(key)+ return stableJSON(a) === stableJSON(b) ? [] : [{ key, before: a, after: b }]+ })+}++// Overlays are plain JSON; a JSON round trip also unwraps Vue reactive+// proxies, which structuredClone rejects.+const cloneOverlay = (overlay: CatalogOverlay): CatalogOverlay => JSON.parse(JSON.stringify(overlay))++// Both overlay forms are supported. A form edit must also remove the same+// fields from model_overrides, which otherwise wins later during resolution.+export function patchCatalogModel(overlay: CatalogOverlay, provider: string, model: CatalogModel, patch: Record<string, unknown>) {+ const next = cloneOverlay(overlay)+ const p = next.providers[provider] ||= {}+ const entries: CatalogModel[] = p.models ||= []+ const type = model.type || 'KnowledgeQA'+ let entry = entries.find(m => m.id.toLowerCase() === model.id.toLowerCase() && (!m.type || m.type === type))+ if (!entry) { entry = { id: model.id, type }; entries.push(entry) }+ for (const [field, value] of Object.entries(patch)) {+ if (value === undefined) delete entry[field]+ else entry[field] = value+ for (const [id, override] of Object.entries(p.model_overrides || {})) {+ if (id.toLowerCase() === model.id.toLowerCase()) delete (override as Record<string, unknown>)[field]+ }+ }+ p.models = entries.filter(m => Object.keys(m).some(k => k !== 'id' && k !== 'type'))+ return next+}++export function removeCatalogModelOverride(overlay: CatalogOverlay, provider: string, model: CatalogModel) {+ const next = cloneOverlay(overlay)+ const p = next.providers[provider]+ if (!p) return next+ p.models = (p.models || []).filter((m: CatalogModel) => !(m.id.toLowerCase() === model.id.toLowerCase() && (!m.type || m.type === (model.type || 'KnowledgeQA'))))+ for (const id of Object.keys(p.model_overrides || {})) {+ if (id.toLowerCase() === model.id.toLowerCase()) delete p.model_overrides[id]+ }+ return next+}++// True when the console overlay mentions this model in either overlay form.+export function hasModelOverride(overlay: CatalogOverlay | undefined, provider: string, model: CatalogModel) {+ const p = overlay?.providers[provider]+ if (!p || !model.id) return false+ const id = model.id.toLowerCase(), type = model.type || 'KnowledgeQA'+ return (p.models || []).some((m: CatalogModel) => m.id?.toLowerCase() === id && (!m.type || m.type === type))+ || Object.keys(p.model_overrides || {}).some(key => key.toLowerCase() === id)+}++export type CatalogSource = 'console' | 'deployment' | 'builtin'+// The layer that last changed the effective entry; admins care about their+// own overrides first, then whether a deployment file shadows the built-in.+export function catalogSource(overlay: CatalogOverlay | undefined, row: CatalogRow,+ deployment: CatalogModel | undefined, builtin: CatalogModel | undefined): CatalogSource {+ if (hasModelOverride(overlay, row.provider, row.model) || stableJSON(deployment) !== stableJSON(row.model)) return 'console'+ return stableJSON(builtin) !== stableJSON(row.model) ? 'deployment' : 'builtin'+}++// Token counts are usually powers of two or round thousands; show them the+// way vendors publish them (128K, 1M) and fall back to grouped digits.+export function formatTokens(value?: number) {+ if (!value) return ''+ for (const [unit, size] of [['M', 1000000], ['M', 1048576], ['K', 1000], ['K', 1024]] as const) {+ if (value >= size && value % size === 0) return `${value / size}${unit}`+ }+ return value.toLocaleString('en-US')+}++export interface CatalogChangeSummary { key: string; provider: string; target: string; kind: 'added' | 'removed' | 'updated' | 'provider'; fields: string[] }+export function summarizeChanges(changes: ReturnType<typeof catalogChanges>): CatalogChangeSummary[] {+ return changes.map(({ key, before, after }) => {+ const [provider = key, type, ...id] = key.split(':')+ const fields = [...new Set([...Object.keys(before || {}), ...Object.keys(after || {})])].filter(field =>+ stableJSON((before as Record<string, unknown> | undefined)?.[field]) !== stableJSON((after as Record<string, unknown> | undefined)?.[field])).sort()+ if (!type) return { key, provider, target: provider, kind: 'provider', fields }+ const target = id.join(':') || type+ return { key, provider, target, kind: !before ? 'added' : !after ? 'removed' : 'updated', fields: before && after ? fields : [] }+ })+}++export type FieldKind = 'text' | 'tokens' | 'number' | 'bool' | 'modalities' | 'levels'++// Modalities the console edits; text is implied for chat models and any+// other value from the deployment file is kept as-is.+export const EDITABLE_INPUTS = ['image', 'audio', 'video'] as const+export function composeInput(current: string[] | undefined, extras: string[]) {+ const kept = (current?.length ? current : ['text']).filter(m => !(EDITABLE_INPUTS as readonly string[]).includes(m))+ return [...kept, ...EDITABLE_INPUTS.filter(m => extras.includes(m))]+}+export const sameMembers = (a: readonly string[] = [], b: readonly string[] = []) =>+ a.length === b.length && a.every(item => b.includes(item))++export const THINKING_LEVELS = ['off', 'auto', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const++// Builds the model's thinking_levels overlay from the levels an admin wants.+// Keys agreeing with the inherited resolution are dropped so vendor changes+// keep flowing through; a re-enabled level reuses the vendor's wire value,+// and custom values written in the JSON editor survive while still enabled.+export function thinkingLevelsPatch(selected: readonly string[], inherited: readonly string[],+ current: Record<string, string | null> | undefined, vendorMap: Record<string, string | null> | undefined) {+ const out: Record<string, string | null> = {}+ for (const level of THINKING_LEVELS) {+ const want = selected.includes(level)+ if (want && typeof current?.[level] === 'string') out[level] = current[level]!+ else if (want !== inherited.includes(level)) out[level] = want ? (typeof vendorMap?.[level] === 'string' ? vendorMap[level]! : level) : null+ }+ return Object.keys(out).length ? out : undefined+}diff --git a/internal/application/repository/model_catalog_config.go b/internal/application/repository/model_catalog_config.gonew file mode 100644index 000000000..2e585a0a6--- /dev/null+++ b/internal/application/repository/model_catalog_config.go@@ -0,0 +1,51 @@+package repository++import (+ "context"+ "errors"++ "github.com/Tencent/WeKnora/internal/types"+ "gorm.io/gorm"+)++// ErrCatalogVersionConflict reports a publish based on a stale version.+var ErrCatalogVersionConflict = errors.New("model catalog changed; reload and preview again")++// ModelCatalogRepository stores the singleton console overlay row.+type ModelCatalogRepository struct{ db *gorm.DB }++// NewModelCatalogRepository creates a repository on db.+func NewModelCatalogRepository(db *gorm.DB) *ModelCatalogRepository {+ return &ModelCatalogRepository{db: db}+}++// Get loads the overlay row, including its bounded history.+func (r *ModelCatalogRepository) Get(ctx context.Context) (*types.ModelCatalogConfig, error) {+ var row types.ModelCatalogConfig+ err := r.db.WithContext(ctx).First(&row, 1).Error+ return &row, err+}++// Save replaces the row only if it is still at the expected version.+func (r *ModelCatalogRepository) Save(ctx context.Context, expected uint64, row *types.ModelCatalogConfig) error {+ result := r.db.WithContext(ctx).Model(&types.ModelCatalogConfig{}).+ Where("id = ? AND version = ?", 1, expected).+ Updates(map[string]any{+ "version": row.Version, "overlay": row.Overlay,+ "history": row.History, "updated_by": row.UpdatedBy, "updated_at": row.UpdatedAt,+ })+ if result.Error != nil {+ return result.Error+ }+ if result.RowsAffected != 1 {+ return ErrCatalogVersionConflict+ }+ return nil+}++// Version avoids transferring the bounded configuration history on every poll.+func (r *ModelCatalogRepository) Version(ctx context.Context) (uint64, error) {+ var row types.ModelCatalogConfig+ err := r.db.WithContext(ctx).Select("version").First(&row, 1).Error+ return row.Version, err+}diff --git a/internal/application/service/model_catalog.go b/internal/application/service/model_catalog.gonew file mode 100644index 000000000..a3d06d07a--- /dev/null+++ b/internal/application/service/model_catalog.go@@ -0,0 +1,447 @@+package service++import (+ "bytes"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "sort"+ "strings"+ "sync"+ "time"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/models"+ "github.com/Tencent/WeKnora/internal/models/api"+ modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)++// ErrInvalidCatalog marks overlays rejected by validation or compilation.+var ErrInvalidCatalog = errors.New("invalid model catalog")++// MaxCatalogOverlayBytes bounds a console overlay document.+const MaxCatalogOverlayBytes = 1024 * 1024++const catalogHistoryLimit = 20++// CatalogProviderView deliberately omits provider credentials and headers.+type CatalogProviderView struct {+ ID string `json:"id"`+ Name string `json:"name"`+ API string `json:"api"`+ ModelTypes []types.ModelType `json:"model_types"`+ Settings map[string]any `json:"settings"`+ Models []models.ModelSpec `json:"models"`+ // ModelThinkingLevels lists, per chat model id, the levels offered once+ // thinking is enabled, resolved against the vendor map and protocol so+ // the console does not re-implement level inheritance.+ ModelThinkingLevels map[string][]api.ReasoningEffort `json:"model_thinking_levels"`+ // VendorThinkingLevels is what a chat model without its own map offers.+ VendorThinkingLevels []api.ReasoningEffort `json:"vendor_thinking_levels"`+}++// CatalogRevision is one earlier published overlay.+type CatalogRevision struct {+ Version uint64 `json:"version"`+ Overlay json.RawMessage `json:"overlay"`+ UpdatedBy string `json:"updated_by"`+ UpdatedAt time.Time `json:"updated_at"`+}++// CatalogState is what the console reads: every layer plus the overlay.+type CatalogState struct {+ SyncError string `json:"sync_error,omitempty"`+ AppliedVersion uint64 `json:"applied_version"`+ Version uint64 `json:"version"`+ Baseline string `json:"baseline"`+ Overlay json.RawMessage `json:"overlay"`+ History []CatalogRevision `json:"history"`+ Builtin []CatalogProviderView `json:"builtin"`+ Deployment []CatalogProviderView `json:"deployment"`+ Effective []CatalogProviderView `json:"effective"`+ DeploymentError string `json:"deployment_error,omitempty"`+}++// CatalogUpdate is a preview or publish request.+type CatalogUpdate struct {+ Version uint64 `json:"version"`+ Baseline string `json:"baseline"`+ Overlay json.RawMessage `json:"overlay"`+}++// ModelCatalogService persists console overlays independently of the mounted+// deployment file. Every replica re-reads the singleton every five seconds;+// this also repairs missed notifications and works without Redis in Lite mode.+type ModelCatalogService struct {+ repo *repository.ModelCatalogRepository+ audit interfaces.AuditLogService+ base *modelruntime.Runtime+ target *modelruntime.Runtime+ baseline string+ deploymentError string+ // Both lower layers are fixed after construction, so their views are too.+ builtinViews []CatalogProviderView+ deploymentViews []CatalogProviderView+ mu sync.Mutex+ applied uint64+ loaded bool+ // failed remembers a stored version this replica cannot compile, so the+ // poll does not re-read and recompile it until the version changes.+ failed uint64+ failedErr error+ startOnce sync.Once+}++// NewModelCatalogService loads the deployment layer and applies the stored overlay.+func NewModelCatalogService(+ repo *repository.ModelCatalogRepository, audit interfaces.AuditLogService,+) *ModelCatalogService {+ s := &ModelCatalogService{repo: repo, audit: audit, base: modelruntime.New(), target: modelruntime.Default()}+ data, baseDir, err := modelruntime.ReadDeploymentOverlay(config.ConfigDir())+ if err != nil {+ s.deploymentError = err.Error()+ } else if data != nil {+ if err = s.base.Reload(data, baseDir); err != nil {+ s.deploymentError = err.Error()+ }+ }+ s.builtinViews = catalogProviderViews(modelruntime.New())+ s.deploymentViews = catalogProviderViews(s.base)+ // Include the executable's baseline as well as the file in the preview+ // token, so a rolling upgrade cannot publish against another replica's base.+ builtins, _ := json.Marshal(s.builtinViews)+ hash := sha256.Sum256(append(builtins, data...))+ s.baseline = hex.EncodeToString(hash[:])+ if err := s.Sync(context.Background()); err != nil {+ logger.Warnf(context.Background(), "[model_catalog] initial sync failed: %v", err)+ }+ return s+}++// Start polls for overlays published by other replicas.+func (s *ModelCatalogService) Start(ctx context.Context) {+ s.startOnce.Do(func() {+ go func() {+ ticker := time.NewTicker(5 * time.Second)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ if err := s.Sync(ctx); err != nil {+ logger.Warnf(ctx, "[model_catalog] sync failed: %v", err)+ }+ }+ }+ }()+ })+}++// Sync applies the stored overlay if its version changed.+func (s *ModelCatalogService) Sync(ctx context.Context) error {+ s.mu.Lock()+ defer s.mu.Unlock()+ version, err := s.repo.Version(ctx)+ if err != nil {+ return err+ }+ if (s.loaded && version == s.applied) || (s.failedErr != nil && version == s.failed) {+ return nil+ }+ _, err = s.syncLocked(ctx)+ return err+}++func (s *ModelCatalogService) syncLocked(ctx context.Context) (*types.ModelCatalogConfig, error) {+ row, err := s.repo.Get(ctx)+ if err != nil {+ return nil, err+ }+ if s.loaded && row.Version == s.applied {+ return row, nil+ }+ if s.failedErr != nil && row.Version == s.failed {+ return row, s.failedErr+ }+ overlay, err := validateConsoleOverlay(row.Overlay)+ if err == nil {+ var candidate *modelruntime.Runtime+ if candidate, err = s.base.WithOverlay(overlay, ""); err == nil {+ s.target.RestoreSnapshot(candidate.SnapshotCurrent())+ s.applied, s.loaded, s.failedErr = row.Version, true, nil+ return row, nil+ }+ }+ s.failed, s.failedErr = row.Version, err+ return row, err+}++// State returns the current catalog state for the console.+func (s *ModelCatalogService) State(ctx context.Context) (*CatalogState, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ row, err := s.syncLocked(ctx)+ if row == nil {+ return nil, err+ }+ state := s.state(row, s.target)+ if err != nil {+ state.SyncError = err.Error()+ }+ return state, nil+}++func (s *ModelCatalogService) state(row *types.ModelCatalogConfig, runtime *modelruntime.Runtime) *CatalogState {+ history := []CatalogRevision{}+ _ = json.Unmarshal(row.History, &history)+ return &CatalogState{+ Version: row.Version, AppliedVersion: s.applied, Baseline: s.baseline,+ Overlay: json.RawMessage(row.Overlay), History: history,+ Builtin: s.builtinViews, Deployment: s.deploymentViews,+ Effective: catalogProviderViews(runtime), DeploymentError: s.deploymentError,+ }+}++// Preview and Publish use the same compiler. Invalid overlays never reach the+// database or runtime; a stale editor must reload instead of losing changes.+func (s *ModelCatalogService) change(ctx context.Context, req CatalogUpdate, publish bool) (*CatalogState, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ // Recovery must remain possible even if a stored overlay no longer+ // compiles against this deployment baseline after an upgrade.+ row, err := s.repo.Get(ctx)+ if err != nil {+ return nil, err+ }+ if req.Version != row.Version || req.Baseline != s.baseline {+ return nil, repository.ErrCatalogVersionConflict+ }+ overlay, err := validateConsoleOverlay(req.Overlay)+ if err != nil {+ return nil, fmt.Errorf("%w: %v", ErrInvalidCatalog, err)+ }+ candidate, err := s.base.WithOverlay(overlay, "")+ if err != nil {+ return nil, fmt.Errorf("%w: %v", ErrInvalidCatalog, err)+ }+ if !publish {+ // A check only reads the candidate; history and the lower layers are+ // unchanged, so they are left out of the response.+ return &CatalogState{+ Version: row.Version, AppliedVersion: s.applied, Baseline: s.baseline,+ Overlay: json.RawMessage(overlay), Effective: catalogProviderViews(candidate),+ DeploymentError: s.deploymentError,+ }, nil+ }+ history := []CatalogRevision{}+ if err := json.Unmarshal(row.History, &history); err != nil {+ return nil, err+ }+ history = append([]CatalogRevision{{+ Version: row.Version, Overlay: json.RawMessage(row.Overlay),+ UpdatedBy: row.UpdatedBy, UpdatedAt: row.UpdatedAt,+ }}, history...)+ if len(history) > catalogHistoryLimit {+ history = history[:catalogHistoryLimit]+ }+ rawHistory, _ := json.Marshal(history)+ next := &types.ModelCatalogConfig{+ ID: 1, Version: row.Version + 1, Overlay: types.JSON(overlay),+ History: types.JSON(rawHistory), UpdatedBy: auditActor(ctx), UpdatedAt: time.Now().UTC(),+ }+ if err := s.repo.Save(ctx, row.Version, next); err != nil {+ return nil, err+ }+ s.target.RestoreSnapshot(candidate.SnapshotCurrent())+ s.applied, s.loaded, s.failedErr = next.Version, true, nil+ if s.audit != nil {+ details, _ := json.Marshal(map[string]any{+ "key": "model_catalog", "previous_version": row.Version, "version": next.Version,+ })+ _ = s.audit.Log(ctx, &types.AuditLog{+ TenantID: 0, ActorUserID: auditActor(ctx), ActorRole: "system_admin",+ Action: types.AuditActionSystemSettingChanged, TargetType: "model_catalog", TargetID: "model_catalog",+ Outcome: types.AuditOutcomeSuccess, Details: types.JSON(details),+ })+ }+ return s.state(next, candidate), nil+}++// Preview compiles an overlay without persisting or applying it.+func (s *ModelCatalogService) Preview(ctx context.Context, req CatalogUpdate) (*CatalogState, error) {+ return s.change(ctx, req, false)+}++// Publish persists an overlay as a new version and applies it.+func (s *ModelCatalogService) Publish(ctx context.Context, req CatalogUpdate) (*CatalogState, error) {+ return s.change(ctx, req, true)+}++func catalogProviderViews(runtime *modelruntime.Runtime) []CatalogProviderView {+ out := []CatalogProviderView{}+ for _, p := range runtime.List() {+ view := CatalogProviderView{+ ID: p.ID, Name: p.Name, API: string(p.API), ModelTypes: p.ModelTypes, Models: p.Models(),+ Settings: map[string]any{+ "names": p.Names, "description": p.Description, "descriptions": p.Descriptions,+ // Base URLs are omitted: deployment values may carry+ // interpolated tokens, and the console cannot change them.+ "website": p.Website, "auth": p.Auth,+ "requires_auth": p.RequiresAuth, "url_patterns": p.URLPatterns,+ "compat": p.Compat, "thinking_levels": p.ThinkingLevels,+ "icon_sha256": fmt.Sprintf("%x", sha256.Sum256(p.Icon)),+ },+ }+ view.ModelThinkingLevels = map[string][]api.ReasoningEffort{}+ view.VendorThinkingLevels = []api.ReasoningEffort{}+ // Resolve as if thinking were on: a non-reasoning model reports no+ // levels, which would hide what enabling reasoning would offer.+ enabled := true+ override := &types.ModelSpecOverride{Reasoning: &enabled}+ vendorRef := modelruntime.Ref{Provider: p.ID, Model: "__vendor_default__", Override: override}+ if resolved, err := p.Resolve(vendorRef); err == nil {+ view.VendorThinkingLevels = resolved.Capabilities().ThinkingLevels+ }+ for _, m := range p.ModelsByType(types.ModelTypeKnowledgeQA) {+ if m.ID == "" {+ continue+ }+ ref := modelruntime.Ref{Provider: p.ID, Model: m.ID, Override: override}+ if resolved, err := p.Resolve(ref); err == nil {+ view.ModelThinkingLevels[m.ID] = resolved.Capabilities().ThinkingLevels+ }+ }+ out = append(out, view)+ }+ sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })+ return out+}++// Console documents are portable metadata. Environment expansion, server file+// reads and provider secrets remain deployment-owned. This prevents the editor+// and export/history endpoints becoming environment or credential readers.+func validateConsoleOverlay(raw []byte) ([]byte, error) {+ if len(raw) > MaxCatalogOverlayBytes {+ return nil, fmt.Errorf("catalog overlay exceeds 1 MiB")+ }+ if err := rejectDuplicateCatalogKeys(raw); err != nil {+ return nil, err+ }+ var root map[string]json.RawMessage+ if err := json.Unmarshal(raw, &root); err != nil {+ return nil, fmt.Errorf("invalid catalog JSON: %w", err)+ }+ if root == nil {+ return nil, fmt.Errorf("catalog must be an object with providers")+ }+ delete(root, "_comment") // accepted by the shipped example, never persisted+ for key := range root {+ if key != "providers" {+ return nil, fmt.Errorf("unknown catalog field %q", key)+ }+ }+ var providers map[string]map[string]json.RawMessage+ if err := json.Unmarshal(root["providers"], &providers); err != nil || providers == nil {+ return nil, fmt.Errorf("providers must be an object")+ }+ seen := map[string]bool{}+ normalizedProviders := map[string]map[string]json.RawMessage{}+ for id, fields := range providers {+ normalized := strings.ToLower(strings.TrimSpace(id))+ if fields == nil || normalized == "" || seen[normalized] {+ return nil, fmt.Errorf("invalid or duplicate provider %q", id)+ }+ seen[normalized] = true+ normalizedProviders[normalized] = fields+ for field := range fields {+ if field != strings.ToLower(field) {+ return nil, fmt.Errorf("provider %s: field names must use lowercase: %s", id, field)+ }+ }+ // Routing fields stay deployment-owned too: moving a vendor's default+ // URL would send its deployment api_key, and the keys of rows without+ // their own base URL, to another host.+ for _, field := range []string{"api_key", "headers", "base_url", "base_urls", "url_patterns", "auth"} {+ if _, exists := fields[field]; exists {+ return nil, fmt.Errorf(+ "provider %s: %s must be managed in deployment configuration or model credentials", id, field)+ }+ }+ if icon, exists := fields["icon"]; exists {+ var value string+ err := json.Unmarshal(icon, &value)+ inline := value == "" || strings.HasPrefix(strings.TrimSpace(value), "<svg")+ if err != nil || !inline {+ return nil, fmt.Errorf("provider %s: console icons must be inline SVG", id)+ }+ }+ }+ // Environment interpolation only applies to the fields rejected above, so+ // a '$' anywhere else (names, descriptions, SVG) is plain text.+ root["providers"], _ = json.Marshal(normalizedProviders)+ canonical, _ := json.Marshal(root)+ return canonical, nil+}++// Duplicate members are ambiguous to operators and different JSON parsers.+func rejectDuplicateCatalogKeys(raw []byte) error {+ d := json.NewDecoder(bytes.NewReader(raw))+ var value func() error+ value = func() error {+ token, err := d.Token()+ if err != nil {+ return err+ }+ delim, ok := token.(json.Delim)+ if !ok {+ return nil+ }+ switch delim {+ case '{':+ seen := map[string]bool{}+ for d.More() {+ key, err := d.Token()+ if err != nil {+ return err+ }+ name, ok := key.(string)+ if !ok {+ return fmt.Errorf("invalid object key")+ }+ if seen[name] {+ return fmt.Errorf("duplicate catalog field %q", name)+ }+ seen[name] = true+ if err := value(); err != nil {+ return err+ }+ }+ case '[':+ for d.More() {+ if err := value(); err != nil {+ return err+ }+ }+ default:+ return fmt.Errorf("invalid JSON delimiter")+ }+ _, err = d.Token()+ return err+ }+ if err := value(); err != nil {+ return err+ }+ if _, err := d.Token(); err != io.EOF {+ return fmt.Errorf("expected a single JSON document")+ }+ return nil+}diff --git a/internal/application/service/model_catalog_test.go b/internal/application/service/model_catalog_test.gonew file mode 100644index 000000000..ba208d5a7--- /dev/null+++ b/internal/application/service/model_catalog_test.go@@ -0,0 +1,207 @@+package service++import (+ "context"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/models/api"+ modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++var emptyOverlay = json.RawMessage(`{"providers":{}}`)++func catalogFixture(t *testing.T) (*ModelCatalogService, *repository.ModelCatalogRepository) {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "catalog.db")), &gorm.Config{})+ require.NoError(t, err)+ ddl, err := os.ReadFile("../../../migrations/sqlite/000031_model_catalog_config.up.sql")+ require.NoError(t, err)+ require.NoError(t, db.Exec(string(ddl)).Error)+ sqlDB, err := db.DB()+ require.NoError(t, err)+ t.Cleanup(func() { _ = sqlDB.Close() })+ repo := repository.NewModelCatalogRepository(db)+ base := modelruntime.New()+ deployment := `{"providers":{"openai":{` ++ `"models":[{"id":"gpt-5","context_window":12345}],"api_key":"deployment-secret"}}}`+ require.NoError(t, base.Reload([]byte(deployment), ""))+ return &ModelCatalogService{repo: repo, base: base, target: modelruntime.New(), baseline: "test-base"}, repo+}++func TestModelCatalogPreviewPublishRollbackAndReplica(t *testing.T) {+ s, repo := catalogFixture(t)+ ctx := context.Background()+ initial, err := s.State(ctx)+ require.NoError(t, err)+ overlay := `{"providers":{"openai":{"models":[{"id":"gpt-5","context_window":54321}]},` ++ `"lab":{"models":[{"id":"sample"}]}}}`+ req := CatalogUpdate{Version: initial.Version, Baseline: initial.Baseline, Overlay: json.RawMessage(overlay)}+ preview, err := s.Preview(ctx, req)+ require.NoError(t, err)+ require.Equal(t, uint64(0), preview.Version)+ require.Nil(t, preview.History)+ require.NotEmpty(t, preview.Effective)+ row, err := repo.Get(ctx)+ require.NoError(t, err)+ require.Equal(t, uint64(0), row.Version)+ resolved, err := s.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, 12345, resolved.Spec.ContextWindow)+ published, err := s.Publish(ctx, req)+ require.NoError(t, err)+ require.Equal(t, uint64(1), published.Version)+ require.Len(t, published.History, 1)+ resolved, err = s.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, 54321, resolved.Spec.ContextWindow)+ require.Equal(t, "deployment-secret", resolved.Vendor.DefaultAPIKey)+ wire, err := json.Marshal(published)+ require.NoError(t, err)+ require.NotContains(t, string(wire), "deployment-secret")+ _, err = s.Publish(ctx, req)+ require.ErrorIs(t, err, repository.ErrCatalogVersionConflict)+ replica := &ModelCatalogService{repo: repo, base: s.base, target: modelruntime.New(), baseline: "test-base"}+ require.NoError(t, replica.Sync(ctx))+ resolved, err = replica.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, 54321, resolved.Spec.ContextWindow)+ _, err = s.Publish(ctx, CatalogUpdate{Version: 1, Baseline: s.baseline, Overlay: published.History[0].Overlay})+ require.NoError(t, err)+ require.NoError(t, replica.Sync(ctx))+ resolved, err = replica.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, 12345, resolved.Spec.ContextWindow)+ _, exists := replica.target.Get("lab")+ require.False(t, exists)+ // A restarted instance loads the persisted rollback, including its history.+ restarted := &ModelCatalogService{repo: repo, base: s.base, target: modelruntime.New(), baseline: "test-base"}+ state, err := restarted.State(ctx)+ require.NoError(t, err)+ require.Equal(t, uint64(2), state.Version)+ require.Len(t, state.History, 2)+}++func TestModelCatalogInvalidOverlayDoesNotPersistOrPublish(t *testing.T) {+ for name, overlay := range map[string]string{+ "typo": `{"providers":{"openai":{"models":[{"id":"gpt-5","compat":{"typo":true}}]}}}`,+ "negative": `{"providers":{"openai":{"models":[{"id":"gpt-5","context_window":-1}]}}}`,+ "mixed case secret": `{"providers":{"openai":{"API_KEY":"secret"}}}`,+ "mixed case icon": `{"providers":{"openai":{"ICON":"icons/provider.svg"}}}`,+ "duplicate member": `{"providers":{"openai":{"name":"first","name":"second"}}}`,+ "secret": `{"providers":{"openai":{"api_key":"secret"}}}`,+ "headers": `{"providers":{"openai":{"headers":{"Authorization":"secret"}}}}`,+ "environment": `{"providers":{"openai":{"base_url":"https://${SECRET}.example"}}}`,+ "base url": `{"providers":{"openai":{"base_url":"https://other.example/v1"}}}`,+ "base urls": `{"providers":{"openai":{"base_urls":{"embedding":"https://other.example"}}}}`,+ "url patterns": `{"providers":{"openai":{"url_patterns":["other.example"]}}}`,+ "auth": `{"providers":{"openai":{"auth":"none"}}}`,+ "file read": `{"providers":{"openai":{"icon":"icons/provider.svg"}}}`,+ "normalized collision": `{"providers":{"OpenAI":{},"openai":{}}}`,+ "wrong format": `{"version":1,"providers":{"openai":[]}}`,+ } {+ t.Run(name, func(t *testing.T) {+ s, repo := catalogFixture(t)+ require.NoError(t, s.Sync(context.Background()))+ req := CatalogUpdate{Baseline: s.baseline, Overlay: json.RawMessage(overlay)}+ _, err := s.Publish(context.Background(), req)+ require.ErrorIs(t, err, ErrInvalidCatalog)+ row, err := repo.Get(context.Background())+ require.NoError(t, err)+ require.Zero(t, row.Version)+ r, err := s.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, 12345, r.Spec.ContextWindow)+ })+ }+}++func TestModelCatalogAcceptsDollarSignsInMetadata(t *testing.T) {+ s, _ := catalogFixture(t)+ ctx := context.Background()+ overlay := `{"providers":{"openai":{"description":"Pro ($20 plan)",` ++ `"models":[{"id":"gpt-5","name":"GPT-5 ($)"}]}}}`+ _, err := s.Publish(ctx, CatalogUpdate{Baseline: s.baseline, Overlay: json.RawMessage(overlay)})+ require.NoError(t, err)+ resolved, err := s.target.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})+ require.NoError(t, err)+ require.Equal(t, "GPT-5 ($)", resolved.Spec.Name)+}++func TestModelCatalogStorageCASAndHistoryBound(t *testing.T) {+ s, repo := catalogFixture(t)+ ctx := context.Background()+ for i := uint64(0); i < 22; i++ {+ _, err := s.Publish(ctx, CatalogUpdate{Version: i, Baseline: s.baseline, Overlay: emptyOverlay})+ require.NoError(t, err)+ }+ state, err := s.State(ctx)+ require.NoError(t, err)+ require.Len(t, state.History, 20)+ require.Equal(t, uint64(21), state.History[0].Version)+ require.Equal(t, uint64(2), state.History[19].Version)+ err = repo.Save(ctx, 0, &types.ModelCatalogConfig{+ Version: 99, Overlay: types.JSON(emptyOverlay), History: types.JSON(`[]`),+ })+ require.ErrorIs(t, err, repository.ErrCatalogVersionConflict)+ _, err = s.Publish(ctx, CatalogUpdate{Version: 22, Baseline: "another-file", Overlay: emptyOverlay})+ require.ErrorIs(t, err, repository.ErrCatalogVersionConflict)+}++func TestModelCatalogCanRepairAnOverlayRejectedByCurrentDeployment(t *testing.T) {+ s, repo := catalogFixture(t)+ ctx := context.Background()+ require.NoError(t, s.Sync(ctx))+ require.NoError(t, repo.Save(ctx, 0, &types.ModelCatalogConfig{+ Version: 1,+ Overlay: types.JSON(`{"providers":{"openai":{"api":"unsupported"}}}`), History: types.JSON(`[]`),+ }))+ require.Error(t, s.Sync(ctx))+ // The rejected version is remembered instead of being recompiled each poll.+ require.NoError(t, s.Sync(ctx))+ state, err := s.State(ctx)+ require.NoError(t, err)+ require.NotEmpty(t, state.SyncError)+ require.Equal(t, uint64(1), state.Version)+ require.Zero(t, state.AppliedVersion)+ published, err := s.Publish(ctx, CatalogUpdate{Version: 1, Baseline: s.baseline, Overlay: emptyOverlay})+ require.NoError(t, err)+ require.Equal(t, uint64(2), published.AppliedVersion)+ state, err = s.State(ctx)+ require.NoError(t, err)+ require.Empty(t, state.SyncError)+}++func TestCatalogViewsResolveThinkingLevels(t *testing.T) {+ levelsFor := func(rt *modelruntime.Runtime, provider, model string) ([]api.ReasoningEffort, []api.ReasoningEffort) {+ for _, view := range catalogProviderViews(rt) {+ if view.ID == provider {+ return view.ModelThinkingLevels[model], view.VendorThinkingLevels+ }+ }+ t.Fatalf("provider %s missing", provider)+ return nil, nil+ }+ rt := modelruntime.New()+ base, vendor := levelsFor(rt, "openai", "gpt-5")+ require.Contains(t, base, api.ReasoningHigh)+ require.NotEmpty(t, vendor)++ // A console overlay can drop one level; the others keep inheriting, and+ // a non-reasoning override still reports what enabling thinking offers.+ overlay := `{"providers":{"openai":{"models":[` ++ `{"id":"gpt-5","reasoning":false,"thinking_levels":{"high":null}}]}}}`+ candidate, err := rt.WithOverlay([]byte(overlay), "")+ require.NoError(t, err)+ next, _ := levelsFor(candidate, "openai", "gpt-5")+ require.NotContains(t, next, api.ReasoningHigh)+ require.Contains(t, next, api.ReasoningLow)+ require.Len(t, next, len(base)-1)+}diff --git a/internal/container/container.go b/internal/container/container.goindex 19392a788..c368abbd3 100644--- a/internal/container/container.go+++ b/internal/container/container.go@@ -173,6 +173,7 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(repository.NewUserRepository))must(container.Provide(repository.NewAuthTokenRepository))must(container.Provide(repository.NewSystemSettingRepository))+ must(container.Provide(repository.NewModelCatalogRepository))must(container.Provide(neo4jRepo.NewNeo4jRepository))must(container.Provide(repository.NewMCPServiceRepository))must(container.Provide(repository.NewMCPToolApprovalRepository))@@ -246,6 +247,7 @@ func BuildContainer(container *dig.Container) *dig.Container {must(container.Provide(service.NewEvaluationService))must(container.Provide(service.NewUserService))must(container.Provide(service.NewSystemSettingService))+ must(container.Provide(service.NewModelCatalogService))must(container.Provide(func(repo repository.TenantSandboxConfigRepository,agents interfaces.CustomAgentRepository,diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.goindex 82565c7a8..42d384711 100644--- a/internal/database/migration_sqlite_versioned_schema_test.go+++ b/internal/database/migration_sqlite_versioned_schema_test.go@@ -21,6 +21,7 @@ var versionedSQLiteTables = []string{"task_pending_ops","task_dead_letters","system_settings",+ "model_catalog_configs","knowledge_processing_spans","knowledge_tag_relations","browser_devices",@@ -38,13 +39,14 @@ var versionedSQLiteTables = []string{// versionedSQLiteColumns maps each existing table to the columns that the// versioned migrations add and the SQLite baseline was missing.var versionedSQLiteColumns = map[string][]string{- "memory_subjects": {"extraction_state"}, // 000094- "memory_items": {"replaces_id"}, // 000094- "tenants": {"api_principal_config"}, // 000064- "users": {"is_system_admin"}, // 000053- "knowledges": {"pending_subtasks_count", "profile"}, // 000056, 000101- "knowledge_bases": {"profile_config", "generated_profile"}, // 000101- "messages": {"attachments", "usage", "sandbox_checkpoint", "context_checkpoint"}, // 000034/085/097/105+ "model_catalog_configs": {"version", "overlay", "history", "updated_by", "updated_at"}, // 000031+ "memory_subjects": {"extraction_state"}, // 000094+ "memory_items": {"replaces_id"}, // 000094+ "tenants": {"api_principal_config"}, // 000064+ "users": {"is_system_admin"}, // 000053+ "knowledges": {"pending_subtasks_count", "profile"}, // 000056, 000101+ "knowledge_bases": {"profile_config", "generated_profile"}, // 000101+ "messages": {"attachments", "usage", "sandbox_checkpoint", "context_checkpoint"}, // 000034/085/097/105"sessions": {"parent_session_id", "forked_from_message_id", "fork_bootstrap", // 000097"sandbox_config_tenant_id", // 000027@@ -65,7 +67,7 @@ var versionedSQLiteColumns = map[string][]string{}, // 000028}-const expectedSQLiteMigrationVersion = 30+const expectedSQLiteMigrationVersion = 31func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {repoRoot := sqliteRepoRoot(t)@@ -98,6 +100,13 @@ func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {"SQLite migrations must add the session/created_at index") // 000106assertSQLiteAgentHistoryQueriesUseTheIndex(t, db)+ var catalogVersion int+ var catalogOverlay string+ catalogRow := db.QueryRow("SELECT version, overlay FROM model_catalog_configs WHERE id = 1")+ require.NoError(t, catalogRow.Scan(&catalogVersion, &catalogOverlay))+ require.Zero(t, catalogVersion)+ require.JSONEq(t, `{"providers":{}}`, catalogOverlay)+assertSQLiteShareLinkInvitationsWork(t, db)assertSQLiteMCPOAuthPrincipalUpsertWorks(t, db)require.False(t, sqliteColumnExists(t, db, "knowledges", "tag_id"),diff --git a/internal/handler/system.go b/internal/handler/system.goindex cee7f54d8..40cabdc53 100644--- a/internal/handler/system.go+++ b/internal/handler/system.go@@ -43,6 +43,7 @@ type SystemHandler struct {documentReader interfaces.DocumentReadertenantSvc interfaces.TenantServiceuserSvc interfaces.UserService+ modelCatalogSvc *service.ModelCatalogServicesystemSettingSvc interfaces.SystemSettingServiceapiKeySvc interfaces.TenantAPIKeyService// auditSvc is optional — when nil, emitAdminAudit no-ops so unit@@ -75,6 +76,7 @@ func NewSystemHandler(cfg *config.Config,tenantSvc interfaces.TenantService,userSvc interfaces.UserService,systemSettingSvc interfaces.SystemSettingService,+ modelCatalogSvc *service.ModelCatalogService,apiKeySvc interfaces.TenantAPIKeyService,auditSvc interfaces.AuditLogService,taskInspector interfaces.TaskInspector,@@ -89,6 +91,7 @@ func NewSystemHandler(cfg *config.Config,tenantSvc: tenantSvc,userSvc: userSvc,systemSettingSvc: systemSettingSvc,+ modelCatalogSvc: modelCatalogSvc,apiKeySvc: apiKeySvc,auditSvc: auditSvc,taskInspector: taskInspector,diff --git a/internal/handler/system_model_catalog.go b/internal/handler/system_model_catalog.gonew file mode 100644index 000000000..58b85eb47--- /dev/null+++ b/internal/handler/system_model_catalog.go@@ -0,0 +1,54 @@+package handler++import (+ "errors"+ "net/http"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/application/service"+ "github.com/gin-gonic/gin"+)++// GetModelCatalog returns the catalog layers, overlay and version history.+func (h *SystemHandler) GetModelCatalog(c *gin.Context) {+ state, err := h.modelCatalogSvc.State(c.Request.Context())+ if err != nil {+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Model catalog is unavailable"})+ return+ }+ c.JSON(http.StatusOK, state)+}++// PreviewModelCatalog validates an overlay and returns the candidate catalog.+func (h *SystemHandler) PreviewModelCatalog(c *gin.Context) { h.changeModelCatalog(c, false) }++// PublishModelCatalog validates, persists and applies an overlay.+func (h *SystemHandler) PublishModelCatalog(c *gin.Context) { h.changeModelCatalog(c, true) }++func (h *SystemHandler) changeModelCatalog(c *gin.Context, publish bool) {+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, service.MaxCatalogOverlayBytes+4096)+ var req service.CatalogUpdate+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid model catalog request (maximum 1 MiB)"})+ return+ }+ var state *service.CatalogState+ var err error+ if publish {+ state, err = h.modelCatalogSvc.Publish(c.Request.Context(), req)+ } else {+ state, err = h.modelCatalogSvc.Preview(c.Request.Context(), req)+ }+ if err != nil {+ switch {+ case errors.Is(err, repository.ErrCatalogVersionConflict):+ c.JSON(http.StatusConflict, gin.H{"error": err.Error()})+ case errors.Is(err, service.ErrInvalidCatalog):+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ default:+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update model catalog"})+ }+ return+ }+ c.JSON(http.StatusOK, state)+}diff --git a/internal/handler/system_model_catalog_test.go b/internal/handler/system_model_catalog_test.gonew file mode 100644index 000000000..bb5bb2638--- /dev/null+++ b/internal/handler/system_model_catalog_test.go@@ -0,0 +1,70 @@+package handler++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/application/repository"+ "github.com/Tencent/WeKnora/internal/application/service"+ modelruntime "github.com/Tencent/WeKnora/internal/models/runtime"+ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++func TestSystemModelCatalogPreviewAndPublish(t *testing.T) {+ gin.SetMode(gin.TestMode)+ snapshot := modelruntime.SnapshotCurrent()+ t.Cleanup(func() { modelruntime.RestoreSnapshot(snapshot) })+ t.Setenv("MODELS_CONFIG", filepath.Join(t.TempDir(), "absent.json"))+ db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "catalog.db")), &gorm.Config{})+ require.NoError(t, err)+ sqlDB, err := db.DB()+ require.NoError(t, err)+ t.Cleanup(func() { _ = sqlDB.Close() })+ ddl, err := os.ReadFile("../../migrations/sqlite/000031_model_catalog_config.up.sql")+ require.NoError(t, err)+ require.NoError(t, db.Exec(string(ddl)).Error)+ h := &SystemHandler{modelCatalogSvc: service.NewModelCatalogService(repository.NewModelCatalogRepository(db), nil)}+ r := gin.New()+ r.GET("/catalog", h.GetModelCatalog)+ r.POST("/preview", h.PreviewModelCatalog)+ r.PUT("/catalog", h.PublishModelCatalog)+ request := func(method, path, body string) *httptest.ResponseRecorder {+ w := httptest.NewRecorder()+ req := httptest.NewRequest(method, path, strings.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ r.ServeHTTP(w, req)+ return w+ }+ w := request(http.MethodGet, "/catalog", "")+ require.Equal(t, 200, w.Code)+ var initial service.CatalogState+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &initial))+ payload, _ := json.Marshal(service.CatalogUpdate{+ Version: initial.Version, Baseline: initial.Baseline,+ Overlay: json.RawMessage(`{"providers":{"openai":{"models":[{"id":"gpt-5","context_window":64000}]}}}`),+ })+ w = request(http.MethodPost, "/preview", string(payload))+ require.Equal(t, 200, w.Code)+ var preview service.CatalogState+ require.NoError(t, json.Unmarshal(w.Body.Bytes(), &preview))+ require.Zero(t, preview.Version)+ w = request(http.MethodPut, "/catalog", string(payload))+ require.Equal(t, 200, w.Code)+ w = request(http.MethodPut, "/catalog", string(payload))+ require.Equal(t, 409, w.Code)+ invalid, _ := json.Marshal(service.CatalogUpdate{+ Version: 1, Baseline: initial.Baseline,+ Overlay: json.RawMessage(`{"providers":{"openai":{"api_key":"secret"}}}`),+ })+ w = request(http.MethodPost, "/preview", string(invalid))+ require.Equal(t, 400, w.Code)+ require.NotContains(t, w.Body.String(), "\"secret\"")+}diff --git a/internal/models/runtime/layers.go b/internal/models/runtime/layers.gonew file mode 100644index 000000000..028f65f4b--- /dev/null+++ b/internal/models/runtime/layers.go@@ -0,0 +1,14 @@+package runtime++// WithOverlay builds an independent candidate on top of this generation.+// It never publishes partial changes or mutates either input layer. Unlike+// Reload, this explicitly retains the deployment layer beneath a UI overlay.+func (rt *Runtime) WithOverlay(data []byte, baseDir string) (*Runtime, error) {+ snapshot := rt.SnapshotCurrent()+ candidate := &Runtime{providers: cloneProviders(snapshot.current), builtins: cloneProviders(snapshot.current)}+ if err := candidate.Reload(data, baseDir); err != nil {+ return nil, err+ }+ candidate.builtins = cloneProviders(snapshot.base)+ return candidate, nil+}diff --git a/internal/models/runtime/overlay.go b/internal/models/runtime/overlay.goindex 8d7d23273..3f4210041 100644--- a/internal/models/runtime/overlay.go+++ b/internal/models/runtime/overlay.go@@ -94,20 +94,31 @@ func (rt *Runtime) LoadOverlay(configDir string) error {return rt.loadOverlayValidated(configDir, nil)}-// loadOverlayValidated validates every candidate before publishing a generation.-func (rt *Runtime) loadOverlayValidated(configDir string, validate func(*Provider) error) error {+// ReadDeploymentOverlay reads config/models.json (or the path in+// MODELS_CONFIG). A missing file returns nil data and no error; baseDir+// resolves the overlay's relative icon paths.+func ReadDeploymentOverlay(configDir string) (data []byte, baseDir string, err error) {path := os.Getenv("MODELS_CONFIG")if path == "" {path = filepath.Join(configDir, "models.json")}- data, err := os.ReadFile(path)+ data, err = os.ReadFile(path)if err != nil {if os.IsNotExist(err) {- return nil+ return nil, "", nil}- return fmt.Errorf("read %s: %w", path, err)+ return nil, "", fmt.Errorf("read %s: %w", path, err)+ }+ return data, filepath.Dir(path), nil+}++// loadOverlayValidated validates every candidate before publishing a generation.+func (rt *Runtime) loadOverlayValidated(configDir string, validate func(*Provider) error) error {+ data, baseDir, err := ReadDeploymentOverlay(configDir)+ if err != nil || data == nil {+ return err}- return rt.applyOverlayValidated(data, filepath.Dir(path), validate)+ return rt.applyOverlayValidated(data, baseDir, validate)}// ApplyOverlay applies overlay JSON to the registry. baseDir resolvesdiff --git a/internal/router/model_catalog_test.go b/internal/router/model_catalog_test.gonew file mode 100644index 000000000..9af605c44--- /dev/null+++ b/internal/router/model_catalog_test.go@@ -0,0 +1,32 @@+package router++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Tencent/WeKnora/internal/config"+ "github.com/Tencent/WeKnora/internal/handler"+ "github.com/gin-gonic/gin"+ "github.com/stretchr/testify/require"+)++func TestModelCatalogRequiresSystemAdmin(t *testing.T) {+ gin.SetMode(gin.TestMode)+ g := &rbacGuards{cfg: &config.Config{}}+ r := gin.New()+ RegisterSystemAdminRoutes(r.Group("/api/v1"), &handler.SystemHandler{}, nil, g)+ for _, tc := range []struct{ method, path string }{+ {http.MethodGet, "/api/v1/system/admin/model-catalog"},+ {http.MethodPost, "/api/v1/system/admin/model-catalog/preview"},+ {http.MethodPut, "/api/v1/system/admin/model-catalog"},+ } {+ t.Run(tc.method+tc.path, func(t *testing.T) {+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))+ require.Equal(t, http.StatusForbidden, w.Code, "gate must hold even when workspace RBAC is disabled")+ _, declared := g.apiKeyAuthorizer.Lookup(tc.method, tc.path)+ require.False(t, declared, "API keys must remain default-denied")+ })+ }+}diff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.goindex 0144e6786..d4b6ddc10 100644--- a/internal/router/routes_auth_tenant.go+++ b/internal/router/routes_auth_tenant.go@@ -288,6 +288,12 @@ func RegisterSystemAdminRoutes(// the guard, so adding new endpoints can't accidentally drop the gate.adminRoutes := r.Group("/system/admin", g.SystemAdmin()){+ // Catalog mutation is reserved to authenticated system-admin users.+ // API keys remain default-denied by the API-key gate.+ adminRoutes.GET("/model-catalog", handler.GetModelCatalog)+ adminRoutes.POST("/model-catalog/preview", handler.PreviewModelCatalog)+ adminRoutes.PUT("/model-catalog", handler.PublishModelCatalog)+// P0: SystemAdmin role managementadminRoutes.POST("/promote", handler.PromoteUserToSystemAdmin)adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)diff --git a/internal/types/model_catalog_config.go b/internal/types/model_catalog_config.gonew file mode 100644index 000000000..b332e211e--- /dev/null+++ b/internal/types/model_catalog_config.go@@ -0,0 +1,15 @@+package types++import "time"++// ModelCatalogConfig is the singleton platform catalog override. Version is+// an optimistic lock; History contains previous console overlays, never the+// deployment file (which can contain secrets).+type ModelCatalogConfig struct {+ ID uint `gorm:"primaryKey" json:"-"`+ Version uint64 `json:"version"`+ Overlay JSON `gorm:"type:jsonb" json:"overlay"`+ History JSON `gorm:"type:jsonb" json:"-"`+ UpdatedBy string `json:"updated_by"`+ UpdatedAt time.Time `json:"updated_at"`+}diff --git a/migrations/sqlite/000031_model_catalog_config.down.sql b/migrations/sqlite/000031_model_catalog_config.down.sqlnew file mode 100644index 000000000..5421e45d6--- /dev/null+++ b/migrations/sqlite/000031_model_catalog_config.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS model_catalog_configs;diff --git a/migrations/sqlite/000031_model_catalog_config.up.sql b/migrations/sqlite/000031_model_catalog_config.up.sqlnew file mode 100644index 000000000..b4dabd548--- /dev/null+++ b/migrations/sqlite/000031_model_catalog_config.up.sql@@ -0,0 +1,11 @@+CREATE TABLE model_catalog_configs (+ id INTEGER PRIMARY KEY,+ version BIGINT NOT NULL DEFAULT 0,+ overlay TEXT NOT NULL,+ history TEXT NOT NULL,+ updated_by VARCHAR(36) NOT NULL DEFAULT '',+ updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CHECK (id = 1)+);+INSERT INTO model_catalog_configs (id, version, overlay, history)+VALUES (1, 0, '{"providers":{}}', '[]');diff --git a/migrations/versioned/000111_model_catalog_config.down.sql b/migrations/versioned/000111_model_catalog_config.down.sqlnew file mode 100644index 000000000..5421e45d6--- /dev/null+++ b/migrations/versioned/000111_model_catalog_config.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS model_catalog_configs;diff --git a/migrations/versioned/000111_model_catalog_config.up.sql b/migrations/versioned/000111_model_catalog_config.up.sqlnew file mode 100644index 000000000..6579bd954--- /dev/null+++ b/migrations/versioned/000111_model_catalog_config.up.sql@@ -0,0 +1,11 @@+CREATE TABLE model_catalog_configs (+ id INTEGER PRIMARY KEY,+ version BIGINT NOT NULL DEFAULT 0,+ overlay JSONB NOT NULL,+ history JSONB NOT NULL,+ updated_by VARCHAR(36) NOT NULL DEFAULT '',+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,+ CHECK (id = 1)+);+INSERT INTO model_catalog_configs (id, version, overlay, history)+VALUES (1, 0, '{"providers":{}}', '[]');diff --git a/website-docs/03-features/06-models.md b/website-docs/03-features/06-models.mdindex ee86ebebd..6f664d49a 100644--- a/website-docs/03-features/06-models.md+++ b/website-docs/03-features/06-models.md@@ -425,6 +425,24 @@ builtin_models:叠加只改变厂商定义和模型目录;每个模型仍单独保存自己的 URL、API Key、额外字段和 `spec`,不会修改已有模型的 ID 或引用关系。+### 系统管理员维护模型目录++在「设置 → 系统管理 → 模型目录」查看所有目录模型:列表展示每个模型的厂商、类型、上下文窗口 / 最大输出、能力(思考、图像等输入)以及配置来源(内置 / 部署文件 / 管理员修改),可按厂商、类型筛选,或只看管理员修改过的条目。通配匹配规则排在各厂商的具体模型之后,只提供默认参数、不进入候选列表。++管理员修改单独保存在数据库中,优先顺序为:**内置目录 → 启动时读取的部署文件 → 管理员修改 → 单个模型的显式配置**。页面不会改写挂载的配置文件;修改部署文件仍需重启,各实例应使用一致的文件。++常用操作都是「保存即生效」:本实例立即切换完整目录,其他实例每 5 秒检查版本并同步;校验失败或数据库故障时保留原生效目录。另一位管理员先发布时返回 409,页面会提示并刷新到最新版本。++- **编辑模型**:点击列表中的模型,在抽屉里修改显示名称、上下文窗口、是否在候选列表中隐藏;对话模型还可改最大输出、输入模态(图像 / 音频 / 视频,勾选图像后可作为视觉模型)、是否支持思考和思考等级;Embedding 模型可改向量维度(添加模型时预填)。每项都显示默认值(部署文件或内置目录的取值),并标出已被管理员修改的字段;输入框留空即恢复默认。下方「各层取值」对比内置目录、部署文件和当前生效值。「恢复默认」一次性移除该模型的全部管理员修改。+ - 思考等级按服务端解析结果展示(已合并厂商等级映射与协议能力)。取消勾选写入 `null` 标记不支持,重新勾选沿用厂商映射的线上取值;与默认一致的等级不写入覆盖,继续跟随厂商。不勾选「关闭」表示模型始终思考。等级到厂商取值的自定义映射仍在 JSON 编辑中维护。+- **添加模型**:为厂商补充目录中没有的模型(厂商、类型、模型 ID,可选显示名称和默认参数;思考等级沿用厂商默认,添加后可再调整)。管理员添加的模型可在编辑抽屉里删除。+- **JSON 编辑**(「更多」菜单):直接编辑 `models.json` 格式的管理员修改文档(最大 1 MiB,支持顶层 `_comment`,发布时移除),适合批量调整或迁移。先点「检查变更」由服务端校验,并列出将新增、修改、移除的条目及变更字段;确认后点「发布 N 项变更」。「导入 JSON」会把文件载入此编辑器,确认后才发布;「导出修改」下载当前生效的管理员修改。+- **版本历史**(「更多」菜单):保留最近 20 个版本,显示发布人、时间和修改的模型数;「恢复」会以该版本内容发布一个新版本。++目录文档用于元数据管理。控制台不接受厂商 `api_key`、`headers`、`base_url` / `base_urls`、`url_patterns`、`auth` 或服务器图标文件路径;这些继续在模型配置 / 部署文件中维护(环境变量引用也只在部署文件的这些字段中展开,控制台文档里的 `$` 按普通文本处理)。控制台图标仅接受内联 SVG。生成文件 `models.generated.json` 的 `version + providers:数组` 结构不能直接作为覆盖文档导入,应按 `config/models.json.example` 的 `providers:对象` 结构编写。++目录更新后,重新打开模型编辑器会刷新厂商与模型候选。模型管理页有系统管理员专用的「模型目录」入口。目录中的模型不会自动创建为已配置模型,`deprecated` 只隐藏下拉候选;已有模型的上下文窗口等显式值继续保留,不会被批量改写。目录中的 API / compat 等未被单行覆盖的值会影响之后创建的模型客户端;已经创建的客户端继续使用原快照。+### 模型用量统计- **Token 用量**:`types.TokenUsage`(`internal/types/chat.go`)记录 `prompt_tokens / completion_tokens / total_tokens` 及 prompt cache 细分(`cache_read_tokens / cache_write_tokens / cache_miss_tokens / cache_status`)。所有协议客户端通过 `internal/models/api/usage_log.go` 的 `LogUsage` 输出统一的结构化日志行:diff --git a/website-docs/03-features/20-platform-admin.md b/website-docs/03-features/20-platform-admin.mdindex 517a4ac2e..3ad34ac62 100644--- a/website-docs/03-features/20-platform-admin.md+++ b/website-docs/03-features/20-platform-admin.md@@ -32,11 +32,12 @@## 使用平台控制台 {#_2-控制台能做什么}-系统管理员可在「设置」侧栏查看四个管理分区:+系统管理员可在「设置」侧栏查看以下管理分区:| 分区 | 作用 | 接口 || --- | --- | --- || 系统设置 | 全局运行时开关(注册模式、空间策略、并发、SSRF 白名单等),按设置项的生效规则应用,见下方设置表 | `GET/PUT/DELETE /system/admin/settings[/:key]` |+| 模型目录 | 查看目录模型及其来源,编辑、添加模型或用 JSON 批量修改(保存即生效),按版本历史恢复;详见[模型目录管理](06-models.md#系统管理员维护模型目录) | `/system/admin/model-catalog*` || 任务队列 | 查看 asynq 各队列实时积压、逐个任务的重试/归档/删除、批量清空归档任务;Lite 模式返回 `available=false` | `/system/admin/runtime/queues*` || 平台 API Key | 面向控制面自动化的 platform 作用域 Key,能力包括 `system_tenants_read/manage`、`system_settings_read/manage`、`system_runtime_read/manage`、`system_audit_read` | `/system/admin/api-keys` || 系统审计日志 | `tenant_id = 0` 的平台级事件(改设置、提升/撤销管理员、队列操作等)。空间级审计接口按 tenant 过滤,看不到这些行 | `GET /system/admin/audit-log` |diff --git a/website-docs/04-api/02-api-system.md b/website-docs/04-api/02-api-system.mdindex 5bc24f27c..e3a30cbb2 100644--- a/website-docs/04-api/02-api-system.md+++ b/website-docs/04-api/02-api-system.md@@ -279,3 +279,32 @@ curl $BASE/api/v1/system/admin/audit-log -H "Authorization: Bearer $TOKEN"## 实现参考路由注册:`internal/router/routes_auth_tenant.go` 的 `RegisterSystemAdminRoutes` 与 `RegisterSystemRoutes`。Handler:`internal/handler/system.go`、`internal/handler/audit_log.go`。+++## 模型目录(/api/v1/system/admin/model-catalog)++仅系统管理员用户会话可访问,API Key 不开放此组接口。++| 方法与路径 | 作用 |+| --- | --- |+| `GET /system/admin/model-catalog` | 返回当前 `version`、`baseline`、管理员 `overlay`、最近 20 个历史版本,以及 `builtin` / `deployment` / `effective` 目录 |+| `POST /system/admin/model-catalog/preview` | 校验覆盖文档并返回候选目录(仅 `effective` 与规范化后的 `overlay`,`history` / `builtin` / `deployment` 为 `null`),不持久化、不发布 |+| `PUT /system/admin/model-catalog` | 校验、保存新版本并发布;审计仅记录版本元信息 |++预览和发布使用相同请求体:++```json+{+ "version": 0,+ "baseline": "GET 返回的部署基线标识",+ "overlay": {+ "providers": {+ "openai": {+ "models": [{"id": "gpt-5", "context_window": 128000}]+ }+ }+ }+}+```++响应为未包装的目录状态对象。每个厂商条目额外带 `model_thinking_levels`(按对话模型 id 列出开启思考后可选的等级,已合并厂商映射与协议能力)和 `vendor_thinking_levels`(未单独配置等级的模型所用的厂商默认等级)。非法文档返回 400;版本过期或请求实例的部署基线不一致返回 409。发布先持久化再切换本实例,其他实例约 5 秒内同步。回滚使用历史 `overlay` 配合当前 `version` / `baseline` 再次发布。完整规则和限制见[模型管理](../03-features/06-models.md#系统管理员维护模型目录)。