fix: improve model editor connection tests and save flow
parent
935b456c3c
commit
fbad5b3730
|
|
@ -1,18 +1,14 @@
|
|||
<template>
|
||||
<SettingDrawer :visible="dialogVisible" :title="isEdit ? $t('model.editor.editTitle') : $t('model.editor.addTitle')"
|
||||
:description="getModalDescription()" :icon="modelTypeIcon" :confirm-loading="saving"
|
||||
:description="getModalDescription()" :icon="modelTypeIcon" :confirm-loading="saving" :cancel-disabled="saving"
|
||||
:confirm-text="$t('model.editor.saveAndClose')"
|
||||
:close-on-overlay-click="!saving" :close-on-esc-keydown="!saving"
|
||||
:confirm-disabled="formData.provider === 'weknoracloud' && wkcCredentialState !== 'configured'"
|
||||
@update:visible="(v: boolean) => dialogVisible = v" @confirm="handleConfirm" @cancel="handleCancel">
|
||||
|
||||
<!--
|
||||
Footer-left slot: connection-test button lives here so it sits next to
|
||||
Save/Cancel — primary actions all aligned along the bottom of the
|
||||
drawer. Avoids the "test, then scroll back down to save" dance.
|
||||
Mirrors the pattern used in WebSearchSettings' provider drawer.
|
||||
-->
|
||||
<template v-if="formData.source === 'remote'" #footer-left>
|
||||
<t-button variant="outline" @click="checkRemoteAPI" :loading="checking"
|
||||
:disabled="!formData.modelName || (!formData.baseUrl && formData.provider !== 'weknoracloud') || (formData.provider === 'weknoracloud' && wkcCredentialState !== 'configured')">
|
||||
:disabled="saving || !formData.modelName || (!formData.baseUrl && formData.provider !== 'weknoracloud') || (formData.provider === 'weknoracloud' && wkcCredentialState !== 'configured')">
|
||||
<template #icon>
|
||||
<t-icon v-if="!checking && remoteChecked && remoteAvailable" name="check-circle-filled"
|
||||
class="status-icon available" />
|
||||
|
|
@ -21,13 +17,32 @@
|
|||
</template>
|
||||
{{ checking ? $t('model.editor.testing') : $t('model.editor.testConnection') }}
|
||||
</t-button>
|
||||
<span v-if="remoteChecked" :class="['footer-test-message', remoteAvailable ? 'success' : 'error']"
|
||||
:title="remoteMessage">
|
||||
{{ remoteMessage }}
|
||||
<span v-if="remoteChecked" :class="['connection-status', remoteAvailable ? 'success' : 'error']">
|
||||
{{ remoteAvailable ? $t('model.editor.connectionSuccess') : $t('model.editor.connectionFailed') }}
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<t-form ref="formRef" :data="formData" :rules="rules" layout="vertical">
|
||||
<template #footer-extra>
|
||||
<div v-if="saveError" class="connection-result error" role="alert">
|
||||
<strong>{{ $t('modelSettings.toasts.saveFailed') }}</strong>
|
||||
<div class="connection-result__details" tabindex="0">{{ saveError }}</div>
|
||||
</div>
|
||||
<div v-if="formData.source === 'remote'" class="connection-feedback" aria-live="polite">
|
||||
<p class="connection-hint">{{ $t(isEdit ? 'model.editor.testDraftEditHint' : 'model.editor.testDraftHint') }}</p>
|
||||
<p v-if="remoteStale" class="connection-hint">{{ $t('model.editor.testStale') }}</p>
|
||||
<div v-if="remoteChecked && !remoteAvailable" class="connection-result error">
|
||||
<div class="connection-result__header">
|
||||
<strong>{{ $t('model.editor.connectionFailed') }}</strong>
|
||||
<t-button size="small" variant="text" @click="copyWithToast(remoteMessage, 'common.copied')">
|
||||
{{ $t('common.copy') }}
|
||||
</t-button>
|
||||
</div>
|
||||
<div class="connection-result__details" tabindex="0">{{ remoteMessage }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<t-form :inert="saving || undefined" ref="formRef" :data="formData" :rules="rules" layout="vertical">
|
||||
|
||||
<section v-if="!isEdit" class="setting-drawer__section">
|
||||
<h4 class="setting-drawer__section-title">{{ $t('model.editor.sectionType') }}</h4>
|
||||
|
|
@ -249,7 +264,7 @@
|
|||
show/hide eye toggle.
|
||||
-->
|
||||
<CredentialResource v-if="isEdit && props.modelData?.id" :api="credentialApi" :fields="credentialFields"
|
||||
:meta="credentialMeta" />
|
||||
:meta="credentialMeta" @changed="invalidateConnectionTest()" />
|
||||
<t-input v-else v-model="formData.apiKey" :type="showApiKey ? 'text' : 'password'"
|
||||
:placeholder="isSignedRerank ? signedRerankAccessKeyPlaceholder : apiKeyPlaceholder"
|
||||
class="api-key-input" autocomplete="off" spellcheck="false">
|
||||
|
|
@ -420,6 +435,7 @@ import {
|
|||
type ThinkingControlValue,
|
||||
} from '@/utils/thinkingControl'
|
||||
import { DEFAULT_MODEL_CONTEXT_WINDOW } from '@/utils/contextWindow'
|
||||
import { copyWithToast } from '@/utils/clipboard'
|
||||
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
|
||||
import CredentialResource, {
|
||||
type CredentialFieldDef,
|
||||
|
|
@ -466,6 +482,7 @@ interface Props {
|
|||
visible: boolean
|
||||
modelType: EditorModelType
|
||||
modelData?: ModelFormData | null
|
||||
saveModel: (data: ModelFormData & { modelType?: EditorModelType }) => Promise<void>
|
||||
}
|
||||
|
||||
const { t, te } = useI18n()
|
||||
|
|
@ -478,7 +495,6 @@ const props = withDefaults(defineProps<Props>(), {
|
|||
|
||||
const emit = defineEmits<{
|
||||
'update:visible': [value: boolean]
|
||||
'confirm': [data: ModelFormData & { modelType?: EditorModelType }]
|
||||
}>()
|
||||
|
||||
const draftModelType = ref<EditorModelType>(props.modelType)
|
||||
|
|
@ -683,7 +699,9 @@ const providerOptions = computed(() => {
|
|||
|
||||
const dialogVisible = computed({
|
||||
get: () => props.visible,
|
||||
set: (val) => emit('update:visible', val)
|
||||
set: (val) => {
|
||||
if (!saving.value) emit('update:visible', val)
|
||||
}
|
||||
})
|
||||
|
||||
const showThinkingControlField = computed(() =>
|
||||
|
|
@ -825,6 +843,20 @@ const apiKeyPlaceholder = computed(() => t('model.editor.apiKeyPlaceholder'))
|
|||
|
||||
const formRef = ref()
|
||||
const saving = ref(false)
|
||||
const saveError = ref('')
|
||||
|
||||
// Settings itself listens on window for Escape. Capture it while saving so
|
||||
// the parent cannot unmount this editor before the request finishes.
|
||||
const handleSaveEscape = (event: KeyboardEvent) => {
|
||||
if (props.visible && saving.value && (event.key === 'Escape' || event.code === 'Escape')) {
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
}
|
||||
}
|
||||
watch(() => props.visible && saving.value, (locked) => {
|
||||
if (locked) window.addEventListener('keydown', handleSaveEscape, true)
|
||||
else window.removeEventListener('keydown', handleSaveEscape, true)
|
||||
}, { flush: 'sync' })
|
||||
// Toggles the create-mode API key input between masked and plain text. Lets
|
||||
// the user proofread a freshly pasted secret without losing the password
|
||||
// affordance for everyday use. Reset every time the drawer closes (see
|
||||
|
|
@ -837,6 +869,31 @@ const checking = ref(false)
|
|||
const remoteChecked = ref(false)
|
||||
const remoteAvailable = ref(false)
|
||||
const remoteMessage = ref('')
|
||||
const remoteStale = ref(false)
|
||||
let connectionRevision = 0
|
||||
let applyingDetectedDimension = false
|
||||
|
||||
// Invalidate pending responses too, even when the user changes a field back.
|
||||
const invalidateConnectionTest = (showStale = true) => {
|
||||
connectionRevision++
|
||||
remoteStale.value = showStale && (remoteStale.value || checking.value || remoteChecked.value)
|
||||
checking.value = false
|
||||
remoteChecked.value = false
|
||||
remoteAvailable.value = false
|
||||
remoteMessage.value = ''
|
||||
dimensionChecked.value = false
|
||||
dimensionSuccess.value = false
|
||||
dimensionMessage.value = ''
|
||||
}
|
||||
|
||||
const applyDetectedDimension = (dimension: number) => {
|
||||
applyingDetectedDimension = true
|
||||
try {
|
||||
formData.value.dimension = dimension
|
||||
} finally {
|
||||
applyingDetectedDimension = false
|
||||
}
|
||||
}
|
||||
const dimensionChecked = ref(false)
|
||||
const dimensionSuccess = ref(false)
|
||||
const dimensionMessage = ref('')
|
||||
|
|
@ -1121,6 +1178,25 @@ watch(() => props.visible, (val) => {
|
|||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [
|
||||
activeModelType.value, props.modelData?.id, formData.value.source,
|
||||
formData.value.provider, formData.value.modelName, formData.value.baseUrl,
|
||||
formData.value.apiKey, formData.value.appSecret, formData.value.customHeaders,
|
||||
formData.value.dimension, formData.value.supportsDimensionOverride,
|
||||
formData.value.lkeapRegion, formData.value.thinkingControl,
|
||||
],
|
||||
() => {
|
||||
if (!applyingDetectedDimension) invalidateConnectionTest(props.visible && !hydratingForm.value)
|
||||
},
|
||||
{ deep: true, flush: 'sync' },
|
||||
)
|
||||
|
||||
watch(() => props.visible, () => {
|
||||
invalidateConnectionTest(false)
|
||||
saveError.value = ''
|
||||
}, { flush: 'sync' })
|
||||
|
||||
// 重置表单
|
||||
const resetForm = () => {
|
||||
thinkingControlManual.value = false
|
||||
|
|
@ -1319,10 +1395,12 @@ const checkModelStatus = async () => {
|
|||
|
||||
// 检查 Ollama 本地 Embedding 模型维度
|
||||
const checkOllamaDimension = async () => {
|
||||
if (checking.value || saving.value) return
|
||||
if (!formData.value.modelName || formData.value.source !== 'local' || activeModelType.value !== 'embedding') {
|
||||
return
|
||||
}
|
||||
|
||||
const revision = ++connectionRevision
|
||||
checking.value = true
|
||||
dimensionChecked.value = false
|
||||
dimensionMessage.value = ''
|
||||
|
|
@ -1335,11 +1413,12 @@ const checkOllamaDimension = async () => {
|
|||
supportsDimensionOverride: formData.value.supportsDimensionOverride ?? false,
|
||||
})
|
||||
|
||||
if (revision !== connectionRevision) return
|
||||
dimensionChecked.value = true
|
||||
dimensionSuccess.value = result.available || false
|
||||
|
||||
if (result.available && result.dimension) {
|
||||
formData.value.dimension = result.dimension
|
||||
applyDetectedDimension(result.dimension)
|
||||
dimensionMessage.value = t('model.editor.dimensionDetected', { value: result.dimension })
|
||||
MessagePlugin.success(dimensionMessage.value)
|
||||
} else {
|
||||
|
|
@ -1350,24 +1429,28 @@ const checkOllamaDimension = async () => {
|
|||
MessagePlugin.warning(dimensionMessage.value)
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (revision !== connectionRevision) return
|
||||
console.error('Ollama dimension check failed:', error)
|
||||
dimensionChecked.value = true
|
||||
dimensionSuccess.value = false
|
||||
dimensionMessage.value = t('model.editor.dimensionFailed')
|
||||
MessagePlugin.error(dimensionMessage.value)
|
||||
} finally {
|
||||
checking.value = false
|
||||
if (revision === connectionRevision) checking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 Remote API 连接(根据模型类型调用不同的接口)
|
||||
const checkRemoteAPI = async () => {
|
||||
if (checking.value || saving.value) return
|
||||
if (!formData.value.modelName || (!formData.value.baseUrl && formData.value.provider !== 'weknoracloud')) {
|
||||
MessagePlugin.warning(t('model.editor.fillModelAndUrl'))
|
||||
return
|
||||
}
|
||||
|
||||
const revision = ++connectionRevision
|
||||
checking.value = true
|
||||
remoteStale.value = false
|
||||
remoteChecked.value = false
|
||||
remoteMessage.value = ''
|
||||
|
||||
|
|
@ -1425,10 +1508,8 @@ const checkRemoteAPI = async () => {
|
|||
...headerPayload,
|
||||
})
|
||||
// 如果测试成功且返回了维度,自动填充
|
||||
if (result.available && result.dimension) {
|
||||
formData.value.dimension = result.dimension
|
||||
MessagePlugin.info(t('model.editor.remoteDimensionDetected', { value: result.dimension }))
|
||||
}
|
||||
if (revision !== connectionRevision) return
|
||||
if (result.available && result.dimension) applyDetectedDimension(result.dimension)
|
||||
break
|
||||
|
||||
case 'rerank': {
|
||||
|
|
@ -1488,37 +1569,28 @@ const checkRemoteAPI = async () => {
|
|||
return
|
||||
}
|
||||
|
||||
if (revision !== connectionRevision) return
|
||||
remoteChecked.value = true
|
||||
remoteAvailable.value = result.available || false
|
||||
// 之前这里把 backend 的错误 message 只丢到 console.debug,用户只能
|
||||
// 看到通用的 "连接失败" toast,根本看不出是 401 / 404 / 模型不存在
|
||||
// 还是别的什么。改成:成功时用 i18n 通用提示;失败时直接展示后端
|
||||
// 给到的具体原因(已经在后端 classifyConnectionError 中包了一层
|
||||
// 易读的中文 hint + 原始 SDK 报错),方便排查。
|
||||
if (result.available) {
|
||||
remoteMessage.value = t('model.editor.connectionSuccess')
|
||||
MessagePlugin.success(remoteMessage.value)
|
||||
} else {
|
||||
remoteMessage.value = result.message || t('model.editor.connectionFailed')
|
||||
console.debug('Backend message:', result.message)
|
||||
MessagePlugin.error(remoteMessage.value)
|
||||
}
|
||||
remoteMessage.value = result.available
|
||||
? t('model.editor.connectionSuccess')
|
||||
: result.message || t('model.editor.connectionFailed')
|
||||
} catch (error: any) {
|
||||
console.error('Remote API check failed:', error)
|
||||
if (revision !== connectionRevision) return
|
||||
remoteChecked.value = true
|
||||
remoteAvailable.value = false
|
||||
// 后端 4xx/5xx(如 SSRF 校验失败)会走到这里。axios 拦截器把后端
|
||||
// { error: { message: "..." } } 提到了 error.message,里面已经包含
|
||||
// 易读 hint + 原因,直接展示出来,比通用 "请检查配置" 有用得多。
|
||||
remoteMessage.value = error?.message || t('model.editor.connectionConfigError')
|
||||
MessagePlugin.error(remoteMessage.value)
|
||||
} finally {
|
||||
checking.value = false
|
||||
if (revision === connectionRevision) checking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 确认保存
|
||||
const handleConfirm = async () => {
|
||||
if (saving.value) return
|
||||
saving.value = true
|
||||
if (checking.value) invalidateConnectionTest()
|
||||
saveError.value = ''
|
||||
try {
|
||||
// 手动校验必填字段
|
||||
if (!formData.value.modelName || !formData.value.modelName.trim()) {
|
||||
|
|
@ -1548,30 +1620,30 @@ const handleConfirm = async () => {
|
|||
}
|
||||
|
||||
// 执行表单验证
|
||||
await formRef.value?.validate()
|
||||
const validation = await formRef.value?.validate()
|
||||
if (validation !== undefined && validation !== true) return
|
||||
|
||||
// Credential removal in edit mode is handled inline by the
|
||||
// CredentialResource card (it confirms + DELETEs to /credentials), so
|
||||
// the main save flow no longer needs to confirm or handle clear flags.
|
||||
|
||||
saving.value = true
|
||||
|
||||
// 如果是新增且没有 id,生成一个
|
||||
if (!formData.value.id) {
|
||||
formData.value.id = generateId()
|
||||
}
|
||||
|
||||
emit('confirm', {
|
||||
await props.saveModel({
|
||||
...formData.value,
|
||||
...(isEdit.value ? {} : { modelType: activeModelType.value }),
|
||||
})
|
||||
dialogVisible.value = false
|
||||
emit('update:visible', false)
|
||||
invalidateConnectionTest(false)
|
||||
// 保存成功后重置草稿,下次打开新增模型时是空白
|
||||
resetForm()
|
||||
lastOpenedModelId.value = null
|
||||
// 移除此处的成功提示,由父组件统一处理
|
||||
} catch (error) {
|
||||
console.error('表单验证失败:', error)
|
||||
} catch (error: any) {
|
||||
saveError.value = error?.message || t('modelSettings.toasts.saveFailed')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
|
|
@ -1666,6 +1738,8 @@ const startDownload = async (modelName: string) => {
|
|||
|
||||
// 组件卸载时清理定时器
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('keydown', handleSaveEscape, true)
|
||||
invalidateConnectionTest(false)
|
||||
if (downloadInterval) {
|
||||
clearInterval(downloadInterval)
|
||||
}
|
||||
|
|
@ -1713,6 +1787,7 @@ watch(() => formData.value.modelName, () => {
|
|||
|
||||
// 取消(点击底部"取消"按钮触发;点遮罩/ESC 不触发,从而保留草稿)
|
||||
const handleCancel = () => {
|
||||
if (saving.value) return
|
||||
resetForm()
|
||||
lastOpenedModelId.value = null
|
||||
dialogVisible.value = false
|
||||
|
|
@ -1953,24 +2028,43 @@ const handleCancel = () => {
|
|||
}
|
||||
}
|
||||
|
||||
// Connection-test message rendered next to the test button in the drawer
|
||||
// footer. Truncates with ellipsis so a long backend error doesn't push
|
||||
// Save/Cancel off-screen — the full text is in the title attribute.
|
||||
.footer-test-message {
|
||||
.connection-status {
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
&.success { color: var(--td-brand-color-active); }
|
||||
&.error { color: var(--td-error-color); }
|
||||
}
|
||||
|
||||
&.success {
|
||||
color: var(--td-brand-color-active);
|
||||
.connection-hint {
|
||||
margin: 0 0 8px;
|
||||
color: var(--td-text-color-secondary);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.connection-result {
|
||||
margin-bottom: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--td-error-color-3);
|
||||
border-radius: var(--td-radius-default);
|
||||
background: var(--td-error-color-1);
|
||||
color: var(--td-error-color);
|
||||
font-size: 12px;
|
||||
text-align: left;
|
||||
|
||||
&__header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&.error {
|
||||
color: var(--td-error-color);
|
||||
&__details {
|
||||
max-height: min(160px, 20vh);
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.5;
|
||||
user-select: text;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,325 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
import test from 'node:test'
|
||||
import { compileScript, parse } from '@vue/compiler-sfc'
|
||||
import ts from 'typescript'
|
||||
import { createRenderer, h, nextTick, reactive } from 'vue'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const filename = fileURLToPath(new URL('./ModelEditorDialog.vue', import.meta.url))
|
||||
const { descriptor } = parse(readFileSync(filename, 'utf8'), { filename })
|
||||
const script = compileScript(descriptor, { id: 'model-editor-flow-test' }).content
|
||||
.replace('__expose();', '')
|
||||
.replace('return __returned__', '__expose(__returned__); return __returned__')
|
||||
const compiled = ts.transpileModule(script, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: unknown) => void
|
||||
const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
type Result = { available: boolean; message?: string; dimension?: number }
|
||||
async function fixture(options: {
|
||||
type?: string
|
||||
edit?: boolean
|
||||
check?: (payload: any) => Promise<Result>
|
||||
save?: (payload: any) => Promise<void>
|
||||
} = {}) {
|
||||
const requests: any[] = []
|
||||
const saves: any[] = []
|
||||
const toasts: string[] = []
|
||||
const visibility: boolean[] = []
|
||||
const props = reactive({
|
||||
visible: false,
|
||||
modelType: options.type || 'chat',
|
||||
modelData: options.edit ? {
|
||||
id: 'saved-model', modelName: 'old-model', name: '', source: 'remote',
|
||||
baseUrl: 'https://example.com/v1', provider: 'generic', isDefault: false,
|
||||
} : null,
|
||||
})
|
||||
const check = async (payload: any) => {
|
||||
requests.push(payload)
|
||||
return options.check ? options.check(payload) : { available: true }
|
||||
}
|
||||
const exports: any = {}
|
||||
runInNewContext(compiled, {
|
||||
exports, URL, setInterval, clearInterval,
|
||||
window: { addEventListener() {}, removeEventListener() {} },
|
||||
console: { error() {}, debug() {}, log() {} },
|
||||
require(name: string) {
|
||||
if (name === 'vue') return require('vue')
|
||||
if (name === 'vue-i18n') return { useI18n: () => ({ t: (key: string) => key, te: () => false }) }
|
||||
if (name === '@/stores/ui') return { useUIStore: () => ({}) }
|
||||
if (name === 'tdesign-vue-next') return {
|
||||
MessagePlugin: Object.fromEntries(['success', 'error', 'warning', 'info'].map(key => [key, (text: string) => toasts.push(text)])),
|
||||
}
|
||||
if (name === '@/api/initialization') return {
|
||||
checkRemoteModel: check, testEmbeddingModel: check, checkRerankModel: check, checkASRModel: check,
|
||||
listModelProviders: async () => [], checkOllamaStatus: async () => ({ available: false }),
|
||||
}
|
||||
if (name === '@/utils/thinkingControl') return require('../utils/thinkingControl.ts')
|
||||
if (name === '@/utils/contextWindow') return require('../utils/contextWindow.ts')
|
||||
if (name === '@/components/modelEditorSourceState') return require('./modelEditorSourceState.ts')
|
||||
return { default: {} }
|
||||
},
|
||||
})
|
||||
exports.default.render = () => null
|
||||
const renderer = createRenderer<any, any>({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert() {}, remove() {}, setElementText() {}, setText() {}, patchProp() {},
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
let vm: any
|
||||
const app = renderer.createApp({
|
||||
setup: () => () => h(exports.default, {
|
||||
...props,
|
||||
ref: (value: any) => { vm = value },
|
||||
saveModel: async (payload: any) => { saves.push(payload); await options.save?.(payload) },
|
||||
'onUpdate:visible': (value: boolean) => { visibility.push(value); props.visible = value },
|
||||
}),
|
||||
})
|
||||
app.mount({})
|
||||
props.visible = true
|
||||
await nextTick()
|
||||
await nextTick()
|
||||
Object.assign(vm.formData, { modelName: 'draft-model', baseUrl: 'https://example.com/v1', apiKey: options.edit ? '' : 'draft-key' })
|
||||
vm.formRef = { validate: async () => true }
|
||||
await nextTick()
|
||||
return { vm, props, requests, saves, toasts, visibility, close: () => app.unmount() }
|
||||
}
|
||||
|
||||
for (const type of ['chat', 'embedding', 'rerank', 'vllm', 'asr']) {
|
||||
test(`${type}: connection tests use unsaved form values without saving`, async () => {
|
||||
const f = await fixture({ type })
|
||||
try {
|
||||
f.vm.formData.customHeaders = [{ key: ' X-Test ', value: ' draft ' }]
|
||||
await f.vm.checkRemoteAPI()
|
||||
assert.equal(f.requests[0].modelName, 'draft-model')
|
||||
assert.equal(f.requests[0].apiKey, 'draft-key')
|
||||
assert.equal(f.requests[0].customHeaders['X-Test'], 'draft')
|
||||
assert.equal(f.saves.length, 0)
|
||||
assert.equal(f.props.visible, true)
|
||||
assert.equal(f.vm.remoteAvailable, true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('editing keeps the saved-key fallback and invalidates results after credential changes', async () => {
|
||||
const f = await fixture({ edit: true })
|
||||
try {
|
||||
await f.vm.checkRemoteAPI()
|
||||
assert.equal(f.requests[0].modelId, 'saved-model')
|
||||
assert.equal(f.requests[0].apiKey, '')
|
||||
f.vm.invalidateConnectionTest()
|
||||
assert.equal(f.vm.remoteChecked, false)
|
||||
assert.equal(f.vm.remoteStale, true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('long backend errors remain complete inline without duplicate error toasts', async () => {
|
||||
const message = 'Upstream rejected request\n' + 'diagnostic '.repeat(1000)
|
||||
for (const rejects of [false, true]) {
|
||||
const f = await fixture({ check: async () => {
|
||||
if (rejects) throw new Error(message)
|
||||
return { available: false, message }
|
||||
} })
|
||||
try {
|
||||
await f.vm.checkRemoteAPI()
|
||||
assert.equal(f.vm.remoteChecked, true)
|
||||
assert.equal(f.vm.remoteAvailable, false)
|
||||
assert.equal(f.vm.remoteMessage, message)
|
||||
assert.deepEqual(f.toasts, [])
|
||||
} finally { f.close() }
|
||||
}
|
||||
})
|
||||
|
||||
test('connection edits invalidate results; display-only edits preserve them', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
await f.vm.checkRemoteAPI()
|
||||
f.vm.formData.displayName = 'Display only'
|
||||
assert.equal(f.vm.remoteChecked, true)
|
||||
for (const patch of [
|
||||
{ modelName: 'other' }, { baseUrl: 'https://other.example/v1' },
|
||||
{ apiKey: 'another-key' }, { customHeaders: [{ key: 'X-Test', value: 'one' }] },
|
||||
{ dimension: 1024 }, { supportsDimensionOverride: true },
|
||||
]) {
|
||||
Object.assign(f.vm.formData, patch)
|
||||
assert.equal(f.vm.remoteChecked, false)
|
||||
assert.equal(f.vm.remoteStale, true)
|
||||
await f.vm.checkRemoteAPI()
|
||||
}
|
||||
f.vm.formData.customHeaders[0].value = 'two'
|
||||
assert.equal(f.vm.remoteChecked, false, 'nested header edits invalidate immediately')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('late responses cannot overwrite newer results, including after reverting a field', async () => {
|
||||
const old = deferred<Result>()
|
||||
let calls = 0
|
||||
const f = await fixture({ check: () => ++calls === 1 ? old.promise : Promise.resolve({ available: false, message: 'current failure' }) })
|
||||
try {
|
||||
const pending = f.vm.checkRemoteAPI()
|
||||
f.vm.formData.modelName = 'changed'
|
||||
f.vm.formData.modelName = 'draft-model'
|
||||
assert.equal(f.vm.checking, false)
|
||||
await f.vm.checkRemoteAPI()
|
||||
old.resolve({ available: true })
|
||||
await pending
|
||||
assert.equal(f.vm.remoteAvailable, false)
|
||||
assert.equal(f.vm.remoteMessage, 'current failure')
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('a stale failure does not clear the loading state of a newer test', async () => {
|
||||
const old = deferred<Result>()
|
||||
const current = deferred<Result>()
|
||||
let calls = 0
|
||||
const f = await fixture({ check: () => ++calls === 1 ? old.promise : current.promise })
|
||||
try {
|
||||
const pending = f.vm.checkRemoteAPI()
|
||||
f.vm.formData.baseUrl = 'https://changed.example/v1'
|
||||
const newer = f.vm.checkRemoteAPI()
|
||||
old.reject(new Error('old failure'))
|
||||
await pending
|
||||
assert.equal(f.vm.checking, true)
|
||||
assert.equal(f.vm.remoteChecked, false)
|
||||
current.resolve({ available: true })
|
||||
await newer
|
||||
assert.equal(f.vm.remoteAvailable, true)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('closing and reopening the editor discards pending test responses', async () => {
|
||||
const response = deferred<Result>()
|
||||
const f = await fixture({ check: () => response.promise })
|
||||
try {
|
||||
const pending = f.vm.checkRemoteAPI()
|
||||
f.props.visible = false
|
||||
await nextTick()
|
||||
f.props.visible = true
|
||||
await nextTick()
|
||||
response.resolve({ available: true })
|
||||
await pending
|
||||
assert.equal(f.vm.remoteChecked, false)
|
||||
assert.equal(f.vm.remoteStale, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
for (const source of ['remote', 'local']) {
|
||||
test(`${source} embedding: detect dimensions without invalidating success or overwriting newer input`, async () => {
|
||||
const response = deferred<Result>()
|
||||
const f = await fixture({ type: 'embedding', check: () => response.promise })
|
||||
try {
|
||||
f.vm.formData.source = source
|
||||
await nextTick()
|
||||
const run = () => source === 'remote' ? f.vm.checkRemoteAPI() : f.vm.checkOllamaDimension()
|
||||
const pending = run()
|
||||
f.vm.formData.dimension = 2048
|
||||
response.resolve({ available: true, dimension: 1024 })
|
||||
await pending
|
||||
assert.equal(f.vm.formData.dimension, 2048)
|
||||
await run()
|
||||
assert.equal(f.vm.formData.dimension, 1024)
|
||||
assert.equal(source === 'remote' ? f.vm.remoteAvailable : f.vm.dimensionSuccess, true)
|
||||
assert.equal(f.vm.checking, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
}
|
||||
|
||||
test('save waits for success, blocks duplicate saves and cancellation, then closes and clears the draft', async () => {
|
||||
const response = deferred<void>()
|
||||
const f = await fixture({ save: () => response.promise })
|
||||
try {
|
||||
const pending = f.vm.handleConfirm()
|
||||
await nextTick()
|
||||
assert.equal(f.vm.saving, true)
|
||||
assert.equal(f.props.visible, true)
|
||||
assert.equal(f.vm.formData.modelName, 'draft-model')
|
||||
await f.vm.handleConfirm()
|
||||
f.vm.handleCancel()
|
||||
f.vm.dialogVisible = false
|
||||
assert.equal(f.saves.length, 1)
|
||||
assert.equal(f.visibility.length, 0)
|
||||
let stopped = false
|
||||
f.vm.handleSaveEscape({ key: 'Escape', preventDefault() {}, stopImmediatePropagation() { stopped = true } })
|
||||
assert.equal(stopped, true, 'Escape must not bubble to the outer Settings modal while saving')
|
||||
response.resolve()
|
||||
await pending
|
||||
assert.equal(f.props.visible, false)
|
||||
assert.equal(f.vm.formData.modelName, '')
|
||||
assert.equal(f.vm.saving, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('failed saves retain draft and drawer, show the error and allow a successful retry', async () => {
|
||||
let calls = 0
|
||||
const f = await fixture({ save: async () => { if (++calls === 1) throw new Error('save rejected') } })
|
||||
try {
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.props.visible, true)
|
||||
assert.equal(f.vm.formData.modelName, 'draft-model')
|
||||
assert.equal(f.vm.formData.apiKey, 'draft-key')
|
||||
assert.equal(f.vm.saveError, 'save rejected')
|
||||
assert.equal(f.vm.saving, false)
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.props.visible, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('failed form validation prevents persistence and leaves the drawer open', async () => {
|
||||
const f = await fixture()
|
||||
try {
|
||||
f.vm.formRef = { validate: async () => ({ modelName: [{ result: false }] }) }
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 0)
|
||||
assert.equal(f.props.visible, true)
|
||||
assert.equal(f.vm.saving, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
test('failed connection test does not prevent saving', async () => {
|
||||
const f = await fixture({ check: async () => ({ available: false, message: 'offline' }) })
|
||||
try {
|
||||
await f.vm.checkRemoteAPI()
|
||||
await f.vm.handleConfirm()
|
||||
assert.equal(f.saves.length, 1)
|
||||
assert.equal(f.props.visible, false)
|
||||
} finally { f.close() }
|
||||
})
|
||||
|
||||
// Exercise the real parent persistence handler too: swallowed API or validation
|
||||
// errors would otherwise look like a successful save to the editor.
|
||||
const settingsSource = readFileSync(new URL('../views/settings/ModelSettings.vue', import.meta.url), 'utf8')
|
||||
const saveStart = settingsSource.indexOf('const handleModelSave =')
|
||||
const saveEnd = settingsSource.indexOf('// 删除模型', saveStart)
|
||||
const saveScript = ts.transpileModule(settingsSource.slice(saveStart, saveEnd), {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText
|
||||
|
||||
for (const edit of [false, true]) {
|
||||
test(`${edit ? 'update' : 'create'}: parent propagates API and validation failures to the editor`, async () => {
|
||||
let calls = 0
|
||||
const api = async () => { calls++; throw new Error('API rejected') }
|
||||
const save = runInNewContext(saveScript + '\nhandleModelSave', {
|
||||
URL, console: { error() {} },
|
||||
currentModelType: { value: 'chat' }, editingModel: { value: edit ? { id: 'saved-model' } : null },
|
||||
getModelType: () => 'KnowledgeQA', t: (key: string) => key,
|
||||
createModel: api, updateModelAPI: api,
|
||||
MessagePlugin: { success() {}, error() {}, warning() {} }, loadModels: async () => {},
|
||||
})
|
||||
const valid = { modelName: 'model', source: 'remote', baseUrl: 'https://example.com/v1' }
|
||||
await assert.rejects(save(valid), /API rejected/)
|
||||
assert.equal(calls, 1)
|
||||
await assert.rejects(save({ ...valid, displayName: 'x'.repeat(101) }), /displayNameTooLong/)
|
||||
await assert.rejects(save({ ...valid, modelType: 'embedding', dimension: 0 }), /dimensionInvalid/)
|
||||
assert.equal(calls, 1, 'invalid drafts must not reach persistence')
|
||||
})
|
||||
}
|
||||
|
|
@ -43,13 +43,16 @@
|
|||
<slot />
|
||||
</div>
|
||||
<template v-if="!hideFooter" #footer>
|
||||
<div v-if="$slots['footer-extra']" class="setting-drawer__footer-extra">
|
||||
<slot name="footer-extra" />
|
||||
</div>
|
||||
<div class="setting-drawer__footer">
|
||||
<div class="setting-drawer__footer-left">
|
||||
<slot name="footer-left" />
|
||||
</div>
|
||||
<div class="setting-drawer__footer-right">
|
||||
<slot name="footer-right">
|
||||
<t-button theme="default" variant="outline" @click="handleCancel">
|
||||
<t-button theme="default" variant="outline" :disabled="cancelDisabled" @click="handleCancel">
|
||||
{{ cancelText || t('common.cancel') }}
|
||||
</t-button>
|
||||
<t-button theme="primary" :loading="confirmLoading" :disabled="confirmDisabled" @click="handleConfirm">
|
||||
|
|
@ -100,6 +103,7 @@ interface Props {
|
|||
*/
|
||||
storageKey?: string
|
||||
confirmLoading?: boolean
|
||||
cancelDisabled?: boolean
|
||||
confirmDisabled?: boolean
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
|
|
@ -118,6 +122,7 @@ const props = withDefaults(defineProps<Props>(), {
|
|||
maxWidth: 1200,
|
||||
storageKey: '',
|
||||
confirmLoading: false,
|
||||
cancelDisabled: false,
|
||||
confirmDisabled: false,
|
||||
confirmText: '',
|
||||
cancelText: '',
|
||||
|
|
@ -440,6 +445,12 @@ const handleCancel = () => {
|
|||
}
|
||||
|
||||
/* ---------- Footer ---------- */
|
||||
.setting-drawer__footer-extra {
|
||||
margin-bottom: 12px;
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.setting-drawer__footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
|
|
|||
|
|
@ -4541,6 +4541,10 @@ export default {
|
|||
fillModelAndUrl: 'Please fill in the model identifier and Base URL first',
|
||||
remoteBaseUrlRequired: 'Remote API type requires a Base URL',
|
||||
unsupportedModelType: 'Unsupported model type',
|
||||
saveAndClose: 'Save and close',
|
||||
testDraftHint: 'Test the current connection settings without saving first.',
|
||||
testDraftEditHint: 'Test the current connection settings using the API key saved separately.',
|
||||
testStale: 'Settings changed. Run the test again.',
|
||||
connectionSuccess: 'Connection succeeded',
|
||||
connectionFailed: 'Connection failed',
|
||||
connectionConfigError: 'Connection failed, please check the configuration',
|
||||
|
|
@ -4983,7 +4987,7 @@ export default {
|
|||
},
|
||||
debug: {
|
||||
title: 'Model Test',
|
||||
description: 'Send a real request to a saved model and inspect the response',
|
||||
description: 'Send a real request using saved model settings. Save pending edits before testing here.',
|
||||
groupModel: 'Select model',
|
||||
groupInput: 'Test input',
|
||||
groupResult: 'Result',
|
||||
|
|
|
|||
|
|
@ -4541,6 +4541,10 @@ export default {
|
|||
fillModelAndUrl: '先にモデル識別子とベースURLを入力してください',
|
||||
remoteBaseUrlRequired: 'リモートAPIタイプではベースURLが必要です',
|
||||
unsupportedModelType: '未対応のモデルタイプです',
|
||||
saveAndClose: '保存して閉じる',
|
||||
testDraftHint: '保存せずに、現在入力されている接続設定をテストします。',
|
||||
testDraftEditHint: '現在の接続設定と、個別に保存された API キーを使用してテストします。',
|
||||
testStale: '設定が変更されました。もう一度テストしてください。',
|
||||
connectionSuccess: '接続に成功しました',
|
||||
connectionFailed: '接続に失敗しました',
|
||||
connectionConfigError: '接続に失敗しました。設定を確認してください',
|
||||
|
|
@ -4983,7 +4987,7 @@ export default {
|
|||
},
|
||||
debug: {
|
||||
title: 'モデルテスト',
|
||||
description: '保存済みのモデルに実際のリクエストを送信し、応答を確認します',
|
||||
description: '保存済みのモデル設定でリクエストを送信します。編集中の変更は保存後に反映されます。',
|
||||
groupModel: 'モデルを選択',
|
||||
groupInput: 'テスト入力',
|
||||
groupResult: '結果',
|
||||
|
|
|
|||
|
|
@ -2217,7 +2217,7 @@ export default {
|
|||
},
|
||||
debug: {
|
||||
title: '모델 테스트',
|
||||
description: '구성된 모델에 실제 요청을 보내고 응답과 소요 시간을 확인합니다',
|
||||
description: '저장된 모델 설정으로 요청을 보냅니다. 편집 중인 변경 사항은 저장 후 반영됩니다.',
|
||||
groupModel: '모델 선택',
|
||||
groupInput: '테스트 입력',
|
||||
groupResult: '실행 결과',
|
||||
|
|
@ -2609,6 +2609,10 @@ export default {
|
|||
fillModelAndUrl: '먼저 모델 식별자와 Base URL을 입력해주세요',
|
||||
remoteBaseUrlRequired: 'Remote API 유형은 Base URL이 필수입니다',
|
||||
unsupportedModelType: '지원되지 않는 모델 유형',
|
||||
saveAndClose: '저장 후 닫기',
|
||||
testDraftHint: '저장하지 않고 현재 입력한 연결 설정을 테스트합니다.',
|
||||
testDraftEditHint: '현재 연결 설정과 별도로 저장한 API 키를 사용하여 테스트합니다.',
|
||||
testStale: '설정이 변경되었습니다. 다시 테스트해 주세요.',
|
||||
connectionSuccess: '연결 성공',
|
||||
connectionFailed: '연결 실패',
|
||||
connectionConfigError: '연결 실패, 설정을 확인해주세요',
|
||||
|
|
|
|||
|
|
@ -2217,7 +2217,7 @@ export default {
|
|||
},
|
||||
debug: {
|
||||
title: 'Тест модели',
|
||||
description: 'Отправьте реальный запрос к настроенной модели и проверьте ответ и время выполнения',
|
||||
description: 'Запрос с сохранёнными настройками модели. Перед проверкой сохраните изменения.',
|
||||
groupModel: 'Выбор модели',
|
||||
groupInput: 'Тестовый ввод',
|
||||
groupResult: 'Результат',
|
||||
|
|
@ -2609,6 +2609,10 @@ export default {
|
|||
fillModelAndUrl: 'Сначала заполните идентификатор модели и Base URL',
|
||||
remoteBaseUrlRequired: 'Для Remote API необходимо указать Base URL',
|
||||
unsupportedModelType: 'Неподдерживаемый тип модели',
|
||||
saveAndClose: 'Сохранить и закрыть',
|
||||
testDraftHint: 'Проверка текущих настроек подключения без предварительного сохранения.',
|
||||
testDraftEditHint: 'Проверка текущих настроек подключения с отдельно сохранённым API-ключом.',
|
||||
testStale: 'Настройки изменены. Повторите проверку.',
|
||||
connectionSuccess: 'Соединение установлено',
|
||||
connectionFailed: 'Соединение не установлено',
|
||||
connectionConfigError: 'Соединение не установлено, проверьте конфигурацию',
|
||||
|
|
|
|||
|
|
@ -2219,7 +2219,7 @@ export default {
|
|||
},
|
||||
debug: {
|
||||
title: '模型测试',
|
||||
description: '向已配置的模型发送真实请求,查看响应与耗时',
|
||||
description: '使用已保存的模型配置发送真实请求;编辑中的修改需保存后才会生效',
|
||||
groupModel: '选择模型',
|
||||
groupInput: '测试输入',
|
||||
groupResult: '运行结果',
|
||||
|
|
@ -2611,6 +2611,10 @@ export default {
|
|||
fillModelAndUrl: '请先填写模型标识和 Base URL',
|
||||
remoteBaseUrlRequired: 'Remote API 类型必须填写 Base URL',
|
||||
unsupportedModelType: '不支持的模型类型',
|
||||
saveAndClose: '保存并关闭',
|
||||
testDraftHint: '使用当前填写的连接配置,无需提前保存。',
|
||||
testDraftEditHint: '使用当前填写的连接配置;API Key 使用已单独保存的值。',
|
||||
testStale: '配置已修改,请重新测试。',
|
||||
connectionSuccess: '连接成功',
|
||||
connectionFailed: '连接失败',
|
||||
connectionConfigError: '连接失败,请检查配置',
|
||||
|
|
|
|||
|
|
@ -260,7 +260,7 @@
|
|||
|
||||
<!-- 模型编辑器抽屉 -->
|
||||
<ModelEditorDialog v-model:visible="showDialog" :model-type="currentModelType" :model-data="editingModel"
|
||||
@confirm="handleModelSave" />
|
||||
:save-model="handleModelSave" />
|
||||
<ModelDebugDrawer v-model:visible="showDebugDrawer" :models="allModels" />
|
||||
|
||||
</div>
|
||||
|
|
@ -547,38 +547,32 @@ const handleModelSave = async (modelData: any) => {
|
|||
|
||||
try {
|
||||
if (!modelData.modelName || !modelData.modelName.trim()) {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.nameRequired'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.nameRequired'))
|
||||
}
|
||||
|
||||
if (modelData.modelName.trim().length > 100) {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.nameTooLong'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.nameTooLong'))
|
||||
}
|
||||
|
||||
if (modelData.displayName && modelData.displayName.trim().length > 100) {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.displayNameTooLong'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.displayNameTooLong'))
|
||||
}
|
||||
|
||||
if (modelData.source === 'remote') {
|
||||
if (!modelData.baseUrl || !modelData.baseUrl.trim()) {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.baseUrlRequired'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.baseUrlRequired'))
|
||||
}
|
||||
|
||||
try {
|
||||
new URL(modelData.baseUrl.trim())
|
||||
} catch {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.baseUrlInvalid'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.baseUrlInvalid'))
|
||||
}
|
||||
}
|
||||
|
||||
if (saveType === 'embedding') {
|
||||
if (!modelData.dimension || modelData.dimension < 128 || modelData.dimension > 4096) {
|
||||
MessagePlugin.warning(t('modelSettings.toasts.dimensionInvalid'))
|
||||
return
|
||||
throw new Error(t('modelSettings.toasts.dimensionInvalid'))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -662,11 +656,10 @@ const handleModelSave = async (modelData: any) => {
|
|||
MessagePlugin.success(t('modelSettings.toasts.added'))
|
||||
}
|
||||
|
||||
showDialog.value = false
|
||||
await loadModels()
|
||||
} catch (error: any) {
|
||||
console.error('保存模型失败:', error)
|
||||
MessagePlugin.error(error.message || t('modelSettings.toasts.saveFailed'))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue