refactor(settings): update event handling and UI interactions in various components

Modified event handling for form submissions in CreateTenantDialog and CredentialResource components to use the `@enter` directive for improved clarity. Removed console log from i18n initialization and updated localization files to include new section labels for the redesigned drawer across multiple languages. Enhanced the UI in Login and McpSettings views by adjusting input types and integrating test connection functionality into the drawer components. Streamlined the layout and interactions in ModelSettings, ParserEngineSettings, StorageEngineSettings, and VectorStoreSettings to ensure consistency and better user experience.
This commit is contained in:
wizardchen
2026-05-31 15:28:00 +08:00
committed by lyingbug
parent 9d1f3001e8
commit d56370b30f
16 changed files with 2835 additions and 1292 deletions
@@ -18,7 +18,7 @@
<t-form ref="formRef" :data="form" :rules="formRules" label-align="top" class="create-tenant-form" @submit.prevent>
<t-form-item :label="$t('tenant.create.nameLabel')" name="name">
<t-input v-model="form.name" :placeholder="$t('tenant.create.namePlaceholder')" :maxlength="128" autofocus
@keydown.enter="handleSubmit" />
@enter="handleSubmit" />
</t-form-item>
<t-form-item :label="$t('tenant.create.descriptionLabel')" name="description">
<t-textarea v-model="form.description" :placeholder="$t('tenant.create.descriptionPlaceholder')"
@@ -118,7 +118,7 @@
<div class="credential-edit">
<t-input v-model="drafts[field.key]" type="password"
:placeholder="field.placeholder ?? t('credential.inputPlaceholder')" :autocomplete="'new-password'"
class="credential-edit-input" @keydown.enter.prevent="onSave(field)">
class="credential-edit-input" @enter="onSave(field)">
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
<div class="credential-edit-actions">
-1
View File
@@ -13,7 +13,6 @@ const messages = {
// Получаем сохраненный язык из localStorage или используем китайский по умолчанию
const savedLocale = localStorage.getItem('locale') || 'zh-CN'
console.log('i18n инициализация с языком:', savedLocale)
const i18n = createI18n({
legacy: false,
+33 -1
View File
@@ -895,6 +895,11 @@ export default {
parser: {
title: 'Parser Engine',
description: 'Document parser engine status and configuration. Settings here take priority over server environment variables. Leave empty to use environment variable defaults.',
// Section / label keys for the redesigned drawer
supportedFileTypes: 'Supported Formats',
statusSection: 'Status',
configSection: 'Configuration',
featuresLabel: 'Features',
loading: 'Loading...',
retry: 'Retry',
noEngineDetected: 'No parser engine detected. Please ensure the DocReader service is running properly.',
@@ -932,6 +937,12 @@ export default {
storage: {
title: 'Storage Engine',
description: 'Configure document and image storage. Set engine parameters here; knowledge bases only select which engine to use.',
// Section / label keys for the redesigned drawer
basicSection: 'Basic',
modeSection: 'Deployment Mode',
credentialsSection: 'Credentials',
bucketSection: 'Bucket',
useSslDesc: 'Connect to MinIO over HTTPS',
loading: 'Loading...',
retry: 'Retry',
defaultEngine: 'Default Engine',
@@ -1010,6 +1021,10 @@ export default {
webSearchSettings: {
title: 'Web Search Configuration',
description: 'Configure web search so answers can include up-to-date information from the internet.',
// Section keys for the redesigned drawer
basicSection: 'Basic',
credentialsSection: 'Connection',
optionsSection: 'Options',
// Provider entity management
providersTitle: 'Search Engine Providers',
addProvider: 'Add Provider',
@@ -1077,6 +1092,8 @@ export default {
vectorStoreSettings: {
title: 'Vector Database Engine',
description: 'Register and manage vector database instances for knowledge base search.',
// Section key for the redesigned drawer
basicSection: 'Basic',
storesTitle: 'Vector Databases',
addStore: 'Add Database',
editStore: 'Edit Database',
@@ -3498,6 +3515,9 @@ export default {
mcpSettings: {
title: 'MCP Services',
description: 'Manage external MCP (Model Context Protocol) services for tools/resources in Agent mode',
// Drawer subtitle chip
enabled: 'Enabled',
disabled: 'Disabled',
configuredServices: 'Configured Services',
manageAndTest: 'Manage and test MCP service connections',
addService: 'Add Service',
@@ -3538,7 +3558,8 @@ export default {
},
source: {
remote: 'Remote',
openaiCompatible: 'OpenAI-compatible'
openaiCompatible: 'OpenAI-compatible',
custom: 'Custom',
},
rawModelName: 'Model name',
chat: {
@@ -3645,6 +3666,13 @@ export default {
mcpServiceDialog: {
addTitle: 'Add MCP Service',
editTitle: 'Edit MCP Service',
// Section + drawer-only keys
basicSection: 'Basic',
connectionSection: 'Connection',
enableServiceDesc: 'When off, this service will not be invoked',
testAfterSaveHint: 'Save first to test the connection',
unitSecond: 's',
unitTimes: '×',
name: 'Service Name',
namePlaceholder: 'Enter service name',
description: 'Description',
@@ -4176,6 +4204,10 @@ export default {
name: 'WeKnora Cloud',
desc: 'Document parsing via WeKnora Cloud',
},
markitdown: {
name: 'MarkItDown',
desc: "Microsoft MarkItDown converter (PDF/Office/HTML and more)",
},
},
},
supportedFormats: 'Supported formats',
+32
View File
@@ -755,6 +755,11 @@ export default {
parser: {
title: '파서 엔진',
description: '문서 파서 엔진 상태 및 구성. 이 설정은 서버 환경변수보다 우선 적용됩니다. 비워두면 환경변수 기본값을 사용합니다.',
// Section / label keys for the redesigned drawer
supportedFileTypes: '지원 형식',
statusSection: '상태',
configSection: '구성',
featuresLabel: '기능',
loading: '로딩 중...',
retry: '재시도',
noEngineDetected: '파서 엔진이 감지되지 않았습니다. DocReader 서비스가 정상적으로 실행 중인지 확인하세요.',
@@ -792,6 +797,12 @@ export default {
storage: {
title: '스토리지 엔진',
description: '문서 및 이미지 저장 방식을 구성합니다. 엔진 파라미터를 설정하면 지식베이스에서 사용할 엔진만 선택합니다.',
// Section / label keys for the redesigned drawer
basicSection: '기본',
modeSection: '배포 모드',
credentialsSection: '자격 증명',
bucketSection: '버킷',
useSslDesc: 'HTTPS로 MinIO에 연결',
loading: '로딩 중...',
retry: '재시도',
defaultEngine: '기본 엔진',
@@ -871,6 +882,10 @@ export default {
title: "웹 검색 설정",
description:
"웹 검색 기능을 구성하여 질문에 답변할 때 인터넷에서 실시간 정보를 가져와 지식베이스 내용을 보완합니다",
// Section keys for the redesigned drawer
basicSection: '기본',
credentialsSection: '연결',
optionsSection: '옵션',
providersTitle: "검색 엔진 프로바이더 설정",
addProvider: "프로바이더 추가",
editProvider: "프로바이더 편집",
@@ -937,6 +952,8 @@ export default {
vectorStoreSettings: {
title: "벡터 데이터베이스 엔진",
description: "지식 베이스 검색을 위한 벡터 데이터베이스 인스턴스를 등록하고 관리합니다.",
// Section key for the redesigned drawer
basicSection: '기본',
storesTitle: "벡터 데이터베이스",
addStore: "데이터베이스 추가",
editStore: "데이터베이스 수정",
@@ -3539,6 +3556,9 @@ export default {
title: "MCP 서비스 관리",
description:
"외부 MCP (Model Context Protocol) 서비스를 관리합니다. Agent 모드에서 외부 도구와 리소스를 호출합니다",
// Drawer subtitle chip
enabled: "활성화됨",
disabled: "비활성화됨",
configuredServices: "설정된 서비스",
manageAndTest: "MCP 서비스 연결 관리 및 테스트",
addService: "서비스 추가",
@@ -3580,6 +3600,7 @@ export default {
source: {
remote: "Remote",
openaiCompatible: "OpenAI 호환",
custom: "사용자 지정",
},
rawModelName: "모델 이름",
chat: {
@@ -3686,6 +3707,13 @@ export default {
mcpServiceDialog: {
addTitle: "MCP 서비스 추가",
editTitle: "MCP 서비스 편집",
// Section + drawer-only keys
basicSection: "기본",
connectionSection: "연결",
enableServiceDesc: "비활성화 시 이 서비스가 호출되지 않습니다",
testAfterSaveHint: "저장 후 연결을 테스트할 수 있습니다",
unitSecond: "초",
unitTimes: "회",
name: "서비스 이름",
namePlaceholder: "서비스 이름을 입력해주세요",
description: "설명",
@@ -4238,6 +4266,10 @@ export default {
name: 'WeKnora Cloud',
desc: 'WeKnora Cloud를 통한 문서 파싱',
},
markitdown: {
name: 'MarkItDown',
desc: 'Microsoft MarkItDown 변환기 (PDF/Office/HTML 등)',
},
},
},
supportedFormats: '지원 형식',
+33 -1
View File
@@ -810,6 +810,11 @@ export default {
parser: {
title: 'Парсер',
description: 'Состояние и конфигурация парсеров документов. Настройки здесь приоритетнее переменных окружения сервера. Оставьте пустым для значений по умолчанию.',
// Section / label keys for the redesigned drawer
supportedFileTypes: 'Поддерживаемые форматы',
statusSection: 'Статус',
configSection: 'Конфигурация',
featuresLabel: 'Опции',
loading: 'Загрузка...',
retry: 'Повторить',
noEngineDetected: 'Парсеры не обнаружены. Убедитесь, что сервис DocReader работает.',
@@ -844,6 +849,12 @@ export default {
storage: {
title: 'Хранилище',
description: 'Настройте хранение документов и изображений. Здесь задаются параметры хранилищ; в базе знаний выбирается только тип хранилища.',
// Section / label keys for the redesigned drawer
basicSection: 'Основное',
modeSection: 'Режим развёртывания',
credentialsSection: 'Учётные данные',
bucketSection: 'Bucket',
useSslDesc: 'Подключаться к MinIO по HTTPS',
loading: 'Загрузка...',
retry: 'Повторить',
defaultEngine: 'Хранилище по умолчанию',
@@ -922,6 +933,10 @@ export default {
webSearchSettings: {
title: 'Настройки веб-поиска',
description: 'Настройте веб-поиск, чтобы ответы могли включать актуальную информацию из интернета.',
// Section keys for the redesigned drawer
basicSection: 'Основное',
credentialsSection: 'Подключение',
optionsSection: 'Опции',
providersTitle: 'Поисковые провайдеры',
addProvider: 'Добавить провайдер',
editProvider: 'Редактировать провайдер',
@@ -989,6 +1004,8 @@ export default {
vectorStoreSettings: {
title: 'Движок векторной базы данных',
description: 'Регистрация и управление экземплярами векторных баз данных для поиска по базе знаний.',
// Section key for the redesigned drawer
basicSection: 'Основное',
storesTitle: 'Векторные базы данных',
addStore: 'Добавить базу данных',
editStore: 'Редактировать базу данных',
@@ -3200,6 +3217,9 @@ export default {
mcpSettings: {
title: 'Сервисы MCP',
description: 'Управление внешними сервисами MCP (Model Context Protocol) для использования инструментов и ресурсов в режиме Agent',
// Drawer subtitle chip
enabled: 'Включён',
disabled: 'Отключён',
configuredServices: 'Настроенные сервисы',
manageAndTest: 'Управляйте и тестируйте подключения MCP',
addService: 'Добавить сервис',
@@ -3244,7 +3264,8 @@ export default {
},
source: {
remote: 'Удалённая',
openaiCompatible: 'Совместимо с OpenAI'
openaiCompatible: 'Совместимо с OpenAI',
custom: 'Своё',
},
rawModelName: 'Имя модели',
embedding: {
@@ -3344,6 +3365,13 @@ export default {
mcpServiceDialog: {
addTitle: 'Добавить сервис MCP',
editTitle: 'Редактировать сервис MCP',
// Section + drawer-only keys
basicSection: 'Основное',
connectionSection: 'Подключение',
enableServiceDesc: 'При выключении сервис не будет вызываться',
testAfterSaveHint: 'Сохраните, чтобы протестировать подключение',
unitSecond: 'с',
unitTimes: '×',
name: 'Название сервиса',
namePlaceholder: 'Введите название сервиса',
description: 'Описание',
@@ -3738,6 +3766,10 @@ export default {
name: 'WeKnora Cloud',
desc: 'Парсинг документов через WeKnora Cloud',
},
markitdown: {
name: 'MarkItDown',
desc: 'Конвертер Microsoft MarkItDown (PDF/Office/HTML и др.)',
},
},
},
supportedFormats: 'Поддерживаемые форматы'
+32
View File
@@ -751,6 +751,11 @@ export default {
parser: {
title: "解析引擎",
description: "文档解析引擎状态及配置。此处设置优先于服务端环境变量,留空则使用环境变量默认值。",
// Section / label keys for the redesigned drawer
supportedFileTypes: "支持文件类型",
statusSection: "状态信息",
configSection: "配置",
featuresLabel: "识别选项",
loading: "加载中...",
retry: "重试",
noEngineDetected: "未检测到解析引擎,请确认 DocReader 服务正常运行。",
@@ -788,6 +793,12 @@ export default {
storage: {
title: "存储引擎",
description: "配置文档与图片的存储方式。此处设置各引擎参数,知识库中仅选择使用哪个引擎。",
// Section / label keys for the redesigned drawer
basicSection: "基本配置",
modeSection: "部署模式",
credentialsSection: "凭证",
bucketSection: "Bucket",
useSslDesc: "通过 HTTPS 访问 MinIO",
loading: "加载中...",
retry: "重试",
defaultEngine: "默认引擎",
@@ -867,6 +878,10 @@ export default {
title: "网络搜索配置",
description:
"配置网络搜索功能,在回答问题时可以从互联网获取实时信息补充知识库内容",
// Section keys for the redesigned drawer
basicSection: "基本信息",
credentialsSection: "连接配置",
optionsSection: "选项",
// Provider entity management
providersTitle: "搜索引擎配置",
addProvider: "添加搜索引擎",
@@ -935,6 +950,8 @@ export default {
vectorStoreSettings: {
title: "向量数据库引擎",
description: "注册和管理用于知识库搜索的向量数据库实例。",
// Section key for the redesigned drawer
basicSection: "基本信息",
storesTitle: "向量数据库",
addStore: "添加数据库",
editStore: "编辑数据库",
@@ -3491,6 +3508,9 @@ export default {
title: "MCP 服务管理",
description:
"管理外部 MCP (Model Context Protocol) 服务,在 Agent 模式下调用外部工具和资源",
// Drawer subtitle chip
enabled: "已启用",
disabled: "已禁用",
configuredServices: "已配置的服务",
manageAndTest: "管理和测试 MCP 服务连接",
addService: "添加服务",
@@ -3533,6 +3553,7 @@ export default {
source: {
remote: "Remote",
openaiCompatible: "OpenAI兼容",
custom: "自定义",
},
rawModelName: "模型名称",
chat: {
@@ -3639,6 +3660,13 @@ export default {
mcpServiceDialog: {
addTitle: "添加 MCP 服务",
editTitle: "编辑 MCP 服务",
// Section + drawer-only keys
basicSection: "基本信息",
connectionSection: "连接配置",
enableServiceDesc: "关闭后该服务不会被调用",
testAfterSaveHint: "保存后可测试连接",
unitSecond: "秒",
unitTimes: "次",
name: "服务名称",
namePlaceholder: "请输入服务名称",
description: "描述",
@@ -4170,6 +4198,10 @@ export default {
name: "WeKnora Cloud",
desc: "使用 WeKnora Cloud 进行文档解析",
},
markitdown: {
name: "MarkItDown",
desc: "Microsoft MarkItDown 文档转换工具(支持 PDF/Office/HTML 等)",
},
},
},
supportedFormats: "支持格式",
+6 -4
View File
@@ -201,7 +201,8 @@
<t-input
v-model="formData.email"
:placeholder="$t('auth.emailPlaceholder')"
type="email"
type="text"
autocomplete="email"
size="large"
:disabled="loading"
/>
@@ -214,7 +215,7 @@
type="password"
size="large"
:disabled="loading"
@keydown.enter="handleLogin"
@enter="handleLogin"
/>
</t-form-item>
@@ -321,7 +322,8 @@
<t-input
v-model="registerData.email"
:placeholder="$t('auth.emailPlaceholder')"
type="email"
type="text"
autocomplete="email"
size="large"
:disabled="loading"
/>
@@ -344,7 +346,7 @@
type="password"
size="large"
:disabled="loading"
@keydown.enter="handleRegister"
@enter="handleRegister"
/>
</t-form-item>
+19 -59
View File
@@ -99,6 +99,7 @@
:service="currentService"
:mode="dialogMode"
@success="handleDialogSuccess"
@test="handleDrawerTest"
/>
<!-- Test Result Dialog -->
@@ -119,7 +120,6 @@ import {
listMCPServices,
updateMCPService,
deleteMCPService,
testMCPService,
type MCPService,
type MCPTestResult
} from '@/api/mcp-service'
@@ -141,7 +141,6 @@ const testDialogVisible = ref(false)
const testResult = ref<MCPTestResult | null>(null)
const testingServiceName = ref('')
const testingServiceId = ref('')
const testing = ref(false)
// Load MCP services
const loadServices = async () => {
@@ -191,52 +190,6 @@ const handleToggleEnabled = async (service: MCPService) => {
}
}
// Handle test button click
const handleTest = async (service: MCPService) => {
if (!service || !service.id) return
testingServiceName.value = service.name
testingServiceId.value = service.id
testing.value = true
MessagePlugin.info({
content: t('mcpSettings.toasts.testing', { name: service.name }),
duration: 0,
closeBtn: false
})
try {
const result = await testMCPService(service.id)
MessagePlugin.closeAll()
if (!result) {
testResult.value = {
success: false,
message: t('mcpSettings.toasts.noResponse')
}
testDialogVisible.value = true
return
}
testResult.value = result
testDialogVisible.value = true
} catch (error: any) {
MessagePlugin.closeAll()
const errorMessage = error?.response?.data?.error?.message || error?.message || t('mcpSettings.toasts.testFailed')
console.error('Failed to test MCP service:', error)
testResult.value = {
success: false,
message: errorMessage
}
testDialogVisible.value = true
} finally {
testing.value = false
}
}
// Handle delete button click
const handleDelete = (service: MCPService) => {
if (!service || !service.id) return
@@ -256,9 +209,10 @@ const handleDelete = (service: MCPService) => {
})
}
// Get service options for dropdown menu. MCP service mutations and the
// /test endpoint (which probes external infra with stored creds) are all
// Get service options for dropdown menu. MCP service mutations are all
// Admin+ in the backend matrix, so non-Admins see an empty action menu.
// 测试连接已挪到编辑抽屉的 footer,不再放在外层菜单里 — 单一入口减少
// 用户疑惑("为什么有两个测试入口,结果一样吗?")。
const getServiceOptions = (service: MCPService) => {
if (!authStore.hasRole('admin')) {
return []
@@ -268,26 +222,35 @@ const getServiceOptions = (service: MCPService) => {
content: service.enabled ? t('common.off') : t('common.on'),
value: 'toggle',
},
{ content: t('mcpSettings.actions.test'), value: 'test' },
{ content: t('common.edit'), value: 'edit' },
{ content: t('common.delete'), value: 'delete', theme: 'error' as const }
]
}
// Builtin: 仅测试 (Admin+ only as well — testing a builtin still hits
// the same /test endpoint that requires Admin+ role).
// Builtin: 仅编辑(同样 Admin+ only)。内置服务测试也通过抽屉的 footer 触发,
// 不再在外层菜单露出"测试连接"项。
const getBuiltinServiceOptions = () => {
if (!authStore.hasRole('admin')) {
return []
}
return [
{ content: t('mcpSettings.actions.test'), value: 'test' }
{ content: t('common.edit'), value: 'edit' }
]
}
// Handle menu action
// Drawer 内点击"测试连接"后,复用现有的 testResult dialog 展示结果。
// 抽屉只负责调 API + 拿结果,弹窗位置/状态由父组件统一管。
const handleDrawerTest = ({ service, result }: { service: MCPService; result: MCPTestResult }) => {
testingServiceName.value = service.name
testingServiceId.value = service.id
testResult.value = result
testDialogVisible.value = true
}
// Handle menu action. 'test' has been removed from the menu — testing now
// lives only in the editor drawer. We keep the switch's case list narrow
// so a stray 'test' from somewhere else falls through harmlessly.
const handleMenuAction = (data: { value: string }, service: MCPService) => {
if (testing.value) return
switch (data.value) {
case 'toggle':
// Flip the local model and reuse the toggle path so the API call,
@@ -295,9 +258,6 @@ const handleMenuAction = (data: { value: string }, service: MCPService) => {
service.enabled = !service.enabled
handleToggleEnabled(service)
break
case 'test':
handleTest(service)
break
case 'edit':
handleEdit(service)
break
+270 -68
View File
@@ -42,9 +42,9 @@
<div v-if="filteredModels.length > 0" class="model-grid">
<!--
Model card (this page only). 我们刻意不复用 SettingCard:
模型卡需要左侧类型徽章 + 多级元信息,而 SettingCard 还在 Mcp /
WebSearch 页用,加 prefix 槽给单一消费者属于过度抽象。
Model card. 我们刻意不复用 SettingCard:模型卡需要左侧类型徽章 + 多
级元信息(chip 行 + monospace 原名 + baseUrl),SettingCard 还在
Mcp / WebSearch 页用,加 prefix 槽属于过度抽象。
-->
<div
v-for="model in filteredModels"
@@ -56,10 +56,22 @@
<t-icon :name="typeIcon(model._modelType)" size="18px" />
</div>
<div class="model-card__body">
<!--
Title row. Display name primary; on hover the lock (builtin) and
ellipsis menu fade in from the right. The lock badge is muted by
default since most cards in a typical install ARE built-in —
making it loud everywhere just produces visual noise. User-added
cards stand out by NOT having a lock.
-->
<div class="model-card__header">
<h3 class="model-card__title" :title="model.name">{{ modelDisplayName(model) }}</h3>
<span v-if="model.isBuiltin" class="model-card__pill">
{{ $t('modelSettings.builtinTag') }}
<h3 class="model-card__title" :title="modelDisplayName(model)">{{ modelDisplayName(model) }}</h3>
<span
v-if="model.isBuiltin"
class="model-card__lock"
:title="$t('modelSettings.builtinTag')"
:aria-label="$t('modelSettings.builtinTag')"
>
<t-icon name="lock-on" />
</span>
<t-dropdown
v-if="getModelOptions(model._modelType, model).length > 0"
@@ -74,25 +86,55 @@
</t-button>
</t-dropdown>
</div>
<div class="model-card__subtitle">
<span class="model-card__type">{{ typeLabel(model._modelType) }}</span>
<span class="model-card__sep">·</span>
<span class="model-card__source">
{{ model.source === 'local' ? 'Ollama' : sourceLabel(model._modelType) }}
<!--
Compact identity row. Only rendered when there's actually
something to show — most built-in models have no displayName
AND no baseUrl, so an "always render" approach left them with
either a blank line or a noisy pseudo-URL. CSS grid's default
row stretching keeps cards in the same row aligned, so we
don't need to fake content for visual symmetry.
When both raw name and URL are present we show ONLY the URL
here, because cramming both into one ellipsizing line — as
seen in the screenshot — produced "deepseek-… · https://…tencen…"
with both ends truncated and neither readable. The raw name
is already accessible via the title attribute on the card.
-->
<div
v-if="identityVisible(model)"
class="model-card__identity"
:title="identityTooltip(model)"
>
<!-- Show URL by preference (it's the more diagnostic of the
two for "is this model wired up correctly"); fall back to
the raw name when there's no URL (display-name-only case). -->
<span class="model-card__identity-text">{{ identityText(model) }}</span>
</div>
<!--
Meta chips, single row. We deliberately keep this line to a
FIXED set of facts so every card renders to the same height,
no matter what optional fields are filled out. Order: type →
vendor → optional dim → optional vision flag. Type chip is
text-only (the 36×36 badge on the left already shows the icon).
-->
<div class="model-card__meta">
<span class="model-card__chip model-card__chip--type">
{{ typeLabel(model._modelType) }}
</span>
<span class="model-card__chip">
{{ vendorLabel(model) }}
</span>
<span v-if="model._modelType === 'embedding' && model.dimension" class="model-card__chip">
{{ model.dimension }} dim
</span>
<span v-if="model._modelType === 'chat' && model.supportsVision"
class="model-card__chip model-card__chip--icon-only"
:title="$t('model.editor.supportsVisionLabel')"
:aria-label="$t('model.editor.supportsVisionLabel')">
<t-icon name="image" />
</span>
<template v-if="model._modelType === 'embedding' && model.dimension">
<span class="model-card__sep">·</span>
<span>{{ $t('model.editor.dimensionLabel') }} {{ model.dimension }}</span>
</template>
</div>
<div v-if="model.displayName" class="model-card__raw-name" :title="model.name">
{{ $t('modelSettings.rawModelName') }}: {{ model.name }}
</div>
<div v-if="model.baseUrl" class="model-card__url" :title="model.baseUrl">
{{ model.baseUrl }}
</div>
<div v-else-if="model.source === 'local'" class="model-card__url model-card__url--muted">
Ollama local
</div>
</div>
</div>
@@ -130,7 +172,7 @@ import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import { listModels, createModel, updateModel as updateModelAPI, deleteModel as deleteModelAPI, type ModelConfig } from '@/api/model'
import { useAuthStore } from '@/stores/auth'
const { t } = useI18n()
const { t, te } = useI18n()
const authStore = useAuthStore()
const confirmDelete = useConfirmDelete()
@@ -232,6 +274,88 @@ const sourceLabel = (type: ModelType) => {
return t('modelSettings.source.remote')
}
// Maps a backend `provider` id (e.g. "openai", "aliyun", "weknoracloud")
// to its localized short label. Reuses the same i18n keys the editor's
// provider dropdown uses, so the model card and the editor stay in sync
// when a provider is renamed. Falls back to '' when the backend didn't
// store a provider — caller falls back to sourceLabel().
const providerLabel = (model: any): string => {
const id = model.provider
if (!id) return ''
const key = `model.editor.providers.${id}.label`
return te(key) ? t(key) : id
}
// What the vendor chip on a card shows. Keeps the chip text uniformly
// short so cards line up:
// local → "Ollama"
// remote → provider's localized short name (e.g. "腾讯云 LKEAP",
// "阿里云 DashScope"). For the catch-all "generic" provider
// we render a single short word ("自定义" / "Custom") — the
// editor dropdown's longer "自定义 (OpenAI兼容接口)" label
// blows out the card chip row, and the "OpenAI 兼容" framing
// isn't meaningful to most end users (they didn't pick "I
// want OpenAI compatibility", they just pasted a base URL).
const vendorLabel = (model: any): string => {
if (model.source === 'local') return 'Ollama'
if (model.provider === 'generic') {
return t('modelSettings.source.custom')
}
return providerLabel(model) || sourceLabel(model._modelType)
}
// Hover tooltip for the whole card — shows the long-form details we
// removed from the visible card body so they're still one mouseover
// away. baseUrl is the most useful for debugging "why is this model
// failing" scenarios.
const cardTooltip = (model: any): string => {
const lines: string[] = []
if (model.displayName && model.displayName !== model.name) {
lines.push(`${t('modelSettings.rawModelName')}: ${model.name}`)
}
if (model.baseUrl) {
lines.push(model.baseUrl)
} else if (model.source === 'local') {
lines.push('Ollama (localhost)')
}
return lines.join('\n')
}
// Whether the raw model identifier is worth showing on the card. We hide
// it when the user did NOT set a display name, because then the title is
// already the raw name and printing it again is just noise.
const rawNameVisible = (model: any): boolean => {
const displayName = typeof model.displayName === 'string' ? model.displayName.trim() : ''
return Boolean(displayName) && displayName !== model.name
}
// What goes in the URL slot of the identity row. Local models intentionally
// return '' here — "ollama://localhost" is just noise on Ollama-only built-in
// cards. Only remote models with an explicit base URL get this row.
const urlText = (model: any): string => {
return model.baseUrl || ''
}
// Single-line text shown in the identity row. Picks the more useful of
// the two (URL > raw name) — never crams both into one ellipsizing line
// because that produces double-end truncation that nobody can read.
const identityText = (model: any): string => {
return urlText(model) || (rawNameVisible(model) ? model.name : '')
}
// Whether the identity row should render at all.
const identityVisible = (model: any): boolean => identityText(model).length > 0
// Identity-row tooltip — exposes BOTH name and URL when the user hovers,
// so the diagnostic info we hid from the visible row is still one mouse
// move away.
const identityTooltip = (model: any): string => {
const parts: string[] = []
if (rawNameVisible(model)) parts.push(model.name)
if (urlText(model)) parts.push(urlText(model))
return parts.join('\n')
}
const modelDisplayName = (model: any) => {
const displayName = typeof model.displayName === 'string' ? model.displayName.trim() : ''
return displayName || model.name
@@ -612,12 +736,13 @@ onMounted(() => {
gap: 12px;
}
// 模型卡片 —— 左侧类型徽章 + 标题 / 副标题 / baseUrl 三段式
// 模型卡片 —— 左侧类型徽章 + 标题 / identity / 元 chip 行(固定三行)
.model-card {
position: relative;
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 14px 14px 12px;
padding: 12px 14px;
border: 1px solid var(--td-component-stroke);
border-radius: 10px;
background: var(--td-bg-color-container);
@@ -632,10 +757,6 @@ onMounted(() => {
&--builtin {
background: var(--td-bg-color-secondarycontainer);
.model-card__title {
color: var(--td-text-color-secondary);
}
&:hover {
box-shadow: none;
border-color: var(--td-component-stroke);
@@ -688,6 +809,7 @@ onMounted(() => {
min-width: 0;
display: flex;
flex-direction: column;
justify-content: center;
gap: 4px;
}
@@ -711,15 +833,105 @@ onMounted(() => {
white-space: nowrap;
}
.model-card__pill {
/*
Generic chip used for: built-in tag, type chip, source chip, dimension,
vision flag. Same shape across all so the row reads as one consistent
rhythm of pills. Variants tweak color only.
*/
.model-card__chip {
flex-shrink: 0;
padding: 1px 6px;
display: inline-flex;
align-items: center;
gap: 3px;
padding: 1px 7px 1px 6px;
height: 20px;
font-size: 11px;
font-weight: 500;
line-height: 16px;
color: var(--td-warning-color-7, #B85C00);
background: var(--td-warning-color-1, #FEF3E6);
border-radius: 3px;
line-height: 18px;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-component);
border-radius: 4px;
white-space: nowrap;
.t-icon {
font-size: 12px;
flex-shrink: 0;
}
}
/*
Built-in lock indicator. Most cards in a typical install ARE built-in,
so loud styling everywhere becomes noise — instead the lock is muted
and small by default, and lights up on hover. The signal that matters
to users is "which models did I add" → user-added cards stand out by
the absence of the lock.
*/
.model-card__lock {
flex-shrink: 0;
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
color: var(--td-text-color-placeholder);
opacity: 0.6;
transition: color 0.15s ease, opacity 0.15s ease;
.t-icon {
font-size: 13px;
}
}
.model-card:hover .model-card__lock {
opacity: 1;
color: var(--td-text-color-secondary);
}
/*
Icon-only chip variant. Drops horizontal padding to a tight square so the
chip reads as a status badge (vision flag) rather than a text pill that
happens to start with an icon.
*/
.model-card__chip--icon-only {
padding: 0;
width: 20px;
justify-content: center;
.t-icon {
font-size: 12px;
}
}
/* Type chip in the meta row — slightly emphasized, picks up the type's
accent color so it links to the left badge. */
.model-card__chip--type {
color: var(--td-text-color-primary);
font-weight: 500;
}
.model-card--chat .model-card__chip--type {
color: #0052D9;
background: rgba(0, 82, 217, 0.08);
}
.model-card--embedding .model-card__chip--type {
color: #6235BB;
background: rgba(98, 53, 187, 0.08);
}
.model-card--rerank .model-card__chip--type {
color: #B85C00;
background: rgba(184, 92, 0, 0.08);
}
.model-card--vllm .model-card__chip--type {
color: #C93E3E;
background: rgba(201, 62, 62, 0.08);
}
.model-card--asr .model-card__chip--type {
color: #118053;
background: rgba(17, 128, 83, 0.08);
}
.model-card__more {
@@ -742,50 +954,40 @@ onMounted(() => {
opacity: 1;
}
.model-card__subtitle {
.model-card__meta {
display: flex;
align-items: center;
flex-wrap: wrap;
flex-wrap: nowrap;
gap: 4px;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-secondary);
min-width: 0;
}
.model-card__raw-name {
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.4;
color: var(--td-text-color-placeholder);
// Truncate at the row level rather than within each chip — chips clip
// off-screen if the card narrows below the chip set's natural width
// (rare at 320px+ minmax but possible if grid recomputes).
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.model-card__type {
font-weight: 500;
color: var(--td-text-color-secondary);
}
.model-card__sep {
color: var(--td-text-color-placeholder);
}
.model-card__url {
/*
Compact identity row: monospace one-liner showing whichever of
baseUrl / raw name is more useful (URL preferred). Conditionally
rendered — empty cards (most built-in ones) skip this row entirely
and grid auto-sizing handles the height.
*/
.model-card__identity {
display: flex;
align-items: center;
min-width: 0;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.4;
color: var(--td-text-color-placeholder);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
}
.model-card__url--muted {
font-family: inherit;
font-style: italic;
.model-card__identity-text {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.empty-state {
@@ -92,81 +92,140 @@
</div>
</template>
<!-- 配置抽屉 -->
<t-drawer
<!-- 配置抽屉 — 用 SettingDrawer 包装,保持与 ModelEditorDialog 同款视觉/交互 -->
<SettingDrawer
v-model:visible="drawerVisible"
:header="drawerTitle"
size="500px"
:title="drawerTitle"
:class="currentEngine ? `parser-engine-drawer parser-engine-drawer--${currentEngine.Name}` : 'parser-engine-drawer'"
:hide-footer="!authStore.hasRole('admin') && !needsTestButton"
:confirm-loading="saving"
@confirm="onSave"
@cancel="drawerVisible = false"
>
<div v-if="currentEngine" class="drawer-content">
<div class="engine-info-block">
<p class="engine-desc">{{ getEngineDisplayDesc(currentEngine.Name, currentEngine.Description) }}
<a
v-if="engineDocLink(currentEngine.Name)"
:href="engineDocLink(currentEngine.Name)"
target="_blank"
rel="noopener noreferrer"
class="doc-link"
>
{{ engineDocLabel(currentEngine.Name) }}
<t-icon name="link" class="link-icon" />
</a>
</p>
</div>
<!--
Header icon — 与列表卡片同款 monogram 徽章:首字母 + per-engine 配色,
通过 .parser-engine-drawer--{name} .setting-drawer__header-icon 在
非 scoped 块里覆盖背景与文字色。Parser 引擎没有真实 logo,所以这
里只渲染字母;存储引擎那边走的是 logo 图片/mask,pattern 一致。
-->
<template v-if="currentEngine" #headerIcon>
<span class="header-icon__text">{{ engineInitial(currentEngine.Name) }}</span>
</template>
<!--
Subtitle slot: 引擎描述 + 内联文档链接。我们把"参考资料"从一个
独立 section 收回到头部副标题里 — 一个外链不值得占一整个 section。
-->
<template v-if="currentEngine" #subtitle>
<span>{{ getEngineDisplayDesc(currentEngine.Name, currentEngine.Description) }}</span>
<a
v-if="engineDocLink(currentEngine.Name)"
:href="engineDocLink(currentEngine.Name)"
target="_blank"
rel="noopener noreferrer"
class="doc-link doc-link--inline"
>
{{ engineDocLabel(currentEngine.Name) }}
<t-icon name="link" class="link-icon" />
</a>
</template>
<!--
Footer-left slot: 测试连接按钮 + 状态文案 — 主操作栏沿底边对齐,
与 ModelEditorDialog 远程模型抽屉保持一致。仅在引擎有可校验的
配置/状态时才挂载。
-->
<template v-if="needsTestButton" #footer-left>
<t-button variant="outline" :loading="checking" @click="onCheck">
<template #icon>
<t-icon v-if="!checking && saveSuccess && checkMessage" name="check-circle-filled"
class="status-icon available" />
<t-icon v-else-if="!checking && checkMessage && !saveSuccess" name="close-circle-filled"
class="status-icon unavailable" />
</template>
{{ checking ? $t('settings.parser.checking', $t('settings.parser.testConnection')) : $t('settings.parser.testConnection') }}
</t-button>
<span v-if="checkMessage" :class="['footer-test-message', saveSuccess ? 'success' : 'error']" :title="checkMessage">
{{ checkMessage }}
</span>
</template>
<!-- builtin: DocReader 连接信息 -->
<div v-if="currentEngine.Name === 'builtin'" class="docreader-inline">
<div class="status-line">
<t-tag v-if="connected" theme="success" variant="light" size="small">{{ $t('settings.parser.connected') }}</t-tag>
<t-tag v-else theme="danger" variant="light" size="small">{{ $t('settings.parser.disconnected') }}</t-tag>
<t-tag theme="default" variant="light" size="small">{{ docreaderTransport === 'http' ? 'HTTP' : 'gRPC' }}</t-tag>
<span v-if="docreaderAddrEnv" class="env-hint">{{ $t('settings.parser.currentAddr') }}: {{ docreaderAddrEnv }}</span>
<div v-if="currentEngine">
<!--
Section 1 — 支持文件类型。放在内容开头作为引擎"能干什么"的
一目了然概览,对所有引擎都有意义;与状态/配置区分开。
-->
<section
v-if="currentEngine.FileTypes && currentEngine.FileTypes.length"
class="setting-drawer__section"
>
<h4 class="setting-drawer__section-title">{{ $t('settings.parser.supportedFileTypes', '支持文件类型') }}</h4>
<div class="file-types">
<span v-for="ft in currentEngine.FileTypes" :key="ft" class="file-type-chip">
{{ ft }}
</span>
</div>
<p class="docreader-desc">
{{ $t('settings.parser.envVarHint') }}
</p>
</div>
</section>
<!-- weknoracloud: 凭证状态 -->
<template v-if="currentEngine.Name === 'weknoracloud'">
<div v-if="wkcState === 'configured'" class="wkc-status wkc-status--ok">
<t-icon name="check-circle" style="font-size: 15px; color: var(--td-success-color); flex-shrink: 0;" />
<span>{{ $t('settings.weknoraCloud.credentialConfigured') }}</span>
</div>
<div v-else-if="wkcState === 'loading'" class="wkc-status">
<t-loading size="small" />
<span>{{ $t('settings.weknoraCloud.checkingStatus') }}</span>
</div>
<div v-else class="wkc-status wkc-status--warn">
<t-icon name="error-circle" style="font-size: 15px; color: #f97316; flex-shrink: 0;" />
<div style="flex: 1;">
<span v-if="wkcState === 'expired'">{{ $t('settings.weknoraCloud.credentialExpired') }}</span>
<span v-else>{{ $t('settings.weknoraCloud.unconfigured') }}</span>
<div style="margin-top: 6px;">
<t-button
variant="text"
size="small"
theme="primary"
@click="goToWkcSettings"
style="padding: 0; height: auto;"
>{{ $t('settings.weknoraCloud.goToSettings') }}</t-button>
</div>
<!--
Section 2 — 状态信息(DocReader 连接 / WeKnoraCloud 凭证)
只有有内容时才渲染,避免空 section 空底部分隔线。
-->
<section
v-if="currentEngine.Name === 'builtin' || currentEngine.Name === 'weknoracloud'"
class="setting-drawer__section"
>
<h4 class="setting-drawer__section-title">{{ $t('settings.parser.statusSection', '状态信息') }}</h4>
<!-- builtin: DocReader 连接信息 -->
<div v-if="currentEngine.Name === 'builtin'" class="docreader-block">
<div class="status-line">
<t-tag v-if="connected" theme="success" variant="light" size="small">
{{ $t('settings.parser.connected') }}
</t-tag>
<t-tag v-else theme="danger" variant="light" size="small">
{{ $t('settings.parser.disconnected') }}
</t-tag>
<t-tag theme="default" variant="light" size="small">
{{ docreaderTransport === 'http' ? 'HTTP' : 'gRPC' }}
</t-tag>
<span v-if="docreaderAddrEnv" class="env-hint">
{{ $t('settings.parser.currentAddr') }}: {{ docreaderAddrEnv }}
</span>
</div>
<p class="form-desc">{{ $t('settings.parser.envVarHint') }}</p>
</div>
</template>
<div v-if="currentEngine.FileTypes && currentEngine.FileTypes.length" class="file-types">
<t-tag
v-for="ft in currentEngine.FileTypes"
:key="ft"
size="small"
variant="light"
theme="default"
>{{ ft }}</t-tag>
</div>
<!--
weknoracloud: 凭证状态 — 不再用大块卡片。已配置 / 加载中 / 未配置
统一用 inline alert:图标 + 一行文案 + 行尾跳转 link,体量
匹配"一条信息"该有的样子。
-->
<template v-if="currentEngine.Name === 'weknoracloud'">
<div v-if="wkcState === 'configured'" class="inline-alert inline-alert--ok">
<t-icon name="check-circle-filled" class="inline-alert__icon" />
<span>{{ $t('settings.weknoraCloud.credentialConfigured') }}</span>
</div>
<div v-else-if="wkcState === 'loading'" class="inline-alert">
<t-icon name="loading" class="inline-alert__icon spinning" />
<span>{{ $t('settings.weknoraCloud.checkingStatus') }}</span>
</div>
<div v-else class="inline-alert inline-alert--warn">
<t-icon name="error-circle-filled" class="inline-alert__icon" />
<span class="inline-alert__text">
<span v-if="wkcState === 'expired'">{{ $t('settings.weknoraCloud.credentialExpired') }}</span>
<span v-else>{{ $t('settings.weknoraCloud.unconfigured') }}</span>
</span>
<a class="inline-alert__action" @click="goToWkcSettings">
{{ $t('settings.weknoraCloud.goToSettings') }}
<t-icon name="chevron-right" />
</a>
</div>
</template>
</section>
<!-- Section 3 — mineru 自建配置 -->
<section v-if="currentEngine.Name === 'mineru'" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.parser.configSection', '配置') }}</h4>
<!-- mineru 自建配置 -->
<div v-if="currentEngine.Name === 'mineru'" class="engine-form">
<div class="form-item">
<label class="form-label">{{ t('settings.parser.selfHostedEndpoint') }}</label>
<t-input
@@ -192,14 +251,17 @@
:placeholder="$t('settings.parser.vlmServerUrlPlaceholder')"
clearable
/>
<p class="form-hint">{{ $t('settings.parser.vlmServerUrlHint') }}</p>
<p class="form-desc">{{ $t('settings.parser.vlmServerUrlHint') }}</p>
</div>
<div class="form-toggles">
<t-checkbox v-model="config.mineru_enable_formula">{{ $t('settings.parser.formulaRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_enable_table">{{ $t('settings.parser.tableRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_enable_ocr">OCR</t-checkbox>
<div class="form-item">
<label class="form-label">{{ $t('settings.parser.featuresLabel', '识别选项') }}</label>
<div class="form-toggles">
<t-checkbox v-model="config.mineru_enable_formula">{{ $t('settings.parser.formulaRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_enable_table">{{ $t('settings.parser.tableRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_enable_ocr">OCR</t-checkbox>
</div>
</div>
<div class="form-item" style="margin-top: 16px;">
<div class="form-item">
<label class="form-label">{{ t('settings.parser.language') }}</label>
<t-input
v-model="config.mineru_language"
@@ -207,18 +269,22 @@
clearable
/>
</div>
</div>
</section>
<!-- Section 3 — mineru_cloud 云 API 配置 -->
<section v-if="currentEngine.Name === 'mineru_cloud'" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ $t('settings.parser.configSection', '配置') }}</h4>
<!-- mineru_cloud 云 API 配置 -->
<div v-if="currentEngine.Name === 'mineru_cloud'" class="engine-form">
<div class="form-item">
<label class="form-label">API Key</label>
<label class="form-label required">API Key</label>
<t-input
v-model="config.mineru_api_key"
type="password"
:placeholder="$t('settings.parser.mineruCloudApiKeyPlaceholder')"
clearable
/>
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">Model Version</label>
@@ -228,12 +294,15 @@
<t-option value="MinerU-HTML" :label="$t('settings.parser.mineruHtmlLabel')" />
</t-select>
</div>
<div class="form-toggles">
<t-checkbox v-model="config.mineru_cloud_enable_formula">{{ $t('settings.parser.formulaRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_cloud_enable_table">{{ $t('settings.parser.tableRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_cloud_enable_ocr">OCR</t-checkbox>
<div class="form-item">
<label class="form-label">{{ $t('settings.parser.featuresLabel', '识别选项') }}</label>
<div class="form-toggles">
<t-checkbox v-model="config.mineru_cloud_enable_formula">{{ $t('settings.parser.formulaRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_cloud_enable_table">{{ $t('settings.parser.tableRecognition') }}</t-checkbox>
<t-checkbox v-model="config.mineru_cloud_enable_ocr">OCR</t-checkbox>
</div>
</div>
<div class="form-item" style="margin-top: 16px;">
<div class="form-item">
<label class="form-label">{{ t('settings.parser.language') }}</label>
<t-input
v-model="config.mineru_cloud_language"
@@ -241,27 +310,9 @@
clearable
/>
</div>
</div>
<div class="form-item" v-if="currentEngine && (hasConfigFields(currentEngine.Name) || currentEngine.Name === 'builtin')">
<label class="form-label">{{ $t('settings.parser.testConnection', '测试连接') }}</label>
<div class="api-test-section">
<t-button variant="outline" :loading="checking" @click="onCheck">
{{ $t('settings.parser.testConnection', '测试连接') }}
</t-button>
<span v-if="checkMessage || saveMessage" :class="['test-message', saveSuccess && !checkMessage ? 'success' : (checkMessage ? 'hint' : 'error')]">
{{ checkMessage || saveMessage }}
</span>
</div>
</div>
</section>
</div>
<template #footer>
<div class="drawer-footer-actions">
<t-button theme="default" variant="outline" @click="drawerVisible = false">{{ $t('common.cancel') }}</t-button>
<t-button v-if="authStore.hasRole('admin')" theme="primary" :loading="saving" @click="onSave">{{ $t('common.save') }}</t-button>
</div>
</template>
</t-drawer>
</SettingDrawer>
</div>
</template>
@@ -270,6 +321,7 @@ import { ref, computed, onMounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import {
getParserEngines,
getParserEngineConfig,
@@ -335,6 +387,18 @@ const drawerTitle = computed(() => {
return currentEngine.value ? getEngineDisplayName(currentEngine.value.Name) : ''
})
// SettingDrawer 头部图标走 #headerIcon 槽(首字母 monogram + per-engine
// 配色,与列表卡片完全一致),不再需要 t-icon name 兜底。
// Whether the footer test-connection button should appear. Engines without
// configurable fields and that aren't the builtin DocReader (whose connection
// status is the whole point of the drawer) skip the test affordance — for
// e.g. simple/markitdown there's nothing to validate beyond presence.
const needsTestButton = computed(() => {
if (!currentEngine.value) return false
return hasConfigFields(currentEngine.value.Name) || currentEngine.value.Name === 'builtin'
})
/** 固定展示顺序,未列出的引擎排在末尾按名称排序 */
const ENGINE_ORDER: Record<string, number> = {
builtin: 0,
@@ -755,69 +819,71 @@ onMounted(loadAll)
overflow: hidden;
}
// ---- 抽屉内容 ----
.drawer-content {
display: flex;
flex-direction: column;
gap: 20px;
// ---- 抽屉内容 — 与 ModelEditorDialog 同款约定 ----
// .form-item / .form-label / .form-desc / .weknoracloud-hint / .api-test
// 参照 frontend/src/components/ModelEditorDialog.vue 的命名与字号/间距
.form-item {
margin-bottom: 0;
}
.engine-info-block {
.engine-desc {
font-size: 13px;
color: var(--td-text-color-secondary);
margin: 0 0 8px 0;
line-height: 1.5;
.form-label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
line-height: 1.4;
// 与 ModelEditorDialog 一致:必填星号前置
&.required::before {
content: '*';
color: var(--td-error-color);
margin-right: 4px;
font-weight: 500;
line-height: 1;
}
}
// 输入框样式
.form-desc {
margin: 4px 0 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-placeholder);
}
// 输入框统一字号
:deep(.t-input),
:deep(.t-select) {
:deep(.t-select),
:deep(.t-textarea),
:deep(.t-input-number) {
width: 100%;
font-size: 13px;
}
.t-input__inner,
.t-input__wrap,
input {
:deep(.t-checkbox) {
font-size: 13px;
.t-checkbox__label {
font-size: 13px;
border-radius: 6px;
border-color: var(--td-component-stroke);
transition: all 0.15s ease;
}
&:hover .t-input__inner,
&:hover .t-input__wrap,
&:hover input {
border-color: var(--td-component-stroke);
}
&.t-is-focused .t-input__inner,
&.t-is-focused .t-input__wrap,
&.t-is-focused input {
border-color: var(--td-brand-color);
box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.1);
color: var(--td-text-color-primary);
}
}
// ---- DocReader 连接信息 ----
.docreader-inline {
padding: 12px 16px;
background: var(--td-bg-color-secondarycontainer);
// ---- DocReader 连接信息(builtin 引擎) ----
.docreader-block {
display: flex;
flex-direction: column;
gap: 8px;
padding: 12px 14px;
background: var(--td-bg-color-container-hover);
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
.status-line {
margin-bottom: 8px;
.form-desc {
margin-top: 0;
}
}
.docreader-desc {
margin: 0;
font-size: 12px;
color: var(--td-text-color-placeholder);
line-height: 1.6;
}
.status-line {
display: flex;
align-items: center;
@@ -828,152 +894,200 @@ onMounted(loadAll)
.env-hint {
font-size: 12px;
color: var(--td-text-color-placeholder);
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
}
// ---- 文件类型标签 ----
// ---- 文件类型 chip ----
.file-types {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
// ---- 配置表单 ----
.engine-form {
display: flex;
flex-direction: column;
gap: 0;
}
.form-item {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.form-label {
display: block;
margin-bottom: 8px;
font-size: 14px;
.file-type-chip {
display: inline-flex;
align-items: center;
height: 22px;
padding: 0 8px;
font-size: 11px;
font-weight: 500;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-component);
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
letter-spacing: 0.02em;
}
// ---- Inline alert(替代之前的 .weknoracloud-hint 卡片) ----
// 一行内表达 "状态信号 + 一句话 + 跳转 link",无外框/无 3px 左边,
// 视觉重量与一行文字相当,section 内不会再被一个独立卡片打断。
.inline-alert {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
line-height: 1.5;
color: var(--td-text-color-secondary);
flex-wrap: wrap;
}
.inline-alert__icon {
font-size: 15px;
flex-shrink: 0;
color: var(--td-text-color-placeholder);
}
.inline-alert--ok .inline-alert__icon {
color: var(--td-success-color);
}
.inline-alert--warn {
color: var(--td-text-color-primary);
&.required::after {
content: '*';
color: var(--td-error-color);
margin-left: 4px;
font-weight: 600;
.inline-alert__icon {
color: var(--td-warning-color, #f97316);
}
}
.form-hint {
margin: 4px 0 0 0;
font-size: 12px;
color: var(--td-text-color-placeholder);
line-height: 1.5;
.inline-alert__text {
flex: 1 1 auto;
min-width: 0;
}
// 行尾 link:跟普通 doc-link 一致的主题色,但更紧凑,行内排版
.inline-alert__action {
display: inline-flex;
align-items: center;
gap: 2px;
font-size: 13px;
font-weight: 500;
color: var(--td-brand-color);
cursor: pointer;
white-space: nowrap;
transition: color 0.15s ease;
&:hover {
color: var(--td-brand-color-active);
}
.t-icon {
font-size: 14px;
}
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.spinning {
animation: spin 1s linear infinite;
}
// ---- 表单切换组(公式/表格/OCR) ----
.form-toggles {
display: flex;
flex-wrap: wrap;
gap: 16px;
margin-bottom: 20px;
padding: 8px 0 0;
}
// ---- WeKnoraCloud 凭证状态 ----
.wkc-status {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 12px 16px;
border-radius: 6px;
font-size: 13px;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
// ---- footer-left 测试连接消息(与 ModelEditorDialog 同款) ----
.footer-test-message {
font-size: 12px;
line-height: 1.4;
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
&--ok {
background: var(--td-success-color-light);
border: 1px solid var(--td-success-color-focus);
color: var(--td-success-color);
&.success {
color: var(--td-brand-color-active);
}
&--warn {
background: #fff7ed;
border: 1px solid #fed7aa;
border-left: 3px solid #f97316;
&.error {
color: var(--td-error-color);
}
}
.api-test-section {
display: flex;
.status-icon {
font-size: 16px;
flex-shrink: 0;
&.available {
color: var(--td-brand-color);
}
&.unavailable {
color: var(--td-error-color);
}
}
// ---- 文档外链 ----
.doc-link {
display: inline-flex;
align-items: center;
gap: 12px;
gap: 4px;
font-size: 13px;
font-weight: 500;
color: var(--td-brand-color);
text-decoration: none;
transition: color 0.15s ease;
.test-message {
font-size: 13px;
line-height: 1.5;
flex: 1;
&.success {
color: var(--td-brand-color-active);
}
&.error {
color: var(--td-error-color);
}
&.hint {
color: var(--td-text-color-secondary);
}
&:hover {
color: var(--td-brand-color-active);
}
:deep(.t-button) {
min-width: 88px;
height: 32px;
font-size: 13px;
border-radius: 6px;
flex-shrink: 0;
.link-icon {
font-size: 14px;
}
.status-icon {
font-size: 16px;
flex-shrink: 0;
// 副标题里的 inline 文档链接:与描述文字平铺一行,体量等同小字
&--inline {
margin-left: 6px;
font-size: 12px;
font-weight: 500;
vertical-align: baseline;
&.available {
color: var(--td-brand-color);
}
&.unavailable {
color: var(--td-error-color);
.link-icon {
font-size: 12px;
}
}
}
.drawer-footer-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
width: 100%;
:deep(.t-button) {
min-width: 80px;
height: 36px;
font-weight: 500;
font-size: 14px;
border-radius: 6px;
transition: all 0.15s ease;
&.t-button--variant-outline {
color: var(--td-text-color-secondary);
border-color: var(--td-component-stroke);
&:hover {
border-color: var(--td-brand-color);
color: var(--td-brand-color);
background: rgba(7, 192, 95, 0.04);
}
}
}
// ---- Header 图标的首字母 monogram(per-engine 配色见非 scoped 块)----
.header-icon__text {
font-size: 15px;
font-weight: 600;
letter-spacing: 0.02em;
}
</style>
<!--
Non-scoped block: per-engine header-icon coloring. Same approach as
StorageEngineSettings — keep these rules global so they always apply
regardless of whether the drawer panel inherits the parent's scoped
data attributes. Each rule mirrors the matching .engine-card--{name}
.engine-card__badge from the scoped block above.
-->
<style lang="less">
.parser-engine-drawer--builtin .setting-drawer__header-icon,
.parser-engine-drawer--weknoracloud .setting-drawer__header-icon {
background: rgba(7, 192, 95, 0.12);
color: #07C05F;
}
.parser-engine-drawer--simple .setting-drawer__header-icon {
background: rgba(70, 70, 70, 0.1);
color: #464646;
}
.parser-engine-drawer--markitdown .setting-drawer__header-icon {
background: rgba(0, 137, 255, 0.12);
color: #0089FF;
}
.parser-engine-drawer--mineru .setting-drawer__header-icon,
.parser-engine-drawer--mineru_cloud .setting-drawer__header-icon {
background: rgba(98, 53, 187, 0.12);
color: #6235BB;
}
</style>
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -176,8 +176,9 @@
<div class="setting-control">
<div class="usage-control">
<span class="usage-text">{{ getUsagePercentage() }}%</span>
<!-- t-progress: theme = 形态(line/plump/circle);颜色用 status -->
<t-progress :percentage="getUsagePercentage()" :show-info="false" size="small"
:theme="getUsagePercentage() > 80 ? 'warning' : 'success'" style="flex: 1;" />
:status="getUsagePercentage() > 80 ? 'warning' : 'success'" style="flex: 1;" />
</div>
</div>
</div>
@@ -54,15 +54,12 @@
<span v-if="store.source === 'env'" class="store-card__pill">
{{ t('vectorStoreSettings.envTag') }}
</span>
<!-- 测试连接收进三点菜单,结果走 MessagePlugin toast;测试中卡片标题
右侧用一个小 spinner 给出进度反馈,避免菜单已经关掉后没有可见状态。 -->
<t-loading
v-if="testingId === store.id"
size="14px"
class="store-card__loading"
/>
<!--
测试连接已挪到编辑抽屉的 footer,外层菜单不再有"测试"入口。
env 来源(.env 写入)也不需要 dropdown — 没有可执行的动作。
-->
<t-dropdown
v-if="authStore.hasRole('admin')"
v-if="authStore.hasRole('admin') && storeActionsFor(store).length > 0"
:options="storeActionsFor(store)"
placement="bottom-right"
attach="body"
@@ -93,22 +90,87 @@
</div>
</template>
<!-- Add/Edit Dialog -->
<t-dialog
<!-- Add/Edit Drawer — 与 ModelEditorDialog/Storage/Parser/WebSearch 同款 -->
<SettingDrawer
v-model:visible="showDialog"
:header="editingStore ? t('vectorStoreSettings.editStore') : t('vectorStoreSettings.addStore')"
width="580px"
placement="center"
:footer="false"
destroy-on-close
:title="editingStore ? t('vectorStoreSettings.editStore') : t('vectorStoreSettings.addStore')"
:class="drawerClass"
:confirm-loading="saving"
@confirm="onDrawerConfirm"
@cancel="showDialog = false"
>
<div class="dialog-form-container">
<!-- Edit Mode: immutable info banner + readonly fields -->
<template v-if="editingStore">
<div class="immutable-notice">
<t-icon name="info-circle" size="14px" />
<span>{{ t('vectorStoreSettings.immutableNotice') }}</span>
<!--
Header icon — 与列表 .store-card__badge 同款 logo/mono/fallback。
per-engine 配色由非 scoped 块的 .vectorstore-drawer--{engine} 注入。
-->
<template v-if="form.engine_type" #headerIcon>
<img
v-if="drawerLogo?.mode === 'color'"
:src="drawerLogo.url"
:alt="form.engine_type"
class="header-icon__img"
/>
<span
v-else-if="drawerLogo?.mode === 'mono'"
class="header-icon__mono"
:style="drawerLogoStyle"
/>
<span v-else class="header-icon__text">{{ engineInitial(form.engine_type) }}</span>
</template>
<!-- 副标题:engine display_name -->
<template v-if="selectedType" #subtitle>
<span>{{ selectedType.display_name || form.engine_type }}</span>
</template>
<!--
Test connection (footer-left). create 模式:实时验证当前表单的连接信息;
edit 模式:用存储的连接配置(连接配置在编辑模式不可改 — engine 是 immutable)。
始终显示按钮,由 canTestConnection 控制 disabled。
-->
<template #footer-left>
<t-button
variant="outline"
:loading="testing"
:disabled="!canTestConnection"
@click="onDrawerTest"
>
<template #icon>
<t-icon
v-if="!testing && lastTestOk === true"
name="check-circle-filled"
class="status-icon available"
/>
<t-icon
v-else-if="!testing && lastTestOk === false"
name="close-circle-filled"
class="status-icon unavailable"
/>
</template>
{{ testing ? t('vectorStoreSettings.testing') : t('vectorStoreSettings.testConnection') }}
</t-button>
</template>
<t-form ref="formRef" :data="form" :rules="formRules" label-align="top" class="store-form">
<!--
Edit 模式特殊提示:engine_type / connection_config / index_config
创建后不可改,仅 name 可编辑。用 inline-alert 而不是大块 banner,
视觉与其他抽屉的提示一致。
-->
<section v-if="editingStore" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('vectorStoreSettings.basicSection', '基本信息') }}</h4>
<div class="inline-alert inline-alert--info">
<t-icon name="info-circle-filled" class="inline-alert__icon" />
<span class="inline-alert__text">{{ t('vectorStoreSettings.immutableNotice') }}</span>
</div>
<div class="form-item">
<label class="form-label required">{{ t('vectorStoreSettings.nameLabel') }}</label>
<t-input v-model="form.name" :placeholder="t('vectorStoreSettings.namePlaceholder')" />
</div>
<!-- 只读字段以 inline list 展示(轻量 readonly 行) -->
<div class="readonly-fields">
<div class="readonly-row">
<span class="readonly-label">{{ t('vectorStoreSettings.engineTypeLabel') }}</span>
@@ -118,7 +180,9 @@
<template v-for="field in selectedType.connection_fields" :key="field.name">
<div v-if="field.sensitive || form.connection_config[field.name]" class="readonly-row">
<span class="readonly-label">{{ fieldLabel(field.name) }}</span>
<span class="readonly-value">{{ field.sensitive ? '********' : form.connection_config[field.name] }}</span>
<span class="readonly-value">
{{ field.sensitive ? '********' : form.connection_config[field.name] }}
</span>
</div>
</template>
</template>
@@ -131,14 +195,16 @@
</template>
</template>
</div>
<div class="form-divider"></div>
</template>
</section>
<t-form :data="form" :rules="formRules" label-align="top" @submit="saveStore" class="store-form">
<div class="form-scroll-area">
<!-- Create Mode: engine type + connection fields -->
<template v-if="!editingStore">
<t-form-item :label="t('vectorStoreSettings.engineTypeLabel')" name="engine_type">
<!-- Create 模式:基本信息 + 连接配置 + 高级索引 三段 -->
<template v-else>
<!-- Section 1 — 基本信息:engine 类型 + 名称 -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('vectorStoreSettings.basicSection', '基本信息') }}</h4>
<div class="form-item">
<label class="form-label required">{{ t('vectorStoreSettings.engineTypeLabel') }}</label>
<t-select v-model="form.engine_type" @change="onEngineTypeChange">
<t-option
v-for="st in storeTypes"
@@ -147,122 +213,129 @@
:label="st.display_name"
/>
</t-select>
</t-form-item>
</template>
</div>
<!-- Name (always editable) -->
<t-form-item :label="t('vectorStoreSettings.nameLabel')" name="name">
<t-input v-model="form.name" :placeholder="t('vectorStoreSettings.namePlaceholder')" />
</t-form-item>
<div class="form-item">
<label class="form-label required">{{ t('vectorStoreSettings.nameLabel') }}</label>
<t-input v-model="form.name" :placeholder="t('vectorStoreSettings.namePlaceholder')" />
</div>
</section>
<!-- Create Mode: connection fields -->
<template v-if="!editingStore && selectedType">
<div class="form-divider"></div>
<div class="form-section-label">{{ t('vectorStoreSettings.connectionInfo') }}</div>
<!-- Section 2 — 连接配置(engine type 决定具体字段) -->
<section v-if="selectedType" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('vectorStoreSettings.connectionInfo') }}</h4>
<template v-for="field in selectedType.connection_fields" :key="field.name">
<t-form-item
:label="fieldLabel(field.name)"
:name="`connection_config.${field.name}`"
>
<div v-if="field.type === 'boolean'" class="boolean-field">
<div
v-for="field in selectedType.connection_fields"
:key="field.name"
class="form-item"
>
<label
class="form-label"
:class="{ required: field.required }"
>{{ fieldLabel(field.name) }}</label>
<!-- boolean 字段:switch + 行内描述 / TLS 警告 -->
<template v-if="field.type === 'boolean'">
<div class="vision-toggle">
<t-switch v-model="form.connection_config[field.name]" />
<div
v-if="field.name === 'insecure_skip_verify' && form.connection_config[field.name]"
class="field-warning"
>
{{ t('vectorStoreSettings.insecureSkipVerifyWarning') }}
</div>
</div>
<p
v-if="field.name === 'insecure_skip_verify' && form.connection_config[field.name]"
class="form-desc form-desc--warn"
>
{{ t('vectorStoreSettings.insecureSkipVerifyWarning') }}
</p>
</template>
<!-- 敏感字段(password / api key 等):lock prefix + password -->
<t-input
v-else-if="field.type === 'string' && field.sensitive"
v-model="form.connection_config[field.name]"
type="password"
placeholder="********"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
<!-- 数字字段:用 t-input + type=number,与 MCP 高级配置同款;无单位提示 -->
<t-input
v-else-if="field.type === 'number'"
v-model="connectionNumberTextProxy[field.name].value"
type="number"
:placeholder="field.default != null ? String(field.default) : ' '"
class="number-input"
/>
<!-- 普通字符串 -->
<t-input
v-else
v-model="form.connection_config[field.name]"
:placeholder="field.default?.toString() || ''"
/>
</div>
</section>
<!-- Section 3 — 高级索引(仅 selectedType 有 index_fields 时显示) -->
<section v-if="selectedType?.index_fields?.length" class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('vectorStoreSettings.advancedIndexConfig') }}</h4>
<!-- 折叠/展开开关:保留之前的可选展示行为,但样式更轻量 -->
<button
type="button"
class="advanced-toggle"
@click="showAdvanced = !showAdvanced"
>
<t-icon :name="showAdvanced ? 'chevron-down' : 'chevron-right'" />
<span>{{ showAdvanced ? t('common.collapse', '收起') : t('common.expand', '展开') }}</span>
</button>
<template v-if="showAdvanced">
<div
v-for="field in selectedType.index_fields"
:key="field.name"
class="form-item"
>
<label class="form-label">{{ fieldLabel(field.name) }}</label>
<!-- 枚举 → 下拉 -->
<t-select
v-if="field.enum && field.enum.length"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString() || ''"
>
<t-option v-for="opt in field.enum" :key="opt" :value="opt" :label="opt" />
</t-select>
<!-- 数字 → number input -->
<t-input
v-else-if="field.type === 'string' && field.sensitive"
v-model="form.connection_config[field.name]"
type="password"
placeholder="********"
/>
<t-input-number
v-else-if="field.type === 'number'"
v-model="form.connection_config[field.name]"
:placeholder="field.default != null ? String(field.default) : ' '"
theme="normal"
style="width: 100%;"
v-model="indexNumberTextProxy[field.name].value"
type="number"
:placeholder="field.default?.toString()"
:min="field.min ?? 1"
:max="field.max ?? (isReplicaField(field.name) ? 10 : 64)"
class="number-input"
/>
<!-- 字符串 -->
<t-input
v-else
v-model="form.connection_config[field.name]"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString() || ''"
:maxlength="128"
/>
</t-form-item>
</template>
<!-- Advanced: index fields -->
<template v-if="selectedType.index_fields?.length">
<div class="form-divider"></div>
<div class="advanced-toggle" @click="showAdvanced = !showAdvanced">
<t-icon :name="showAdvanced ? 'chevron-down' : 'chevron-right'" size="14px" />
<span>{{ t('vectorStoreSettings.advancedIndexConfig') }}</span>
</div>
<template v-if="showAdvanced">
<template v-for="field in selectedType.index_fields" :key="field.name">
<t-form-item :label="fieldLabel(field.name)" :name="`index_config.${field.name}`">
<!-- Closed value set → dropdown (e.g. knn_engine) -->
<t-select
v-if="field.enum && field.enum.length"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString() || ''"
>
<t-option v-for="opt in field.enum" :key="opt" :value="opt" :label="opt" />
</t-select>
<t-input-number
v-else-if="field.type === 'number'"
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString()"
:min="field.min ?? 1"
:max="field.max ?? (isReplicaField(field.name) ? 10 : 64)"
theme="normal"
style="width: 100%;"
/>
<t-input
v-else
v-model="form.index_config[field.name]"
:placeholder="field.default?.toString() || ''"
:maxlength="128"
/>
</t-form-item>
</template>
</template>
</template>
</template>
</div><!-- /.form-scroll-area -->
<!-- Dialog Footer (outside scroll area) -->
<div class="dialog-footer">
<div class="footer-left">
<t-button
v-if="!editingStore"
theme="default"
variant="outline"
:loading="testing"
@click="testFromDialog"
>
{{ testing ? t('vectorStoreSettings.testing') : t('vectorStoreSettings.testConnection') }}
</t-button>
</div>
<div class="footer-right">
<t-button theme="default" variant="base" @click="showDialog = false">{{ t('common.cancel') }}</t-button>
<t-button theme="primary" type="submit" :loading="saving">{{ t('common.save') }}</t-button>
</div>
</div>
</t-form>
</div>
</t-dialog>
</section>
</template>
</t-form>
</SettingDrawer>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ref, computed, onMounted, watch, type WritableComputedRef } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { AddIcon } from 'tdesign-icons-vue-next'
@@ -273,12 +346,12 @@ import {
updateVectorStore,
deleteVectorStore as deleteVectorStoreAPI,
testVectorStoreRaw,
testVectorStoreById,
type VectorStoreEntity,
type VectorStoreTypeInfo,
} from '@/api/vector-store'
import { useAuthStore } from '@/stores/auth'
import { providerLogo } from './providerLogos'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
const { t } = useI18n()
const authStore = useAuthStore()
@@ -290,9 +363,9 @@ const loading = ref(false)
const showDialog = ref(false)
const editingStore = ref<VectorStoreEntity | null>(null)
const testing = ref(false)
const testingId = ref<string | null>(null)
const saving = ref(false)
const showAdvanced = ref(false)
const formRef = ref<any>()
const form = ref<{
name: string
@@ -306,22 +379,66 @@ const form = ref<{
index_config: {},
})
// Tri-state hint icon next to the test button: null=neutral, true=just
// succeeded, false=just failed. Cleared when the user changes any
// connection-relevant field so a stale ✓/✗ doesn't follow a config the
// user is still editing.
const lastTestOk = ref<boolean | null>(null)
watch(
() => [form.value.engine_type, form.value.connection_config],
() => { lastTestOk.value = null },
{ deep: true },
)
// ===== Computed =====
const envStores = computed(() => stores.value.filter(s => s.source === 'env'))
const userStores = computed(() => stores.value.filter(s => s.source === 'user'))
const selectedType = computed(() => storeTypes.value.find(st => st.type === form.value.engine_type))
// Per-store dropdown options. env 来源是 .env 写入的,UI 不允许 edit / delete,
// 但仍然需要一个"测试连接"入口;user 来源叠加 edit / delete。
const storeActionsFor = (store: VectorStoreEntity) => {
const actions: Array<{ content: string; value: string; theme?: 'error' }> = [
{ content: t('vectorStoreSettings.testConnection'), value: 'test' },
]
if (store.source !== 'env') {
actions.push({ content: t('common.edit'), value: 'edit' })
actions.push({ content: t('common.delete'), value: 'delete', theme: 'error' })
// Drawer header logo — 与列表 .store-card__badge 同源(providerLogo()),让
// 列表卡 → 抽屉 hand-off 视觉连贯。
const drawerLogo = computed(() => {
if (!form.value.engine_type) return null
return providerLogo('vectorstore', form.value.engine_type)
})
const drawerLogoStyle = computed((): Record<string, string> => {
const logo = drawerLogo.value
if (!logo || logo.mode !== 'mono') return {}
return { '--logo-url': `url("${logo.url}")` }
})
// per-engine class on drawer for non-scoped header-icon coloring rules.
const drawerClass = computed(() => {
return form.value.engine_type
? `vectorstore-drawer vectorstore-drawer--${form.value.engine_type}`
: 'vectorstore-drawer'
})
// 测试连接是否可点。create 模式:必须填全所有 required 连接字段;
// edit 模式:engine 不可改、连接配置只读,禁用测试(要重新建条目,不在抽屉里测)。
const canTestConnection = computed(() => {
if (editingStore.value) return false
const st = selectedType.value
if (!st) return false
for (const f of st.connection_fields) {
if (!f.required) continue
const v = form.value.connection_config[f.name]
if (v == null || v === '' || (typeof v === 'string' && v.trim() === '')) return false
}
return actions
return true
})
// Per-store dropdown options. env 来源由 .env 写入,UI 不允许 edit / delete;
// 测试连接已挪到编辑抽屉的 footer,外层菜单不再露出"测试"项。env 来源没有
// 编辑/删除入口 → 整个 dropdown 都不需要展示。
const storeActionsFor = (store: VectorStoreEntity) => {
if (store.source === 'env') return []
return [
{ content: t('common.edit'), value: 'edit' },
{ content: t('common.delete'), value: 'delete', theme: 'error' as const },
]
}
const formRules = computed(() => {
@@ -403,8 +520,54 @@ const onEngineTypeChange = () => {
form.value.connection_config = {}
form.value.index_config = {}
showAdvanced.value = false
// Drop cached number-text proxies so a switch to a different engine
// doesn't keep stale entries pointing at the old field set.
for (const k of Object.keys(connectionNumberText)) delete connectionNumberText[k]
for (const k of Object.keys(indexNumberText)) delete indexNumberText[k]
}
// ---- Number-input text proxies (lazy per field name) ----
// type=number 输入会因为 v-model 把空字符串 coerce 成 0 / NaN,导致
// "用户清空 → 自动塞回 0" 的烦躁交互。我们用 WritableComputedRef 包一层:
// 读取时把数字转成字符串展示;写入时空串 → 删除字段(让 placeholder 显示
// 出来),非空 → 转 int。Proxy 按字段名按需创建并缓存,避免重复 computed。
const connectionNumberText: Record<string, WritableComputedRef<string>> = {}
const indexNumberText: Record<string, WritableComputedRef<string>> = {}
function ensureNumberProxy(
bag: Record<string, WritableComputedRef<string>>,
store: Record<string, any>,
key: string,
): WritableComputedRef<string> {
if (bag[key]) return bag[key]
bag[key] = computed<string>({
get: () => {
const v = store[key]
return v == null || v === '' ? '' : String(v)
},
set: (raw: string) => {
const s = String(raw ?? '').trim()
if (!s) {
delete store[key]
return
}
const n = Number(s)
store[key] = Number.isFinite(n) ? n : s
},
})
return bag[key]
}
// Vue templates can't call ensureNumberProxy on every render without the
// keys multiplying — wrap in a Proxy so `connectionNumberText[name].value`
// from the template lazily creates the proxy on first read.
const connectionNumberTextProxy = new Proxy(connectionNumberText, {
get: (target, name: string) => ensureNumberProxy(target, form.value.connection_config, name),
})
const indexNumberTextProxy = new Proxy(indexNumberText, {
get: (target, name: string) => ensureNumberProxy(target, form.value.index_config, name),
})
const loadStores = async () => {
try {
const response = await listVectorStores()
@@ -433,6 +596,7 @@ const openAddDialog = () => {
connection_config: {},
index_config: {},
}
lastTestOk.value = null
showDialog.value = true
}
@@ -445,12 +609,21 @@ const editStore = (store: VectorStoreEntity) => {
connection_config: { ...store.connection_config },
index_config: { ...store.index_config },
}
lastTestOk.value = null
showDialog.value = true
}
const saveStore = async ({ validateResult, firstError }: any) => {
if (validateResult !== true && validateResult !== undefined) {
MessagePlugin.warning(firstError || t('vectorStoreSettings.toasts.errorGeneric'))
// SettingDrawer 的"保存"按钮触发:手动校验后写后端。
// edit 模式只能改 name;create 模式提交完整 connection / index 配置。
const onDrawerConfirm = async () => {
const result = await formRef.value?.validate()
if (result !== true && result !== undefined) {
// 取第一条错误展示
const firstError =
typeof result === 'object'
? Object.values(result).map((errs: any) => Array.isArray(errs) ? errs[0]?.message : '').find(Boolean)
: ''
MessagePlugin.warning(firstError || (t('vectorStoreSettings.toasts.errorGeneric') as string))
return
}
@@ -484,9 +657,8 @@ const saveStore = async ({ validateResult, firstError }: any) => {
}
const handleAction = (action: { value: string }, store: VectorStoreEntity) => {
if (action.value === 'test') {
testExisting(store)
} else if (action.value === 'edit') {
// test 已挪到抽屉,外层菜单不再处理 'test' 值。
if (action.value === 'edit') {
editStore(store)
} else if (action.value === 'delete') {
confirmDelete(store)
@@ -512,23 +684,10 @@ const confirmDelete = (store: VectorStoreEntity) => {
})
}
const testExisting = async (store: VectorStoreEntity) => {
testingId.value = store.id!
try {
const res = await testVectorStoreById(store.id!)
if (res.success) {
MessagePlugin.success(t('vectorStoreSettings.toasts.testSuccess'))
} else {
MessagePlugin.error(res.error || t('vectorStoreSettings.toasts.testFailed'))
}
} catch (error: any) {
MessagePlugin.error(error?.message || t('vectorStoreSettings.toasts.testFailed'))
} finally {
testingId.value = null
}
}
const testFromDialog = async () => {
// 测试连接(在抽屉内触发)。create 模式下用当前表单数据,调
// /test/raw 端点。edit 模式按钮 disabled,所以这里只处理 create 路径。
const onDrawerTest = async () => {
if (editingStore.value) return
testing.value = true
try {
const data = {
@@ -536,12 +695,14 @@ const testFromDialog = async () => {
connection_config: { ...form.value.connection_config },
}
const res = await testVectorStoreRaw(data)
lastTestOk.value = !!res.success
if (res.success) {
MessagePlugin.success(t('vectorStoreSettings.toasts.testSuccess'))
} else {
MessagePlugin.error(res.error || t('vectorStoreSettings.toasts.testFailed'))
}
} catch (error: any) {
lastTestOk.value = false
MessagePlugin.error(error?.message || t('vectorStoreSettings.toasts.testFailed'))
} finally {
testing.value = false
@@ -776,12 +937,6 @@ onMounted(async () => {
background: var(--td-warning-color-1, #FEF3E6);
}
// 测试中 spinner(toast 弹出前的进度反馈)
.store-card__loading {
flex-shrink: 0;
color: var(--td-text-color-placeholder);
}
.store-card__more {
flex-shrink: 0;
color: var(--td-text-color-placeholder);
@@ -840,131 +995,249 @@ onMounted(async () => {
font-size: 14px;
}
// Dialog
.dialog-form-container {
margin-top: 12px;
display: flex;
flex-direction: column;
max-height: 70vh;
// ---- 抽屉内容 — 与 ModelEditorDialog 同款约定 ----
.form-item {
margin-bottom: 0;
}
.store-form {
display: flex;
flex-direction: column;
min-height: 0;
.form-label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
line-height: 1.4;
&.required::before {
content: '*';
color: var(--td-error-color);
margin-right: 4px;
font-weight: 500;
line-height: 1;
}
}
.form-scroll-area {
flex: 1;
overflow-y: auto;
padding-right: 12px;
.form-desc {
margin: 4px 0 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-placeholder);
&--inline { margin: 0; }
// TLS 警告等"危险确认"用红字
&--warn { color: var(--td-error-color); }
}
.immutable-notice {
:deep(.t-input),
:deep(.t-select),
:deep(.t-textarea) {
width: 100%;
font-size: 13px;
}
// 隐藏 t-form 默认 form-item 容器 — 走自定义 .form-item / .form-label
:deep(.t-form) .t-form-item {
display: none;
}
.vision-toggle {
display: flex;
align-items: flex-start;
align-items: center;
gap: 8px;
}
// ---- inline alert(替代之前的 .immutable-notice 大块横幅) ----
.inline-alert {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 14px;
margin-bottom: 16px;
background: rgba(7, 192, 95, 0.1);
border-radius: 6px;
font-size: 13px;
line-height: 1.5;
color: var(--td-brand-color);
color: var(--td-text-color-secondary);
flex-wrap: wrap;
white-space: pre-line;
&__icon {
font-size: 15px;
flex-shrink: 0;
color: var(--td-text-color-placeholder);
}
&__text {
flex: 1 1 auto;
min-width: 0;
}
&--info {
color: var(--td-text-color-primary);
.inline-alert__icon { color: var(--td-brand-color); }
}
}
/* Wrap switch + warning in a vertical stack so the warning sits on its own
line below the switch, independent of TDesign's form-item content flex
(which is a nowrap row — margin-top alone has no visible effect there). */
.boolean-field {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 100%;
}
.field-warning {
margin-top: 8px;
font-size: 12px;
line-height: 1.4;
color: var(--td-error-color, #d54941);
}
// ---- 编辑模式只读字段列表(保持原有视觉,但去掉外框,紧贴 alert 下方)----
.readonly-fields {
padding: 10px 14px;
padding: 10px 12px;
background: var(--td-bg-color-secondarycontainer);
border-radius: 6px;
margin-bottom: 16px;
border-radius: 8px;
}
.readonly-row {
display: flex;
align-items: baseline;
gap: 8px;
padding: 3px 0;
padding: 4px 0;
font-size: 12px;
line-height: 1.4;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
&:last-child { border-bottom: none; }
}
.readonly-label {
color: var(--td-text-color-placeholder);
font-size: 11px;
white-space: nowrap;
min-width: 60px;
min-width: 80px;
}
.readonly-value {
color: var(--td-text-color-primary);
font-size: 12px;
font-family: var(--app-font-family-mono);
font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;
word-break: break-all;
}
.form-divider {
height: 1px;
background: var(--td-component-border);
margin: 20px 0;
}
.form-section-label {
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-secondary);
margin-bottom: 12px;
}
// ---- 高级索引展开/收起按钮 ----
.advanced-toggle {
display: flex;
display: inline-flex;
align-items: center;
gap: 6px;
gap: 4px;
padding: 4px 0;
font-size: 13px;
color: var(--td-text-color-secondary);
background: transparent;
border: none;
font-family: inherit;
cursor: pointer;
user-select: none;
margin-bottom: 12px;
align-self: flex-start;
&:hover {
color: var(--td-brand-color);
&:hover { color: var(--td-brand-color); }
.t-icon { font-size: 14px; }
}
// ---- Number input:去原生 spinner(与 MCP 高级配置同款)----
.number-input {
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
:deep(input[type="number"]) {
-moz-appearance: textfield;
appearance: textfield;
}
}
.dialog-footer {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 32px;
padding-top: 20px;
border-top: 1px solid var(--td-component-border);
// ---- Header 图标徽章 ----
.header-icon__img {
width: 24px;
height: 24px;
object-fit: contain;
display: block;
}
.footer-right {
display: flex;
gap: 12px;
}
.header-icon__mono {
display: inline-block;
width: 22px;
height: 22px;
background-color: currentColor;
-webkit-mask-image: var(--logo-url);
-webkit-mask-position: center;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: contain;
mask-image: var(--logo-url);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
}
.header-icon__text {
font-size: 15px;
font-weight: 600;
letter-spacing: 0.02em;
}
// ---- footer-left 测试按钮的状态 icon ----
.status-icon {
font-size: 16px;
flex-shrink: 0;
&.available { color: var(--td-brand-color); }
&.unavailable { color: var(--td-error-color); }
}
</style>
<!--
Non-scoped block: per-engine header-icon coloring + color-logo background
tweak. Same pattern as Storage/Parser/WebSearch drawers — these rules
must be global so they reach the t-drawer panel even if its scoped
data-attribute is dropped in some builds. Each rule mirrors the matching
.store-card--{engine} .store-card__badge from the scoped block above so
list-card → drawer hand-off stays visually continuous.
-->
<style lang="less">
// 彩色 logo 时给 header-icon 容器一个白底 + 1px 边
.vectorstore-drawer .setting-drawer__header-icon:has(.header-icon__img) {
background: var(--td-bg-color-container, #fff);
box-shadow: inset 0 0 0 1px var(--td-component-stroke);
}
.vectorstore-drawer--qdrant .setting-drawer__header-icon {
background: rgba(225, 38, 38, 0.12);
color: #E12626;
}
.vectorstore-drawer--milvus .setting-drawer__header-icon {
background: rgba(0, 137, 255, 0.12);
color: #0089FF;
}
.vectorstore-drawer--weaviate .setting-drawer__header-icon {
background: rgba(7, 192, 95, 0.12);
color: #07A050;
}
.vectorstore-drawer--elasticsearch .setting-drawer__header-icon,
.vectorstore-drawer--elasticfaiss .setting-drawer__header-icon {
background: rgba(255, 153, 0, 0.12);
color: #D97706;
}
.vectorstore-drawer--postgres .setting-drawer__header-icon {
background: rgba(0, 82, 217, 0.1);
color: #0052D9;
}
.vectorstore-drawer--opensearch .setting-drawer__header-icon {
background: rgba(98, 53, 187, 0.12);
color: #6235BB;
}
.vectorstore-drawer--infinity .setting-drawer__header-icon {
background: rgba(98, 53, 187, 0.12);
color: #6235BB;
}
.vectorstore-drawer--tencent_vectordb .setting-drawer__header-icon {
background: rgba(0, 82, 217, 0.1);
color: #0052D9;
}
.vectorstore-drawer--doris .setting-drawer__header-icon {
background: rgba(255, 90, 0, 0.12);
color: #E55A00;
}
.vectorstore-drawer--sqlite .setting-drawer__header-icon {
background: rgba(70, 70, 70, 0.1);
color: #464646;
}
</style>
+406 -149
View File
@@ -79,106 +79,202 @@
</t-empty>
</div>
<!-- Add/Edit Drawer -->
<SettingDrawer v-model:visible="showAddProviderDialog"
<!-- Add/Edit Drawer — 与 ModelEditorDialog / Parser / Storage 抽屉同款风格 -->
<SettingDrawer
v-model:visible="showAddProviderDialog"
:title="editingProvider ? t('webSearchSettings.editProvider') : t('webSearchSettings.addProvider')"
:confirm-loading="saving" @confirm="saveProvider">
<t-form ref="formRef" :data="providerForm" label-align="top" class="provider-form">
<t-form-item :label="t('webSearchSettings.providerTypeLabel')" name="provider">
<t-select v-model="providerForm.provider" :disabled="!!editingProvider" @change="onProviderTypeChange">
<t-option v-for="pt in providerTypes" :key="pt.id" :value="pt.id" :label="pt.name">
<div class="provider-option">
<span>{{ pt.name }}</span>
<t-tag v-if="isProviderFree(pt)" theme="success" size="small" variant="light">
{{ t('webSearchSettings.free') }}
</t-tag>
</div>
</t-option>
</t-select>
</t-form-item>
:class="drawerClass"
:confirm-loading="saving"
@confirm="saveProvider"
>
<!--
Header icon — 与列表 .provider-card__badge 同款 logo/mono/fallback。
- color logo(如 Bing/Google 彩色徽标)→ <img>,header 容器变白底 + 细边
- mono logo(mask-image)→ ::before-style span,currentColor 染色
- fallback:providerId 首字母 monogram
-->
<template v-if="selectedProviderType" #headerIcon>
<img
v-if="drawerLogo?.mode === 'color'"
:src="drawerLogo.url"
:alt="selectedProviderType.id"
class="header-icon__img"
/>
<span
v-else-if="drawerLogo?.mode === 'mono'"
class="header-icon__mono"
:style="drawerLogoStyle"
/>
<span v-else class="header-icon__text">{{ providerInitial(selectedProviderType.id) }}</span>
</template>
<t-form-item :label="t('webSearchSettings.providerNameLabel')" name="name">
<t-input v-model="providerForm.name"
:placeholder="selectedProviderType?.name || t('webSearchSettings.providerNamePlaceholder')" />
</t-form-item>
<!--
Subtitle: provider 类型名 + 官方文档外链(若有)。
-->
<template v-if="selectedProviderType" #subtitle>
<span>{{ selectedProviderType.name }}</span>
<a
v-if="selectedProviderType.docs_url"
:href="selectedProviderType.docs_url"
target="_blank"
rel="noopener noreferrer"
class="doc-link doc-link--inline"
>
{{ t('webSearchSettings.viewDocs') }}
<t-icon name="link" class="link-icon" />
</a>
</template>
<t-form-item :label="t('webSearchSettings.providerDescLabel')" name="description">
<t-input v-model="providerForm.description" :placeholder="t('webSearchSettings.providerDescPlaceholder')" />
</t-form-item>
<!--
Test connection (footer-left, 与其他抽屉同款)。已经统一为唯一入口 —
外层卡片菜单不再露出"测试连接",所有测试都从这里发起。
<template
v-if="selectedProviderType?.requires_api_key || selectedProviderType?.requires_engine_id || selectedProviderType?.requires_base_url">
<div class="form-divider"></div>
<div class="credentials-hint" v-if="selectedProviderType?.docs_url">
<a :href="selectedProviderType.docs_url" target="_blank" rel="noopener noreferrer" class="doc-link">
{{ t('webSearchSettings.viewDocs') }}
<t-icon name="link" class="link-icon" />
</a>
</div>
<t-form-item v-if="selectedProviderType?.requires_base_url" :label="t('webSearchSettings.baseUrlLabel')"
name="parameters.base_url">
<t-input v-model="providerForm.parameters.base_url"
:placeholder="t('webSearchSettings.baseUrlPlaceholder')" />
</t-form-item>
<!--
Edit mode: credential is managed by the shared <CredentialResource>
card via the /credentials subresource. Create mode keeps a plain
input so the initial api_key flows in with the first POST.
API key is mandatory for every requires_api_key=true provider
(validation in service/web_search_provider.go). The component's
"Remove" action is still available because a user might want to
rotate via remove + re-add, but in normal use they will use
"Replace" instead.
-->
<div v-if="selectedProviderType?.requires_api_key" class="credential-field">
<label class="credential-label">{{ t('webSearchSettings.apiKeyLabel') }}</label>
<CredentialResource v-if="editingProvider?.id" :api="credentialApi" :fields="credentialFields"
:meta="credentialMeta" />
<t-input v-else v-model="providerForm.parameters.api_key" type="password"
:placeholder="apiKeyPlaceholder" />
</div>
<t-form-item v-if="selectedProviderType?.requires_engine_id" :label="t('webSearchSettings.engineIdLabel')"
name="parameters.engine_id">
<t-input v-model="providerForm.parameters.engine_id" :placeholder="t('webSearchSettings.engineIdLabel')" />
</t-form-item>
</template>
<t-form-item v-if="selectedProviderType?.supports_proxy" :label="t('webSearchSettings.proxyUrlLabel')"
name="parameters.proxy_url">
<t-input v-model="providerForm.parameters.proxy_url"
:placeholder="t('webSearchSettings.proxyUrlPlaceholder')" />
<template #help>
<span class="switch-help">{{ t('webSearchSettings.proxyUrlHelp') }}</span>
全部 provider 都显示按钮(包括 DuckDuckGo / SearXNG 这些"免费"的)—
免费只是不要 api_key,不代表不需要测:DuckDuckGo 走外网可能被墙、
SearXNG 是自托管要验 base_url 可达性。disabled 由 canTestConnection
统一控制,缺哪个必填字段就置灰。
-->
<template v-if="selectedProviderType" #footer-left>
<t-button
variant="outline"
:loading="testing"
:disabled="!canTestConnection"
@click="testConnection"
>
<template #icon>
<t-icon
v-if="!testing && lastTestOk === true"
name="check-circle-filled"
class="status-icon available"
/>
<t-icon
v-else-if="!testing && lastTestOk === false"
name="close-circle-filled"
class="status-icon unavailable"
/>
</template>
</t-form-item>
<div class="form-divider"></div>
<t-form-item :label="t('webSearchSettings.setAsDefault')" name="is_default">
<template #help>
<div class="switch-help">
{{ t('webSearchSettings.setAsDefaultDesc') }}
</div>
</template>
<t-switch v-model="providerForm.is_default" />
</t-form-item>
</t-form>
<template #footer-left>
<t-button v-if="selectedProviderType && !isProviderFree(selectedProviderType)" theme="default" variant="outline"
:loading="testing" @click="testConnection">
{{ testing ? t('webSearchSettings.testing') : t('webSearchSettings.testConnection') }}
</t-button>
</template>
<t-form ref="formRef" :data="providerForm" label-align="top" class="provider-form">
<!-- Section 1 — 基本信息 -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('webSearchSettings.basicSection', '基本信息') }}</h4>
<!-- providerType 选择器:仅在新建时可改 -->
<div class="form-item">
<label class="form-label required">{{ t('webSearchSettings.providerTypeLabel') }}</label>
<t-select
v-model="providerForm.provider"
:disabled="!!editingProvider"
@change="onProviderTypeChange"
>
<!--
Just provider name in each option — we used to append a "免费"
t-tag for providers that don't take an api_key, but the
"免费"分类对用户决策没什么帮助(DuckDuckGo / SearXNG 也都
需要可用的网络/自托管实例),反而占视觉空间。
-->
<t-option v-for="pt in providerTypes" :key="pt.id" :value="pt.id" :label="pt.name" />
</t-select>
</div>
<div class="form-item">
<label class="form-label">{{ t('webSearchSettings.providerNameLabel') }}</label>
<t-input
v-model="providerForm.name"
:placeholder="selectedProviderType?.name || t('webSearchSettings.providerNamePlaceholder')"
/>
</div>
<div class="form-item">
<label class="form-label">{{ t('webSearchSettings.providerDescLabel') }}</label>
<t-input
v-model="providerForm.description"
:placeholder="t('webSearchSettings.providerDescPlaceholder')"
/>
</div>
</section>
<!-- Section 2 — 连接配置(base url / api key / engine id),仅当任意字段需要时渲染 -->
<section
v-if="selectedProviderType?.requires_api_key || selectedProviderType?.requires_engine_id || selectedProviderType?.requires_base_url"
class="setting-drawer__section"
>
<h4 class="setting-drawer__section-title">{{ t('webSearchSettings.credentialsSection', '连接配置') }}</h4>
<div v-if="selectedProviderType?.requires_base_url" class="form-item">
<label class="form-label required">{{ t('webSearchSettings.baseUrlLabel') }}</label>
<t-input
v-model="providerForm.parameters.base_url"
:placeholder="t('webSearchSettings.baseUrlPlaceholder')"
/>
</div>
<!--
Edit 模式下凭证由 CredentialResource 管理(独立的 /credentials
子资源调用),不与本表单 submit 耦合;Create 模式下用 plain
password input + lock prefix-icon,与 ModelEditorDialog 一致。
-->
<div v-if="selectedProviderType?.requires_api_key" class="form-item">
<label class="form-label required">{{ t('webSearchSettings.apiKeyLabel') }}</label>
<CredentialResource
v-if="editingProvider?.id"
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
<t-input
v-else
v-model="providerForm.parameters.api_key"
type="password"
:placeholder="apiKeyPlaceholder"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div v-if="selectedProviderType?.requires_engine_id" class="form-item">
<label class="form-label required">{{ t('webSearchSettings.engineIdLabel') }}</label>
<t-input
v-model="providerForm.parameters.engine_id"
:placeholder="t('webSearchSettings.engineIdLabel')"
/>
</div>
</section>
<!-- Section 3 — 选项(代理 / 默认) -->
<section
v-if="selectedProviderType?.supports_proxy || selectedProviderType"
class="setting-drawer__section"
>
<h4 class="setting-drawer__section-title">{{ t('webSearchSettings.optionsSection', '选项') }}</h4>
<div v-if="selectedProviderType?.supports_proxy" class="form-item">
<label class="form-label">{{ t('webSearchSettings.proxyUrlLabel') }}</label>
<t-input
v-model="providerForm.parameters.proxy_url"
:placeholder="t('webSearchSettings.proxyUrlPlaceholder')"
/>
<p class="form-desc">{{ t('webSearchSettings.proxyUrlHelp') }}</p>
</div>
<div class="form-item">
<label class="form-label">{{ t('webSearchSettings.setAsDefault') }}</label>
<div class="vision-toggle">
<t-switch v-model="providerForm.is_default" />
<span class="form-desc form-desc--inline">{{ t('webSearchSettings.setAsDefaultDesc') }}</span>
</div>
</div>
</section>
</t-form>
</SettingDrawer>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ref, computed, onMounted, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { AddIcon } from 'tdesign-icons-vue-next'
@@ -214,10 +310,15 @@ const providerTypes = ref<WebSearchProviderTypeInfo[]>([])
const showAddProviderDialog = ref(false)
const editingProvider = ref<WebSearchProviderEntity | null>(null)
const testing = ref(false)
const testingId = ref<string | null>(null)
const saving = ref(false)
const formRef = ref<any>()
// Tri-state hint icon next to the test button: null=neutral, true=just
// succeeded, false=just failed. Cleared whenever the user changes the
// underlying connection inputs (see watch() below, set up after providerForm
// is initialized so the watch's source function doesn't trip on TDZ).
const lastTestOk = ref<boolean | null>(null)
const providerForm = ref<{
name: string
provider: string
@@ -232,6 +333,21 @@ const providerForm = ref<{
is_default: false,
})
// Invalidate the cached test result whenever the user edits a connection
// field. Set up after providerForm is declared so the watch's source
// function — which dereferences providerForm.value on first run — doesn't
// hit a TDZ ReferenceError. proxy_url is excluded because the upstream
// call doesn't actually use it for credential validation.
watch(
() => [
providerForm.value.provider,
providerForm.value.parameters?.api_key,
providerForm.value.parameters?.engine_id,
providerForm.value.parameters?.base_url,
],
() => { lastTestOk.value = null },
)
// ===== Computed =====
const selectedProviderType = computed(() => {
return providerTypes.value.find(pt => pt.id === providerForm.value.provider)
@@ -264,12 +380,42 @@ const credentialMeta = computed(() => editingProvider.value?.credentials ?? {
api_key: { configured: false },
})
const isProviderFree = (providerType: WebSearchProviderTypeInfo) => {
// "Free" here means no upstream-paid credentials are required. Self-hosted
// providers (requires_base_url) are still free to use even though they need
// an instance URL, so they should keep the free badge.
return !providerType.requires_api_key && !providerType.requires_engine_id
}
// Per-provider class on the drawer — the non-scoped CSS block at the
// bottom uses .websearch-drawer--{id} to color the header-icon container
// to match the matching list-card badge.
const drawerClass = computed(() => {
const id = providerForm.value.provider
return id
? `websearch-drawer websearch-drawer--${id}`
: 'websearch-drawer'
})
// Reuses providerLogo() so the drawer header icon matches whatever the
// list card showed for the same provider id.
const drawerLogo = computed(() => {
const id = providerForm.value.provider
return id ? providerLogo('websearch', id) : null
})
const drawerLogoStyle = computed((): Record<string, string> => {
const logo = drawerLogo.value
if (!logo || logo.mode !== 'mono') return {}
return { '--logo-url': `url("${logo.url}")` }
})
// Whether "Test connection" can fire. New-mode requires the user to have
// typed an api_key (and engine_id / base_url where applicable); edit-mode
// can fire with no fresh api_key because the backend will fall back to
// the stored credential. Free providers don't show the button at all.
const canTestConnection = computed(() => {
const pt = selectedProviderType.value
if (!pt) return false
if (editingProvider.value) return true
if (pt.requires_api_key && !providerForm.value.parameters.api_key) return false
if (pt.requires_engine_id && !providerForm.value.parameters.engine_id) return false
if (pt.requires_base_url && !providerForm.value.parameters.base_url) return false
return true
})
// 卡片首字母徽章。复用 providerType 信息表,让多字节缩写也走同一处。
const providerInitial = (providerId: string) => {
@@ -301,6 +447,7 @@ const providerTypeLabel = (providerId: string) => {
// ===== Methods =====
const onProviderTypeChange = () => {
providerForm.value.parameters = {}
lastTestOk.value = null
}
const loadProviderEntities = async () => {
@@ -331,6 +478,7 @@ const openAddDialog = () => {
parameters: {},
is_default: providerEntities.value.length === 0
}
lastTestOk.value = null
showAddProviderDialog.value = true
}
@@ -350,6 +498,7 @@ const editProvider = (entity: WebSearchProviderEntity) => {
},
is_default: entity.is_default || false,
}
lastTestOk.value = null
showAddProviderDialog.value = true
}
@@ -422,8 +571,10 @@ const testConnection = async () => {
parameters: { ...providerForm.value.parameters },
}
let ok = false
if (editingProvider.value && !data.parameters.api_key) {
const res = await testWebSearchProvider(editingProvider.value.id!)
ok = !!res.success
if (res.success) {
MessagePlugin.success(t('webSearchSettings.toasts.testSuccess'))
} else {
@@ -431,44 +582,32 @@ const testConnection = async () => {
}
} else {
const res = await testWebSearchProvider(undefined, data)
ok = !!res.success
if (res.success) {
MessagePlugin.success(t('webSearchSettings.toasts.testSuccess'))
} else {
MessagePlugin.error(res.error || t('webSearchSettings.toasts.testFailed'))
}
}
lastTestOk.value = ok
} catch (error: any) {
MessagePlugin.error(error?.message || t('webSearchSettings.toasts.testFailed'))
lastTestOk.value = false
} finally {
testing.value = false
}
}
const testExistingConnection = async (entity: WebSearchProviderEntity) => {
testingId.value = entity.id!
try {
const res = await testWebSearchProvider(entity.id!)
if (res.success) {
MessagePlugin.success(t('webSearchSettings.toasts.testSuccess'))
} else {
MessagePlugin.error(res.error || t('webSearchSettings.toasts.testFailed'))
}
} catch (error: any) {
MessagePlugin.error(error?.message || t('webSearchSettings.toasts.testFailed'))
} finally {
testingId.value = null
}
}
const getProviderOptions = (_entity: WebSearchProviderEntity) => {
// Web search providers carry external API credentials; the backend
// gates every mutation/test behind Admin+ (RegisterWebSearchProviderRoutes).
// Hide the action menu entirely for non-Admins so they don't trip 403s.
// 测试连接已挪到编辑抽屉的 footer,不再放在外层菜单里 — 单一入口减少
// 用户疑惑("为什么有两个测试入口,结果一样吗?")。
if (!authStore.hasRole('admin')) {
return []
}
return [
{ content: t('webSearchSettings.testConnection'), value: 'test' },
{ content: t('common.edit'), value: 'edit' },
{ content: t('common.delete'), value: 'delete', theme: 'error' as const }
]
@@ -476,9 +615,6 @@ const getProviderOptions = (_entity: WebSearchProviderEntity) => {
const handleMenuAction = (data: { value: string }, entity: WebSearchProviderEntity) => {
switch (data.value) {
case 'test':
testExistingConnection(entity)
break
case 'edit':
editProvider(entity)
break
@@ -621,8 +757,10 @@ onMounted(async () => {
color: #6235BB;
}
.provider-card--baidu .provider-card__badge {
background: rgba(225, 38, 38, 0.12);
color: #E12626;
// 百度官方主色(搜索框 du 标识那个蓝),#2932E1。低饱和版用 12% alpha
// 浅底,跟其他 provider 一致。之前误填红色(混淆了百度地图等子产品)。
background: rgba(41, 50, 225, 0.12);
color: #2932E1;
}
.provider-card--searxng .provider-card__badge {
background: rgba(33, 86, 137, 0.12);
@@ -735,55 +873,174 @@ onMounted(async () => {
width: 100%;
}
.form-divider {
height: 1px;
background: var(--td-component-border);
margin: 20px 0;
// ---- 抽屉内容 — 与 ModelEditorDialog 同款约定 ----
.form-item {
margin-bottom: 0;
}
/**
* Credential field: stacks the label row, password input, and the optional
* "Remove this credential" checkbox vertically. Matches the pattern in
* McpServiceDialog and ModelEditorDialog so the whole UI reads consistently.
*/
.credential-field {
display: flex;
flex-direction: column;
gap: 8px;
margin-bottom: 20px;
}
.credential-label {
.form-label {
display: block;
font-size: 14px;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
}
line-height: 1.4;
.clear-credential {
:deep(.t-checkbox__label) {
&.required::before {
content: '*';
color: var(--td-error-color);
font-size: 13px;
margin-right: 4px;
font-weight: 500;
line-height: 1;
}
}
.credentials-hint {
margin-bottom: 12px;
.form-desc {
margin: 4px 0 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-placeholder);
&--inline {
margin: 0;
}
}
:deep(.t-input),
:deep(.t-select),
:deep(.t-textarea),
:deep(.t-input-number) {
width: 100%;
font-size: 13px;
}
a {
// 隐藏 t-form 默认的 form-item 容器 — 我们走自定义 .form-item / .form-label。
:deep(.t-form) .t-form-item {
display: none;
}
.vision-toggle {
display: flex;
align-items: center;
gap: 8px;
}
// ---- footer-left 测试按钮的状态 icon(与 ModelEditorDialog/MCP 同款) ----
.status-icon {
font-size: 16px;
flex-shrink: 0;
&.available {
color: var(--td-brand-color);
text-decoration: none;
}
&:hover {
text-decoration: underline;
&.unavailable {
color: var(--td-error-color);
}
}
// ---- Header 图标徽章 ----
.header-icon__img {
width: 24px;
height: 24px;
object-fit: contain;
display: block;
}
.header-icon__mono {
display: inline-block;
width: 22px;
height: 22px;
background-color: currentColor;
-webkit-mask-image: var(--logo-url);
-webkit-mask-position: center;
-webkit-mask-repeat: no-repeat;
-webkit-mask-size: contain;
mask-image: var(--logo-url);
mask-position: center;
mask-repeat: no-repeat;
mask-size: contain;
}
.header-icon__text {
font-size: 15px;
font-weight: 600;
letter-spacing: 0.02em;
}
.doc-link {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 13px;
font-weight: 500;
color: var(--td-brand-color);
text-decoration: none;
transition: color 0.15s ease;
&:hover {
color: var(--td-brand-color-active);
}
.link-icon {
font-size: 14px;
}
&--inline {
margin-left: 6px;
font-size: 12px;
font-weight: 500;
vertical-align: baseline;
.link-icon {
font-size: 12px;
}
}
}
</style>
.switch-help {
font-size: 12px;
color: var(--td-text-color-secondary);
margin-top: 4px;
line-height: 1.4;
<!--
Non-scoped block: per-provider header-icon coloring + color-logo
background tweak. Same pattern as Storage/Parser drawers — these rules
must be global so they always reach the t-drawer panel even if its
scoped data-attribute is dropped in some builds. Each rule mirrors the
matching .provider-card--{id} .provider-card__badge from the scoped
block above so list-card → drawer hand-off stays visually continuous.
-->
<style lang="less">
// 彩色 logo 时给 header-icon 容器一个白底 + 1px 边,避免品牌色浅底压在
// 彩色图标上影响对比度。
.websearch-drawer .setting-drawer__header-icon:has(.header-icon__img) {
background: var(--td-bg-color-container, #fff);
box-shadow: inset 0 0 0 1px var(--td-component-stroke);
}
.websearch-drawer--duckduckgo .setting-drawer__header-icon {
background: rgba(222, 88, 51, 0.12);
color: #DE5833;
}
.websearch-drawer--bing .setting-drawer__header-icon {
background: rgba(0, 137, 255, 0.12);
color: #0089FF;
}
.websearch-drawer--google .setting-drawer__header-icon {
background: rgba(66, 133, 244, 0.12);
color: #4285F4;
}
.websearch-drawer--tavily .setting-drawer__header-icon {
background: rgba(98, 53, 187, 0.12);
color: #6235BB;
}
.websearch-drawer--baidu .setting-drawer__header-icon {
background: rgba(41, 50, 225, 0.12);
color: #2932E1;
}
.websearch-drawer--searxng .setting-drawer__header-icon {
background: rgba(33, 86, 137, 0.12);
color: #215689;
}
.websearch-drawer--ollama .setting-drawer__header-icon {
background: rgba(70, 70, 70, 0.12);
color: #464646;
}
</style>
@@ -1,78 +1,222 @@
<template>
<SettingDrawer :visible="dialogVisible"
<SettingDrawer
:visible="dialogVisible"
:title="mode === 'add' ? t('mcpServiceDialog.addTitle') : t('mcpServiceDialog.editTitle')"
:confirm-loading="submitting" @update:visible="(v: boolean) => dialogVisible = v" @confirm="handleSubmit"
@cancel="handleClose">
:class="`mcp-drawer mcp-drawer--${formData.transport_type}`"
:confirm-loading="submitting"
@update:visible="(v: boolean) => dialogVisible = v"
@confirm="handleSubmit"
@cancel="handleClose"
>
<!--
Header icon — 与 McpSettings 列表 .service-card__badge 同款:
transport_type 决定图标和容器配色。SSE 绿、HTTP-Streamable 蓝。
非 scoped 块 .mcp-drawer--{transport} 注入背景与文字色,currentColor
让 t-icon 跟着染色。
-->
<template #headerIcon>
<t-icon :name="transportIcon" />
</template>
<!-- 副标题:transport 类型名 + 启用状态 mini chip -->
<template #subtitle>
<span>{{ transportLabel }}</span>
<span
class="subtitle-tag"
:class="formData.enabled ? 'subtitle-tag--ok' : 'subtitle-tag--muted'"
>
{{ formData.enabled ? t('mcpSettings.enabled', '已启用') : t('mcpSettings.disabled', '已禁用') }}
</span>
</template>
<!--
测试连接按钮挪到 footer-left,与 ModelEditorDialog/Storage/Parser/
WebSearch 抽屉同款。仅 edit 模式有效(需要服务 id 才能调 /test 端点)。
create 模式下按钮 disabled 并提示"保存后可测试"。
-->
<template #footer-left>
<t-button
variant="outline"
:loading="testing"
:disabled="mode === 'add' || !props.service?.id"
:title="mode === 'add' ? t('mcpServiceDialog.testAfterSaveHint', '保存后可测试连接') : ''"
@click="handleTestConnection"
>
<template #icon>
<t-icon
v-if="!testing && lastTestOk === true"
name="check-circle-filled"
class="status-icon available"
/>
<t-icon
v-else-if="!testing && lastTestOk === false"
name="close-circle-filled"
class="status-icon unavailable"
/>
</template>
{{ testing ? t('webSearchSettings.testing', '测试中…') : t('mcpSettings.actions.test', '测试连接') }}
</t-button>
</template>
<t-form ref="formRef" :data="formData" :rules="rules" label-align="top">
<t-form-item :label="t('mcpServiceDialog.name')" name="name">
<t-input v-model="formData.name" :placeholder="t('mcpServiceDialog.namePlaceholder')" />
</t-form-item>
<!-- Section 1 — 基本信息 -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.basicSection', '基本信息') }}</h4>
<t-form-item :label="t('mcpServiceDialog.description')" name="description">
<t-textarea v-model="formData.description" :autosize="{ minRows: 3, maxRows: 5 }"
:placeholder="t('mcpServiceDialog.descriptionPlaceholder')" />
</t-form-item>
<div class="form-item">
<label class="form-label required">{{ t('mcpServiceDialog.name') }}</label>
<t-input v-model="formData.name" :placeholder="t('mcpServiceDialog.namePlaceholder')" />
</div>
<t-form-item :label="t('mcpServiceDialog.transportType')" name="transport_type">
<t-radio-group v-model="formData.transport_type">
<t-radio-button value="sse">{{ t('mcpServiceDialog.transport.sse') }}</t-radio-button>
<t-radio-button value="http-streamable">{{ t('mcpServiceDialog.transport.httpStreamable') }}</t-radio-button>
<!-- Stdio transport is disabled for security reasons -->
</t-radio-group>
</t-form-item>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.description') }}</label>
<t-textarea
v-model="formData.description"
:autosize="{ minRows: 2, maxRows: 5 }"
:placeholder="t('mcpServiceDialog.descriptionPlaceholder')"
/>
</div>
<!-- URL for SSE/HTTP Streamable -->
<t-form-item :label="t('mcpServiceDialog.serviceUrl')" name="url">
<t-input v-model="formData.url" :placeholder="t('mcpServiceDialog.serviceUrlPlaceholder')" />
</t-form-item>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.enableService') }}</label>
<div class="vision-toggle">
<t-switch v-model="formData.enabled" />
<span class="form-desc form-desc--inline">
{{ t('mcpServiceDialog.enableServiceDesc', '关闭后该服务不会被调用') }}
</span>
</div>
</div>
</section>
<!-- Stdio Config removed for security reasons -->
<!-- Section 2 — 连接配置(transport + url) -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.connectionSection', '连接配置') }}</h4>
<t-form-item :label="t('mcpServiceDialog.enableService')" name="enabled">
<t-switch v-model="formData.enabled" />
</t-form-item>
<div class="form-item">
<label class="form-label required">{{ t('mcpServiceDialog.transportType') }}</label>
<!-- 紧凑 pill segmented,与 ModelEditorDialog 来源切换 / Storage MinIO 部署模式同款 -->
<div class="source-options" role="radiogroup">
<button
type="button"
class="source-option"
:class="{ 'is-active': formData.transport_type === 'sse' }"
@click="formData.transport_type = 'sse'"
>
<t-icon name="cast" class="source-option__icon" />
<span class="source-option__label">SSE</span>
</button>
<button
type="button"
class="source-option"
:class="{ 'is-active': formData.transport_type === 'http-streamable' }"
@click="formData.transport_type = 'http-streamable'"
>
<t-icon name="link" class="source-option__icon" />
<span class="source-option__label">HTTP Streamable</span>
</button>
</div>
</div>
<!-- Authentication Config -->
<t-collapse :default-value="[]">
<t-collapse-panel :header="t('mcpServiceDialog.authConfig')" value="auth">
<!--
Edit mode: credentials live behind a dedicated subresource. The
CredentialResource component drives configured/unconfigured/editing
state per field and commits each change to /credentials directly,
decoupling credential edits from the surrounding form.
<div class="form-item">
<label class="form-label required">{{ t('mcpServiceDialog.serviceUrl') }}</label>
<t-input v-model="formData.url" :placeholder="t('mcpServiceDialog.serviceUrlPlaceholder')" />
</div>
</section>
Add mode: the resource doesn't exist yet, so we accept the initial
credentials as plain inputs and POST them together with the rest of
the service in handleSubmit. From the second save onwards, the
edit-mode path takes over.
-->
<CredentialResource v-if="mode === 'edit' && props.service?.id" :api="credentialApi"
:fields="credentialFields" :meta="credentialMeta" />
<template v-else>
<t-form-item :label="t('mcpServiceDialog.apiKey')">
<t-input v-model="formData.auth_config.api_key" type="password"
:placeholder="t('mcpServiceDialog.optional')" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.bearerToken')">
<t-input v-model="formData.auth_config.token" type="password"
:placeholder="t('mcpServiceDialog.optional')" />
</t-form-item>
</template>
</t-collapse-panel>
<!-- Section 3 — 认证配置(API Key / Bearer Token) -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.authConfig') }}</h4>
<!-- Advanced Config -->
<t-collapse-panel :header="t('mcpServiceDialog.advancedConfig')" value="advanced">
<t-form-item :label="t('mcpServiceDialog.timeoutSec')">
<t-input-number v-model="formData.advanced_config.timeout" :min="1" :max="300" placeholder="30" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.retryCount')">
<t-input-number v-model="formData.advanced_config.retry_count" :min="0" :max="10" placeholder="3" />
</t-form-item>
<t-form-item :label="t('mcpServiceDialog.retryDelaySec')">
<t-input-number v-model="formData.advanced_config.retry_delay" :min="0" :max="60" placeholder="1" />
</t-form-item>
</t-collapse-panel>
</t-collapse>
<!--
Edit 模式下凭证由 CredentialResource 管理(独立的 /credentials
子资源调用),不与本表单 submit 耦合;Create 模式下用 plain
password input + lock prefix-icon。两个字段都是 optional —
MCP 服务可能完全不需要鉴权(依赖 IP 白名单等)。
-->
<CredentialResource
v-if="mode === 'edit' && props.service?.id"
:api="credentialApi"
:fields="credentialFields"
:meta="credentialMeta"
/>
<template v-else>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.apiKey') }}</label>
<t-input
v-model="formData.auth_config.api_key"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.bearerToken') }}</label>
<t-input
v-model="formData.auth_config.token"
type="password"
:placeholder="t('mcpServiceDialog.optional')"
>
<template #prefix-icon><t-icon name="lock-on" /></template>
</t-input>
</div>
</template>
</section>
<!-- Section 4 — 高级配置(超时/重试),改用带后缀单位的轻量数字输入框,
不再用 t-input-number 的加减器(步进按钮在这里没必要,用户更倾向直接键入)。 -->
<section class="setting-drawer__section">
<h4 class="setting-drawer__section-title">{{ t('mcpServiceDialog.advancedConfig') }}</h4>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.timeoutSec') }}</label>
<t-input
v-model="advancedTimeoutText"
type="number"
:min="1"
:max="300"
placeholder="30"
class="number-input"
@blur="onAdvancedNumberBlur('timeout', 30, 1, 300)"
>
<template #suffix>
<span class="number-input__unit">{{ t('mcpServiceDialog.unitSecond', '秒') }}</span>
</template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.retryCount') }}</label>
<t-input
v-model="advancedRetryCountText"
type="number"
:min="0"
:max="10"
placeholder="3"
class="number-input"
@blur="onAdvancedNumberBlur('retry_count', 3, 0, 10)"
>
<template #suffix>
<span class="number-input__unit">{{ t('mcpServiceDialog.unitTimes', '次') }}</span>
</template>
</t-input>
</div>
<div class="form-item">
<label class="form-label">{{ t('mcpServiceDialog.retryDelaySec') }}</label>
<t-input
v-model="advancedRetryDelayText"
type="number"
:min="0"
:max="60"
placeholder="1"
class="number-input"
@blur="onAdvancedNumberBlur('retry_delay', 1, 0, 60)"
>
<template #suffix>
<span class="number-input__unit">{{ t('mcpServiceDialog.unitSecond', '秒') }}</span>
</template>
</t-input>
</div>
</section>
</t-form>
</SettingDrawer>
</template>
@@ -87,8 +231,10 @@ import {
updateMCPService,
putMCPCredentials,
deleteMCPCredentialField,
testMCPService,
type MCPService,
type McpCredentialField,
type MCPTestResult,
} from '@/api/mcp-service'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import CredentialResource, {
@@ -105,6 +251,11 @@ interface Props {
interface Emits {
(e: 'update:visible', value: boolean): void
(e: 'success'): void
// Fired after a /test call inside the drawer so the parent can reuse its
// existing McpTestResult dialog. We deliberately don't render that dialog
// here — the parent owns the test-result dialog state across multiple
// entry points (drawer test button, list 行操作菜单 used to call it too).
(e: 'test', payload: { service: MCPService; result: MCPTestResult }): void
}
const props = defineProps<Props>()
@@ -132,6 +283,16 @@ const formData = ref({
},
})
// Header icon name + transport label, mirrored from McpSettings list cards
// so the list-card → drawer hand-off stays visually continuous.
const transportIcon = computed(() => {
return formData.value.transport_type === 'http-streamable' ? 'link' : 'cast'
})
const transportLabel = computed(() => {
return formData.value.transport_type === 'http-streamable' ? 'HTTP Streamable' : 'SSE'
})
// Field metadata for the credential subresource. Keep label keys local to
// MCP so other resources don't accidentally inherit "API Key" / "Bearer
// Token" labels via the shared component.
@@ -189,6 +350,100 @@ const dialogVisible = computed({
set: (value) => emit('update:visible', value),
})
// ---- Test connection state (in-drawer) ----
const testing = ref(false)
// Tri-state icon hint on the test button: null=neutral, true=just succeeded,
// false=just failed. Cleared when transport/url change so a stale ✓/✗
// doesn't sit next to a config the user is now editing.
const lastTestOk = ref<boolean | null>(null)
watch(
() => [formData.value.transport_type, formData.value.url],
() => {
lastTestOk.value = null
},
)
async function handleTestConnection() {
if (!props.service?.id) return
testing.value = true
MessagePlugin.info({
content: t('mcpSettings.toasts.testing', { name: props.service.name || '' }),
duration: 0,
closeBtn: false,
})
try {
const result = await testMCPService(props.service.id)
MessagePlugin.closeAll()
const safe: MCPTestResult = result ?? {
success: false,
message: t('mcpSettings.toasts.noResponse') as string,
}
lastTestOk.value = safe.success === true
emit('test', { service: props.service, result: safe })
} catch (error: any) {
MessagePlugin.closeAll()
const errorMessage =
error?.response?.data?.error?.message ||
error?.message ||
(t('mcpSettings.toasts.testFailed') as string)
console.error('Failed to test MCP service:', error)
lastTestOk.value = false
emit('test', {
service: props.service,
result: { success: false, message: errorMessage },
})
} finally {
testing.value = false
}
}
// ---- Advanced numeric inputs (text-bound proxies) ----
// We bind text instead of v-model directly to advanced_config.<n> so the
// user can clear the field and see the placeholder while typing. On blur
// we coerce, clamp, and write back; bad values fall back to the default.
const advancedTimeoutText = computed<string>({
get: () => String(formData.value.advanced_config.timeout ?? ''),
set: (v) => { formData.value.advanced_config.timeout = parseSloppyInt(v) ?? 30 },
})
const advancedRetryCountText = computed<string>({
get: () => String(formData.value.advanced_config.retry_count ?? ''),
set: (v) => { formData.value.advanced_config.retry_count = parseSloppyInt(v) ?? 3 },
})
const advancedRetryDelayText = computed<string>({
get: () => String(formData.value.advanced_config.retry_delay ?? ''),
set: (v) => { formData.value.advanced_config.retry_delay = parseSloppyInt(v) ?? 1 },
})
// Permissive int parser — keeps '' / NaN inputs as null instead of 0 so the
// field can stay visually empty while the user is still typing. Negative
// numbers and non-int chars are rejected (returns null).
function parseSloppyInt(raw: string): number | null {
if (raw == null) return null
const s = String(raw).trim()
if (!s) return null
const n = Number(s)
if (!Number.isFinite(n)) return null
return Math.trunc(n)
}
function onAdvancedNumberBlur(
field: 'timeout' | 'retry_count' | 'retry_delay',
fallback: number,
min: number,
max: number,
) {
const cur = formData.value.advanced_config[field]
if (cur == null || !Number.isFinite(cur)) {
formData.value.advanced_config[field] = fallback
return
}
// Clamp to [min, max] on blur — gives the input "settled" feedback even
// though native type=number doesn't enforce its own min/max attribute
// for typed values (only for stepper buttons).
formData.value.advanced_config[field] = Math.min(max, Math.max(min, cur))
}
const resetForm = () => {
formData.value = {
name: '',
@@ -205,6 +460,8 @@ const resetForm = () => {
watch(
() => props.service,
(service) => {
// 切到不同服务(或新增)时清空上次测试反馈,避免旧的 ✓/✗ 漂在新表单上
lastTestOk.value = null
if (service) {
const transportType = service.transport_type === 'stdio' ? 'sse' : (service.transport_type || 'sse')
formData.value = {
@@ -279,5 +536,183 @@ const handleClose = () => {
</script>
<style scoped lang="less">
/* Stdio-related styles removed as stdio transport is disabled for security reasons */
// ---- 抽屉内容 — 与 ModelEditorDialog 同款约定 ----
.form-item {
margin-bottom: 0;
}
.form-label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--td-text-color-primary);
line-height: 1.4;
&.required::before {
content: '*';
color: var(--td-error-color);
margin-right: 4px;
font-weight: 500;
line-height: 1;
}
}
.form-desc {
margin: 4px 0 0 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-text-color-placeholder);
&--inline {
margin: 0;
}
}
:deep(.t-input),
:deep(.t-select),
:deep(.t-textarea),
:deep(.t-input-number) {
width: 100%;
font-size: 13px;
}
// 隐藏 t-form 默认 form-item 容器 — 走自定义 .form-item / .form-label
:deep(.t-form) .t-form-item {
display: none;
}
// ---- 紧凑 pill segmented(transport 切换) ----
.source-options {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 3px;
background: var(--td-bg-color-component);
border: 1px solid var(--td-component-stroke);
border-radius: 8px;
}
.source-option {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 12px;
height: 28px;
background: transparent;
border: 1px solid transparent;
border-radius: 6px;
cursor: pointer;
font-family: inherit;
font-size: 13px;
color: var(--td-text-color-secondary);
line-height: 1;
transition: all 0.15s ease;
&:hover:not(.is-active) {
color: var(--td-text-color-primary);
background: var(--td-bg-color-container-hover);
}
&.is-active {
background: var(--td-bg-color-container);
border-color: var(--td-brand-color);
color: var(--td-brand-color);
font-weight: 500;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
}
}
.source-option__icon {
font-size: 14px;
flex-shrink: 0;
}
.source-option__label {
white-space: nowrap;
}
.vision-toggle {
display: flex;
align-items: center;
gap: 8px;
}
// ---- 高级配置数字输入:替代 t-input-number 的步进按钮,更轻量 ----
// 用普通 t-input + suffix 单位 + type=number。原生 number 输入会
// 在 Chrome 上显示一对 spin button,scoped 里把它们隐藏掉以保持视觉
// 干净。最大/最小值通过 onBlur clamp,而不是依赖原生 step 限制。
.number-input {
:deep(input::-webkit-outer-spin-button),
:deep(input::-webkit-inner-spin-button) {
-webkit-appearance: none;
appearance: none;
margin: 0;
}
// Firefox 把 type=number 渲染成 textfield 风格更好看
:deep(input[type="number"]) {
-moz-appearance: textfield;
appearance: textfield;
}
}
.number-input__unit {
font-size: 12px;
color: var(--td-text-color-placeholder);
user-select: none;
}
// ---- footer-left 测试按钮的状态 icon ----
.status-icon {
font-size: 16px;
flex-shrink: 0;
&.available {
color: var(--td-brand-color);
}
&.unavailable {
color: var(--td-error-color);
}
}
// ---- 副标题里的小标签 ----
.subtitle-tag {
display: inline-flex;
align-items: center;
padding: 0 6px;
margin-left: 6px;
height: 16px;
font-size: 10px;
font-weight: 500;
border-radius: 3px;
&--ok {
color: var(--td-success-color);
background: var(--td-success-color-light);
}
&--muted {
color: var(--td-text-color-placeholder);
background: var(--td-bg-color-component);
}
}
</style>
<!--
Non-scoped block: per-transport header-icon coloring. Mirrors the matching
.service-card--{transport} .service-card__badge in McpSettings so the
list-card → drawer hand-off stays visually continuous.
-->
<style lang="less">
.mcp-drawer--sse .setting-drawer__header-icon {
background: rgba(17, 128, 83, 0.12);
color: #118053;
}
.mcp-drawer--http-streamable .setting-drawer__header-icon {
background: rgba(0, 82, 217, 0.1);
color: #0052D9;
}
</style>