diff --git a/docs/api/model.md b/docs/api/model.md index 61f6a165..9a8b16e7 100644 --- a/docs/api/model.md +++ b/docs/api/model.md @@ -436,7 +436,29 @@ curl --location --request DELETE 'http://localhost:8080/api/v1/models/8fdc464d-8 } ``` -404 表示模型不存在。 +如果知识库、智能体或当前空间的长期记忆仍引用该模型,接口保持 HTTP 400,并返回专用错误码 `2300` 和结构化引用详情。例如: + +```json +{ + "success": false, + "error": { + "code": 2300, + "message": "model is used by 2 knowledge base(s); reconfigure or remove those references before deleting", + "details": { + "knowledge_bases": [ + {"id": "kb-1", "name": "Product docs", "bindings": ["vlm_model"]}, + {"id": "kb-2", "name": "Engineering", "bindings": ["vlm_model"]} + ], + "agents": [], + "long_term_memory": {"bindings": []}, + "knowledge_base_total": 2, + "agent_total": 0 + } + } +} +``` + +`bindings` 是稳定的配置类型标识:知识库可能返回 `embedding_model`、`summary_model`、`image_processing_model`、`vlm_model`、`asr_model`、`wiki_synthesis_model`;智能体可能返回 `chat_model`、`rerank_model`、`vlm_model`、`asr_model`、`query_understand_model`、`follow_up_model`;长期记忆可能返回 `embedding_model`、`extract_model`。同一对象的多处引用会合并到一个 `bindings` 数组。`knowledge_bases` / `agents` 最多各返回 50 条;未截断的引用数在 `knowledge_base_total` / `agent_total`。404 表示模型不存在。 ## 参数说明 diff --git a/docs/docs.go b/docs/docs.go index 2ba0a205..6037c0e2 100644 --- a/docs/docs.go +++ b/docs/docs.go @@ -10421,6 +10421,12 @@ const docTemplate = `{ "additionalProperties": true } }, + "400": { + "description": "模型仍被知识库、智能体或长期记忆引用", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, "404": { "description": "模型不存在", "schema": { @@ -17042,7 +17048,8 @@ const docTemplate = `{ 2102, 2103, 2200, - 2201 + 2201, + 2300 ], "x-enum-varnames": [ "ErrBadRequest", @@ -17067,7 +17074,8 @@ const docTemplate = `{ "ErrAgentInvalidMaxIterations", "ErrAgentInvalidTemperature", "ErrVectorStoreBindingInvalid", - "ErrVectorStoreUnavailable" + "ErrVectorStoreUnavailable", + "ErrModelInUse" ] }, "github_com_Tencent_WeKnora_internal_infrastructure_chunker.DocProfile": { diff --git a/docs/swagger.json b/docs/swagger.json index 6d55c429..6d695c8d 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -10414,6 +10414,12 @@ "additionalProperties": true } }, + "400": { + "description": "模型仍被知识库、智能体或长期记忆引用", + "schema": { + "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError" + } + }, "404": { "description": "模型不存在", "schema": { @@ -17035,7 +17041,8 @@ 2102, 2103, 2200, - 2201 + 2201, + 2300 ], "x-enum-varnames": [ "ErrBadRequest", @@ -17060,7 +17067,8 @@ "ErrAgentInvalidMaxIterations", "ErrAgentInvalidTemperature", "ErrVectorStoreBindingInvalid", - "ErrVectorStoreUnavailable" + "ErrVectorStoreUnavailable", + "ErrModelInUse" ] }, "github_com_Tencent_WeKnora_internal_infrastructure_chunker.DocProfile": { @@ -25054,4 +25062,4 @@ "in": "header" } } -} \ No newline at end of file +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 584de683..411b3110 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -116,6 +116,7 @@ definitions: - 2103 - 2200 - 2201 + - 2300 type: integer x-enum-varnames: - ErrBadRequest @@ -141,6 +142,7 @@ definitions: - ErrAgentInvalidTemperature - ErrVectorStoreBindingInvalid - ErrVectorStoreUnavailable + - ErrModelInUse github_com_Tencent_WeKnora_internal_infrastructure_chunker.DocProfile: properties: all_caps_short_line_count: @@ -12844,6 +12846,10 @@ paths: schema: additionalProperties: true type: object + "400": + description: 模型仍被知识库、智能体或长期记忆引用 + schema: + $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError' "404": description: 模型不存在 schema: diff --git a/docs/swagger_contract_test.go b/docs/swagger_contract_test.go index e701ee62..75349c50 100644 --- a/docs/swagger_contract_test.go +++ b/docs/swagger_contract_test.go @@ -9,12 +9,14 @@ import ( "gopkg.in/yaml.v3" ) -func TestKnowledgeSearchRouteContract(t *testing.T) { - tests := []struct { - name string - loadSpec func(t *testing.T) []byte - parse func([]byte, any) error - }{ +type swaggerDocumentCase struct { + name string + loadSpec func(t *testing.T) []byte + parse func([]byte, any) error +} + +func swaggerDocuments() []swaggerDocumentCase { + return []swaggerDocumentCase{ { name: "registered document", loadSpec: func(t *testing.T) []byte { @@ -40,14 +42,24 @@ func TestKnowledgeSearchRouteContract(t *testing.T) { parse: yaml.Unmarshal, }, } +} - for _, tt := range tests { +func TestKnowledgeSearchRouteContract(t *testing.T) { + for _, tt := range swaggerDocuments() { t.Run(tt.name, func(t *testing.T) { assertKnowledgeSearchRouteContract(t, tt.loadSpec(t), tt.parse) }) } } +func TestModelDeleteUsageContract(t *testing.T) { + for _, tt := range swaggerDocuments() { + t.Run(tt.name, func(t *testing.T) { + assertModelDeleteUsageContract(t, tt.loadSpec(t), tt.parse) + }) + } +} + func readSwaggerFile(t *testing.T, name string) []byte { t.Helper() data, err := os.ReadFile(name) @@ -80,3 +92,62 @@ func assertKnowledgeSearchRouteContract(t *testing.T, data []byte, parse func([] } } } + +func assertModelDeleteUsageContract(t *testing.T, data []byte, parse func([]byte, any) error) { + t.Helper() + var spec struct { + Paths map[string]map[string]struct { + Responses map[string]any `json:"responses" yaml:"responses"` + } `json:"paths" yaml:"paths"` + Definitions map[string]map[string]any `json:"definitions" yaml:"definitions"` + } + if err := parse(data, &spec); err != nil { + t.Fatalf("parse generated Swagger document: %v", err) + } + + models, ok := spec.Paths["/models/{id}"] + if !ok { + t.Fatal("generated Swagger document does not expose /models/{id}") + } + deleteOperation, ok := models["delete"] + if !ok { + t.Fatal("generated Swagger document does not expose DELETE /models/{id}") + } + if _, ok := deleteOperation.Responses["400"]; !ok { + t.Fatal("model DELETE Swagger contract does not document the model-in-use 400 response") + } + + const errorCodeDefinition = "github_com_Tencent_WeKnora_internal_errors.ErrorCode" + errorCodes, ok := spec.Definitions[errorCodeDefinition] + if !ok { + t.Fatalf("generated Swagger document does not expose %s", errorCodeDefinition) + } + enum, ok := errorCodes["enum"].([]any) + if !ok { + t.Fatalf("generated Swagger ErrorCode enum has unexpected shape: %#v", errorCodes["enum"]) + } + enumVarNames, ok := errorCodes["x-enum-varnames"].([]any) + if !ok { + t.Fatalf("generated Swagger ErrorCode names have unexpected shape: %#v", errorCodes["x-enum-varnames"]) + } + for i, value := range enum { + if swaggerInteger(value) == 2300 { + if i >= len(enumVarNames) || enumVarNames[i] != "ErrModelInUse" { + t.Fatalf("error code 2300 must align with ErrModelInUse, got names=%v", enumVarNames) + } + return + } + } + t.Fatal("generated Swagger ErrorCode enum does not include model-in-use code 2300") +} + +func swaggerInteger(value any) int { + switch number := value.(type) { + case int: + return number + case float64: + return int(number) + default: + return 0 + } +} diff --git a/frontend/src/api/model/index.ts b/frontend/src/api/model/index.ts index e18d9657..a5f02c2c 100644 --- a/frontend/src/api/model/index.ts +++ b/frontend/src/api/model/index.ts @@ -1,5 +1,8 @@ import { get, post, postUpload, put, del } from '../../utils/request'; import i18n from '@/i18n' +import { ModelInUseError, modelInUseErrorFromRequest } from './modelUsage' + +export * from './modelUsage' const t = (key: string) => i18n.global.t(key) @@ -135,11 +138,25 @@ export function deleteModel(id: string): Promise { if (response.success) { resolve(); } else { + const conflict = modelInUseErrorFromRequest(response) + if (conflict) { + reject(conflict) + return + } reject(new Error(response.message || t('error.model.deleteFailed'))); } }) .catch((error: any) => { console.error('Failed to delete model:', error); + if (error instanceof ModelInUseError) { + reject(error) + return + } + const conflict = modelInUseErrorFromRequest(error) + if (conflict) { + reject(conflict) + return + } reject(error); }); }); diff --git a/frontend/src/api/model/modelUsage.test.ts b/frontend/src/api/model/modelUsage.test.ts new file mode 100644 index 00000000..bbd195b9 --- /dev/null +++ b/frontend/src/api/model/modelUsage.test.ts @@ -0,0 +1,138 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + MODEL_IN_USE_ERROR_CODE, + ModelInUseError, + modelInUseErrorFromRequest, + modelUsageAgentSection, + modelUsageBindingI18nKey, + modelUsageKnowledgeBaseSection, + modelUsageListTruncated, + modelUsageResourceCount, + modelUsageResourceRoute, + parseModelUsageDetails, +} from './modelUsage' + +const details = { + knowledge_bases: [ + { id: 'kb-1', name: 'Product docs', bindings: ['vlm_model'] }, + { id: 'kb-2', name: 'Engineering', bindings: ['vlm_model'] }, + ], + agents: [ + { id: 'agent-1', name: 'Support', bindings: ['chat_model', 'follow_up_model'] }, + ], + long_term_memory: { bindings: ['extract_model'] }, + knowledge_base_total: 2, + agent_total: 1, +} + +test('parses grouped model usage details without dropping multiple bindings', () => { + assert.deepEqual(parseModelUsageDetails(details), details) +}) + +test('fills missing totals from the listed collections', () => { + const { knowledge_base_total, agent_total, ...withoutTotals } = details + assert.deepEqual(parseModelUsageDetails(withoutTotals), details) + assert.equal(knowledge_base_total, 2) + assert.equal(agent_total, 1) +}) + +test('keeps untruncated totals when the listed collections are capped', () => { + const parsed = parseModelUsageDetails({ + ...details, + knowledge_base_total: 80, + agent_total: 12, + }) + assert.equal(parsed?.knowledge_base_total, 80) + assert.equal(parsed?.agent_total, 12) + assert.equal(modelUsageResourceCount(parsed!.knowledge_bases, parsed!.knowledge_base_total), 80) + assert.equal(modelUsageListTruncated(parsed!.knowledge_bases, parsed!.knowledge_base_total), true) + assert.equal(modelUsageListTruncated(parsed!.agents, parsed!.agent_total), true) +}) + +test('recognizes only the dedicated model-in-use code with a valid payload', () => { + const conflict = modelInUseErrorFromRequest({ + status: 400, + success: false, + error: { + code: MODEL_IN_USE_ERROR_CODE, + message: 'backwards-compatible server message', + details, + }, + }) + + assert.ok(conflict instanceof ModelInUseError) + assert.deepEqual(conflict.details, details) + assert.equal(modelInUseErrorFromRequest({ error: { code: 1000, details } }), null) +}) + +test('rejects malformed details instead of guessing from the server message', () => { + assert.equal(parseModelUsageDetails({ knowledge_bases: [], agents: [] }), null) + assert.equal(parseModelUsageDetails({ + knowledge_bases: [], + agents: [], + long_term_memory: { bindings: [] }, + }), null) + assert.equal(parseModelUsageDetails({ + knowledge_bases: [{ id: 'kb-1', name: 'Docs', bindings: [] }], + agents: [], + long_term_memory: { bindings: [] }, + }), null) + assert.equal(parseModelUsageDetails({ + knowledge_bases: [{ id: 'kb-1', name: 'Docs', bindings: 'vlm_model' }], + agents: [], + long_term_memory: { bindings: [] }, + }), null) + assert.equal(modelInUseErrorFromRequest({ + error: { + code: MODEL_IN_USE_ERROR_CODE, + message: 'model is used by 1 knowledge base(s)', + details: null, + }, + }), null) +}) + +test('keeps navigation and localization stable for all resource kinds', () => { + assert.deepEqual( + modelUsageResourceRoute('knowledge_base', 'kb/with slash'), + { path: '/platform/knowledge-bases/kb%2Fwith%20slash' }, + ) + assert.deepEqual( + modelUsageResourceRoute('agent', 'agent-1'), + { path: '/platform/agents', query: { edit: 'agent-1', section: 'model' } }, + ) + assert.deepEqual( + modelUsageResourceRoute('agent', 'agent-1', ['vlm_model']), + { path: '/platform/agents', query: { edit: 'agent-1', section: 'multimodal' } }, + ) + assert.deepEqual( + modelUsageResourceRoute('agent', 'agent-1', ['follow_up_model']), + { path: '/platform/agents', query: { edit: 'agent-1', section: 'suggestions' } }, + ) + assert.equal(modelUsageBindingI18nKey('vlm_model'), 'modelSettings.usage.bindings.vlm_model') + assert.equal(modelUsageBindingI18nKey('future_binding'), 'modelSettings.usage.bindings.unknown') +}) + +test('maps knowledge-base bindings to the configuration section that owns them', () => { + assert.equal(modelUsageKnowledgeBaseSection(['embedding_model']), 'models') + assert.equal(modelUsageKnowledgeBaseSection(['summary_model']), 'models') + assert.equal(modelUsageKnowledgeBaseSection(['wiki_synthesis_model']), 'models') + assert.equal(modelUsageKnowledgeBaseSection(['image_processing_model']), 'multimodal') + assert.equal(modelUsageKnowledgeBaseSection(['vlm_model']), 'multimodal') + assert.equal(modelUsageKnowledgeBaseSection(['asr_model']), 'asr') + assert.equal(modelUsageKnowledgeBaseSection(['future_binding']), 'models') + assert.equal(modelUsageKnowledgeBaseSection(['summary_model', 'vlm_model']), 'models') +}) + +test('maps agent bindings to the configuration section that owns them', () => { + assert.equal(modelUsageAgentSection(['chat_model']), 'model') + assert.equal(modelUsageAgentSection(['rerank_model']), 'model') + assert.equal(modelUsageAgentSection(['query_understand_model']), 'model') + assert.equal(modelUsageAgentSection(['vlm_model']), 'multimodal') + assert.equal(modelUsageAgentSection(['asr_model']), 'multimodal') + assert.equal(modelUsageAgentSection(['follow_up_model']), 'suggestions') + assert.equal(modelUsageAgentSection(['future_binding']), 'model') + assert.equal(modelUsageAgentSection(['chat_model', 'vlm_model']), 'model') + assert.equal(modelUsageAgentSection(['vlm_model', 'follow_up_model']), 'multimodal') +}) diff --git a/frontend/src/api/model/modelUsage.ts b/frontend/src/api/model/modelUsage.ts new file mode 100644 index 00000000..94bc2271 --- /dev/null +++ b/frontend/src/api/model/modelUsage.ts @@ -0,0 +1,182 @@ +export const MODEL_IN_USE_ERROR_CODE = 2300 + +export const KNOWN_MODEL_USAGE_BINDINGS = [ + 'embedding_model', + 'summary_model', + 'image_processing_model', + 'vlm_model', + 'asr_model', + 'wiki_synthesis_model', + 'chat_model', + 'rerank_model', + 'query_understand_model', + 'follow_up_model', + 'extract_model', +] as const + +export type KnownModelUsageBinding = typeof KNOWN_MODEL_USAGE_BINDINGS[number] + +export interface ModelUsageResource { + id: string + name: string + bindings: string[] +} + +export interface ModelUsageDetails { + knowledge_bases: ModelUsageResource[] + agents: ModelUsageResource[] + long_term_memory: { + bindings: string[] + } + knowledge_base_total: number + agent_total: number +} + +export class ModelInUseError extends Error { + readonly details: ModelUsageDetails + + constructor(details: ModelUsageDetails) { + super('model is in use') + this.name = 'ModelInUseError' + this.details = details + } +} + +type UnknownRecord = Record + +function isRecord(value: unknown): value is UnknownRecord { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function parseBindings(value: unknown): string[] | null { + if (!Array.isArray(value) || value.some(binding => typeof binding !== 'string' || binding.trim() === '')) { + return null + } + return [...value] +} + +function parseResources(value: unknown): ModelUsageResource[] | null { + if (!Array.isArray(value)) return null + + const resources: ModelUsageResource[] = [] + for (const item of value) { + if (!isRecord(item) || typeof item.id !== 'string' || item.id.trim() === '' || typeof item.name !== 'string') { + return null + } + const bindings = parseBindings(item.bindings) + if (!bindings || bindings.length === 0) return null + resources.push({ id: item.id, name: item.name, bindings }) + } + return resources +} + +function parseTotal(value: unknown, listed: number): number { + if (typeof value === 'number' && Number.isFinite(value) && value >= listed) { + return Math.floor(value) + } + return listed +} + +export function parseModelUsageDetails(value: unknown): ModelUsageDetails | null { + if (!isRecord(value) || !isRecord(value.long_term_memory)) return null + + const knowledgeBases = parseResources(value.knowledge_bases) + const agents = parseResources(value.agents) + const memoryBindings = parseBindings(value.long_term_memory.bindings) + if (!knowledgeBases || !agents || !memoryBindings) return null + + const details: ModelUsageDetails = { + knowledge_bases: knowledgeBases, + agents, + long_term_memory: { bindings: memoryBindings }, + knowledge_base_total: parseTotal(value.knowledge_base_total, knowledgeBases.length), + agent_total: parseTotal(value.agent_total, agents.length), + } + if (knowledgeBases.length === 0 && agents.length === 0 && memoryBindings.length === 0) { + return null + } + return details +} + +export function modelInUseErrorFromRequest(error: unknown): ModelInUseError | null { + if (!isRecord(error) || !isRecord(error.error) || error.error.code !== MODEL_IN_USE_ERROR_CODE) { + return null + } + const details = parseModelUsageDetails(error.error.details) + return details ? new ModelInUseError(details) : null +} + +const knownBindings = new Set(KNOWN_MODEL_USAGE_BINDINGS) + +export function modelUsageBindingI18nKey(binding: string): string { + const key = knownBindings.has(binding) ? binding : 'unknown' + return `modelSettings.usage.bindings.${key}` +} + +export function modelUsageResourceCount(resources: readonly ModelUsageResource[], total?: number): number { + return typeof total === 'number' && Number.isFinite(total) && total >= resources.length + ? Math.floor(total) + : resources.length +} + +export function modelUsageListTruncated(resources: readonly ModelUsageResource[], total?: number): boolean { + return modelUsageResourceCount(resources, total) > resources.length +} + +export type ModelUsageResourceKind = 'knowledge_base' | 'agent' + +export type KnowledgeBaseModelUsageSection = 'models' | 'multimodal' | 'asr' + +export type AgentModelUsageSection = 'model' | 'multimodal' | 'suggestions' + +const knowledgeBaseUsageSections: Partial> = { + embedding_model: 'models', + summary_model: 'models', + wiki_synthesis_model: 'models', + image_processing_model: 'multimodal', + vlm_model: 'multimodal', + asr_model: 'asr', +} + +const agentUsageSections: Partial> = { + chat_model: 'model', + rerank_model: 'model', + query_understand_model: 'model', + vlm_model: 'multimodal', + asr_model: 'multimodal', + follow_up_model: 'suggestions', +} + +export function modelUsageKnowledgeBaseSection( + bindings: readonly string[], +): KnowledgeBaseModelUsageSection { + for (const binding of bindings) { + const section = knowledgeBaseUsageSections[binding as KnownModelUsageBinding] + if (section) return section + } + return 'models' +} + +export function modelUsageAgentSection( + bindings: readonly string[], +): AgentModelUsageSection { + for (const binding of bindings) { + const section = agentUsageSections[binding as KnownModelUsageBinding] + if (section) return section + } + return 'model' +} + +export function modelUsageResourceRoute( + kind: ModelUsageResourceKind, + id: string, + bindings: readonly string[] = [], +) { + if (kind === 'knowledge_base') { + return { path: `/platform/knowledge-bases/${encodeURIComponent(id)}` } + } + return { + path: '/platform/agents', + query: { edit: id, section: modelUsageAgentSection(bindings) }, + } +} diff --git a/frontend/src/components/AgentCreateContextualGuide.vue b/frontend/src/components/AgentCreateContextualGuide.vue index d502b652..2d4b93d3 100644 --- a/frontend/src/components/AgentCreateContextualGuide.vue +++ b/frontend/src/components/AgentCreateContextualGuide.vue @@ -7,7 +7,7 @@ import { computed, ref, watch } from 'vue' import SpotlightGuide from '@/components/SpotlightGuide.vue' import { - AGENT_EDITOR_FOCUS_SECTION_EVENT, + focusAgentEditorSection, markContextualGuideDone, isContextualGuideDone, isGlobalUserGuideDone, @@ -21,76 +21,70 @@ const props = defineProps<{ const active = ref(false) -const focusSection = (section: string) => { - window.dispatchEvent( - new CustomEvent(AGENT_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }), - ) -} - const guideSteps = computed(() => { const steps: SpotlightGuideStep[] = [ { key: 'mode', target: '[data-guide="agent-create-mode"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusAgentEditorSection('basic'), }, { key: 'agentType', target: '[data-guide="agent-create-agent-type"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusAgentEditorSection('basic'), optional: true, }, { key: 'name', target: '[data-guide="agent-create-name"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusAgentEditorSection('basic'), }, { key: 'navModel', target: '[data-guide="agent-editor-nav-model"]', placement: 'right', - before: () => focusSection('model'), + before: () => focusAgentEditorSection('model'), }, { key: 'model', target: '[data-guide="agent-create-model"]', placement: 'right', - before: () => focusSection('model'), + before: () => focusAgentEditorSection('model'), }, { key: 'navKnowledge', target: '[data-guide="agent-editor-nav-knowledge"]', placement: 'right', - before: () => focusSection('knowledge'), + before: () => focusAgentEditorSection('knowledge'), }, { key: 'knowledge', target: '[data-guide="agent-create-knowledge"]', placement: 'right', - before: () => focusSection('knowledge'), + before: () => focusAgentEditorSection('knowledge'), }, { key: 'navWebsearch', target: '[data-guide="agent-editor-nav-websearch"]', placement: 'right', - before: () => focusSection('websearch'), + before: () => focusAgentEditorSection('websearch'), optional: true, }, { key: 'navMultimodal', target: '[data-guide="agent-editor-nav-multimodal"]', placement: 'right', - before: () => focusSection('multimodal'), + before: () => focusAgentEditorSection('multimodal'), optional: true, }, { key: 'multimodal', target: '[data-guide="agent-create-multimodal"]', placement: 'right', - before: () => focusSection('multimodal'), + before: () => focusAgentEditorSection('multimodal'), optional: true, }, ] @@ -100,7 +94,7 @@ const guideSteps = computed(() => { key: 'navTools', target: '[data-guide="agent-editor-nav-tools"]', placement: 'right', - before: () => focusSection('tools'), + before: () => focusAgentEditorSection('tools'), optional: true, }) } @@ -109,7 +103,7 @@ const guideSteps = computed(() => { key: 'submit', target: '[data-guide="agent-create-submit"]', placement: 'top', - before: () => focusSection('basic'), + before: () => focusAgentEditorSection('basic'), interact: true, }) diff --git a/frontend/src/components/KbCreateContextualGuide.vue b/frontend/src/components/KbCreateContextualGuide.vue index d9a8a82a..88ace311 100644 --- a/frontend/src/components/KbCreateContextualGuide.vue +++ b/frontend/src/components/KbCreateContextualGuide.vue @@ -7,7 +7,7 @@ import { computed, ref, watch } from 'vue' import SpotlightGuide from '@/components/SpotlightGuide.vue' import { - KB_EDITOR_FOCUS_SECTION_EVENT, + focusKbEditorSection, markContextualGuideDone, isContextualGuideDone, isGlobalUserGuideDone, @@ -22,25 +22,19 @@ const props = defineProps<{ const active = ref(false) -const focusSection = (section: string) => { - window.dispatchEvent( - new CustomEvent(KB_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }), - ) -} - const guideSteps = computed(() => { const steps: SpotlightGuideStep[] = [ { key: 'type', target: '[data-guide="kb-create-type"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusKbEditorSection('basic'), }, { key: 'name', target: '[data-guide="kb-create-name"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusKbEditorSection('basic'), }, ] @@ -49,7 +43,7 @@ const guideSteps = computed(() => { key: 'indexing', target: '[data-guide="kb-create-indexing"]', placement: 'right', - before: () => focusSection('basic'), + before: () => focusKbEditorSection('basic'), }) } @@ -58,13 +52,13 @@ const guideSteps = computed(() => { key: 'navModels', target: '[data-guide="kb-editor-nav-models"]', placement: 'right', - before: () => focusSection('models'), + before: () => focusKbEditorSection('models'), }, { key: 'llm', target: '[data-guide="kb-create-llm"]', placement: 'right', - before: () => focusSection('models'), + before: () => focusKbEditorSection('models'), }, ) @@ -73,7 +67,7 @@ const guideSteps = computed(() => { key: 'embedding', target: '[data-guide="kb-create-embedding"]', placement: 'right', - before: () => focusSection('models'), + before: () => focusKbEditorSection('models'), optional: true, }) } @@ -84,42 +78,42 @@ const guideSteps = computed(() => { key: 'parser', target: '[data-guide="kb-editor-nav-parser"]', placement: 'right', - before: () => focusSection('parser'), + before: () => focusKbEditorSection('parser'), optional: true, }, { key: 'chunking', target: '[data-guide="kb-editor-nav-chunking"]', placement: 'right', - before: () => focusSection('chunking'), + before: () => focusKbEditorSection('chunking'), optional: true, }, { key: 'storage', target: '[data-guide="kb-editor-nav-storage"]', placement: 'right', - before: () => focusSection('storage'), + before: () => focusKbEditorSection('storage'), optional: true, }, { key: 'navMultimodal', target: '[data-guide="kb-editor-nav-multimodal"]', placement: 'right', - before: () => focusSection('multimodal'), + before: () => focusKbEditorSection('multimodal'), optional: true, }, { key: 'multimodalToggle', target: '[data-guide="kb-create-multimodal-toggle"]', placement: 'right', - before: () => focusSection('multimodal'), + before: () => focusKbEditorSection('multimodal'), optional: true, }, { key: 'multimodalVllm', target: '[data-guide="kb-create-multimodal-vllm"]', placement: 'right', - before: () => focusSection('multimodal'), + before: () => focusKbEditorSection('multimodal'), optional: true, }, ) @@ -128,7 +122,7 @@ const guideSteps = computed(() => { key: 'faq', target: '[data-guide="kb-editor-nav-faq"]', placement: 'right', - before: () => focusSection('faq'), + before: () => focusKbEditorSection('faq'), optional: true, }) } @@ -137,7 +131,7 @@ const guideSteps = computed(() => { key: 'submit', target: '[data-guide="kb-create-submit"]', placement: 'top', - before: () => focusSection('basic'), + before: () => focusKbEditorSection('basic'), interact: true, }) diff --git a/frontend/src/components/modelSelectorFilter.test.ts b/frontend/src/components/modelSelectorFilter.test.ts index 3397af18..c4213876 100644 --- a/frontend/src/components/modelSelectorFilter.test.ts +++ b/frontend/src/components/modelSelectorFilter.test.ts @@ -1,10 +1,16 @@ import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' import test from 'node:test' import type { ModelConfig } from '@/api/model' import { filterModelsByType } from './modelSelectorFilter.ts' +const selectorSource = readFileSync(new URL('./ModelSelector.vue', import.meta.url), 'utf8') +const kbEditorSource = readFileSync(new URL('../views/knowledge/KnowledgeBaseEditorModal.vue', import.meta.url), 'utf8') +const agentEditorSource = readFileSync(new URL('../views/agent/AgentEditorModal.vue', import.meta.url), 'utf8') +const modelSettingsSource = readFileSync(new URL('../views/settings/ModelSettings.vue', import.meta.url), 'utf8') + function model(overrides: Partial & Pick): ModelConfig { return { name: overrides.name ?? overrides.id!, @@ -15,8 +21,8 @@ function model(overrides: Partial & Pick assert.deepEqual(ids, ['vllm-1', 'chat-vision']) }) +test('VLLM selector keeps the standard model-name presentation without type suffixes', () => { + assert.match(selectorSource, /:label="modelDisplayName\(model\)"/) + assert.doesNotMatch(selectorSource, /modelOptionTypeLabel|modelOptionLabel|vlmOptionType/) +}) + +test('VLM selection, knowledge-base and agent saves, and deletion preserve the selected model ID', () => { + assert.match(selectorSource, /:key="model\.id"[\s\S]*:value="model\.id"/) + assert.match(selectorSource, /emit\('update:selectedModelId', value \|\| ''\)/) + assert.match(kbEditorSource, /handleMultimodalVLLMChange[\s\S]*vllmModelId = modelId/) + assert.match(kbEditorSource, /vlm_config = \{[\s\S]*model_id:[\s\S]*vllmModelId/) + assert.match(agentEditorSource, /model-type="VLLM"[\s\S]*formData\.config\.vlm_model_id[\s\S]*formData\.config\.vlm_model_id = val/) + assert.match(agentEditorSource, /updateAgent\(formData\.value\.id, formData\.value\)/) + assert.match(modelSettingsSource, /@confirm="deleteModel\(model\._modelType, model\.id\)"/) + assert.match(modelSettingsSource, /allModels\.value\.find\(m => m\.id === modelId\)/) + assert.match(modelSettingsSource, /await deleteModelAPI\(modelId\)/) +}) + test('VLLM selector excludes non-vision chat and other types even with supports_vision', () => { const ids = filterModelsByType(fixtures, 'VLLM') assert.ok(!ids.some((m) => m.id === 'chat-text')) diff --git a/frontend/src/config/contextualGuides.ts b/frontend/src/config/contextualGuides.ts index a3c223cf..5b1f575e 100644 --- a/frontend/src/config/contextualGuides.ts +++ b/frontend/src/config/contextualGuides.ts @@ -19,12 +19,18 @@ export type ContextualGuideTourId = | 'agentList' | 'agentCreate' -const focusKbEditorSection = (section: string) => { +export const focusKbEditorSection = (section: string) => { window.dispatchEvent( new CustomEvent(KB_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }), ) } +export const focusAgentEditorSection = (section: string) => { + window.dispatchEvent( + new CustomEvent(AGENT_EDITOR_FOCUS_SECTION_EVENT, { detail: { section } }), + ) +} + const focusKbEditorBasic = () => focusKbEditorSection('basic') export interface ContextualGuideTourConfig { diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index c58c4750..f4260096 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -4671,6 +4671,29 @@ export default { }, builtinTag: 'Built-in', confirmDelete: 'Delete model "{name}"?', + usage: { + title: 'Model cannot be deleted', + description: 'Model "{name}" is still referenced by the following settings. Open each configuration and choose another model before deleting it.', + knowledgeBases: 'Knowledge bases ({count})', + agents: 'Agents ({count})', + longTermMemory: 'Long-term memory', + openConfiguration: 'Open settings', + truncated: 'Showing the first {shown} of {total}', + bindings: { + embedding_model: 'Embedding model', + summary_model: 'Summary model', + image_processing_model: 'Image processing model', + vlm_model: 'Vision model', + asr_model: 'Speech recognition model', + wiki_synthesis_model: 'Wiki synthesis model', + chat_model: 'Chat model', + rerank_model: 'Re-ranking model', + query_understand_model: 'Query understanding model', + follow_up_model: 'Follow-up model', + extract_model: 'Memory extraction model', + unknown: 'Other model setting' + } + }, debug: { title: 'Model Test', description: 'Send a real request to a saved model and inspect the response', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 65aa641a..832d2ac9 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1976,6 +1976,29 @@ export default { copySuffix: ' 사본', builtinTag: '기본제공', confirmDelete: '모델 "{name}"을(를) 삭제하시겠습니까?', + usage: { + title: '모델을 삭제할 수 없습니다', + description: '모델 "{name}"이(가) 다음 설정에서 사용 중입니다. 각 설정을 열어 다른 모델로 변경한 후 다시 삭제하세요.', + knowledgeBases: '지식 베이스 ({count})', + agents: '에이전트 ({count})', + longTermMemory: '장기 메모리', + openConfiguration: '설정 열기', + truncated: '전체 {total}개 중 앞 {shown}개만 표시합니다', + bindings: { + embedding_model: 'Embedding 모델', + summary_model: '요약 모델', + image_processing_model: '이미지 처리 모델', + vlm_model: '비전 모델', + asr_model: '음성 인식 모델', + wiki_synthesis_model: 'Wiki 종합 모델', + chat_model: '대화 모델', + rerank_model: '재정렬 모델', + query_understand_model: '질의 이해 모델', + follow_up_model: '후속 질문 모델', + extract_model: '메모리 추출 모델', + unknown: '기타 모델 설정' + } + }, debug: { title: '모델 테스트', description: '구성된 모델에 실제 요청을 보내고 응답과 소요 시간을 확인합니다', diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 5382e9b4..1128cb57 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1976,6 +1976,29 @@ export default { copySuffix: ' копия', builtinTag: 'Встроенная', confirmDelete: 'Удалить модель «{name}»?', + usage: { + title: 'Модель нельзя удалить', + description: 'Модель «{name}» используется в следующих настройках. Откройте каждую конфигурацию и выберите другую модель, затем повторите удаление.', + knowledgeBases: 'Базы знаний ({count})', + agents: 'Агенты ({count})', + longTermMemory: 'Долговременная память', + openConfiguration: 'Открыть настройки', + truncated: 'Показаны первые {shown} из {total}', + bindings: { + embedding_model: 'Модель эмбеддингов', + summary_model: 'Модель суммаризации', + image_processing_model: 'Модель обработки изображений', + vlm_model: 'Модель компьютерного зрения', + asr_model: 'Модель распознавания речи', + wiki_synthesis_model: 'Модель синтеза Wiki', + chat_model: 'Диалоговая модель', + rerank_model: 'Модель реранжирования', + query_understand_model: 'Модель понимания запроса', + follow_up_model: 'Модель уточняющих вопросов', + extract_model: 'Модель извлечения памяти', + unknown: 'Другая настройка модели' + } + }, debug: { title: 'Тест модели', description: 'Отправьте реальный запрос к настроенной модели и проверьте ответ и время выполнения', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index b5142d82..92ca1514 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1978,6 +1978,29 @@ export default { copySuffix: ' 副本', builtinTag: '内置', confirmDelete: '确定删除模型「{name}」吗?', + usage: { + title: '模型无法删除', + description: '模型「{name}」仍被以下配置引用。请先打开对应配置并更换模型,再重新删除。', + knowledgeBases: '知识库({count})', + agents: '智能体({count})', + longTermMemory: '长期记忆', + openConfiguration: '打开配置', + truncated: '仅显示前 {shown} 个,共 {total} 个', + bindings: { + embedding_model: 'Embedding 模型', + summary_model: '摘要模型', + image_processing_model: '图片处理模型', + vlm_model: '视觉理解模型', + asr_model: '语音识别模型', + wiki_synthesis_model: 'Wiki 综合模型', + chat_model: '对话模型', + rerank_model: '重排序模型', + query_understand_model: '问题理解模型', + follow_up_model: '追问模型', + extract_model: '记忆提取模型', + unknown: '其他模型配置' + } + }, debug: { title: '模型测试', description: '向已配置的模型发送真实请求,查看响应与耗时', diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue index 7cee3807..757f0b03 100644 --- a/frontend/src/views/agent/AgentEditorModal.vue +++ b/frontend/src/views/agent/AgentEditorModal.vue @@ -3,6 +3,9 @@
+
+ +
@@ -815,8 +819,19 @@ const loadAllModels = async (force = false) => { } } +let kbEditorLoadGeneration = 0 + +const isCurrentKBLoad = (generation: number, kbId: string) => ( + generation === kbEditorLoadGeneration + && props.visible + && activeKbId.value === kbId +) + // 加载知识库数据(编辑模式) -const loadKBData = async (kbIdOverride?: string) => { +const loadKBData = async ( + kbIdOverride?: string, + generation = kbEditorLoadGeneration, +) => { const kbId = kbIdOverride ?? activeKbId.value if (editorMode.value !== 'edit' || !kbId) return @@ -826,6 +841,8 @@ const loadKBData = async (kbIdOverride?: string) => { getKnowledgeBaseById(kbId), listKnowledgeFiles(kbId, { page: 1, page_size: 1 }) ]) + + if (!isCurrentKBLoad(generation, kbId)) return if (!kbInfo || !kbInfo.data) { throw new Error(t('knowledgeEditor.messages.notFound')) @@ -940,11 +957,14 @@ const loadKBData = async (kbIdOverride?: string) => { initialStorageProvider.value = formData.value.storageProvider initialIndexingStrategy.value = { ...formData.value.indexingStrategy } } catch (error) { + if (!isCurrentKBLoad(generation, kbId)) return console.error('Failed to load knowledge base data:', error) MessagePlugin.error(t('knowledgeEditor.messages.loadDataFailed')) handleClose() } finally { - loading.value = false + if (isCurrentKBLoad(generation, kbId)) { + loading.value = false + } } } @@ -1530,15 +1550,19 @@ const resetState = () => { const handleClose = () => { emit('update:visible', false) setTimeout(() => { + if (props.visible) return resetState() }, 300) } // 监听弹窗打开/关闭 watch(() => props.visible, async (newVal) => { + const generation = ++kbEditorLoadGeneration if (newVal) { // 打开弹窗时,先重置状态 resetState() + loading.value = true + const targetKbId = props.kbId // 检查是否有初始 section,如果有则跳转 if (uiStore.kbEditorInitialSection) { @@ -1547,20 +1571,24 @@ watch(() => props.visible, async (newVal) => { // 加载模型列表与空间默认存储引擎(创建 KB 时即使用,不依赖是否打开「存储引擎」Tab) await Promise.all([loadAllModels(), loadTenantDefaultStorageProvider()]) + + if (generation !== kbEditorLoadGeneration || !props.visible) return // 根据模式加载数据 - if (props.mode === 'edit' && props.kbId) { - await loadKBData() + if (props.mode === 'edit' && targetKbId) { + await loadKBData(targetKbId, generation) } else { // 创建模式:初始化空表单,并预填空间默认存储引擎 formData.value = initFormData(props.initialType || 'document') formData.value.storageProvider = tenantDefaultStorageProvider.value hasFiles.value = false applyDefaultModelsIfEmpty() + loading.value = false } } else { // 关闭弹窗时,延迟重置状态(等待动画结束) setTimeout(() => { + if (props.visible) return resetState() currentSection.value = 'basic' // 重置为默认 section }, 300) @@ -1608,6 +1636,16 @@ watch( overflow: hidden; } +.editor-initializing { + position: absolute; + inset: 0; + z-index: 20; + display: flex; + align-items: center; + justify-content: center; + background: var(--td-bg-color-container); +} + .close-btn { position: absolute; top: 20px; diff --git a/frontend/src/views/settings/ModelSettings.vue b/frontend/src/views/settings/ModelSettings.vue index ba50c641..749c1242 100644 --- a/frontend/src/views/settings/ModelSettings.vue +++ b/frontend/src/views/settings/ModelSettings.vue @@ -132,6 +132,124 @@
+ +
+

+ {{ $t('modelSettings.usage.description', { name: usageConflictModelName }) }} +

+ +
+
+

+ {{ $t('modelSettings.usage.knowledgeBases', { + count: modelUsageResourceCount(usageConflict.knowledge_bases, usageConflict.knowledge_base_total) + }) }} +

+
    +
  • +
    + {{ resource.name || resource.id }} +
    + + {{ $t(modelUsageBindingI18nKey(binding)) }} + +
    +
    + + {{ $t('modelSettings.usage.openConfiguration') }} + +
  • +
+

+ {{ $t('modelSettings.usage.truncated', { + shown: usageConflict.knowledge_bases.length, + total: modelUsageResourceCount(usageConflict.knowledge_bases, usageConflict.knowledge_base_total) + }) }} +

+
+ +
+

{{ $t('modelSettings.usage.agents', { + count: modelUsageResourceCount(usageConflict.agents, usageConflict.agent_total) + }) }}

+
    +
  • +
    + {{ resource.name || resource.id }} +
    + + {{ $t(modelUsageBindingI18nKey(binding)) }} + +
    +
    + + {{ $t('modelSettings.usage.openConfiguration') }} + +
  • +
+

+ {{ $t('modelSettings.usage.truncated', { + shown: usageConflict.agents.length, + total: modelUsageResourceCount(usageConflict.agents, usageConflict.agent_total) + }) }} +

+
+ +
+

{{ $t('modelSettings.usage.longTermMemory') }}

+
+
+ + {{ $t(modelUsageBindingI18nKey(binding)) }} + +
+
+
+
+ +
+ {{ $t('common.close') }} +
+
+
+ @@ -141,30 +259,58 @@