fix(models): show usage details when deletion is blocked (#2975)

* fix(models): show usage details when deletion is blocked

* fix(models): open the matching agent section and cap usage lists

Agent "open configuration" now lands on the tab that owns the binding
(VLM/ASR vs follow-ups), and delete failures keep the server message when
structured details cannot be parsed. Listed KB/agent rows are capped at 50
while totals still drive the deletion guard and dialog headings.

---------

Co-authored-by: Leon <leon_hfut@foxmail.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
leon4z 2026-09-02 17:20:37 +08:00 committed by GitHub
parent 3d40ee0aff
commit 988cbb0330
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
38 changed files with 1733 additions and 113 deletions

View File

@ -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 表示模型不存在。
## 参数说明

View File

@ -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": {

View File

@ -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"
}
}
}
}

View File

@ -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:

View File

@ -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
}
}

View File

@ -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<void> {
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);
});
});

View File

@ -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')
})

View File

@ -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<string, unknown>
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<string>(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<Record<KnownModelUsageBinding, KnowledgeBaseModelUsageSection>> = {
embedding_model: 'models',
summary_model: 'models',
wiki_synthesis_model: 'models',
image_processing_model: 'multimodal',
vlm_model: 'multimodal',
asr_model: 'asr',
}
const agentUsageSections: Partial<Record<KnownModelUsageBinding, AgentModelUsageSection>> = {
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) },
}
}

View File

@ -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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
key: 'submit',
target: '[data-guide="agent-create-submit"]',
placement: 'top',
before: () => focusSection('basic'),
before: () => focusAgentEditorSection('basic'),
interact: true,
})

View File

@ -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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
key: 'indexing',
target: '[data-guide="kb-create-indexing"]',
placement: 'right',
before: () => focusSection('basic'),
before: () => focusKbEditorSection('basic'),
})
}
@ -58,13 +52,13 @@ const guideSteps = computed<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
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<SpotlightGuideStep[]>(() => {
key: 'submit',
target: '[data-guide="kb-create-submit"]',
placement: 'top',
before: () => focusSection('basic'),
before: () => focusKbEditorSection('basic'),
interact: true,
})

View File

@ -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<ModelConfig> & Pick<ModelConfig, 'id' | 'type'>): ModelConfig {
return {
name: overrides.name ?? overrides.id!,
@ -15,8 +21,8 @@ function model(overrides: Partial<ModelConfig> & Pick<ModelConfig, 'id' | 'type'
}
const fixtures: ModelConfig[] = [
model({ id: 'vllm-1', type: 'VLLM' }),
model({ id: 'chat-vision', type: 'KnowledgeQA', parameters: { supports_vision: true } }),
model({ id: 'vllm-1', name: 'MiniMax-M3', display_name: 'MiniMax M3', type: 'VLLM' }),
model({ id: 'chat-vision', name: 'MiniMax-M3', display_name: 'MiniMax M3', type: 'KnowledgeQA', parameters: { supports_vision: true } }),
model({ id: 'chat-text', type: 'KnowledgeQA' }),
model({ id: 'embed-vision', type: 'Embedding', parameters: { supports_vision: true } }),
model({ id: 'embed-1', type: 'Embedding' }),
@ -27,6 +33,23 @@ test('VLLM selector includes native VLLM and vision-capable chat models', () =>
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'))

View File

@ -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 {

View File

@ -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',

View File

@ -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: '구성된 모델에 실제 요청을 보내고 응답과 소요 시간을 확인합니다',

View File

@ -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: 'Отправьте реальный запрос к настроенной модели и проверьте ответ и время выполнения',

View File

@ -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: '向已配置的模型发送真实请求,查看响应与耗时',

View File

@ -3,6 +3,9 @@
<Transition name="modal">
<div v-if="visible" class="settings-overlay" @click.self="handleClose">
<div class="settings-modal">
<div v-if="editorInitializing" class="editor-initializing" role="status" :aria-label="$t('common.loading')">
<t-loading size="medium" :text="$t('common.loading')" />
</div>
<!-- 关闭按钮 -->
<button class="close-btn" @click="handleClose" :aria-label="$t('common.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
@ -1777,6 +1780,7 @@
$t('common.cancel')
}}</t-button>
<t-button v-if="!props.readOnly" theme="primary" data-guide="agent-create-submit" :loading="saving"
:disabled="editorInitializing"
@click="handleSave">{{
saveButtonLabel
}}</t-button>
@ -2014,6 +2018,7 @@ onBeforeUnmount(() => {
})
const saving = ref(false);
const editorInitializing = ref(false);
const allModels = ref<ModelConfig[]>([]);
const kbOptions = ref<{ label: string; value: string; type?: 'document' | 'faq'; count?: number; shared?: boolean; orgName?: string; ragEnabled?: boolean; wikiEnabled?: boolean; capabilities?: KBCapabilities }[]>([]);
@ -3358,13 +3363,19 @@ const needsRerankModel = computed(() => {
return false;
});
let editorInitializationGeneration = 0;
// 监听可见性变化,重置表单
watch(() => props.visible, async (val) => {
const generation = ++editorInitializationGeneration;
if (val) {
editorInitializing.value = true;
try {
savedAgent.value = null;
currentSection.value = resolveEditorSection(props.initialSection);
// 先加载依赖数据(包括默认配置)
await loadDependencies();
if (generation !== editorInitializationGeneration || !props.visible) return;
if (props.mode === 'edit' && props.agent) {
// 深度复制对象以避免引用问题
@ -3502,11 +3513,21 @@ watch(() => props.visible, async (val) => {
}
await syncInstalledSkills()
if (generation !== editorInitializationGeneration || !props.visible) return;
if (props.initialHighlightField) {
await applyInitialFieldHighlight(props.initialHighlightField);
if (generation !== editorInitializationGeneration || !props.visible) return;
}
} catch (error) {
console.error('Failed to initialize agent editor', error);
} finally {
if (generation === editorInitializationGeneration && props.visible) {
editorInitializing.value = false;
}
}
} else {
editorInitializing.value = false;
clearFieldHighlight();
agentIMChannelCount.value = 0;
agentEmbedChannelCount.value = 0;
@ -4827,6 +4848,16 @@ const handleSave = async () => {
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: 16px;

View File

@ -812,7 +812,7 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
@ -828,7 +828,7 @@ import type { SharedAgentInfo, OrganizationSharedAgentItem } from '@/api/organiz
import AgentEditorModal from './AgentEditorModal.vue'
import ContextualGuide from '@/components/ContextualGuide.vue'
import TenantModelsGuide from '@/components/TenantModelsGuide.vue'
import { markContextualGuideDone } from '@/config/contextualGuides'
import { focusAgentEditorSection, markContextualGuideDone } from '@/config/contextualGuides'
import { useTenantModelReadiness } from '@/composables/useTenantModelReadiness'
import { useUIStore } from '@/stores/ui'
import AgentAvatar from '@/components/AgentAvatar.vue'
@ -1108,7 +1108,7 @@ const applyAgentListData = (res: { data: CustomAgent[]; disabled_own_agent_ids:
showMore: false,
disabled_by_me: disabledOwnIds.includes(agent.id)
}))
checkAndOpenEditModal()
void checkAndOpenEditModal()
}
const fetchList = (force = false) => {
@ -1118,7 +1118,7 @@ const fetchList = (force = false) => {
orgStore.fetchOrganizations({ force }),
orgStore.fetchSharedAgents({ force }),
]).finally(() => { loading.value = false }).then(() => {
checkAndOpenEditModal()
void checkAndOpenEditModal()
// 各空间智能体数量已由 GET /organizations 的 resource_counts 带回,存于 orgStore.resourceCounts
const counts = orgStore.resourceCounts?.agents?.by_organization
if (counts) spaceAgentCountByOrg.value = { ...counts }
@ -1138,7 +1138,10 @@ const resolveAgentForEdit = (editId: string, sourceTenantId?: string): CustomAge
return null
}
const checkAndOpenEditModal = () => {
let editOpenGeneration = 0
const checkAndOpenEditModal = async () => {
const generation = ++editOpenGeneration
const editId = route.query.edit as string
const section = route.query.section as string
const sourceTenantId = route.query.sourceTenantId as string | undefined
@ -1152,13 +1155,36 @@ const checkAndOpenEditModal = () => {
}
if (editId) {
const agent = resolveAgentForEdit(editId, sourceTenantId)
if (agent) {
// A route change can remove a creator filter before the corresponding
// all-agent fetch completes. Keep the deep-link query intact so the list
// refresh callback can resolve and open the target instead of losing it.
if (!agent) return
const requestedSection = section || 'basic'
const requestedHighlight = (route.query.highlight as string) || ''
if (
editorVisible.value
&& editingAgent.value?.id === agent.id
&& !requestedHighlight
) {
// Global Settings may be covering this exact editor. Preserve any
// unsaved draft and focus the requested configuration section in place.
editorInitialSection.value = requestedSection
focusAgentEditorSection(requestedSection)
} else {
// A global Settings dialog can be opened on top of an existing agent
// editor. Flush visible=false before loading the deep-linked target so
// AgentEditorModal's visibility watcher rebuilds its form data.
editorVisible.value = false
await nextTick()
if (generation !== editOpenGeneration) return
editingAgent.value = agent
editorMode.value = 'edit'
editorInitialSection.value = section || 'basic'
editorInitialHighlightField.value = (route.query.highlight as string) || ''
editorInitialSection.value = requestedSection
editorInitialHighlightField.value = requestedHighlight
editorVisible.value = true
}
if (generation !== editOpenGeneration) return
// Drop the transient edit/section params but preserve other filter
// state (scope / creator / q) so refreshing doesn't reset the view.
const { edit: _e, section: _s, highlight: _h, sourceTenantId: _st, ...rest } = route.query
@ -1174,7 +1200,7 @@ watch(
() => route.query.edit,
(v) => {
if (v && (agents.value.length > 0 || sharedAgents.value.length > 0)) {
checkAndOpenEditModal()
void checkAndOpenEditModal()
}
},
)

View File

@ -3,6 +3,9 @@
<Transition name="modal">
<div v-if="visible" class="settings-overlay" @click.self="handleClose">
<div class="settings-modal">
<div v-if="loading" class="editor-initializing" role="status" :aria-label="$t('common.loading')">
<t-loading size="medium" :text="$t('common.loading')" />
</div>
<!-- 关闭按钮 -->
<button class="close-btn" @click="handleClose" :aria-label="$t('general.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
@ -445,7 +448,8 @@
<t-button theme="default" variant="outline" @click="handleClose">
{{ $t('common.cancel') }}
</t-button>
<t-button theme="primary" data-guide="kb-create-submit" @click="handleSubmit" :loading="saving">
<t-button theme="primary" data-guide="kb-create-submit" @click="handleSubmit" :loading="saving"
:disabled="loading">
{{ saveButtonLabel }}
</t-button>
</div>
@ -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;

View File

@ -132,6 +132,124 @@
</div>
</t-loading>
<t-dialog
v-model:visible="showUsageDialog"
:header="$t('modelSettings.usage.title')"
:footer="false"
width="680px"
destroy-on-close
>
<div v-if="usageConflict" class="model-usage-dialog">
<p class="model-usage-dialog__description">
{{ $t('modelSettings.usage.description', { name: usageConflictModelName }) }}
</p>
<div class="model-usage-dialog__content">
<section v-if="usageConflict.knowledge_bases.length" class="model-usage-group">
<h3>
{{ $t('modelSettings.usage.knowledgeBases', {
count: modelUsageResourceCount(usageConflict.knowledge_bases, usageConflict.knowledge_base_total)
}) }}
</h3>
<ul>
<li v-for="resource in usageConflict.knowledge_bases" :key="resource.id">
<div class="model-usage-resource">
<strong>{{ resource.name || resource.id }}</strong>
<div class="model-usage-bindings">
<t-tag
v-for="(binding, index) in resource.bindings"
:key="`${binding}-${index}`"
size="small"
variant="light"
>
{{ $t(modelUsageBindingI18nKey(binding)) }}
</t-tag>
</div>
</div>
<t-button
theme="primary"
variant="text"
size="small"
@click="openUsageResource('knowledge_base', resource.id, resource.bindings)"
>
{{ $t('modelSettings.usage.openConfiguration') }}
</t-button>
</li>
</ul>
<p
v-if="modelUsageListTruncated(usageConflict.knowledge_bases, usageConflict.knowledge_base_total)"
class="model-usage-truncated"
>
{{ $t('modelSettings.usage.truncated', {
shown: usageConflict.knowledge_bases.length,
total: modelUsageResourceCount(usageConflict.knowledge_bases, usageConflict.knowledge_base_total)
}) }}
</p>
</section>
<section v-if="usageConflict.agents.length" class="model-usage-group">
<h3>{{ $t('modelSettings.usage.agents', {
count: modelUsageResourceCount(usageConflict.agents, usageConflict.agent_total)
}) }}</h3>
<ul>
<li v-for="resource in usageConflict.agents" :key="resource.id">
<div class="model-usage-resource">
<strong>{{ resource.name || resource.id }}</strong>
<div class="model-usage-bindings">
<t-tag
v-for="(binding, index) in resource.bindings"
:key="`${binding}-${index}`"
size="small"
variant="light"
>
{{ $t(modelUsageBindingI18nKey(binding)) }}
</t-tag>
</div>
</div>
<t-button
theme="primary"
variant="text"
size="small"
@click="openUsageResource('agent', resource.id, resource.bindings)"
>
{{ $t('modelSettings.usage.openConfiguration') }}
</t-button>
</li>
</ul>
<p
v-if="modelUsageListTruncated(usageConflict.agents, usageConflict.agent_total)"
class="model-usage-truncated"
>
{{ $t('modelSettings.usage.truncated', {
shown: usageConflict.agents.length,
total: modelUsageResourceCount(usageConflict.agents, usageConflict.agent_total)
}) }}
</p>
</section>
<section v-if="usageConflict.long_term_memory.bindings.length" class="model-usage-group">
<h3>{{ $t('modelSettings.usage.longTermMemory') }}</h3>
<div class="model-usage-memory">
<div class="model-usage-bindings">
<t-tag
v-for="(binding, index) in usageConflict.long_term_memory.bindings"
:key="`${binding}-${index}`"
size="small"
variant="light"
>
{{ $t(modelUsageBindingI18nKey(binding)) }}
</t-tag>
</div>
</div>
</section>
</div>
<div class="model-usage-dialog__actions">
<t-button @click="showUsageDialog = false">{{ $t('common.close') }}</t-button>
</div>
</div>
</t-dialog>
<!-- 模型编辑器抽屉 -->
<ModelEditorDialog v-model:visible="showDialog" :model-type="currentModelType" :model-data="editingModel"
@confirm="handleModelSave" />
@ -141,30 +259,58 @@
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ref, computed, nextTick, onMounted, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { AddIcon, PlayCircleIcon } from 'tdesign-icons-vue-next'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import ModelEditorDialog from '@/components/ModelEditorDialog.vue'
import ModelDebugDrawer from '@/components/ModelDebugDrawer.vue'
import { listModels, createModel, updateModel as updateModelAPI, deleteModel as deleteModelAPI, type ModelConfig } from '@/api/model'
import {
listModels,
createModel,
updateModel as updateModelAPI,
deleteModel as deleteModelAPI,
ModelInUseError,
modelUsageBindingI18nKey,
modelUsageKnowledgeBaseSection,
modelUsageListTruncated,
modelUsageResourceCount,
modelUsageResourceRoute,
type ModelConfig,
type ModelUsageDetails,
type ModelUsageResourceKind,
} from '@/api/model'
import { useAuthStore } from '@/stores/auth'
import { useUIStore } from '@/stores/ui'
import { focusKbEditorSection } from '@/config/contextualGuides'
const { t, te } = useI18n()
const authStore = useAuthStore()
const uiStore = useUIStore()
const router = useRouter()
type ModelType = 'chat' | 'embedding' | 'rerank' | 'vllm' | 'asr'
type FilterType = 'all' | ModelType
const showDialog = ref(false)
const showDebugDrawer = ref(false)
const showUsageDialog = ref(false)
const usageConflict = ref<ModelUsageDetails | null>(null)
const usageConflictModelName = ref('')
const currentModelType = ref<ModelType>('chat')
const editingModel = ref<any>(null)
const loading = ref(true)
const activeTypeFilter = ref<FilterType>('all')
const MODEL_TAB_TYPES: FilterType[] = ['chat', 'embedding', 'rerank', 'vllm', 'asr']
const KNOWLEDGE_BASE_EDITOR_HOST_ROUTES = new Set([
'home',
'knowledgeBaseList',
'knowledgeBaseDetail',
'globalCreatChat',
'kbCreatChat',
'chat',
])
watch(
() => uiStore.settingsInitialSubSection,
(sub) => {
@ -508,10 +654,56 @@ const deleteModel = async (_type: ModelType, modelId: string) => {
await loadModels()
} catch (error: any) {
console.error('删除模型失败:', error)
if (error instanceof ModelInUseError) {
usageConflict.value = error.details
usageConflictModelName.value = model?.display_name || model?.name || modelId
showUsageDialog.value = true
return
}
MessagePlugin.error(error.message || t('modelSettings.toasts.deleteFailed'))
}
}
const openUsageResource = async (
kind: ModelUsageResourceKind,
id: string,
bindings: readonly string[] = [],
) => {
showUsageDialog.value = false
const knowledgeBaseSection = modelUsageKnowledgeBaseSection(bindings)
// The UI store can outlive the route component that owns the KB editor.
// Only focus an existing editor when the current route still mounts one;
// otherwise a stale visible/id pair would make a direct Settings page no-op.
const routeName = router.currentRoute.value.name
const canFocusExistingKnowledgeBase = kind === 'knowledge_base'
&& uiStore.showKBEditorModal
&& uiStore.currentKBId === id
&& typeof routeName === 'string'
&& KNOWLEDGE_BASE_EDITOR_HOST_ROUTES.has(routeName)
uiStore.closeSettings()
await nextTick()
if (canFocusExistingKnowledgeBase) {
// Keep unsaved edits when the referenced KB is already open underneath
// global Settings; only move the existing editor to the relevant section.
focusKbEditorSection(knowledgeBaseSection)
return
}
if (kind === 'knowledge_base') {
uiStore.closeKBEditor()
await nextTick()
}
// Both the KB editor and global Settings can already be open underneath the
// usage dialog. Flush their false state before reusing either component so
// its visible watcher reloads the target object instead of keeping stale data.
await router.push(modelUsageResourceRoute(kind, id, bindings))
if (kind === 'knowledge_base') {
uiStore.openKBSettings(id, knowledgeBaseSection)
}
}
// 获取模型操作菜单选项
const getModelOptions = (type: ModelType, model: any) => {
const options: any[] = []
@ -986,4 +1178,88 @@ onMounted(() => {
margin-bottom: 16px;
}
}
.model-usage-dialog__description {
margin: 0 0 16px;
color: var(--td-text-color-secondary);
line-height: 1.6;
}
.model-usage-dialog__content {
max-height: min(58vh, 560px);
overflow-y: auto;
padding-right: 4px;
}
.model-usage-group {
& + & {
margin-top: 20px;
}
h3 {
margin: 0 0 8px;
font-size: 14px;
font-weight: 600;
color: var(--td-text-color-primary);
}
ul {
margin: 0;
padding: 0;
list-style: none;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
overflow: hidden;
}
li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
& + li {
border-top: 1px solid var(--td-component-stroke);
}
}
}
.model-usage-truncated {
margin: 8px 0 0;
font-size: 12px;
color: var(--td-text-color-secondary);
line-height: 1.5;
}
.model-usage-resource {
min-width: 0;
strong {
display: block;
margin-bottom: 6px;
overflow: hidden;
color: var(--td-text-color-primary);
text-overflow: ellipsis;
white-space: nowrap;
}
}
.model-usage-bindings {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.model-usage-memory {
padding: 10px 12px;
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
}
.model-usage-dialog__actions {
display: flex;
justify-content: flex-end;
margin-top: 20px;
}
</style>

View File

@ -0,0 +1,44 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import test from 'node:test'
const source = readFileSync(new URL('./ModelSettings.vue', import.meta.url), 'utf8')
const agentListSource = readFileSync(new URL('../agent/AgentList.vue', import.meta.url), 'utf8')
const knowledgeBaseEditorSource = readFileSync(
new URL('../knowledge/KnowledgeBaseEditorModal.vue', import.meta.url),
'utf8',
)
const agentEditorSource = readFileSync(new URL('../agent/AgentEditorModal.vue', import.meta.url), 'utf8')
test('model deletion renders structured usage groups and localized fallback errors', () => {
assert.match(source, /error instanceof ModelInUseError/)
assert.match(source, /usageConflict\.knowledge_bases/)
assert.match(source, /usageConflict\.agents/)
assert.match(source, /usageConflict\.long_term_memory\.bindings/)
assert.match(source, /MessagePlugin\.error\(error\.message \|\| t\('modelSettings\.toasts\.deleteFailed'\)\)/)
})
test('referenced knowledge bases and agents open their relevant configuration pages', () => {
assert.match(source, /openUsageResource\('knowledge_base', resource\.id, resource\.bindings\)/)
assert.match(source, /openUsageResource\('agent', resource\.id, resource\.bindings\)/)
assert.match(source, /uiStore\.closeKBEditor\(\)/)
assert.match(source, /uiStore\.closeSettings\(\)/)
assert.match(source, /await nextTick\(\)/)
assert.match(
source,
/const routeName = router\.currentRoute\.value\.name[\s\S]*canFocusExistingKnowledgeBase[\s\S]*KNOWLEDGE_BASE_EDITOR_HOST_ROUTES\.has\(routeName\)[\s\S]*focusKbEditorSection\(knowledgeBaseSection\)/,
)
assert.match(source, /await router\.push\(modelUsageResourceRoute\(kind, id, bindings\)\)/)
assert.match(source, /uiStore\.openKBSettings\(id, knowledgeBaseSection\)/)
assert.match(
agentListSource,
/editingAgent\.value\?\.id === agent\.id[\s\S]*focusAgentEditorSection\(requestedSection\)[\s\S]*editorVisible\.value = false\s*await nextTick\(\)\s*if \(generation !== editOpenGeneration\) return[\s\S]*editorVisible\.value = true/,
)
assert.match(agentListSource, /const agent = resolveAgentForEdit\([\s\S]*if \(!agent\) return[\s\S]*router\.replace/)
assert.match(agentEditorSource, /v-if="editorInitializing"[\s\S]*:disabled="editorInitializing"/)
assert.match(agentEditorSource, /generation !== editorInitializationGeneration \|\| !props\.visible/)
assert.match(knowledgeBaseEditorSource, /v-if="loading"[\s\S]*:disabled="loading"/)
assert.match(knowledgeBaseEditorSource, /isCurrentKBLoad\(generation, kbId\)/)
assert.match(knowledgeBaseEditorSource, /generation !== kbEditorLoadGeneration \|\| !props\.visible/)
assert.match(knowledgeBaseEditorSource, /setTimeout\(\(\) => \{\s*if \(props\.visible\) return\s*resetState\(\)/)
})

View File

@ -74,6 +74,36 @@ func (r *customAgentRepository) CountByModelID(
return count, err
}
// ListModelUsages returns active agents that reference modelID. Only id, name,
// and config are loaded; the config is decoded locally and never returned.
func (r *customAgentRepository) ListModelUsages(
ctx context.Context, tenantID uint64, modelID string,
) ([]types.ModelUsageResource, error) {
rows := make([]*types.CustomAgent, 0)
query := r.db.WithContext(ctx).
Model(&types.CustomAgent{}).
Select("id", "name", "config").
Where("tenant_id = ?", tenantID)
query = scopeCustomAgentsByModelID(query, modelID)
if err := query.Order("name ASC, id ASC").Limit(types.ModelUsageListLimit).Find(&rows).Error; err != nil {
return nil, err
}
usages := make([]types.ModelUsageResource, 0, len(rows))
for _, row := range rows {
bindings := customAgentModelUsageBindings(row, modelID)
if len(bindings) == 0 {
continue
}
usages = append(usages, types.ModelUsageResource{
ID: row.ID,
Name: row.Name,
Bindings: bindings,
})
}
return usages, nil
}
// CountBySandboxConfigID counts agents pointing at a sandbox config.
//
// Used only to warn the admin which agents reference a config; never use it to

View File

@ -217,3 +217,37 @@ func (r *knowledgeBaseRepository) CountByModelID(
err := query.Count(&count).Error
return count, err
}
// ListModelUsages returns active knowledge bases that reference modelID. It
// selects only the columns needed to identify the resource and its bindings;
// GORM's default scope excludes soft-deleted rows.
func (r *knowledgeBaseRepository) ListModelUsages(
ctx context.Context, tenantID uint64, modelID string,
) ([]types.ModelUsageResource, error) {
rows := make([]*types.KnowledgeBase, 0)
query := r.db.WithContext(ctx).
Model(&types.KnowledgeBase{}).
Select(
"id", "name", "embedding_model_id", "summary_model_id",
"image_processing_config", "vlm_config", "asr_config", "wiki_config",
).
Where("tenant_id = ?", tenantID)
query = scopeKnowledgeBasesByModelID(query, modelID)
if err := query.Order("name ASC, id ASC").Limit(types.ModelUsageListLimit).Find(&rows).Error; err != nil {
return nil, err
}
usages := make([]types.ModelUsageResource, 0, len(rows))
for _, row := range rows {
bindings := knowledgeBaseModelUsageBindings(row, modelID)
if len(bindings) == 0 {
continue
}
usages = append(usages, types.ModelUsageResource{
ID: row.ID,
Name: row.Name,
Bindings: bindings,
})
}
return usages, nil
}

View File

@ -1,9 +1,57 @@
package repository
import (
"github.com/Tencent/WeKnora/internal/types"
"gorm.io/gorm"
)
func knowledgeBaseModelUsageBindings(kb *types.KnowledgeBase, modelID string) []types.ModelUsageBinding {
bindings := make([]types.ModelUsageBinding, 0, 6)
if kb.EmbeddingModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingEmbeddingModel)
}
if kb.SummaryModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingSummaryModel)
}
if kb.ImageProcessingConfig.ModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingImageProcessingModel)
}
if kb.VLMConfig.ModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingVLMModel)
}
if kb.ASRConfig.ModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingASRModel)
}
if kb.WikiConfig != nil && kb.WikiConfig.SynthesisModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingWikiSynthesisModel)
}
return bindings
}
func customAgentModelUsageBindings(agent *types.CustomAgent, modelID string) []types.ModelUsageBinding {
bindings := make([]types.ModelUsageBinding, 0, 6)
if agent.Config.ModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingChatModel)
}
if agent.Config.RerankModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingRerankModel)
}
if agent.Config.VLMModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingVLMModel)
}
if agent.Config.ASRModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingASRModel)
}
if agent.Config.QueryUnderstandModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingQueryUnderstandModel)
}
if agent.Config.QuestionSuggestions != nil &&
agent.Config.QuestionSuggestions.FollowUps.ModelID == modelID {
bindings = append(bindings, types.ModelUsageBindingFollowUpModel)
}
return bindings
}
// scopeKnowledgeBasesByModelID filters knowledge_bases rows that reference
// modelID in any model-binding field.
func scopeKnowledgeBasesByModelID(db *gorm.DB, modelID string) *gorm.DB {

View File

@ -2,6 +2,7 @@ package repository
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/types"
@ -68,6 +69,78 @@ func TestCountByModelID_KnowledgeBase(t *testing.T) {
assert.Equal(t, int64(1), count)
}
func TestListModelUsages_KnowledgeBase(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewKnowledgeBaseRepository(db)
modelID := "all-kb-bindings"
allBindings := makeKB(nil)
allBindings.Name = "Zulu KB"
allBindings.EmbeddingModelID = modelID
allBindings.SummaryModelID = modelID
allBindings.ImageProcessingConfig = types.ImageProcessingConfig{ModelID: modelID}
allBindings.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
allBindings.ASRConfig = types.ASRConfig{Enabled: true, ModelID: modelID}
allBindings.WikiConfig = &types.WikiConfig{SynthesisModelID: modelID}
require.NoError(t, db.Create(allBindings).Error)
vlmOnly := makeKB(nil)
vlmOnly.Name = "Alpha KB"
vlmOnly.VLMConfig = types.VLMConfig{Enabled: true, ModelID: modelID}
require.NoError(t, db.Create(vlmOnly).Error)
otherTenant := makeKB(nil)
otherTenant.Name = "Other tenant"
otherTenant.TenantID = 2
otherTenant.EmbeddingModelID = modelID
require.NoError(t, db.Create(otherTenant).Error)
deleted := makeKB(nil)
deleted.Name = "Deleted KB"
deleted.EmbeddingModelID = modelID
require.NoError(t, db.Create(deleted).Error)
require.NoError(t, db.Delete(deleted).Error)
usages, err := repo.ListModelUsages(ctx, 1, modelID)
require.NoError(t, err)
require.Len(t, usages, 2)
assert.Equal(t, "Alpha KB", usages[0].Name)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, usages[0].Bindings)
assert.Equal(t, "Zulu KB", usages[1].Name)
assert.Equal(t, []types.ModelUsageBinding{
types.ModelUsageBindingEmbeddingModel,
types.ModelUsageBindingSummaryModel,
types.ModelUsageBindingImageProcessingModel,
types.ModelUsageBindingVLMModel,
types.ModelUsageBindingASRModel,
types.ModelUsageBindingWikiSynthesisModel,
}, usages[1].Bindings)
}
func TestListModelUsages_KnowledgeBaseRespectsLimit(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewKnowledgeBaseRepository(db)
modelID := "shared-embed"
for i := 0; i < types.ModelUsageListLimit+3; i++ {
kb := makeKB(nil)
kb.Name = fmt.Sprintf("KB %03d", i)
kb.EmbeddingModelID = modelID
require.NoError(t, db.Create(kb).Error)
}
usages, err := repo.ListModelUsages(ctx, 1, modelID)
require.NoError(t, err)
require.Len(t, usages, types.ModelUsageListLimit)
assert.Equal(t, "KB 000", usages[0].Name)
count, err := repo.CountByModelID(ctx, 1, modelID)
require.NoError(t, err)
assert.Equal(t, int64(types.ModelUsageListLimit+3), count)
}
func TestCountByModelID_CustomAgent(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
@ -112,6 +185,66 @@ func TestCountByModelID_CustomAgent(t *testing.T) {
assert.Equal(t, int64(1), count)
}
func TestListModelUsages_CustomAgent(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)
repo := NewCustomAgentRepository(db)
modelID := "all-agent-bindings"
allBindings := &types.CustomAgent{
ID: uuid.New().String(),
Name: "Zulu agent",
TenantID: 1,
Config: types.CustomAgentConfig{
ModelID: modelID,
RerankModelID: modelID,
VLMModelID: modelID,
ASRModelID: modelID,
QueryUnderstandModelID: modelID,
QuestionSuggestions: &types.QuestionSuggestionConfig{
FollowUps: types.FollowUpSuggestionConfig{ModelID: modelID},
},
},
}
require.NoError(t, repo.CreateAgent(ctx, allBindings))
vlmOnly := &types.CustomAgent{
ID: uuid.New().String(),
Name: "Alpha agent",
TenantID: 1,
Config: types.CustomAgentConfig{VLMModelID: modelID},
}
require.NoError(t, repo.CreateAgent(ctx, vlmOnly))
otherTenant := &types.CustomAgent{
ID: uuid.New().String(), Name: "Other tenant", TenantID: 2,
Config: types.CustomAgentConfig{ModelID: modelID},
}
require.NoError(t, repo.CreateAgent(ctx, otherTenant))
deleted := &types.CustomAgent{
ID: uuid.New().String(), Name: "Deleted agent", TenantID: 1,
Config: types.CustomAgentConfig{ModelID: modelID},
}
require.NoError(t, repo.CreateAgent(ctx, deleted))
require.NoError(t, repo.DeleteAgent(ctx, deleted.ID, deleted.TenantID))
usages, err := repo.ListModelUsages(ctx, 1, modelID)
require.NoError(t, err)
require.Len(t, usages, 2)
assert.Equal(t, "Alpha agent", usages[0].Name)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, usages[0].Bindings)
assert.Equal(t, "Zulu agent", usages[1].Name)
assert.Equal(t, []types.ModelUsageBinding{
types.ModelUsageBindingChatModel,
types.ModelUsageBindingRerankModel,
types.ModelUsageBindingVLMModel,
types.ModelUsageBindingASRModel,
types.ModelUsageBindingQueryUnderstandModel,
types.ModelUsageBindingFollowUpModel,
}, usages[1].Bindings)
}
func TestCustomAgentSandboxConfigReferences(t *testing.T) {
ctx := context.Background()
db := setupModelUsageTestDB(t)

View File

@ -125,9 +125,15 @@ func (r *fakeKBRepo) CountByVectorStoreID(_ context.Context, _ *gorm.DB, _ uint6
func (r *fakeKBRepo) CountByModelID(_ context.Context, _ uint64, _ string) (int64, error) {
return 0, nil
}
func (r *fakeKBRepo) ListModelUsages(_ context.Context, _ uint64, _ string) ([]types.ModelUsageResource, error) {
return []types.ModelUsageResource{}, nil
}
func (r *fakeKBRepo) SetUserKBPin(_ context.Context, _ uint64, _ string, _ string, _ bool) (*time.Time, error) {
return nil, nil
}
func (r *fakeKBRepo) ListUserKBPinIDs(_ context.Context, _ uint64, _ string) (map[string]time.Time, error) {
return map[string]time.Time{}, nil
}

View File

@ -375,44 +375,28 @@ func (s *modelService) DeleteModel(ctx context.Context, id string) error {
return apperrors.NewBadRequestError("builtin models cannot be deleted")
}
kbCount, err := s.kbRepo.CountByModelID(ctx, tenantID, id)
usage, err := s.getModelUsageDetails(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": id,
})
return err
}
agentCount, err := s.agentRepo.CountByModelID(ctx, tenantID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": id,
})
return err
}
if kbCount > 0 || agentCount > 0 {
logger.Warnf(ctx, "Model %s is in use: kb=%d agent=%d", id, kbCount, agentCount)
return apperrors.NewBadRequestError(formatModelInUseMessage(kbCount, agentCount, false))
}
if s.tenantService != nil {
tenant, err := s.tenantService.GetTenantByID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"model_id": id,
"tenant_id": tenantID,
})
return err
if usage.InUse() {
kbCount := usage.KnowledgeBaseTotal
if kbCount == 0 {
kbCount = int64(len(usage.KnowledgeBases))
}
// Both models memory pins have to be checked. Deleting the extraction
// model leaves the workspace pointing at a model that no longer exists,
// and distillation only warns when it cannot resolve one, so auto
// extraction would stop with nothing surfaced to the admin who did it.
if tenant != nil && tenant.MemoryConfig != nil &&
(strings.TrimSpace(tenant.MemoryConfig.EmbeddingModelID) == id ||
strings.TrimSpace(tenant.MemoryConfig.ExtractModelID) == id) {
logger.Warnf(ctx, "Model %s is used by long-term memory", id)
return apperrors.NewBadRequestError(formatModelInUseMessage(0, 0, true))
agentCount := usage.AgentTotal
if agentCount == 0 {
agentCount = int64(len(usage.Agents))
}
memoryInUse := len(usage.LongTermMemory.Bindings) > 0
logger.Warnf(ctx, "Model %s is in use: kb=%d agent=%d memory=%t", id, kbCount, agentCount, memoryInUse)
return apperrors.NewModelInUseError(
formatModelInUseMessage(kbCount, agentCount, memoryInUse),
usage,
)
}
// Delete model from repository
@ -429,6 +413,73 @@ func (s *modelService) DeleteModel(ctx context.Context, id string) error {
return nil
}
func (s *modelService) getModelUsageDetails(
ctx context.Context, tenantID uint64, modelID string,
) (types.ModelUsageDetails, error) {
details := types.ModelUsageDetails{
KnowledgeBases: make([]types.ModelUsageResource, 0),
Agents: make([]types.ModelUsageResource, 0),
LongTermMemory: types.ModelUsageMemory{Bindings: make([]types.ModelUsageBinding, 0)},
}
kbCount, err := s.kbRepo.CountByModelID(ctx, tenantID, modelID)
if err != nil {
return details, err
}
details.KnowledgeBaseTotal = kbCount
if kbCount > 0 {
details.KnowledgeBases, err = s.kbRepo.ListModelUsages(ctx, tenantID, modelID)
if err != nil {
return details, err
}
if details.KnowledgeBases == nil {
details.KnowledgeBases = make([]types.ModelUsageResource, 0)
}
}
agentCount, err := s.agentRepo.CountByModelID(ctx, tenantID, modelID)
if err != nil {
return details, err
}
details.AgentTotal = agentCount
if agentCount > 0 {
details.Agents, err = s.agentRepo.ListModelUsages(ctx, tenantID, modelID)
if err != nil {
return details, err
}
if details.Agents == nil {
details.Agents = make([]types.ModelUsageResource, 0)
}
}
if s.tenantService == nil {
return details, nil
}
tenant, err := s.tenantService.GetTenantByID(ctx, tenantID)
if err != nil {
return details, err
}
if tenant == nil || tenant.MemoryConfig == nil {
return details, nil
}
// Both memory model pins have to be checked. Deleting either one leaves
// the workspace pointing at a model that no longer exists.
if strings.TrimSpace(tenant.MemoryConfig.EmbeddingModelID) == modelID {
details.LongTermMemory.Bindings = append(
details.LongTermMemory.Bindings,
types.ModelUsageBindingEmbeddingModel,
)
}
if strings.TrimSpace(tenant.MemoryConfig.ExtractModelID) == modelID {
details.LongTermMemory.Bindings = append(
details.LongTermMemory.Bindings,
types.ModelUsageBindingExtractModel,
)
}
return details, nil
}
// GetEmbeddingModel retrieves and initializes an embedding model instance
// Takes a model ID and returns an Embedder interface implementation
func (s *modelService) GetEmbeddingModel(ctx context.Context, modelId string) (embedding.Embedder, error) {

View File

@ -2,6 +2,7 @@ package service
import (
"context"
"errors"
"testing"
"time"
@ -13,7 +14,9 @@ import (
)
type stubKBRepoForModelDelete struct {
count int64
usages []types.ModelUsageResource
count *int64
usageErr error
}
func (s *stubKBRepoForModelDelete) CreateKnowledgeBase(context.Context, *types.KnowledgeBase) error {
@ -42,7 +45,16 @@ func (s *stubKBRepoForModelDelete) CountByVectorStoreID(context.Context, *gorm.D
return 0, nil
}
func (s *stubKBRepoForModelDelete) CountByModelID(context.Context, uint64, string) (int64, error) {
return s.count, nil
if s.count != nil {
return *s.count, s.usageErr
}
return int64(len(s.usages)), s.usageErr
}
func (s *stubKBRepoForModelDelete) ListModelUsages(
context.Context, uint64, string,
) ([]types.ModelUsageResource, error) {
return s.usages, s.usageErr
}
func (s *stubKBRepoForModelDelete) SetUserKBPin(context.Context, uint64, string, string, bool) (*time.Time, error) {
return nil, nil
@ -52,7 +64,9 @@ func (s *stubKBRepoForModelDelete) ListUserKBPinIDs(context.Context, uint64, str
}
type stubAgentRepoForModelDelete struct {
count int64
usages []types.ModelUsageResource
count *int64
usageErr error
}
func (s *stubAgentRepoForModelDelete) CreateAgent(context.Context, *types.CustomAgent) error {
@ -69,7 +83,16 @@ func (s *stubAgentRepoForModelDelete) UpdateAgent(context.Context, *types.Custom
}
func (s *stubAgentRepoForModelDelete) DeleteAgent(context.Context, string, uint64) error { return nil }
func (s *stubAgentRepoForModelDelete) CountByModelID(context.Context, uint64, string) (int64, error) {
return s.count, nil
if s.count != nil {
return *s.count, s.usageErr
}
return int64(len(s.usages)), s.usageErr
}
func (s *stubAgentRepoForModelDelete) ListModelUsages(
context.Context, uint64, string,
) ([]types.ModelUsageResource, error) {
return s.usages, s.usageErr
}
func (s *stubAgentRepoForModelDelete) CountBySandboxConfigID(context.Context, uint64, string) (int64, error) {
return 0, nil
@ -116,8 +139,11 @@ func TestDeleteModel_RejectsWhenReferenced(t *testing.T) {
svc := NewModelService(
&stubModelRepoForDelete{model: &types.Model{ID: modelID, TenantID: 1}},
&stubKBRepoForModelDelete{count: 1},
&stubAgentRepoForModelDelete{count: 0},
&stubKBRepoForModelDelete{usages: []types.ModelUsageResource{
{ID: "kb-1", Name: "Product docs", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}},
{ID: "kb-2", Name: "Engineering", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}},
}},
&stubAgentRepoForModelDelete{},
nil, nil, nil,
)
@ -125,8 +151,16 @@ func TestDeleteModel_RejectsWhenReferenced(t *testing.T) {
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrBadRequest, appErr.Code)
assert.Contains(t, appErr.Message, "knowledge base")
assert.Equal(t, apperrors.ErrModelInUse, appErr.Code)
assert.Contains(t, appErr.Message, "2 knowledge base(s)")
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
require.Len(t, details.KnowledgeBases, 2)
assert.Equal(t, int64(2), details.KnowledgeBaseTotal)
assert.Equal(t, "Product docs", details.KnowledgeBases[0].Name)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, details.KnowledgeBases[0].Bindings)
assert.Equal(t, "Engineering", details.KnowledgeBases[1].Name)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingVLMModel}, details.KnowledgeBases[1].Bindings)
}
func TestDeleteModel_RejectsWhenUsedByAgent(t *testing.T) {
@ -135,8 +169,11 @@ func TestDeleteModel_RejectsWhenUsedByAgent(t *testing.T) {
svc := NewModelService(
&stubModelRepoForDelete{model: &types.Model{ID: modelID, TenantID: 1}},
&stubKBRepoForModelDelete{count: 0},
&stubAgentRepoForModelDelete{count: 2},
&stubKBRepoForModelDelete{},
&stubAgentRepoForModelDelete{usages: []types.ModelUsageResource{
{ID: "agent-1", Name: "Support", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingChatModel}},
{ID: "agent-2", Name: "Writer", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingFollowUpModel}},
}},
nil, nil, nil,
)
@ -144,7 +181,12 @@ func TestDeleteModel_RejectsWhenUsedByAgent(t *testing.T) {
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrModelInUse, appErr.Code)
assert.Contains(t, appErr.Message, "2 agent(s)")
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
assert.Len(t, details.Agents, 2)
assert.Equal(t, int64(2), details.AgentTotal)
}
func TestDeleteModel_SucceedsWhenUnreferenced(t *testing.T) {
@ -170,6 +212,85 @@ func TestDeleteModel_SucceedsWhenUnreferenced(t *testing.T) {
assert.True(t, deleted)
}
func TestGetModelUsageDetails_NormalizesEmptyCollections(t *testing.T) {
svc := NewModelService(
&stubModelRepoForDelete{},
&stubKBRepoForModelDelete{},
&stubAgentRepoForModelDelete{},
nil, nil, nil,
)
details, err := svc.(*modelService).getModelUsageDetails(context.Background(), 1, "unused-model")
require.NoError(t, err)
assert.NotNil(t, details.KnowledgeBases)
assert.NotNil(t, details.Agents)
assert.NotNil(t, details.LongTermMemory.Bindings)
assert.Equal(t, int64(0), details.KnowledgeBaseTotal)
assert.Equal(t, int64(0), details.AgentTotal)
}
func TestDeleteModel_DoesNotDeleteWhenUsageLookupFails(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
modelID := "lookup-failure"
wantErr := errors.New("usage lookup failed")
deleted := false
svc := NewModelService(
&stubModelRepoForDelete{
model: &types.Model{ID: modelID, TenantID: 1},
delete: func(string) error {
deleted = true
return nil
},
},
&stubKBRepoForModelDelete{usageErr: wantErr},
&stubAgentRepoForModelDelete{},
nil, nil, nil,
)
err := svc.DeleteModel(ctx, modelID)
require.ErrorIs(t, err, wantErr)
assert.False(t, deleted)
}
func TestDeleteModel_ReportsUntruncatedTotalsWhenListsAreCapped(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
modelID := "popular-embedding"
kbTotal := int64(80)
agentTotal := int64(12)
svc := NewModelService(
&stubModelRepoForDelete{model: &types.Model{ID: modelID, TenantID: 1}},
&stubKBRepoForModelDelete{
count: &kbTotal,
usages: []types.ModelUsageResource{
{ID: "kb-1", Name: "Alpha", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingEmbeddingModel}},
{ID: "kb-2", Name: "Beta", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingEmbeddingModel}},
},
},
&stubAgentRepoForModelDelete{
count: &agentTotal,
usages: []types.ModelUsageResource{
{ID: "agent-1", Name: "Support", Bindings: []types.ModelUsageBinding{types.ModelUsageBindingChatModel}},
},
},
nil, nil, nil,
)
err := svc.DeleteModel(ctx, modelID)
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Contains(t, appErr.Message, "80 knowledge base(s)")
assert.Contains(t, appErr.Message, "12 agent(s)")
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
assert.Equal(t, int64(80), details.KnowledgeBaseTotal)
assert.Len(t, details.KnowledgeBases, 2)
assert.Equal(t, int64(12), details.AgentTotal)
assert.Len(t, details.Agents, 1)
}
type stubTenantServiceForModelDelete struct {
tenant *types.Tenant
}
@ -227,7 +348,11 @@ func TestDeleteModel_RejectsWhenUsedByMemory(t *testing.T) {
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrModelInUse, appErr.Code)
assert.Contains(t, appErr.Message, "long-term memory")
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingEmbeddingModel}, details.LongTermMemory.Bindings)
}
// The extraction model is pinned by the workspace exactly like the embedding
@ -257,7 +382,42 @@ func TestDeleteModel_RejectsWhenUsedByMemoryExtraction(t *testing.T) {
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Equal(t, apperrors.ErrModelInUse, appErr.Code)
assert.Contains(t, appErr.Message, "long-term memory")
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
assert.Equal(t, []types.ModelUsageBinding{types.ModelUsageBindingExtractModel}, details.LongTermMemory.Bindings)
}
func TestDeleteModel_ReportsAllMemoryBindings(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
modelID := "shared-memory-model"
svc := NewModelService(
&stubModelRepoForDelete{model: &types.Model{ID: modelID, TenantID: 1}},
&stubKBRepoForModelDelete{},
&stubAgentRepoForModelDelete{},
nil, nil,
&stubTenantServiceForModelDelete{
tenant: &types.Tenant{
ID: 1,
MemoryConfig: &types.MemoryConfig{
Enabled: true, EmbeddingModelID: modelID, ExtractModelID: modelID,
},
},
},
)
err := svc.DeleteModel(ctx, modelID)
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
details, ok := appErr.Details.(types.ModelUsageDetails)
require.True(t, ok)
assert.Equal(t, []types.ModelUsageBinding{
types.ModelUsageBindingEmbeddingModel,
types.ModelUsageBindingExtractModel,
}, details.LongTermMemory.Bindings)
}
func TestFormatModelInUseMessage(t *testing.T) {

View File

@ -926,6 +926,9 @@ func (r *realKBRepo) CountByVectorStoreID(ctx context.Context, db *gorm.DB, tena
func (r *realKBRepo) CountByModelID(_ context.Context, _ uint64, _ string) (int64, error) {
return 0, nil
}
func (r *realKBRepo) ListModelUsages(_ context.Context, _ uint64, _ string) ([]types.ModelUsageResource, error) {
return []types.ModelUsageResource{}, nil
}
// The remaining methods are not called by the tested code paths; declare them
// so realKBRepo satisfies interfaces.KnowledgeBaseRepository.

View File

@ -44,6 +44,11 @@ const (
ErrVectorStoreBindingInvalid ErrorCode = 2200
ErrVectorStoreUnavailable ErrorCode = 2201
// Model lifecycle errors (2300-2399).
// The dedicated code lets clients render structured usage details without
// parsing the backwards-compatible English error message.
ErrModelInUse ErrorCode = 2300
// Add more error codes here
)
@ -75,6 +80,17 @@ func NewBadRequestError(message string) *AppError {
}
}
// NewModelInUseError creates the typed HTTP 400 returned when active tenant
// resources still reference a model.
func NewModelInUseError(message string, details any) *AppError {
return &AppError{
Code: ErrModelInUse,
Message: message,
Details: details,
HTTPCode: http.StatusBadRequest,
}
}
// NewUnauthorizedError creates an unauthorized error
func NewUnauthorizedError(message string) *AppError {
return &AppError{

View File

@ -667,6 +667,7 @@ func (h *ModelHandler) UpdateModel(c *gin.Context) {
// @Produce json
// @Param id path string true "模型ID"
// @Success 200 {object} map[string]interface{} "删除成功"
// @Failure 400 {object} errors.AppError "模型仍被知识库、智能体或长期记忆引用"
// @Failure 404 {object} errors.AppError "模型不存在"
// @Security Bearer
// @Security ApiKeyAuth

View File

@ -0,0 +1,70 @@
package middleware
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestErrorHandler_PreservesStructuredModelUsageDetails(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(ErrorHandler())
router.DELETE("/models/:id", func(c *gin.Context) {
_ = c.Error(apperrors.NewModelInUseError(
"model is used by 2 knowledge base(s); reconfigure or remove those references before deleting",
types.ModelUsageDetails{
KnowledgeBases: []types.ModelUsageResource{
{
ID: "kb-1",
Name: "Product docs",
Bindings: []types.ModelUsageBinding{types.ModelUsageBindingVLMModel},
},
{
ID: "kb-2",
Name: "Engineering",
Bindings: []types.ModelUsageBinding{
types.ModelUsageBindingEmbeddingModel,
types.ModelUsageBindingSummaryModel,
},
},
},
Agents: []types.ModelUsageResource{},
LongTermMemory: types.ModelUsageMemory{Bindings: []types.ModelUsageBinding{}},
},
))
})
request := httptest.NewRequest(http.MethodDelete, "/models/model-1", nil)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
require.Equal(t, http.StatusBadRequest, response.Code)
var body struct {
Success bool `json:"success"`
Error struct {
Code apperrors.ErrorCode `json:"code"`
Message string `json:"message"`
Details types.ModelUsageDetails `json:"details"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(response.Body.Bytes(), &body))
assert.False(t, body.Success)
assert.Equal(t, apperrors.ErrModelInUse, body.Error.Code)
assert.NotEmpty(t, body.Error.Message)
require.Len(t, body.Error.Details.KnowledgeBases, 2)
assert.Equal(t, "Product docs", body.Error.Details.KnowledgeBases[0].Name)
assert.Equal(t,
[]types.ModelUsageBinding{types.ModelUsageBindingEmbeddingModel, types.ModelUsageBindingSummaryModel},
body.Error.Details.KnowledgeBases[1].Bindings,
)
assert.Empty(t, body.Error.Details.Agents)
assert.Empty(t, body.Error.Details.LongTermMemory.Bindings)
}

View File

@ -360,6 +360,7 @@ func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
}{
{http.MethodGet, "/api/v1/tenants", types.APIKeyCapabilityManageTenantSettings},
{http.MethodGet, "/api/v1/models", types.APIKeyCapabilityManageModels},
{http.MethodDelete, "/api/v1/models/:id", types.APIKeyCapabilityManageModels},
{http.MethodPost, "/api/v1/evaluation", types.APIKeyCapabilityRunEvaluations},
{http.MethodGet, "/api/v1/system/info", types.APIKeyCapabilityManageVectorStores},
{http.MethodGet, "/api/v1/mcp-services", types.APIKeyCapabilityManageMCPServices},

View File

@ -136,6 +136,11 @@ type CustomAgentRepository interface {
// CountByModelID counts active agents in the tenant whose config references
// the given model ID (chat, rerank, VLM, ASR, query-understand, etc.).
CountByModelID(ctx context.Context, tenantID uint64, modelID string) (int64, error)
// ListModelUsages returns the minimal active agent projections that
// reference the model, with every matching binding merged per object.
// Implementations must cap the result at types.ModelUsageListLimit;
// callers that need the untruncated size should use CountByModelID.
ListModelUsages(ctx context.Context, tenantID uint64, modelID string) ([]types.ModelUsageResource, error)
// CountBySandboxConfigID counts agents pointing at a sandbox config.
//

View File

@ -225,6 +225,11 @@ type KnowledgeBaseRepository interface {
// CountByModelID counts active KBs in the tenant that reference the given
// model ID in any model-binding field (embedding, summary, VLM, ASR, etc.).
CountByModelID(ctx context.Context, tenantID uint64, modelID string) (int64, error)
// ListModelUsages returns the minimal active KB projections that reference
// the model, with every matching binding merged per object. Implementations
// must cap the result at types.ModelUsageListLimit; callers that need the
// untruncated size should use CountByModelID.
ListModelUsages(ctx context.Context, tenantID uint64, modelID string) ([]types.ModelUsageResource, error)
// SetUserKBPin inserts or removes a row in user_kb_pins for the given
// (tenant, user, kb) triple. Returns the resulting pinned_at (nil when
// pinned=false) and an error. The tenant_id is captured to support

View File

@ -31,6 +31,63 @@ const (
ModelStatusDownloadFailed ModelStatus = "download_failed" // Model download failed
)
// ModelUsageBinding is a stable API identifier for one configuration field
// that references a model. Clients localize these values; repository column
// names and JSON paths must not leak into the response contract.
type ModelUsageBinding string
// Model usage binding constants identify supported model-reference roles.
const (
ModelUsageBindingEmbeddingModel ModelUsageBinding = "embedding_model"
ModelUsageBindingSummaryModel ModelUsageBinding = "summary_model"
ModelUsageBindingImageProcessingModel ModelUsageBinding = "image_processing_model"
ModelUsageBindingVLMModel ModelUsageBinding = "vlm_model"
ModelUsageBindingASRModel ModelUsageBinding = "asr_model"
ModelUsageBindingWikiSynthesisModel ModelUsageBinding = "wiki_synthesis_model"
ModelUsageBindingChatModel ModelUsageBinding = "chat_model"
ModelUsageBindingRerankModel ModelUsageBinding = "rerank_model"
ModelUsageBindingQueryUnderstandModel ModelUsageBinding = "query_understand_model"
ModelUsageBindingFollowUpModel ModelUsageBinding = "follow_up_model"
ModelUsageBindingExtractModel ModelUsageBinding = "extract_model"
)
// ModelUsageResource is the minimal, non-sensitive projection returned when a
// knowledge base or agent prevents model deletion.
type ModelUsageResource struct {
ID string `json:"id"`
Name string `json:"name"`
Bindings []ModelUsageBinding `json:"bindings"`
}
// ModelUsageMemory describes workspace-level long-term-memory model pins.
type ModelUsageMemory struct {
Bindings []ModelUsageBinding `json:"bindings"`
}
// ModelUsageListLimit caps how many knowledge bases or agents are listed in a
// model-in-use error. Totals are returned separately so the cap cannot
// under-count the references that actually block deletion.
const ModelUsageListLimit = 50
// ModelUsageDetails explains every active tenant-scoped reference that blocks
// model deletion. KnowledgeBases and Agents may be truncated to
// ModelUsageListLimit entries; KnowledgeBaseTotal and AgentTotal are the
// untruncated counts used by the deletion guard and UI headings.
type ModelUsageDetails struct {
KnowledgeBases []ModelUsageResource `json:"knowledge_bases"`
Agents []ModelUsageResource `json:"agents"`
LongTermMemory ModelUsageMemory `json:"long_term_memory"`
KnowledgeBaseTotal int64 `json:"knowledge_base_total"`
AgentTotal int64 `json:"agent_total"`
}
// InUse reports whether at least one active object references the model.
func (d ModelUsageDetails) InUse() bool {
return d.KnowledgeBaseTotal > 0 || d.AgentTotal > 0 ||
len(d.KnowledgeBases) > 0 || len(d.Agents) > 0 ||
len(d.LongTermMemory.Bindings) > 0
}
// ModelSource represents the source of the model
type ModelSource string

View File

@ -251,7 +251,7 @@ r.GET("/health", func(c *gin.Context) {
- `scopeKnowledgeBasesByModelID`:匹配 `knowledge_bases` 中任一模型绑定字段 —— `embedding_model_id`、`summary_model_id`、`image_processing_config.model_id`、`vlm_config.model_id`、`asr_config.model_id`、`wiki_config.synthesis_model_id`(Postgres 用 `->>` JSON 操作符,SQLite 用 `json_extract`,双方言等价)。
- `scopeCustomAgentsByModelID`:匹配 `custom_agents.config` 中的 `model_id`、`rerank_model_id`、`vlm_model_id`、`asr_model_id`、`query_understand_model_id`、`question_suggestions.follow_ups.model_id`。
- 消费方:`knowledgebase.go` / `custom_agent.go` 仓储的 `CountByModelID`,被 `internal/application/service/model.go` 的删除守卫调用(KB 或 Agent 引用计数 > 0 时阻止删除模型)。
- 消费方:`knowledgebase.go` / `custom_agent.go` 仓储的 `ListModelUsages` 复用上述 scope,返回租户内活动对象的最小投影(`id`、`name`、合并后的 `bindings`),条数上限为 `ModelUsageListLimit`(50)。`internal/application/service/model.go` 的删除守卫以 `CountByModelID` 得到的 `knowledge_base_total` / `agent_total` 为是否拦截的依据,并在 HTTP 400 的 `error.details` 中同时返回截断列表和总数。
token 级别的模型用量则由 Langfuse Generation 的 `usage_details`(`TokenUsage`:input/output/total/cache_*)上报,在 Langfuse UI 中按模型 / 用户(`tenant:<id>`)/ 会话聚合查看。

View File

@ -85,6 +85,30 @@ curl -X PUT $BASE/api/v1/models/m-1 -H "Authorization: Bearer $TOKEN" \
响应:200 `{"success":true,"message":"Model deleted"}`
仍被当前空间的知识库、智能体或长期记忆引用时,响应为 HTTP 400;兼容 message 保留,同时 `error.code=2300`,`error.details` 给出具体对象和引用位置:
```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
}
}
}
```
知识库绑定值:`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`。详情包含对象 `id`、`name`、合并后的 `bindings`,以及 `knowledge_base_total` / `agent_total`。列表最多各 50 条,删除守卫以总数为准。
```bash
curl -X DELETE $BASE/api/v1/models/m-1 -H "Authorization: Bearer $TOKEN"
```