Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(tenant): implement tenant creation limit and error handling

wizardchen7d030a6f6a47
diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts
index 377aca03b..d9a3b8632 100644
--- a/frontend/src/api/system/index.ts
+++ b/frontend/src/api/system/index.ts
@@ -17,29 +17,12 @@ export interface SystemInfo {
db_migration_error?: string
}
-export interface ToolDefinition {
- name: string
- label: string
- description: string
-}
-
export interface PlaceholderDefinition {
name: string
label: string
description: string
}
-export interface AgentConfig {
- max_iterations: number
- reflection_enabled: boolean
- allowed_tools: string[]
- temperature: number
- knowledge_bases?: string[]
- system_prompt?: string // Unified system prompt (uses {{web_search_status}} placeholder)
- available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要
- available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
-}
-
export interface PromptTemplate {
id: string
name: string
@@ -71,14 +54,6 @@ export function getSystemInfo(): Promise<{ data: SystemInfo }> {
return get('/api/v1/system/info')
}
-export function getAgentConfig(): Promise<{ data: AgentConfig }> {
- return get('/api/v1/tenants/kv/agent-config')
-}
-
-export function updateAgentConfig(config: AgentConfig): Promise<{ data: AgentConfig }> {
- return put('/api/v1/tenants/kv/agent-config', config)
-}
-
export function getPromptTemplates(): Promise<{ data: PromptTemplatesConfig }> {
return get('/api/v1/tenants/kv/prompt-templates')
}
diff --git a/frontend/src/components/CreateTenantDialog.vue b/frontend/src/components/CreateTenantDialog.vue
index 5eac54283..502b019eb 100644
--- a/frontend/src/components/CreateTenantDialog.vue
+++ b/frontend/src/components/CreateTenantDialog.vue
@@ -62,10 +62,17 @@ const form = reactive({
description: '',
})
+// Trim-aware required check:t-input 的 required 不会去空白,全空格也算
+// 通过;这里手动校验 trim 后非空,避免后端因 binding:"required,min=1"
+// 才把请求挡下来。max 长度由 <t-input :maxlength="128"> 在键入时硬限制,
+// 所以这里不再重复挂规则(避免与硬限制双重提示)。
const formRules: Record<string, FormRule[]> = {
name: [
- { required: true, message: t('tenant.create.nameRequired'), trigger: 'blur' },
- { max: 128, message: t('tenant.create.nameRequired'), trigger: 'blur' },
+ {
+ validator: (val: string) => (val ?? '').trim().length > 0,
+ message: t('tenant.create.nameRequired'),
+ trigger: 'blur',
+ },
],
}
diff --git a/frontend/src/views/agent/AgentEditorModal.vue b/frontend/src/views/agent/AgentEditorModal.vue
index 36be2fe1f..1333cc3bb 100644
--- a/frontend/src/views/agent/AgentEditorModal.vue
+++ b/frontend/src/views/agent/AgentEditorModal.vue
@@ -6,7 +6,7 @@
<!-- 关闭按钮 -->
<button class="close-btn" @click="handleClose" :aria-label="$t('common.close')">
<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
- <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
+ <path d="M15 5L5 15M5 5L15 15" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
</svg>
</button>
@@ -14,15 +14,12 @@
<!-- 左侧导航 -->
<div class="settings-sidebar">
<div class="sidebar-header">
- <h2 class="sidebar-title">{{ mode === 'create' ? $t('agent.editor.createTitle') : $t('agent.editor.editTitle') }}</h2>
+ <h2 class="sidebar-title">{{ mode === 'create' ? $t('agent.editor.createTitle') :
+ $t('agent.editor.editTitle') }}</h2>
</div>
<div class="settings-nav">
- <div
- v-for="(item, index) in navItems"
- :key="index"
- :class="['nav-item', { 'active': currentSection === item.key }]"
- @click="currentSection = item.key"
- >
+ <div v-for="(item, index) in navItems" :key="index"
+ :class="['nav-item', { 'active': currentSection === item.key }]" @click="currentSection = item.key">
<t-icon :name="item.icon" class="nav-icon" />
<span class="nav-label">{{ item.label }}</span>
</div>
@@ -38,7 +35,7 @@
<h2>{{ $t('agent.editor.basicInfo') }}</h2>
<p class="section-description">{{ $t('agent.editor.basicInfoDesc') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 内置智能体提示 -->
<div v-if="isBuiltinAgent" class="builtin-agent-notice">
@@ -50,7 +47,8 @@
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.mode') }} <span class="required">*</span></label>
- <p class="desc">{{ agentMode === 'smart-reasoning' ? $t('agent.editor.agentDesc') : $t('agent.editor.normalDesc') }}</p>
+ <p class="desc">{{ agentMode === 'smart-reasoning' ? $t('agent.editor.agentDesc') :
+ $t('agent.editor.normalDesc') }}</p>
</div>
<div class="setting-control">
<t-radio-group v-model="agentMode" :disabled="isBuiltinAgent">
@@ -69,21 +67,13 @@
<div class="setting-info">
<label>{{ $t('agentEditor.agentType.label') }}</label>
<p class="desc">{{ $t('agentEditor.agentType.desc') }}</p>
- <p
- v-if="activeAgentTypePreset"
- class="desc agent-type-preset-desc"
- >{{ agentTypePresetDescription(activeAgentTypePreset) }}</p>
+ <p v-if="activeAgentTypePreset" class="desc agent-type-preset-desc">{{
+ agentTypePresetDescription(activeAgentTypePreset) }}</p>
</div>
<div class="setting-control">
- <t-select
- :value="agentType"
- @change="onAgentTypeChange"
- :disabled="isBuiltinAgent"
- :placeholder="$t('agentEditor.agentType.label')"
- :options="agentTypeSelectOptions"
- :popup-props="{ overlayClassName: 'agent-type-popup' }"
- class="agent-type-select"
- >
+ <t-select :value="agentType" @change="onAgentTypeChange" :disabled="isBuiltinAgent"
+ :placeholder="$t('agentEditor.agentType.label')" :options="agentTypeSelectOptions"
+ :popup-props="{ overlayClassName: 'agent-type-popup' }" class="agent-type-select">
<template #option="{ option }">
<div class="agent-type-option">
<span class="agent-type-option-label">{{ option.label }}</span>
@@ -97,7 +87,8 @@
<!-- 名称 -->
<div class="setting-row">
<div class="setting-info">
- <label>{{ $t('agent.editor.name') }} <span v-if="!isBuiltinAgent" class="required">*</span></label>
+ <label>{{ $t('agent.editor.name') }} <span v-if="!isBuiltinAgent"
+ class="required">*</span></label>
<p class="desc">{{ $t('agentEditor.desc.name') }}</p>
</div>
<div class="setting-control">
@@ -108,12 +99,8 @@
</div>
<!-- 自定义智能体使用 AgentAvatar -->
<AgentAvatar v-else :name="formData.name || '?'" size="medium" />
- <t-input
- v-model="formData.name"
- :placeholder="$t('agent.editor.namePlaceholder')"
- class="name-input"
- :disabled="isBuiltinAgent"
- />
+ <t-input v-model="formData.name" :placeholder="$t('agent.editor.namePlaceholder')"
+ class="name-input" :disabled="isBuiltinAgent" />
</div>
</div>
</div>
@@ -125,33 +112,26 @@
<p class="desc">{{ $t('agentEditor.desc.description') }}</p>
</div>
<div class="setting-control">
- <t-textarea
- v-model="formData.description"
+ <t-textarea v-model="formData.description"
:placeholder="$t('agent.editor.descriptionPlaceholder')"
- :autosize="{ minRows: 2, maxRows: 4 }"
- :disabled="isBuiltinAgent"
- />
+ :autosize="{ minRows: 2, maxRows: 4 }" :disabled="isBuiltinAgent" />
</div>
</div>
<!-- 系统提示词 -->
<div class="setting-row setting-row-vertical">
<div class="setting-info">
- <label>{{ $t('agent.editor.systemPrompt') }} <span v-if="!isBuiltinAgent" class="required">*</span></label>
- <p class="desc">{{ $t('agentEditor.desc.systemPrompt') }}{{ isBuiltinAgent ? $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
+ <label>{{ $t('agent.editor.systemPrompt') }} <span v-if="!isBuiltinAgent"
+ class="required">*</span></label>
+ <p class="desc">{{ $t('agentEditor.desc.systemPrompt') }}{{ isBuiltinAgent ?
+ $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
<div class="placeholder-tags">
<span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
- <t-tooltip
- v-for="placeholder in availablePlaceholders"
- :key="placeholder.name"
+ <t-tooltip v-for="placeholder in availablePlaceholders" :key="placeholder.name"
:content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
- placement="top"
- >
- <span
- class="placeholder-tag"
- @click="handlePlaceholderClick('system', placeholder.name)"
- v-text="'{{' + placeholder.name + '}}'"
- ></span>
+ placement="top">
+ <span class="placeholder-tag" @click="handlePlaceholderClick('system', placeholder.name)"
+ v-text="'{{' + placeholder.name + '}}'"></span>
</t-tooltip>
<span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
</div>
@@ -159,56 +139,31 @@
<div class="setting-control setting-control-full" style="position: relative;">
<!-- Agent模式:统一提示词(使用 {{web_search_status}} 占位符动态控制行为) -->
<div v-if="isAgentMode" class="textarea-with-template">
- <t-textarea
- ref="promptTextareaRef"
- v-model="formData.config.system_prompt"
- :placeholder="systemPromptPlaceholder"
- :autosize="{ minRows: 10, maxRows: 25 }"
- @input="handlePromptInput"
- class="system-prompt-textarea"
- />
- <PromptTemplateSelector
- type="agentSystemPrompt"
- position="corner"
- :hasKnowledgeBase="hasKnowledgeBase"
- @select="handleSystemPromptTemplateSelect"
- @reset-default="handleAgentSystemPromptResetDefault"
- />
+ <t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
+ :placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
+ @input="handlePromptInput" class="system-prompt-textarea" />
+ <PromptTemplateSelector type="agentSystemPrompt" position="corner"
+ :hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
+ @reset-default="handleAgentSystemPromptResetDefault" />
</div>
<!-- 普通模式:单个提示词 -->
<div v-else class="textarea-with-template">
- <t-textarea
- ref="promptTextareaRef"
- v-model="formData.config.system_prompt"
- :placeholder="systemPromptPlaceholder"
- :autosize="{ minRows: 10, maxRows: 25 }"
- @input="handlePromptInput"
- class="system-prompt-textarea"
- />
- <PromptTemplateSelector
- type="systemPrompt"
- position="corner"
- :hasKnowledgeBase="hasKnowledgeBase"
- @select="handleSystemPromptTemplateSelect"
- @reset-default="handleSystemPromptTemplateSelect"
- />
+ <t-textarea ref="promptTextareaRef" v-model="formData.config.system_prompt"
+ :placeholder="systemPromptPlaceholder" :autosize="{ minRows: 10, maxRows: 25 }"
+ @input="handlePromptInput" class="system-prompt-textarea" />
+ <PromptTemplateSelector type="systemPrompt" position="corner"
+ :hasKnowledgeBase="hasKnowledgeBase" @select="handleSystemPromptTemplateSelect"
+ @reset-default="handleSystemPromptTemplateSelect" />
</div>
<!-- 占位符提示下拉框 -->
<Teleport to="body">
- <div
- v-if="showPlaceholderPopup && filteredPlaceholders.length > 0"
- class="placeholder-popup-wrapper"
- :style="popupStyle"
- >
+ <div v-if="showPlaceholderPopup && filteredPlaceholders.length > 0"
+ class="placeholder-popup-wrapper" :style="popupStyle">
<div class="placeholder-popup">
- <div
- v-for="(placeholder, index) in filteredPlaceholders"
- :key="placeholder.name"
- class="placeholder-item"
- :class="{ active: selectedPlaceholderIndex === index }"
+ <div v-for="(placeholder, index) in filteredPlaceholders" :key="placeholder.name"
+ class="placeholder-item" :class="{ active: selectedPlaceholderIndex === index }"
@mousedown.prevent="insertPlaceholder(placeholder.name, true)"
- @mouseenter="selectedPlaceholderIndex = index"
- >
+ @mouseenter="selectedPlaceholderIndex = index">
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
@@ -223,59 +178,39 @@
<!-- 上下文模板(仅普通模式) -->
<div v-if="!isAgentMode" class="setting-row setting-row-vertical">
<div class="setting-info">
- <label>{{ $t('agent.editor.contextTemplate') }} <span v-if="!isBuiltinAgent" class="required">*</span></label>
- <p class="desc">{{ $t('agentEditor.desc.contextTemplate') }}{{ isBuiltinAgent ? $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
+ <label>{{ $t('agent.editor.contextTemplate') }} <span v-if="!isBuiltinAgent"
+ class="required">*</span></label>
+ <p class="desc">{{ $t('agentEditor.desc.contextTemplate') }}{{ isBuiltinAgent ?
+ $t('agentEditor.desc.leaveEmptyDefault') : '' }}</p>
<div class="placeholder-tags">
<span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
- <t-tooltip
- v-for="placeholder in contextTemplatePlaceholders"
- :key="placeholder.name"
+ <t-tooltip v-for="placeholder in contextTemplatePlaceholders" :key="placeholder.name"
:content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
- placement="top"
- >
- <span
- class="placeholder-tag"
- @click="handlePlaceholderClick('context', placeholder.name)"
- v-text="'{{' + placeholder.name + '}}'"
- ></span>
+ placement="top">
+ <span class="placeholder-tag" @click="handlePlaceholderClick('context', placeholder.name)"
+ v-text="'{{' + placeholder.name + '}}'"></span>
</t-tooltip>
<span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
</div>
</div>
<div class="setting-control setting-control-full" style="position: relative;">
<div class="textarea-with-template">
- <t-textarea
- ref="contextTemplateTextareaRef"
- v-model="formData.config.context_template"
- :placeholder="contextTemplatePlaceholder"
- :autosize="{ minRows: 8, maxRows: 20 }"
- @input="handleContextTemplateInput"
- class="system-prompt-textarea"
- />
- <PromptTemplateSelector
- type="contextTemplate"
- position="corner"
- :hasKnowledgeBase="hasKnowledgeBase"
- @select="handleContextTemplateSelect"
- @reset-default="handleContextTemplateSelect"
- />
+ <t-textarea ref="contextTemplateTextareaRef" v-model="formData.config.context_template"
+ :placeholder="contextTemplatePlaceholder" :autosize="{ minRows: 8, maxRows: 20 }"
+ @input="handleContextTemplateInput" class="system-prompt-textarea" />
+ <PromptTemplateSelector type="contextTemplate" position="corner"
+ :hasKnowledgeBase="hasKnowledgeBase" @select="handleContextTemplateSelect"
+ @reset-default="handleContextTemplateSelect" />
</div>
<!-- 上下文模板占位符提示下拉框 -->
<Teleport to="body">
- <div
- v-if="showContextPlaceholderPopup && filteredContextPlaceholders.length > 0"
- class="placeholder-popup-wrapper"
- :style="contextPopupStyle"
- >
+ <div v-if="showContextPlaceholderPopup && filteredContextPlaceholders.length > 0"
+ class="placeholder-popup-wrapper" :style="contextPopupStyle">
<div class="placeholder-popup">
- <div
- v-for="(placeholder, index) in filteredContextPlaceholders"
- :key="placeholder.name"
- class="placeholder-item"
- :class="{ active: selectedContextPlaceholderIndex === index }"
+ <div v-for="(placeholder, index) in filteredContextPlaceholders" :key="placeholder.name"
+ class="placeholder-item" :class="{ active: selectedContextPlaceholderIndex === index }"
@mousedown.prevent="insertContextPlaceholder(placeholder.name, true)"
- @mouseenter="selectedContextPlaceholderIndex = index"
- >
+ @mouseenter="selectedContextPlaceholderIndex = index">
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
@@ -296,7 +231,7 @@
<h2>{{ $t('agent.editor.modelConfig') }}</h2>
<p class="section-description">{{ $t('agent.editor.modelConfigDesc') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 模型选择 -->
<div class="setting-row">
@@ -305,14 +240,10 @@
<p class="desc">{{ $t('agentEditor.desc.model') }}</p>
</div>
<div class="setting-control">
- <ModelSelector
- model-type="KnowledgeQA"
- :selected-model-id="formData.config.model_id"
+ <ModelSelector model-type="KnowledgeQA" :selected-model-id="formData.config.model_id"
:all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.model_id = val"
- @add-model="handleAddModel('llm')"
- :placeholder="$t('agent.editor.modelPlaceholder')"
- />
+ @add-model="handleAddModel('llm')" :placeholder="$t('agent.editor.modelPlaceholder')" />
</div>
</div>
@@ -337,7 +268,8 @@
<p class="desc">{{ $t('agentEditor.desc.maxTokens') }}</p>
</div>
<div class="setting-control">
- <t-input-number v-model="formData.config.max_completion_tokens" :min="100" :max="100000" :step="100" theme="column" />
+ <t-input-number v-model="formData.config.max_completion_tokens" :min="100" :max="100000"
+ :step="100" theme="column" />
</div>
</div>
@@ -381,14 +313,11 @@
<p class="desc">{{ $t('agentEditor.imageUpload.vlmModelDesc') }}</p>
</div>
<div class="setting-control">
- <ModelSelector
- model-type="VLLM"
- :selected-model-id="formData.config.vlm_model_id"
+ <ModelSelector model-type="VLLM" :selected-model-id="formData.config.vlm_model_id"
:all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.vlm_model_id = val"
@add-model="handleAddModel('vllm')"
- :placeholder="$t('agentEditor.imageUpload.vlmModelPlaceholder')"
- />
+ :placeholder="$t('agentEditor.imageUpload.vlmModelPlaceholder')" />
</div>
</div>
@@ -399,27 +328,20 @@
<p class="desc">{{ $t('agentEditor.imageUpload.storageProviderDesc') }}</p>
</div>
<div class="setting-control" style="flex-direction: column; align-items: flex-end;">
- <t-select
- v-model="formData.config.image_storage_provider"
- style="width: 280px;"
- :placeholder="$t('agentEditor.imageUpload.storageProviderPlaceholder')"
- clearable
- >
+ <t-select v-model="formData.config.image_storage_provider" style="width: 280px;"
+ :placeholder="$t('agentEditor.imageUpload.storageProviderPlaceholder')" clearable>
<t-option value="" :label="$t('agentEditor.imageUpload.storageDefault')" />
- <t-option
- v-for="opt in imageStorageOptions"
- :key="opt.value"
- :value="opt.value"
- :label="opt.label"
- :disabled="opt.disabled"
- >
+ <t-option v-for="opt in imageStorageOptions" :key="opt.value" :value="opt.value"
+ :label="opt.label" :disabled="opt.disabled">
<span class="select-option-with-tag">
<span>{{ opt.label }}</span>
- <t-tag v-if="opt.disabled" theme="warning" variant="light" size="small">{{ $t('agentEditor.imageUpload.notConfigured') }}</t-tag>
+ <t-tag v-if="opt.disabled" theme="warning" variant="light" size="small">{{
+ $t('agentEditor.imageUpload.notConfigured') }}</t-tag>
</span>
</t-option>
</t-select>
- <a href="javascript:void(0)" class="go-settings-link" @click.prevent="uiStore.openSettings('storage')">
+ <a href="javascript:void(0)" class="go-settings-link"
+ @click.prevent="uiStore.openSettings('storage')">
{{ $t('agentEditor.imageUpload.goStorageSettings') }}
</a>
</div>
@@ -443,14 +365,11 @@
<p class="desc">{{ $t('agentEditor.audioUpload.asrModelDesc') }}</p>
</div>
<div class="setting-control">
- <ModelSelector
- model-type="ASR"
- :selected-model-id="formData.config.asr_model_id"
+ <ModelSelector model-type="ASR" :selected-model-id="formData.config.asr_model_id"
:all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.asr_model_id = val"
@add-model="handleAddModel('asr')"
- :placeholder="$t('agentEditor.audioUpload.asrModelPlaceholder')"
- />
+ :placeholder="$t('agentEditor.audioUpload.asrModelPlaceholder')" />
</div>
</div>
</div>
@@ -462,7 +381,7 @@
<h2>{{ $t('agent.editor.conversationSettings') }}</h2>
<p class="section-description">{{ $t('agentEditor.desc.conversationSection') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 多轮对话 -->
<div class="setting-row">
@@ -498,76 +417,56 @@
</div>
<!-- 问题理解模型(独立模型,留空则复用主对话模型) -->
- <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite" class="setting-row">
+ <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite"
+ class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.queryUnderstandModel') }}</label>
<p class="desc">{{ $t('agentEditor.desc.queryUnderstandModel') }}</p>
</div>
<div class="setting-control">
- <ModelSelector
- model-type="KnowledgeQA"
- :selected-model-id="formData.config.query_understand_model_id"
- :all-models="allModels"
+ <ModelSelector model-type="KnowledgeQA"
+ :selected-model-id="formData.config.query_understand_model_id" :all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.query_understand_model_id = val"
@add-model="handleAddModel('llm')"
- :placeholder="$t('agent.editor.queryUnderstandModelPlaceholder')"
- />
+ :placeholder="$t('agent.editor.queryUnderstandModelPlaceholder')" />
</div>
</div>
<!-- 改写系统提示词 -->
- <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite" class="setting-row setting-row-vertical">
+ <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite"
+ class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.rewritePromptSystem') }}</label>
<p class="desc">{{ $t('agentEditor.desc.rewriteSystemPrompt') }}</p>
<div class="placeholder-tags" v-if="rewriteSystemPlaceholders.length > 0">
<span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
- <t-tooltip
- v-for="placeholder in rewriteSystemPlaceholders"
- :key="placeholder.name"
+ <t-tooltip v-for="placeholder in rewriteSystemPlaceholders" :key="placeholder.name"
:content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
- placement="top"
- >
- <span
- class="placeholder-tag"
+ placement="top">
+ <span class="placeholder-tag"
@click="handlePlaceholderClick('rewriteSystem', placeholder.name)"
- v-text="'{{' + placeholder.name + '}}'"
- ></span>
+ v-text="'{{' + placeholder.name + '}}'"></span>
</t-tooltip>
<span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
</div>
</div>
<div class="setting-control setting-control-full" style="position: relative;">
<div class="textarea-with-template">
- <t-textarea
- ref="rewriteSystemTextareaRef"
- v-model="formData.config.rewrite_prompt_system"
+ <t-textarea ref="rewriteSystemTextareaRef" v-model="formData.config.rewrite_prompt_system"
:placeholder="defaultRewritePromptSystem || $t('agent.editor.rewritePromptSystemPlaceholder')"
- :autosize="{ minRows: 4, maxRows: 10 }"
- @input="handleRewriteSystemInput"
- />
- <PromptTemplateSelector
- type="rewrite"
- position="corner"
- @select="handleRewriteTemplateSelect"
- @reset-default="handleRewriteTemplateSelect"
- />
+ :autosize="{ minRows: 4, maxRows: 10 }" @input="handleRewriteSystemInput" />
+ <PromptTemplateSelector type="rewrite" position="corner" @select="handleRewriteTemplateSelect"
+ @reset-default="handleRewriteTemplateSelect" />
</div>
<Teleport to="body">
- <div
- v-if="rewriteSystemPopup.show && filteredRewriteSystemPlaceholders.length > 0"
- class="placeholder-popup-wrapper"
- :style="rewriteSystemPopup.style"
- >
+ <div v-if="rewriteSystemPopup.show && filteredRewriteSystemPlaceholders.length > 0"
+ class="placeholder-popup-wrapper" :style="rewriteSystemPopup.style">
<div class="placeholder-popup">
- <div
- v-for="(placeholder, index) in filteredRewriteSystemPlaceholders"
- :key="placeholder.name"
- class="placeholder-item"
+ <div v-for="(placeholder, index) in filteredRewriteSystemPlaceholders"
+ :key="placeholder.name" class="placeholder-item"
:class="{ active: rewriteSystemPopup.selectedIndex === index }"
@mousedown.prevent="insertGenericPlaceholder('rewriteSystem', placeholder.name, true)"
- @mouseenter="rewriteSystemPopup.selectedIndex = index"
- >
+ @mouseenter="rewriteSystemPopup.selectedIndex = index">
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
@@ -580,58 +479,40 @@
</div>
<!-- 改写用户提示词 -->
- <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite" class="setting-row setting-row-vertical">
+ <div v-if="formData.config.multi_turn_enabled && !isAgentMode && formData.config.enable_rewrite"
+ class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.rewritePromptUser') }}</label>
<p class="desc">{{ $t('agentEditor.desc.rewriteUserPrompt') }}</p>
<div class="placeholder-tags" v-if="rewritePlaceholders.length > 0">
<span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
- <t-tooltip
- v-for="placeholder in rewritePlaceholders"
- :key="placeholder.name"
+ <t-tooltip v-for="placeholder in rewritePlaceholders" :key="placeholder.name"
:content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
- placement="top"
- >
- <span
- class="placeholder-tag"
+ placement="top">
+ <span class="placeholder-tag"
@click="handlePlaceholderClick('rewriteUser', placeholder.name)"
- v-text="'{{' + placeholder.name + '}}'"
- ></span>
+ v-text="'{{' + placeholder.name + '}}'"></span>
</t-tooltip>
<span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
</div>
</div>
<div class="setting-control setting-control-full" style="position: relative;">
<div class="textarea-with-template">
- <t-textarea
- ref="rewriteUserTextareaRef"
- v-model="formData.config.rewrite_prompt_user"
+ <t-textarea ref="rewriteUserTextareaRef" v-model="formData.config.rewrite_prompt_user"
:placeholder="defaultRewritePromptUser || $t('agent.editor.rewritePromptUserPlaceholder')"
- :autosize="{ minRows: 4, maxRows: 10 }"
- @input="handleRewriteUserInput"
- />
- <PromptTemplateSelector
- type="rewrite"
- position="corner"
- @select="handleRewriteTemplateSelect"
- @reset-default="handleRewriteTemplateSelect"
- />
+ :autosize="{ minRows: 4, maxRows: 10 }" @input="handleRewriteUserInput" />
+ <PromptTemplateSelector type="rewrite" position="corner" @select="handleRewriteTemplateSelect"
+ @reset-default="handleRewriteTemplateSelect" />
</div>
<Teleport to="body">
- <div
- v-if="rewriteUserPopup.show && filteredRewriteUserPlaceholders.length > 0"
- class="placeholder-popup-wrapper"
- :style="rewriteUserPopup.style"
- >
+ <div v-if="rewriteUserPopup.show && filteredRewriteUserPlaceholders.length > 0"
+ class="placeholder-popup-wrapper" :style="rewriteUserPopup.style">
<div class="placeholder-popup">
- <div
- v-for="(placeholder, index) in filteredRewriteUserPlaceholders"
- :key="placeholder.name"
- class="placeholder-item"
+ <div v-for="(placeholder, index) in filteredRewriteUserPlaceholders"
+ :key="placeholder.name" class="placeholder-item"
:class="{ active: rewriteUserPopup.selectedIndex === index }"
@mousedown.prevent="insertGenericPlaceholder('rewriteUser', placeholder.name, true)"
- @mouseenter="rewriteUserPopup.selectedIndex = index"
- >
+ @mouseenter="rewriteUserPopup.selectedIndex = index">
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
@@ -686,11 +567,8 @@
</div>
<div class="setting-control setting-control-full">
<t-checkbox-group v-model="formData.config.allowed_tools" class="tool-groups">
- <section
- v-for="group in groupedAvailableTools"
- :key="group.key"
- :class="['tool-group', `tool-group--${group.key}`]"
- >
+ <section v-for="group in groupedAvailableTools" :key="group.key"
+ :class="['tool-group', `tool-group--${group.key}`]">
<header class="tool-group-header">
<span class="tool-group-bar" />
<span class="tool-group-title">{{ group.label }}</span>
@@ -701,13 +579,9 @@
</span>
</header>
<div class="tool-grid">
- <t-checkbox
- v-for="tool in group.tools"
- :key="tool.value"
- :value="tool.value"
+ <t-checkbox v-for="tool in group.tools" :key="tool.value" :value="tool.value"
:disabled="tool.disabled"
- :class="['tool-card', { 'tool-card--disabled': tool.disabled, 'tool-card--danger': tool.danger }]"
- >
+ :class="['tool-card', { 'tool-card--disabled': tool.disabled, 'tool-card--danger': tool.danger }]">
<div class="tool-card-body">
<div class="tool-card-head">
<span class="tool-card-name">{{ tool.label }}</span>
@@ -741,12 +615,9 @@
</div>
</template>
<template v-else>
- <span
- v-for="item in effectiveTools"
- :key="item.value"
+ <span v-for="item in effectiveTools" :key="item.value"
:class="['effective-chip', { 'effective-chip--inactive': !item.active }]"
- :title="item.reason || ''"
- >
+ :title="item.reason || ''">
<span class="effective-chip-label">{{ item.label }}</span>
<span v-if="!item.active" class="effective-chip-reason">{{ item.reason }}</span>
</span>
@@ -774,14 +645,8 @@
<p class="desc-hint">{{ $t('agentEditor.llmCallTimeout.hint') }}</p>
</div>
<div class="setting-control">
- <t-input-number
- v-model="formData.config.llm_call_timeout"
- :min="0"
- :max="3600"
- theme="column"
- :placeholder="$t('agentEditor.llmCallTimeout.placeholder')"
- clearable
- />
+ <t-input-number v-model="formData.config.llm_call_timeout" :min="0" :max="3600" theme="column"
+ :placeholder="$t('agentEditor.llmCallTimeout.placeholder')" clearable />
</div>
</div>
@@ -807,18 +672,9 @@
<p class="desc">{{ $t('agentEditor.mcp.selectDesc') }}</p>
</div>
<div class="setting-control">
- <t-select
- v-model="formData.config.mcp_services"
- multiple
- :placeholder="$t('agentEditor.mcp.selectPlaceholder')"
- filterable
- >
- <t-option
- v-for="mcp in mcpOptions"
- :key="mcp.value"
- :value="mcp.value"
- :label="mcp.label"
- />
+ <t-select v-model="formData.config.mcp_services" multiple
+ :placeholder="$t('agentEditor.mcp.selectPlaceholder')" filterable>
+ <t-option v-for="mcp in mcpOptions" :key="mcp.value" :value="mcp.value" :label="mcp.label" />
</t-select>
</div>
</div>
@@ -849,19 +705,16 @@
</div>
<!-- 选择指定 Skills -->
- <div v-if="skillsSelectionMode === 'selected' && skillOptions.length > 0" class="setting-row setting-row-vertical">
+ <div v-if="skillsSelectionMode === 'selected' && skillOptions.length > 0"
+ class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.selectSkills') }}</label>
<p class="desc">{{ $t('agent.editor.selectSkillsDesc') }}</p>
</div>
<div class="setting-control setting-control-full">
<t-checkbox-group v-model="formData.config.selected_skills" class="skills-checkbox-group">
- <t-checkbox
- v-for="skill in skillOptions"
- :key="skill.name"
- :value="skill.name"
- class="skill-checkbox-item"
- >
+ <t-checkbox v-for="skill in skillOptions" :key="skill.name" :value="skill.name"
+ class="skill-checkbox-item">
<div class="skill-item-content">
<span class="skill-name">{{ skill.name }}</span>
<span class="skill-desc">{{ skill.description }}</span>
@@ -895,7 +748,7 @@
<h2>{{ $t('agent.editor.knowledgeConfig') }}</h2>
<p class="section-description">{{ $t('agent.editor.knowledgeConfigDesc') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 关联知识库 -->
<div class="setting-row">
@@ -906,7 +759,8 @@
<div class="setting-control">
<t-radio-group v-model="kbSelectionMode">
<t-radio-button value="all">{{ $t('agent.editor.allKnowledgeBases') }}</t-radio-button>
- <t-radio-button value="selected">{{ $t('agent.editor.selectedKnowledgeBases') }}</t-radio-button>
+ <t-radio-button value="selected">{{ $t('agent.editor.selectedKnowledgeBases')
+ }}</t-radio-button>
<t-radio-button value="none">{{ $t('agent.editor.noKnowledgeBase') }}</t-radio-button>
</t-radio-group>
</div>
@@ -919,21 +773,12 @@
<p class="desc">{{ $t('agent.editor.selectKnowledgeBasesDesc') }}</p>
</div>
<div class="setting-control">
- <t-select
- v-model="formData.config.knowledge_bases"
- multiple
- :placeholder="$t('agent.editor.selectKnowledgeBases')"
- filterable
- :min-collapsed-num="3"
- >
- <t-option-group v-if="filteredMyKbOptions.length" :label="$t('agent.editor.myKnowledgeBases')">
- <t-option
- v-for="kb in filteredMyKbOptions"
- :key="kb.value"
- :value="kb.value"
- :label="kb.label"
- :disabled="kb.disabled"
- >
+ <t-select v-model="formData.config.knowledge_bases" multiple
+ :placeholder="$t('agent.editor.selectKnowledgeBases')" filterable :min-collapsed-num="3">
+ <t-option-group v-if="filteredMyKbOptions.length"
+ :label="$t('agent.editor.myKnowledgeBases')">
+ <t-option v-for="kb in filteredMyKbOptions" :key="kb.value" :value="kb.value"
+ :label="kb.label" :disabled="kb.disabled">
<div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
<span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
@@ -946,14 +791,10 @@
</div>
</t-option>
</t-option-group>
- <t-option-group v-if="filteredSharedKbOptions.length" :label="$t('agent.editor.sharedKnowledgeBases')">
- <t-option
- v-for="kb in filteredSharedKbOptions"
- :key="kb.value"
- :value="kb.value"
- :label="kb.label"
- :disabled="kb.disabled"
- >
+ <t-option-group v-if="filteredSharedKbOptions.length"
+ :label="$t('agent.editor.sharedKnowledgeBases')">
+ <t-option v-for="kb in filteredSharedKbOptions" :key="kb.value" :value="kb.value"
+ :label="kb.label" :disabled="kb.disabled">
<div class="kb-option-item" :title="kb.disabled ? kb.disabledReason : ''">
<span class="kb-option-icon" :class="kb.type === 'faq' ? 'faq-icon' : 'doc-icon'">
<t-icon :name="kb.type === 'faq' ? 'chat-bubble-help' : 'folder'" />
@@ -978,19 +819,10 @@
<p class="desc">{{ $t('agentEditor.fileTypes.desc') }}</p>
</div>
<div class="setting-control">
- <t-select
- v-model="formData.config.supported_file_types"
- multiple
- :placeholder="$t('agentEditor.fileTypes.allTypes')"
- :min-collapsed-num="3"
- clearable
- >
- <t-option
- v-for="ft in availableFileTypes"
- :key="ft.value"
- :value="ft.value"
- :label="ft.label"
- />
+ <t-select v-model="formData.config.supported_file_types" multiple
+ :placeholder="$t('agentEditor.fileTypes.allTypes')" :min-collapsed-num="3" clearable>
+ <t-option v-for="ft in availableFileTypes" :key="ft.value" :value="ft.value"
+ :label="ft.label" />
</t-select>
</div>
</div>
@@ -1022,14 +854,11 @@
</p>
</div>
<div class="setting-control">
- <ModelSelector
- model-type="Rerank"
- :selected-model-id="formData.config.rerank_model_id"
+ <ModelSelector model-type="Rerank" :selected-model-id="formData.config.rerank_model_id"
:all-models="allModels"
@update:selected-model-id="(val: string) => formData.config.rerank_model_id = val"
@add-model="handleAddModel('rerank')"
- :placeholder="$t('agent.editor.rerankModelPlaceholder')"
- />
+ :placeholder="$t('agent.editor.rerankModelPlaceholder')" />
</div>
</div>
@@ -1062,8 +891,10 @@
</div>
<div class="setting-control">
<div class="slider-wrapper">
- <t-slider v-model="formData.config.faq_direct_answer_threshold" :min="0.7" :max="1" :step="0.05" />
- <span class="slider-value">{{ formData.config.faq_direct_answer_threshold?.toFixed(2) }}</span>
+ <t-slider v-model="formData.config.faq_direct_answer_threshold" :min="0.7" :max="1"
+ :step="0.05" />
+ <span class="slider-value">{{ formData.config.faq_direct_answer_threshold?.toFixed(2)
+ }}</span>
</div>
</div>
</div>
@@ -1092,7 +923,7 @@
<h2>{{ $t('agent.editor.webSearchConfig') }}</h2>
<p class="section-description">{{ $t('agent.editor.webSearchConfigDesc') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 网络搜索 -->
<div class="setting-row">
@@ -1112,20 +943,13 @@
<p class="desc">{{ $t('agentEditor.desc.webSearchProvider') }}</p>
</div>
<div class="setting-control">
- <t-select
- v-model="formData.config.web_search_provider_id"
- clearable
- :placeholder="$t('agent.editor.webSearchProviderPlaceholder')"
- style="width: 240px;"
- >
- <t-option
- v-for="p in webSearchProviderList"
- :key="p.id"
- :value="p.id"
- :label="p.name"
- >
+ <t-select v-model="formData.config.web_search_provider_id" clearable
+ :placeholder="$t('agent.editor.webSearchProviderPlaceholder')" style="width: 240px;">
+ <t-option v-for="p in webSearchProviderList" :key="p.id" :value="p.id" :label="p.name">
<span>{{ p.name }}</span>
- <t-tag v-if="p.is_default" theme="primary" size="small" style="margin-left: 6px;">{{ $t('common.default') }}</t-tag>
+ <t-tag v-if="p.is_default" theme="primary" size="small" style="margin-left: 6px;">{{
+ $t('common.default')
+ }}</t-tag>
</t-option>
</t-select>
</div>
@@ -1157,7 +981,8 @@
</div>
<!-- 抓取页面数 -->
- <div v-if="formData.config.web_search_enabled && formData.config.web_fetch_enabled" class="setting-row">
+ <div v-if="formData.config.web_search_enabled && formData.config.web_fetch_enabled"
+ class="setting-row">
<div class="setting-info">
<label>{{ $t('agent.editor.webFetchTopN') }}</label>
<p class="desc">{{ $t('agentEditor.desc.webFetchTopN') }}</p>
@@ -1178,7 +1003,7 @@
<h2>{{ $t('agent.editor.retrievalStrategy') }}</h2>
<p class="section-description">{{ $t('agentEditor.desc.retrievalSection') }}</p>
</div>
-
+
<div class="settings-group">
<!-- 查询扩展(仅普通模式) -->
<div v-if="!isAgentMode" class="setting-row">
@@ -1282,83 +1107,60 @@
</div>
<!-- 固定兜底回复 -->
- <div v-if="formData.config.fallback_strategy === 'fixed'" class="setting-row setting-row-vertical">
+ <div v-if="formData.config.fallback_strategy === 'fixed'"
+ class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.fallbackResponse') }}</label>
<p class="desc">{{ $t('agentEditor.desc.fallbackResponse') }}</p>
</div>
<div class="setting-control setting-control-full">
<div class="textarea-with-template">
- <t-textarea
- v-model="formData.config.fallback_response"
+ <t-textarea v-model="formData.config.fallback_response"
:placeholder="defaultFallbackResponse || $t('agent.editor.fallbackResponsePlaceholder')"
- :autosize="{ minRows: 2, maxRows: 6 }"
- />
- <PromptTemplateSelector
- type="fallback"
- position="corner"
- fallbackMode="fixed"
+ :autosize="{ minRows: 2, maxRows: 6 }" />
+ <PromptTemplateSelector type="fallback" position="corner" fallbackMode="fixed"
@select="handleFallbackResponseTemplateSelect"
- @reset-default="handleFallbackResponseTemplateSelect"
- />
+ @reset-default="handleFallbackResponseTemplateSelect" />
</div>
</div>
</div>
<!-- 兜底提示词 -->
- <div v-if="formData.config.fallback_strategy === 'model'" class="setting-row setting-row-vertical">
+ <div v-if="formData.config.fallback_strategy === 'model'"
+ class="setting-row setting-row-vertical">
<div class="setting-info">
<label>{{ $t('agent.editor.fallbackPrompt') }}</label>
<p class="desc">{{ $t('agentEditor.desc.fallbackPrompt') }}</p>
<div class="placeholder-tags" v-if="fallbackPlaceholders.length > 0">
<span class="placeholder-label">{{ $t('agentEditor.placeholders.available') }}</span>
- <t-tooltip
- v-for="placeholder in fallbackPlaceholders"
- :key="placeholder.name"
+ <t-tooltip v-for="placeholder in fallbackPlaceholders" :key="placeholder.name"
:content="placeholder.description + $t('agentEditor.placeholders.clickToInsert')"
- placement="top"
- >
- <span
- class="placeholder-tag"
+ placement="top">
+ <span class="placeholder-tag"
@click="handlePlaceholderClick('fallback', placeholder.name)"
- v-text="'{{' + placeholder.name + '}}'"
- ></span>
+ v-text="'{{' + placeholder.name + '}}'"></span>
</t-tooltip>
<span class="placeholder-hint">{{ $t('agentEditor.placeholders.hint') }}</span>
</div>
</div>
<div class="setting-control setting-control-full" style="position: relative;">
<div class="textarea-with-template">
- <t-textarea
- ref="fallbackPromptTextareaRef"
- v-model="formData.config.fallback_prompt"
+ <t-textarea ref="fallbackPromptTextareaRef" v-model="formData.config.fallback_prompt"
:placeholder="defaultFallbackPrompt || $t('agent.editor.fallbackPromptPlaceholder')"
- :autosize="{ minRows: 4, maxRows: 10 }"
- @input="handleFallbackPromptInput"
- />
- <PromptTemplateSelector
- type="fallback"
- position="corner"
- fallbackMode="model"
+ :autosize="{ minRows: 4, maxRows: 10 }" @input="handleFallbackPromptInput" />
+ <PromptTemplateSelector type="fallback" position="corner" fallbackMode="model"
@select="handleFallbackPromptTemplateSelect"
- @reset-default="handleFallbackPromptTemplateSelect"
- />
+ @reset-default="handleFallbackPromptTemplateSelect" />
</div>
<Teleport to="body">
- <div
- v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0"
- class="placeholder-popup-wrapper"
- :style="fallbackPromptPopup.style"
- >
+ <div v-if="fallbackPromptPopup.show && filteredFallbackPlaceholders.length > 0"
+ class="placeholder-popup-wrapper" :style="fallbackPromptPopup.style">
<div class="placeholder-popup">
- <div
- v-for="(placeholder, index) in filteredFallbackPlaceholders"
- :key="placeholder.name"
- class="placeholder-item"
+ <div v-for="(placeholder, index) in filteredFallbackPlaceholders"
+ :key="placeholder.name" class="placeholder-item"
:class="{ active: fallbackPromptPopup.selectedIndex === index }"
@mousedown.prevent="insertGenericPlaceholder('fallback', placeholder.name, true)"
- @mouseenter="fallbackPromptPopup.selectedIndex = index"
- >
+ @mouseenter="fallbackPromptPopup.selectedIndex = index">
<div class="placeholder-name">
<code v-html="`{{${placeholder.name}}}`"></code>
</div>
@@ -1374,7 +1176,8 @@
</div>
<!-- 共享管理(仅编辑模式且非内置智能体) -->
- <div v-if="props.mode === 'edit' && props.agent?.id && !props.agent?.is_builtin" v-show="currentSection === 'share'" class="section">
+ <div v-if="props.mode === 'edit' && props.agent?.id && !props.agent?.is_builtin"
+ v-show="currentSection === 'share'" class="section">
<AgentShareSettings :agent-id="props.agent.id" :agent="props.agent" />
</div>
@@ -1384,7 +1187,8 @@
<h2>{{ $t('agentEditor.im.title') }}</h2>
<p class="section-description">
{{ $t('agentEditor.im.description') }}
- <a href="https://github.com/Tencent/WeKnora/blob/main/docs/IM%E9%9B%86%E6%88%90%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3.md" target="_blank" rel="noopener noreferrer" class="doc-link">
+ <a href="https://github.com/Tencent/WeKnora/blob/main/docs/IM%E9%9B%86%E6%88%90%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3.md"
+ target="_blank" rel="noopener noreferrer" class="doc-link">
{{ $t('agentEditor.im.docLink') }}
<t-icon name="link" class="link-icon" />
</a>
@@ -1398,8 +1202,12 @@
<!-- 底部操作栏 -->
<div class="settings-footer">
- <t-button variant="outline" @click="handleClose">{{ props.readOnly ? $t('common.close') : $t('common.cancel') }}</t-button>
- <t-button v-if="!props.readOnly" theme="primary" :loading="saving" @click="handleSave">{{ $t('common.confirm') }}</t-button>
+ <t-button variant="outline" @click="handleClose">{{ props.readOnly ? $t('common.close') :
+ $t('common.cancel')
+ }}</t-button>
+ <t-button v-if="!props.readOnly" theme="primary" :loading="saving" @click="handleSave">{{
+ $t('common.confirm')
+ }}</t-button>
</div>
</div>
</div>
@@ -1430,7 +1238,7 @@ import { listKnowledgeBases } from '@/api/knowledge-base';
import { listMCPServices, type MCPService } from '@/api/mcp-service';
import { listSkills, type SkillInfo } from '@/api/skill';
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider';
-import { getAgentConfig, getStorageEngineStatus, getPromptTemplates, type StorageEngineStatusItem, type PromptTemplate } from '@/api/system';
+import { getStorageEngineStatus, getPromptTemplates, type StorageEngineStatusItem, type PromptTemplate } from '@/api/system';
import { getTenantRetrievalConfig } from '@/api/retrieval';
import { useUIStore } from '@/stores/ui';
import { useAuthStore } from '@/stores/auth';
@@ -1503,7 +1311,10 @@ const imageStorageOptions = computed(() => {
});
// 系统默认配置(用于内置智能体显示默认提示词)
-const defaultAgentSystemPrompt = ref(''); // Agent 模式的默认系统提示词(来自 agent-config)
+// Agent (smart-reasoning) 模式的默认系统提示词。直接从 prompt-templates
+// 的 agent_system_prompt 数组里挑 mode==='rag' && default 的那条得到,
+// 与后端 agent.GetProgressiveRAGSystemPrompt 是同一份数据源。
+const defaultAgentSystemPrompt = ref('');
const defaultNormalSystemPrompt = ref(''); // 普通模式默认系统提示词(来自 prompt-templates 的 default 项)
const defaultContextTemplate = ref('');
const defaultRewritePromptSystem = ref('');
@@ -1573,12 +1384,12 @@ const allTools = computed(() => [
// 工具分组元信息
const toolGroups = computed(() => [
- { key: 'base', label: t('agentEditor.tools.groupBase') },
- { key: 'rag', label: t('agentEditor.tools.groupRag') },
- { key: 'wiki_read', label: t('agentEditor.tools.groupWikiRead') },
- { key: 'wiki_edit', label: t('agentEditor.tools.groupWikiEdit') },
+ { key: 'base', label: t('agentEditor.tools.groupBase') },
+ { key: 'rag', label: t('agentEditor.tools.groupRag') },
+ { key: 'wiki_read', label: t('agentEditor.tools.groupWikiRead') },
+ { key: 'wiki_edit', label: t('agentEditor.tools.groupWikiEdit') },
{ key: 'wiki_issue', label: t('agentEditor.tools.groupWikiIssue') },
- { key: 'data', label: t('agentEditor.tools.groupData') },
+ { key: 'data', label: t('agentEditor.tools.groupData') },
]);
// 知识库分组:我的 vs 共享的
@@ -1653,13 +1464,13 @@ const scopeCapabilities = computed<ScopeCapabilities>(() => {
// 后续可按需增加独立的 i18n 键。
const missKindToReason = (kind: RequirementMissKind): string | undefined => {
switch (kind) {
- case 'needsKb': return t('agentEditor.tools.requiresKb');
- case 'needsWiki': return t('agentEditor.tools.requiresWikiKb');
+ case 'needsKb': return t('agentEditor.tools.requiresKb');
+ case 'needsWiki': return t('agentEditor.tools.requiresWikiKb');
case 'needsRag':
case 'needsGraph':
- case 'needsFaq': return t('agentEditor.tools.requiresRagKb');
+ case 'needsFaq': return t('agentEditor.tools.requiresRagKb');
case 'none':
- default: return undefined;
+ default: return undefined;
}
};
@@ -1713,7 +1524,7 @@ const effectiveTools = computed(() => {
}
if (formData.value.config.web_search_enabled) {
items.push({ value: 'web_search', label: t('agentEditor.tools.webSearch'), active: true });
- items.push({ value: 'web_fetch', label: t('agentEditor.tools.webFetch'), active: true });
+ items.push({ value: 'web_fetch', label: t('agentEditor.tools.webFetch'), active: true });
}
items.push({ value: 'final_answer', label: t('agentEditor.tools.finalAnswer'), active: true });
return items;
@@ -1992,10 +1803,10 @@ const isDescriptionSystemGenerated = (desc: string): boolean => {
// 不要直接把 "vector / keyword / wiki" 这些底层 capability 名回传给用户 —
// 用户不关心技术实现,只想知道"为什么我这个知识库不能用"。
const presetKbMismatchKeyMap: Record<string, string> = {
- 'rag-qa': 'ragQa',
- 'wiki-qa': 'wikiQa',
+ 'rag-qa': 'ragQa',
+ 'wiki-qa': 'wikiQa',
'hybrid-rag-wiki': 'hybridRagWiki',
- 'data-analysis': 'dataAnalysis',
+ 'data-analysis': 'dataAnalysis',
};
const presetKbMismatchReason = (preset: AgentTypePreset): string => {
const subKey = presetKbMismatchKeyMap[preset.id];
@@ -2215,19 +2026,19 @@ watch(() => props.visible, async (val) => {
currentSection.value = props.initialSection || 'basic';
// 先加载依赖数据(包括默认配置)
await loadDependencies();
-
+
if (props.mode === 'edit' && props.agent) {
// 深度复制对象以避免引用问题
const agentData = JSON.parse(JSON.stringify(props.agent));
-
+
// 确保 config 对象存在
if (!agentData.config) {
agentData.config = JSON.parse(JSON.stringify(defaultFormData.config));
}
-
+
// 补全可能缺失的字段
agentData.config = { ...defaultFormData.config, ...agentData.config };
-
+
// 确保数组字段存在
if (!agentData.config.suggested_prompts) agentData.config.suggested_prompts = [];
if (!agentData.config.knowledge_bases) agentData.config.knowledge_bases = [];
@@ -2367,7 +2178,7 @@ const initSkillsSelectionMode = () => {
const fillBuiltinAgentDefaults = () => {
const config = formData.value.config;
const isAgent = config.agent_mode === 'smart-reasoning';
-
+
if (isAgent) {
// Agent 模式:使用 agent-config 的默认提示词
if (!config.system_prompt && defaultAgentSystemPrompt.value) {
@@ -2382,7 +2193,7 @@ const fillBuiltinAgentDefaults = () => {
config.context_template = defaultContextTemplate.value;
}
}
-
+
// 通用默认值
if (!config.rewrite_prompt_system && defaultRewritePromptSystem.value) {
config.rewrite_prompt_system = defaultRewritePromptSystem.value;
@@ -2659,6 +2470,15 @@ const loadDependencies = async () => {
const cfg = tmplRes?.data;
if (cfg?.agent_system_prompt && Array.isArray(cfg.agent_system_prompt)) {
agentSystemPromptTemplates.value = cfg.agent_system_prompt;
+ // Smart-reasoning (Progressive RAG) 默认提示词:取 mode='rag' &&
+ // default 的那条;找不到就退化到第一条 mode==='rag'。这块取代了
+ // 之前的 getAgentConfig() —— 后端实现就是从同一份模板里挑这条。
+ const ragDefault =
+ cfg.agent_system_prompt.find(t => t.mode === 'rag' && t.default) ||
+ cfg.agent_system_prompt.find(t => t.mode === 'rag');
+ if (ragDefault?.content) {
+ defaultAgentSystemPrompt.value = ragDefault.content;
+ }
}
const pickDefault = (arr?: PromptTemplate[]): PromptTemplate | undefined =>
Array.isArray(arr) ? arr.find(t => t.default) : undefined;
@@ -2709,16 +2529,6 @@ const loadDependencies = async () => {
console.warn('Failed to load placeholders', e);
}
- // 加载 Agent 模式默认提示词(来自 agent-config,用于 smart-reasoning 模式)
- try {
- const agentConfig = await getAgentConfig();
- if (agentConfig.data?.system_prompt) {
- defaultAgentSystemPrompt.value = agentConfig.data.system_prompt;
- }
- } catch (e) {
- console.warn('Failed to load agent config', e);
- }
-
// 加载租户检索默认参数(embedding_top_k / 阈值 / rerank top_k 等)。
// temperature 与 max_completion_tokens 不在 RetrievalConfig 中,保持组件内
// 硬编码默认值(0.7 / 2048);用户在 agent 表单里可逐项调整。
@@ -2758,7 +2568,7 @@ const filteredPlaceholders = computed(() => {
return availablePlaceholders.value;
}
const prefix = placeholderPrefix.value.toLowerCase();
- return availablePlaceholders.value.filter(p =>
+ return availablePlaceholders.value.filter(p =>
p.name.toLowerCase().startsWith(prefix)
);
});
@@ -2769,7 +2579,7 @@ const filteredContextPlaceholders = computed(() => {
return contextTemplatePlaceholders.value;
}
const prefix = contextPlaceholderPrefix.value.toLowerCase();
- return contextTemplatePlaceholders.value.filter(p =>
+ return contextTemplatePlaceholders.value.filter(p =>
p.name.toLowerCase().startsWith(prefix)
);
});
@@ -2780,7 +2590,7 @@ const filteredRewriteSystemPlaceholders = computed(() => {
return rewriteSystemPlaceholders.value;
}
const prefix = rewriteSystemPopup.value.prefix.toLowerCase();
- return rewriteSystemPlaceholders.value.filter(p =>
+ return rewriteSystemPlaceholders.value.filter(p =>
p.name.toLowerCase().startsWith(prefix)
);
});
@@ -2791,7 +2601,7 @@ const filteredRewriteUserPlaceholders = computed(() => {
return rewritePlaceholders.value;
}
const prefix = rewriteUserPopup.value.prefix.toLowerCase();
- return rewritePlaceholders.value.filter(p =>
+ return rewritePlaceholders.value.filter(p =>
p.name.toLowerCase().startsWith(prefix)
);
});
@@ -2802,7 +2612,7 @@ const filteredFallbackPlaceholders = computed(() => {
return fallbackPlaceholders.value;
}
const prefix = fallbackPromptPopup.value.prefix.toLowerCase();
- return fallbackPlaceholders.value.filter(p =>
+ return fallbackPlaceholders.value.filter(p =>
p.name.toLowerCase().startsWith(prefix)
);
});
@@ -2824,19 +2634,19 @@ const getTextareaElement = (): HTMLTextAreaElement | null => {
const calculateCursorPosition = (textarea: HTMLTextAreaElement) => {
const cursorPos = textarea.selectionStart;
const textBeforeCursor = formData.value.config.system_prompt.substring(0, cursorPos);
-
+
const style = window.getComputedStyle(textarea);
const textareaRect = textarea.getBoundingClientRect();
-
+
const lineHeight = parseFloat(style.lineHeight) || 20;
const paddingTop = parseFloat(style.paddingTop) || 0;
const paddingLeft = parseFloat(style.paddingLeft) || 0;
-
+
// 计算当前行号
const lines = textBeforeCursor.split('\n');
const currentLine = lines.length - 1;
const currentLineText = lines[currentLine];
-
+
// 创建临时 span 计算文本宽度
const span = document.createElement('span');
span.style.font = style.font;
@@ -2847,12 +2657,12 @@ const calculateCursorPosition = (textarea: HTMLTextAreaElement) => {
document.body.appendChild(span);
const textWidth = span.offsetWidth;
document.body.removeChild(span);
-
+
const scrollTop = textarea.scrollTop;
const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
const scrollLeft = textarea.scrollLeft;
const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;
-
+
return { top, left };
};
@@ -2860,10 +2670,10 @@ const calculateCursorPosition = (textarea: HTMLTextAreaElement) => {
const checkAndShowPlaceholderPopup = () => {
const textarea = getTextareaElement();
if (!textarea) return;
-
+
const cursorPos = textarea.selectionStart;
const textBeforeCursor = formData.value.config.system_prompt.substring(0, cursorPos);
-
+
// 查找最近的 {{ 位置
let lastOpenPos = -1;
for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
@@ -2875,16 +2685,16 @@ const checkAndShowPlaceholderPopup = () => {
}
}
}
-
+
if (lastOpenPos === -1) {
showPlaceholderPopup.value = false;
placeholderPrefix.value = '';
return;
}
-
+
const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
placeholderPrefix.value = textAfterOpen;
-
+
const filtered = filteredPlaceholders.value;
if (filtered.length > 0) {
nextTick(() => {
@@ -2915,17 +2725,17 @@ const handlePromptInput = () => {
const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {
const textarea = getTextareaElement();
if (!textarea) return;
-
+
showPlaceholderPopup.value = false;
placeholderPrefix.value = '';
selectedPlaceholderIndex.value = 0;
-
+
nextTick(() => {
const cursorPos = textarea.selectionStart;
const currentValue = formData.value.config.system_prompt || '';
const textBeforeCursor = currentValue.substring(0, cursorPos);
const textAfterCursor = currentValue.substring(cursorPos);
-
+
// 只有从下拉列表选择时才查找 {{ 并替换
if (fromPopup) {
let lastOpenPos = -1;
@@ -2935,12 +2745,12 @@ const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false)
break;
}
}
-
+
if (lastOpenPos !== -1) {
const textBeforeOpen = currentValue.substring(0, lastOpenPos);
const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
formData.value.config.system_prompt = newValue;
-
+
nextTick(() => {
const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -2949,11 +2759,11 @@ const insertPlaceholder = (placeholderName: string, fromPopup: boolean = false)
return;
}
}
-
+
// 直接在光标位置插入完整占位符
const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
formData.value.config.system_prompt = newValue;
-
+
nextTick(() => {
const newCursorPos = cursorPos + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -2979,18 +2789,18 @@ const getContextTemplateTextareaElement = (): HTMLTextAreaElement | null => {
const calculateContextCursorPosition = (textarea: HTMLTextAreaElement) => {
const cursorPos = textarea.selectionStart;
const textBeforeCursor = formData.value.config.context_template.substring(0, cursorPos);
-
+
const style = window.getComputedStyle(textarea);
const textareaRect = textarea.getBoundingClientRect();
-
+
const lineHeight = parseFloat(style.lineHeight) || 20;
const paddingTop = parseFloat(style.paddingTop) || 0;
const paddingLeft = parseFloat(style.paddingLeft) || 0;
-
+
const lines = textBeforeCursor.split('\n');
const currentLine = lines.length - 1;
const currentLineText = lines[currentLine];
-
+
const span = document.createElement('span');
span.style.font = style.font;
span.style.visibility = 'hidden';
@@ -3000,12 +2810,12 @@ const calculateContextCursorPosition = (textarea: HTMLTextAreaElement) => {
document.body.appendChild(span);
const textWidth = span.offsetWidth;
document.body.removeChild(span);
-
+
const scrollTop = textarea.scrollTop;
const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
const scrollLeft = textarea.scrollLeft;
const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;
-
+
return { top, left };
};
@@ -3013,10 +2823,10 @@ const calculateContextCursorPosition = (textarea: HTMLTextAreaElement) => {
const checkAndShowContextPlaceholderPopup = () => {
const textarea = getContextTemplateTextareaElement();
if (!textarea) return;
-
+
const cursorPos = textarea.selectionStart;
const textBeforeCursor = formData.value.config.context_template.substring(0, cursorPos);
-
+
let lastOpenPos = -1;
for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
@@ -3027,16 +2837,16 @@ const checkAndShowContextPlaceholderPopup = () => {
}
}
}
-
+
if (lastOpenPos === -1) {
showContextPlaceholderPopup.value = false;
contextPlaceholderPrefix.value = '';
return;
}
-
+
const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
contextPlaceholderPrefix.value = textAfterOpen;
-
+
const filtered = filteredContextPlaceholders.value;
if (filtered.length > 0) {
nextTick(() => {
@@ -3067,17 +2877,17 @@ const handleContextTemplateInput = () => {
const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean = false) => {
const textarea = getContextTemplateTextareaElement();
if (!textarea) return;
-
+
showContextPlaceholderPopup.value = false;
contextPlaceholderPrefix.value = '';
selectedContextPlaceholderIndex.value = 0;
-
+
nextTick(() => {
const cursorPos = textarea.selectionStart;
const currentValue = formData.value.config.context_template || '';
const textBeforeCursor = currentValue.substring(0, cursorPos);
const textAfterCursor = currentValue.substring(cursorPos);
-
+
// 只有从下拉列表选择时才查找 {{ 并替换
if (fromPopup) {
let lastOpenPos = -1;
@@ -3087,12 +2897,12 @@ const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean =
break;
}
}
-
+
if (lastOpenPos !== -1) {
const textBeforeOpen = currentValue.substring(0, lastOpenPos);
const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
formData.value.config.context_template = newValue;
-
+
nextTick(() => {
const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -3101,11 +2911,11 @@ const insertContextPlaceholder = (placeholderName: string, fromPopup: boolean =
return;
}
}
-
+
// 直接在光标位置插入完整占位符
const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
formData.value.config.context_template = newValue;
-
+
nextTick(() => {
const newCursorPos = cursorPos + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -3140,13 +2950,13 @@ const calculateGenericCursorPosition = (textarea: HTMLTextAreaElement, fieldValu
const lines = textBeforeCursor.split('\n');
const currentLine = lines.length - 1;
const currentLineText = lines[currentLine];
-
+
const textareaRect = textarea.getBoundingClientRect();
const style = window.getComputedStyle(textarea);
const lineHeight = parseFloat(style.lineHeight) || 20;
const paddingTop = parseFloat(style.paddingTop) || 0;
const paddingLeft = parseFloat(style.paddingLeft) || 0;
-
+
const span = document.createElement('span');
span.style.font = style.font;
span.style.visibility = 'hidden';
@@ -3156,12 +2966,12 @@ const calculateGenericCursorPosition = (textarea: HTMLTextAreaElement, fieldValu
document.body.appendChild(span);
const textWidth = span.offsetWidth;
document.body.removeChild(span);
-
+
const scrollTop = textarea.scrollTop;
const top = textareaRect.top + paddingTop + (currentLine * lineHeight) - scrollTop + lineHeight + 4;
const scrollLeft = textarea.scrollLeft;
const left = textareaRect.left + paddingLeft + textWidth - scrollLeft;
-
+
return { top, left };
};
@@ -3174,11 +2984,11 @@ const checkAndShowGenericPlaceholderPopup = (
) => {
const textarea = getGenericTextareaElement(type);
if (!textarea) return;
-
+
const cursorPos = textarea.selectionStart;
const fieldValue = String(formData.value.config[fieldKey] || '');
const textBeforeCursor = fieldValue.substring(0, cursorPos);
-
+
let lastOpenPos = -1;
for (let i = textBeforeCursor.length - 1; i >= 1; i--) {
if (textBeforeCursor[i] === '{' && textBeforeCursor[i - 1] === '{') {
@@ -3189,16 +2999,16 @@ const checkAndShowGenericPlaceholderPopup = (
}
}
}
-
+
if (lastOpenPos === -1) {
popup.value.show = false;
popup.value.prefix = '';
return;
}
-
+
const textAfterOpen = textBeforeCursor.substring(lastOpenPos + 2);
popup.value.prefix = textAfterOpen;
-
+
if (filteredPlaceholders.length > 0) {
nextTick(() => {
const position = calculateGenericCursorPosition(textarea, fieldValue);
@@ -3248,7 +3058,7 @@ const handleFallbackPromptInput = () => {
const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallback', placeholderName: string, fromPopup: boolean = false) => {
const textarea = getGenericTextareaElement(type);
if (!textarea) return;
-
+
const popupMap = {
rewriteSystem: rewriteSystemPopup,
rewriteUser: rewriteUserPopup,
@@ -3259,20 +3069,20 @@ const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallb
rewriteUser: 'rewrite_prompt_user',
fallback: 'fallback_prompt',
};
-
+
const popup = popupMap[type];
const fieldKey = fieldKeyMap[type];
-
+
popup.value.show = false;
popup.value.prefix = '';
popup.value.selectedIndex = 0;
-
+
nextTick(() => {
const cursorPos = textarea.selectionStart;
const currentValue = String(formData.value.config[fieldKey] || '');
const textBeforeCursor = currentValue.substring(0, cursorPos);
const textAfterCursor = currentValue.substring(cursorPos);
-
+
// 只有从下拉列表选择时才查找 {{ 并替换
if (fromPopup) {
let lastOpenPos = -1;
@@ -3282,12 +3092,12 @@ const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallb
break;
}
}
-
+
if (lastOpenPos !== -1) {
const textBeforeOpen = currentValue.substring(0, lastOpenPos);
const newValue = textBeforeOpen + `{{${placeholderName}}}` + textAfterCursor;
(formData.value.config as any)[fieldKey] = newValue;
-
+
nextTick(() => {
const newCursorPos = textBeforeOpen.length + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -3296,11 +3106,11 @@ const insertGenericPlaceholder = (type: 'rewriteSystem' | 'rewriteUser' | 'fallb
return;
}
}
-
+
// 直接在光标位置插入完整占位符
const newValue = textBeforeCursor + `{{${placeholderName}}}` + textAfterCursor;
(formData.value.config as any)[fieldKey] = newValue;
-
+
nextTick(() => {
const newCursorPos = cursorPos + placeholderName.length + 4;
textarea.setSelectionRange(newCursorPos, newCursorPos);
@@ -3797,7 +3607,7 @@ const handleSave = async () => {
&.setting-row-vertical {
flex-direction: column;
gap: 12px;
-
+
.setting-info {
max-width: 100%;
padding-right: 0;
@@ -3842,7 +3652,7 @@ const handleSave = async () => {
align-items: center;
justify-content: space-between;
margin-bottom: 4px;
-
+
label {
margin-bottom: 0;
}
@@ -3911,6 +3721,7 @@ const handleSave = async () => {
color: var(--td-brand-color);
margin-top: 4px;
text-decoration: none;
+
&:hover {
text-decoration: underline;
}
@@ -4065,7 +3876,9 @@ const handleSave = async () => {
background: var(--td-warning-color-1, rgba(237, 118, 20, 0.08));
border-color: var(--td-warning-color-light, #fcd7b6);
- .t-icon { color: var(--td-warning-color); }
+ .t-icon {
+ color: var(--td-warning-color);
+ }
}
}
@@ -4127,17 +3940,36 @@ const handleSave = async () => {
border: 1px solid var(--td-warning-color-light, #fcd7b6);
border-radius: 999px;
- .t-icon { font-size: 13px; }
+ .t-icon {
+ font-size: 13px;
+ }
}
}
// 不同分组的左侧色条
-.tool-group--base .tool-group-bar { background: var(--td-gray-color-6, #a0a7ab); }
-.tool-group--rag .tool-group-bar { background: var(--td-brand-color); }
-.tool-group--wiki_read .tool-group-bar { background: var(--td-success-color, #2ba471); }
-.tool-group--wiki_edit .tool-group-bar { background: var(--td-warning-color, #ed7b2f); }
-.tool-group--wiki_issue .tool-group-bar { background: var(--td-purple-5, #8e56dd); }
-.tool-group--data .tool-group-bar { background: var(--td-cyan-6, #09a3b7); }
+.tool-group--base .tool-group-bar {
+ background: var(--td-gray-color-6, #a0a7ab);
+}
+
+.tool-group--rag .tool-group-bar {
+ background: var(--td-brand-color);
+}
+
+.tool-group--wiki_read .tool-group-bar {
+ background: var(--td-success-color, #2ba471);
+}
+
+.tool-group--wiki_edit .tool-group-bar {
+ background: var(--td-warning-color, #ed7b2f);
+}
+
+.tool-group--wiki_issue .tool-group-bar {
+ background: var(--td-purple-5, #8e56dd);
+}
+
+.tool-group--data .tool-group-bar {
+ background: var(--td-cyan-6, #09a3b7);
+}
// 统一两列网格;小屏退化单列
.tool-grid {
@@ -4260,6 +4092,7 @@ const handleSave = async () => {
}
.tool-card--disabled {
+
.tool-card-name,
.tool-card-desc {
color: var(--td-text-color-placeholder);
@@ -4445,12 +4278,14 @@ const handleSave = async () => {
overflow-x: auto;
white-space: nowrap;
padding-bottom: 4px;
-
+
// 隐藏滚动条但保持可滚动
scrollbar-width: thin;
+
&::-webkit-scrollbar {
height: 4px;
}
+
&::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.1);
border-radius: 2px;
@@ -4570,12 +4405,12 @@ const handleSave = async () => {
height: 48px;
border-radius: 12px;
flex-shrink: 0;
-
+
&.normal {
background: linear-gradient(135deg, rgba(7, 192, 95, 0.15) 0%, rgba(7, 192, 95, 0.08) 100%);
color: var(--td-brand-color-active);
}
-
+
&.agent {
background: linear-gradient(135deg, rgba(124, 77, 255, 0.15) 0%, rgba(124, 77, 255, 0.08) 100%);
color: var(--td-brand-color);
@@ -4633,13 +4468,13 @@ const handleSave = async () => {
height: 24px;
border-radius: 6px;
font-size: 14px;
-
+
// Document KB
&.doc-icon {
background: rgba(16, 185, 129, 0.1);
color: var(--td-success-color);
}
-
+
// FAQ KB
&.faq-icon {
background: rgba(0, 82, 217, 0.1);
@@ -4740,11 +4575,11 @@ const handleSave = async () => {
font-size: 14px;
font-weight: 600;
color: var(--td-brand-color);
-
+
.faq-icon {
font-size: 18px;
}
-
+
.help-icon {
font-size: 14px;
color: var(--td-text-color-placeholder);
@@ -4755,12 +4590,12 @@ const handleSave = async () => {
.faq-strategy-section .setting-row {
padding: 12px 0;
border-bottom: 1px solid rgba(0, 82, 217, 0.1);
-
+
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
-
+
&:first-of-type {
padding-top: 0;
}
diff --git a/internal/config/config.go b/internal/config/config.go
index f1b660dee..07febc003 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -182,6 +182,20 @@ type TenantConfig struct {
// where role lookups are observed but not enforced; flip to true once
// role assignments have been audited.
EnableRBAC bool `yaml:"enable_rbac" json:"enable_rbac"`
+ // MaxOwnedPerUser caps how many tenants a single non-superuser can
+ // create (and Own) via self-service POST /tenants. Counts only Owner
+ // memberships so being invited as Admin/Editor/Viewer in another
+ // tenant doesn't burn quota. Cross-tenant superusers
+ // (CanAccessAllTenants) are exempt.
+ // > 0 — enforce the cap (handler returns 429 when reached).
+ // = 0 — fall back to defaultMaxOwnedTenantsPerUser in the handler.
+ // < 0 — disable the cap entirely (not recommended in shared deployments).
+ //
+ // Env override: WEKNORA_TENANT_MAX_OWNED_PER_USER (integer). When set
+ // and parseable it always wins over config.yaml so operators can
+ // loosen / tighten the quota without a redeploy. See
+ // applyAuthAndTenantDefaults for the semantics of <0 / 0 / >0.
+ MaxOwnedPerUser int `yaml:"max_owned_per_user" json:"max_owned_per_user" mapstructure:"max_owned_per_user"`
}
// AuditConfig governs durable audit log behaviour. Writes happen on
@@ -695,6 +709,10 @@ func applyAgentEnvOverrides(cfg *Config) {
// Env overrides (when set and non-empty):
// - WEKNORA_AUTH_REGISTRATION_MODE ("self_serve" or "invite_only")
// - WEKNORA_TENANT_ENABLE_RBAC ("true"/"false", case-insensitive)
+// - WEKNORA_TENANT_MAX_OWNED_PER_USER (integer; <0 disables the cap,
+// 0 falls back to the handler default, >0 enforces that exact cap).
+// Unparseable / empty values are ignored so a stale shell variable
+// can't silently disable the quota for a future deployment.
func applyAuthAndTenantDefaults(cfg *Config) {
if cfg.Auth == nil {
cfg.Auth = &AuthConfig{}
@@ -713,6 +731,17 @@ func applyAuthAndTenantDefaults(cfg *Config) {
if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_ENABLE_RBAC")); value != "" {
cfg.Tenant.EnableRBAC = strings.EqualFold(value, "true")
}
+
+ if value := strings.TrimSpace(os.Getenv("WEKNORA_TENANT_MAX_OWNED_PER_USER")); value != "" {
+ if n, err := strconv.Atoi(value); err == nil {
+ cfg.Tenant.MaxOwnedPerUser = n
+ } else {
+ fmt.Printf(
+ "[config] WEKNORA_TENANT_MAX_OWNED_PER_USER=%q is not an integer, ignoring\n",
+ value,
+ )
+ }
+ }
}
// applyAuditDefaults fills in defaults for the Audit config section
diff --git a/internal/errors/errors.go b/internal/errors/errors.go
index 1458a9835..dc4ca2b6e 100644
--- a/internal/errors/errors.go
+++ b/internal/errors/errors.go
@@ -110,6 +110,19 @@ func NewConflictError(message string) *AppError {
}
}
+// NewTooManyRequestsError creates a 429 error, used by quota-style
+// guards (e.g. per-user self-service tenant creation cap).
+func NewTooManyRequestsError(message string) *AppError {
+ if message == "" {
+ message = "too many requests"
+ }
+ return &AppError{
+ Code: ErrTooManyRequests,
+ Message: message,
+ HTTPCode: http.StatusTooManyRequests,
+ }
+}
+
// NewInternalServerError creates an internal server error
func NewInternalServerError(message string) *AppError {
if message == "" {
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index 0cfd62da1..be27e63ab 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -7,8 +7,6 @@ import (
"github.com/gin-gonic/gin"
- "github.com/Tencent/WeKnora/internal/agent"
- agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
@@ -76,6 +74,26 @@ type createTenantRequest struct {
Description string `json:"description" binding:"max=512"`
}
+// updateTenantRequest is the JSON body for PUT /tenants/:id. Only the
+// fields an Owner is permitted to mutate via the public API are bound;
+// everything else (storage_quota, status, business, api_key, agent /
+// retrieval / storage configs, ...) is intentionally NOT writable here
+// — those go through dedicated endpoints (POST /:id/api-key,
+// PUT /tenants/kv/:key, ...) that have their own validation.
+//
+// Pointers so we can distinguish "not sent" from "explicit empty
+// string"; when nil we leave the existing column untouched.
+type updateTenantRequest struct {
+ Name *string `json:"name" binding:"omitempty,min=1,max=128"`
+ Description *string `json:"description" binding:"omitempty,max=512"`
+}
+
+// defaultMaxOwnedTenantsPerUser is the cap applied when
+// config.Tenant.MaxOwnedPerUser is left at zero. Picked to comfortably
+// cover legitimate "personal + a couple of side-projects" use while
+// blunting drive-by abuse against POST /tenants (see CreateTenant).
+const defaultMaxOwnedTenantsPerUser = 10
+
// CreateTenant godoc
// @Summary 创建租户
// @Description 创建新的租户。任意已登录用户均可调用以建立自己的新工作区,
@@ -116,6 +134,10 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
c.Error(appErr)
return
}
+ // Reset client-supplied primary key so we don't accidentally
+ // insert with a chosen ID that collides with a future
+ // auto-increment value. Tenant IDs must always be DB-generated.
+ tenantData.ID = 0
} else {
// Self-service path: a regular user can only set name and
// description. Everything else is server-generated by
@@ -128,6 +150,41 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
c.Error(appErr)
return
}
+
+ // Per-user quota: cap how many tenants a regular user can spin
+ // up via self-service. Without this any authenticated client
+ // can flood `tenants` (and saturate validateStorageBucketUniqueness
+ // which scans the whole table). Superusers above are exempt
+ // because they're already trusted to manage the catalog.
+ if h.memberService != nil {
+ memberships, listErr := h.memberService.ListByUser(ctx, caller.ID)
+ if listErr != nil {
+ logger.Errorf(ctx, "Failed to count owned tenants for user %s: %v", caller.ID, listErr)
+ c.Error(errors.NewInternalServerError("Failed to validate tenant quota").WithDetails(listErr.Error()))
+ return
+ }
+ ownedCount := 0
+ for _, m := range memberships {
+ if m != nil && m.Role == types.TenantRoleOwner {
+ ownedCount++
+ }
+ }
+ cap := defaultMaxOwnedTenantsPerUser
+ if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {
+ cap = h.config.Tenant.MaxOwnedPerUser
+ }
+ if cap > 0 && ownedCount >= cap {
+ logger.Warnf(ctx,
+ "User %s reached self-service tenant quota (%d/%d)",
+ caller.ID, ownedCount, cap,
+ )
+ c.Error(errors.NewTooManyRequestsError(
+ "reached self-service tenant quota; contact an administrator to raise the limit",
+ ))
+ return
+ }
+ }
+
tenantData = types.Tenant{
Name: strings.TrimSpace(req.Name),
Description: strings.TrimSpace(req.Description),
@@ -150,18 +207,26 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {
}
// Bootstrap an Owner membership so the caller immediately has full
- // control over the tenant they just created. This mirrors what
- // userService.Register does for the auto-created home tenant.
- // Idempotent: EnsureOwner is a no-op if the row already exists,
- // which lets cross-tenant superusers create-and-own without a
- // separate code path. Failure here only logs — the orphan-tenant
- // recovery path in middleware/auth.go will recreate the membership
- // on next login as a safety net.
+ // control over the tenant they just created. We MUST roll the tenant
+ // back if this fails: without a membership row the new tenant is
+ // unreachable (middleware/auth.go's orphan-recovery only fires for a
+ // user's home tenant, never for a freshly-created side workspace),
+ // yet still occupies storage_bucket / name uniqueness slots.
+ // Idempotent: EnsureOwner is a no-op when the row already exists,
+ // so cross-tenant superusers create-and-own through the same path.
if h.memberService != nil {
if _, err := h.memberService.EnsureOwner(ctx, caller.ID, createdTenant.ID); err != nil {
logger.Errorf(ctx,
- "Failed to bootstrap owner membership for user %s tenant %d: %v",
+ "Failed to bootstrap owner membership for user %s tenant %d: %v — rolling back tenant",
caller.ID, createdTenant.ID, err)
+ if delErr := h.service.DeleteTenant(ctx, createdTenant.ID); delErr != nil {
+ logger.Errorf(ctx,
+ "Rollback DeleteTenant failed for orphan tenant %d: %v",
+ createdTenant.ID, delErr,
+ )
+ }
+ c.Error(errors.NewInternalServerError("Failed to finalise tenant ownership").WithDetails(err.Error()))
+ return
}
}
@@ -242,17 +307,50 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
return
}
- var tenantData types.Tenant
- if err := c.ShouldBindJSON(&tenantData); err != nil {
+ // Strict whitelist: only Name / Description are mutable through the
+ // public PUT. Storage quota, status, business, configs, api_key and
+ // every other privileged column live behind dedicated endpoints
+ // (POST /:id/api-key, PUT /tenants/kv/:key, ...). Without this, an
+ // Owner — including any user who just self-served a tenant — could
+ // flip status / bump storage_quota by simply crafting an extended
+ // JSON body. Pointers distinguish "field omitted" from "explicit
+ // empty string" so we can leave untouched columns alone.
+ var req updateTenantRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
- logger.Infof(ctx, "Updating tenant, ID: %d, Name: %s", id, secutils.SanitizeForLog(tenantData.Name))
+ // Load the persisted tenant so any column the request omits keeps
+ // its current value through the GORM `Updates(struct)` zero-skip
+ // behaviour (we always pass back the full struct).
+ existing, err := h.service.GetTenantByID(ctx, id)
+ if err != nil {
+ if appErr, ok := errors.IsAppError(err); ok {
+ c.Error(appErr)
+ } else {
+ logger.ErrorWithFields(ctx, err, nil)
+ c.Error(errors.NewInternalServerError("Failed to load tenant").WithDetails(err.Error()))
+ }
+ return
+ }
+
+ if req.Name != nil {
+ trimmed := strings.TrimSpace(*req.Name)
+ if trimmed == "" {
+ c.Error(errors.NewValidationError("name cannot be blank"))
+ return
+ }
+ existing.Name = trimmed
+ }
+ if req.Description != nil {
+ existing.Description = strings.TrimSpace(*req.Description)
+ }
- tenantData.ID = id
- updatedTenant, err := h.service.UpdateTenant(ctx, &tenantData)
+ logger.Infof(ctx, "Updating tenant, ID: %d, Name: %s", id, secutils.SanitizeForLog(existing.Name))
+
+ updatedTenant, err := h.service.UpdateTenant(ctx, existing)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
@@ -500,158 +598,9 @@ func (h *TenantHandler) SearchTenants(c *gin.Context) {
})
}
-// AgentConfigRequest represents the request body for updating agent configuration
-type AgentConfigRequest struct {
- MaxIterations int `json:"max_iterations"`
- AllowedTools []string `json:"allowed_tools"`
- Temperature float64 `json:"temperature"`
- SystemPrompt string `json:"system_prompt,omitempty"` // Unified system prompt (uses {{web_search_status}} placeholder)
-}
-
-// GetTenantAgentConfig godoc
-// @Summary 获取租户Agent配置
-// @Description 获取租户的全局Agent配置(默认应用于所有会话)
-// @Tags 租户管理
-// @Accept json
-// @Produce json
-// @Success 200 {object} map[string]interface{} "Agent配置"
-// @Failure 400 {object} errors.AppError "请求参数错误"
-// @Security Bearer
-// @Security ApiKeyAuth
-// @Router /tenants/kv/agent-config [get]
-func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
- ctx := c.Request.Context()
- tenant, _ := types.TenantInfoFromContext(ctx)
- if tenant == nil {
- logger.Error(ctx, "Tenant is empty")
- c.Error(errors.NewBadRequestError("Tenant is empty"))
- return
- }
- // 从 tools 包集中配置可用工具列表
- availableTools := make([]gin.H, 0)
- for _, t := range agenttools.AvailableToolDefinitions() {
- availableTools = append(availableTools, gin.H{
- "name": t.Name,
- "label": t.Label,
- "description": t.Description,
- })
- }
-
- // 从 agent 包获取占位符定义
- availablePlaceholders := make([]gin.H, 0)
- for _, p := range agent.AvailablePlaceholders() {
- availablePlaceholders = append(availablePlaceholders, gin.H{
- "name": p.Name,
- "label": p.Label,
- "description": p.Description,
- })
- }
- if tenant.AgentConfig == nil {
- // Return default config if not set
- logger.Info(ctx, "Tenant has no agent config, returning defaults")
-
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "max_iterations": agent.DefaultAgentMaxIterations,
- "allowed_tools": agenttools.DefaultAllowedTools(),
- "temperature": agent.DefaultAgentTemperature,
- "system_prompt": agent.GetProgressiveRAGSystemPrompt(h.config),
- "use_custom_system_prompt": false,
- "available_tools": availableTools,
- "available_placeholders": availablePlaceholders,
- },
- })
- return
- }
-
- // Get system prompt, use default if empty
- systemPrompt := tenant.AgentConfig.ResolveSystemPrompt(true) // webSearchEnabled doesn't matter for unified prompt
- if systemPrompt == "" {
- systemPrompt = agent.GetProgressiveRAGSystemPrompt(h.config)
- }
-
- logger.Infof(ctx, "Retrieved tenant agent config successfully, Tenant ID: %d", tenant.ID)
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": gin.H{
- "max_iterations": tenant.AgentConfig.MaxIterations,
- "allowed_tools": agenttools.DefaultAllowedTools(),
- "temperature": tenant.AgentConfig.Temperature,
- "system_prompt": systemPrompt,
- "use_custom_system_prompt": tenant.AgentConfig.UseCustomSystemPrompt,
- "available_tools": availableTools,
- "available_placeholders": availablePlaceholders,
- },
- })
-}
-
-// updateTenantAgentConfigInternal updates the agent configuration for a tenant
-// This sets the global agent configuration for all sessions in this tenant
-func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
- ctx := c.Request.Context()
- logger.Info(ctx, "Start updating tenant agent config")
- var req AgentConfigRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- logger.Error(ctx, "Failed to parse request parameters", err)
- c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
- return
- }
-
- // Validate configuration
- if req.MaxIterations <= 0 || req.MaxIterations > 30 {
- c.Error(errors.NewAgentInvalidMaxIterationsError())
- return
- }
- if req.Temperature < 0 || req.Temperature > 2 {
- c.Error(errors.NewAgentInvalidTemperatureError())
- return
- }
-
- // Get existing tenant
- tenant, _ := types.TenantInfoFromContext(ctx)
- if tenant == nil {
- logger.Error(ctx, "Tenant is empty")
- c.Error(errors.NewBadRequestError("Tenant is empty"))
- return
- }
- // Update agent configuration
- // Determine if using custom prompt based on whether custom prompts are set
- // Support both new unified SystemPrompt and deprecated separate prompts
- systemPrompt := req.SystemPrompt
- useCustomPrompt := systemPrompt != ""
-
- agentConfig := &types.AgentConfig{
- MaxIterations: req.MaxIterations,
- AllowedTools: agenttools.DefaultAllowedTools(),
- Temperature: req.Temperature,
- SystemPrompt: systemPrompt,
- UseCustomSystemPrompt: useCustomPrompt,
- }
-
- _, err := h.service.UpdateTenant(ctx, tenant)
- if err != nil {
- if appErr, ok := errors.IsAppError(err); ok {
- logger.Error(ctx, "Failed to update tenant: application error", appErr)
- c.Error(appErr)
- } else {
- logger.ErrorWithFields(ctx, err, nil)
- c.Error(errors.NewInternalServerError("Failed to update tenant agent config").WithDetails(err.Error()))
- }
- return
- }
-
- logger.Infof(ctx, "Tenant agent config updated successfully, Tenant ID: %d", tenant.ID)
- c.JSON(http.StatusOK, gin.H{
- "success": true,
- "data": agentConfig,
- "message": "Agent configuration updated successfully",
- })
-}
-
// GetTenantKV godoc
// @Summary 获取租户KV配置
-// @Description 获取租户级别的KV配置(支持agent-config、web-search-config 等)
+// @Description 获取租户级别的KV配置(支持web-search-config、prompt-templates、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 租户管理
// @Accept json
// @Produce json
@@ -666,9 +615,6 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
key := secutils.SanitizeForLog(c.Param("key"))
switch key {
- case "agent-config":
- h.GetTenantAgentConfig(c)
- return
case "web-search-config":
h.GetTenantWebSearchConfig(c)
return
@@ -696,7 +642,7 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
// UpdateTenantKV godoc
// @Summary 更新租户KV配置
-// @Description 更新租户级别的KV配置(支持agent-config、web-search-config 等)
+// @Description 更新租户级别的KV配置(支持web-search-config、parser-engine-config、storage-engine-config、chat-history-config、retrieval-config)
// @Tags 租户管理
// @Accept json
// @Produce json
@@ -712,9 +658,6 @@ func (h *TenantHandler) UpdateTenantKV(c *gin.Context) {
key := secutils.SanitizeForLog(c.Param("key"))
switch key {
- case "agent-config":
- h.updateTenantAgentConfigInternal(c)
- return
case "web-search-config":
h.updateTenantWebSearchConfigInternal(c)
return
diff --git a/internal/types/tenant.go b/internal/types/tenant.go
index 2f43c3182..fa3fec98e 100644
--- a/internal/types/tenant.go
+++ b/internal/types/tenant.go
@@ -98,9 +98,6 @@ type Tenant struct {
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
- // Deprecated: AgentConfig is deprecated, use CustomAgent (builtin-smart-reasoning) config instead.
- // This field is kept for backward compatibility and will be removed in future versions.
- AgentConfig *AgentConfig `yaml:"agent_config" json:"agent_config" gorm:"type:jsonb"`
// Global Context configuration for this tenant (default for all sessions)
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant