feat: optimize model management UI with waterfall fallback editor

This commit is contained in:
friendfish
2026-04-18 13:35:26 +08:00
parent a798f4e09b
commit 540cd405ab
4 changed files with 3706 additions and 60 deletions

View File

@@ -436,6 +436,7 @@
"fallbackModels": "备选模型:",
"fallbackNone": "无",
"fallbackHint": "主模型不可用时,系统会自动切换到备选模型",
"configure": "配置",
"primaryAutoSwitch": "主模型已自动切换为 {model}",
"noProvider": "暂无服务商,点击「+ 添加服务商」开始配置",
"noModel": "暂无模型,点击「+ 模型」添加",

View File

@@ -58,7 +58,7 @@ export async function render() {
`
const state = { config: null, search: '', undoStack: [] }
// 非阻塞先返回 DOM后台加载数据
// 非阻塞:先返回 DOM,后台加载数据
loadConfig(page, state)
bindTopActions(page, state)
@@ -75,12 +75,12 @@ async function loadConfig(page, state) {
const listEl = page.querySelector('#providers-list')
try {
state.config = await api.readOpenclawConfig()
// 自动修复现有配置中的 baseUrl如 Ollama 缺少 /v1一次性迁移
// 自动修复现有配置中的 baseUrl(如 Ollama 缺少 /v1),一次性迁移
const before = JSON.stringify(state.config?.models?.providers || {})
normalizeProviderUrls(state.config)
const after = JSON.stringify(state.config?.models?.providers || {})
if (before !== after) {
console.log('[models] 自动修复了服务商 baseUrl正在保存...')
console.log('[models] 自动修复了服务商 baseUrl,正在保存...')
await api.writeOpenclawConfig(state.config)
toast(t('models.autoFixUrl'), 'info')
}
@@ -116,25 +116,273 @@ function getApiTypeLabel(apiType) {
function renderDefaultBar(page, state) {
const bar = page.querySelector('#default-model-bar')
const primary = getCurrentPrimary(state.config)
const allModels = collectAllModels(state.config)
const fallbacks = allModels.filter(m => m.full !== primary).map(m => m.full)
const fallbacks = state.config?.agents?.defaults?.model?.fallbacks || []
const collapsed = !state.showFallbackEditor
const chevron = collapsed ? '▸' : '▾'
bar.innerHTML = `
<div class="config-section" style="margin-bottom:var(--space-lg)">
<div class="config-section-title">${t('models.currentConfig')}</div>
<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">
<div>
<span style="font-size:var(--font-size-sm);color:var(--text-tertiary)">${t('models.primaryModelLabel')}</span>
<span style="font-family:var(--font-mono);font-size:var(--font-size-sm);color:${primary ? 'var(--success)' : 'var(--error)'}">${primary || t('models.notConfigured')}</span>
</div>
<div>
<span style="font-size:var(--font-size-sm);color:var(--text-tertiary)">${t('models.fallbackModels')}</span>
<span style="font-size:var(--font-size-sm);color:var(--text-secondary)">${fallbacks.length ? fallbacks.join(', ') : t('models.fallbackNone')}</span>
<div class="config-section" style="margin-bottom:var(--space-lg); transition: all 0.3s ease;">
<div class="config-section-title" id="system-model-title" style="display:flex; justify-content:space-between; align-items:center; cursor:pointer; user-select:none;">
<div style="display:flex; align-items:center; gap:8px">
<span style="display:inline-block;width:16px;font-size:12px;color:var(--text-tertiary)">${chevron}</span>
<span>系统主/备模型</span>
<div style="display:flex; gap:8px; margin-left: 12px; align-items: baseline;">
<span style="color:var(--success); font-family:var(--font-mono); font-size: 0.9em; font-weight: 500;">${primary || '未配置'}</span>
<span style="font-size: 11px; color: var(--text-tertiary); font-weight: normal;">${fallbacks.length} 个备选</span>
</div>
</div>
</div>
<div class="form-hint" style="margin-top:6px">${t('models.fallbackHint')}</div>
<div id="fallback-waterfall-container" style="display:${state.showFallbackEditor ? 'block' : 'none'}; margin-top: 16px; border-top: 1px dashed var(--border-color); padding-top: 16px;">
${renderFallbackWaterfall(state)}
</div>
${collapsed ? '' : `<div class="form-hint" style="margin-top:8px">${t('models.fallbackHint')}</div>`}
</div>
`
// 绑定标题点击折叠/展开
bar.querySelector('#system-model-title').onclick = () => {
state.showFallbackEditor = !state.showFallbackEditor
renderDefaultBar(page, state)
}
if (state.showFallbackEditor) {
bindWaterfallActions(page, state)
}
}
function renderFallbackWaterfall(state) {
const primary = getCurrentPrimary(state.config)
const allModels = collectAllModels(state.config)
const currentFallbacks = state.config?.agents?.defaults?.model?.fallbacks || []
// 分组候选模型
const providers = state.config?.models?.providers || {}
const candidatesByProvider = {}
Object.keys(providers).forEach(pKey => {
const pModels = providers[pKey].models || []
const filtered = pModels.map(m => typeof m === 'string' ? m : m.id)
.filter(mId => {
const full = `${pKey}/${mId}`
return full !== primary && !currentFallbacks.includes(full)
})
if (filtered.length > 0) {
candidatesByProvider[pKey] = filtered
}
})
if (!state._fallback_candidates_collapsed) state._fallback_candidates_collapsed = {}
return `
<div class="fallback-editor-panel" style="background: var(--bg-secondary); padding: 12px; border-radius: var(--radius-md);">
<div style="margin-bottom: 12px; font-size: 11px; color: var(--text-secondary); background: var(--bg-info-subtle); padding: 6px 10px; border-radius: 4px; border-left: 3px solid var(--primary); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
<strong>💡 最佳实践:</strong> 建议备选模型保持在 <strong>2-3 款</strong> 并分布在不同服务商,以平衡可用性与延迟。
</div>
<div style="display: grid; grid-template-columns: 1fr 1.2fr; gap: 24px;">
<div>
<div style="font-size: var(--font-size-xs); font-weight: bold; margin-bottom: 8px; color: var(--text-tertiary);">当前生效链 (支持拖拽排序)</div>
<div id="active-fallback-list" style="display: flex; flex-direction: column; gap: 4px; min-height: 50px;">
${currentFallbacks.map((f, i) => `
<div class="fallback-chain-item" data-id="${f}" style="display: flex; align-items: center; justify-content: space-between; background: var(--bg-primary); padding: 6px 10px; border-radius: 4px; border: 1px solid var(--border-color);">
<div style="display: flex; align-items: center; gap: 6px; min-width: 0; flex: 1;">
<span class="fallback-drag-handle" style="color:var(--text-tertiary);cursor:grab;user-select:none;font-size:14px;padding:2px; flex-shrink: 0;">⋮⋮</span>
<span style="font-family: var(--font-mono); font-size: var(--font-size-xs); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${i + 1}. ${f}</span>
</div>
<div style="display: flex; gap: 4px; flex-shrink: 0;">
<button class="btn btn-xs btn-secondary btn-set-primary-from-fb" data-id="${f}" style="padding: 1px 4px; font-size: 10px;">设为主用</button>
<button class="btn-icon btn-remove-fb" data-id="${f}" title="移除">${icon('x', 12)}</button>
</div>
</div>
`).join('')}
${currentFallbacks.length === 0 ? `<div style="font-size: 12px; color: var(--text-tertiary); text-align: center; padding: 20px; border: 1px dashed var(--border-color); border-radius: 4px;">尚未选择备选模型</div>` : ''}
</div>
</div>
<div>
<div style="font-size: var(--font-size-xs); font-weight: bold; margin-bottom: 8px; color: var(--text-tertiary);">可用候选池 (按服务商分组)</div>
<div id="candidate-model-pool" style="display: flex; flex-direction: column; gap: 6px; max-height: 300px; overflow-y: auto; padding-right: 4px;">
${Object.keys(candidatesByProvider).length === 0 ? `<div style="font-size: 12px; color: var(--text-tertiary); text-align: center; padding: 20px;">无可用候选模型</div>` :
Object.keys(candidatesByProvider).map(pKey => {
const collapsed = !!state._fallback_candidates_collapsed[pKey]
const mIds = candidatesByProvider[pKey]
return `
<div class="candidate-provider-group" data-provider="${pKey}">
<div class="candidate-provider-header" style="display: flex; align-items: center; gap: 6px; padding: 4px 8px; background: var(--bg-tertiary); border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: bold; color: var(--text-secondary);">
<span class="chevron">${collapsed ? '▸' : '▾'}</span>
<span>${pKey}</span>
<span style="margin-left: auto; color: var(--text-tertiary); font-weight: normal;">${mIds.length}</span>
</div>
<div class="candidate-provider-list" style="display: ${collapsed ? 'none' : 'flex'}; flex-direction: column; gap: 4px; padding: 4px 0 4px 12px;">
${mIds.map(mId => `
<div class="candidate-item" style="display: flex; align-items: center; justify-content: space-between; background: var(--bg-primary); padding: 4px 8px; border-radius: 4px; border: 1px solid var(--border-color); opacity: 0.9;">
<span style="font-family: var(--font-mono); font-size: 11px; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${mId}</span>
<button class="btn btn-xs btn-primary btn-add-fb" data-full="${pKey}/${mId}" style="padding: 1px 6px; font-size: 10px;">加入</button>
</div>
`).join('')}
</div>
</div>
`
}).join('')
}
</div>
</div>
</div>
<div style="margin-top: 16px; display: flex; justify-content: flex-end; gap: 8px;">
<button class="btn btn-sm btn-secondary" id="btn-cancel-fallback">取消</button>
<button class="btn btn-sm btn-primary" id="btn-save-fallback">保存并应用</button>
</div>
</div>
`
}
function bindWaterfallActions(page, state) {
const container = page.querySelector('#fallback-waterfall-container')
// 移除
container.querySelectorAll('.btn-remove-fb').forEach(btn => {
btn.onclick = () => {
const id = btn.dataset.id
const fallbacks = state.config.agents.defaults.model.fallbacks || []
state.config.agents.defaults.model.fallbacks = fallbacks.filter(f => f !== id)
renderDefaultBar(page, state)
}
})
// 设为主用 (从备选链中提升)
container.querySelectorAll('.btn-set-primary-from-fb').forEach(btn => {
btn.onclick = () => {
const full = btn.dataset.id
const oldPrimary = getCurrentPrimary(state.config)
const fallbacks = state.config.agents.defaults.model.fallbacks || []
pushUndo(state)
// 1. 设置新主模型
setPrimary(state, full)
// 2. 将旧主模型放入备选链(原位置或末尾)
const newFallbacks = fallbacks.filter(f => f !== full)
if (oldPrimary) newFallbacks.push(oldPrimary)
state.config.agents.defaults.model.fallbacks = newFallbacks
renderDefaultBar(page, state)
toast(`已将 ${full} 设为主模型`, 'success')
}
})
// 加入
container.querySelectorAll('.btn-add-fb').forEach(btn => {
btn.onclick = () => {
const full = btn.dataset.full
if (!state.config.agents.defaults.model.fallbacks) state.config.agents.defaults.model.fallbacks = []
state.config.agents.defaults.model.fallbacks.push(full)
renderDefaultBar(page, state)
}
})
// 折叠候选服务商
container.querySelectorAll('.candidate-provider-header').forEach(header => {
header.onclick = () => {
const group = header.closest('.candidate-provider-group')
const pKey = group.dataset.provider
state._fallback_candidates_collapsed[pKey] = !state._fallback_candidates_collapsed[pKey]
renderDefaultBar(page, state)
}
})
// 拖拽排序逻辑 (适配当前列表)
const chainContainer = container.querySelector('#active-fallback-list')
if (chainContainer && state.config.agents.defaults.model.fallbacks?.length > 1) {
let dragged = null
let placeholder = null
let startY = 0
chainContainer.addEventListener('pointerdown', e => {
const handle = e.target.closest('.fallback-drag-handle')
if (!handle) return
const item = handle.closest('.fallback-chain-item')
if (!item) return
e.preventDefault()
dragged = item
startY = e.clientY
placeholder = document.createElement('div')
placeholder.style.cssText = `height:${item.offsetHeight}px;border:1px dashed var(--primary);border-radius:4px;margin-bottom:4px;background:var(--bg-tertiary)`
item.after(placeholder)
const rect = item.getBoundingClientRect()
item.style.position = 'fixed'
item.style.left = rect.left + 'px'
item.style.top = rect.top + 'px'
item.style.width = rect.width + 'px'
item.style.zIndex = '10000'
item.style.opacity = '0.9'
item.style.pointerEvents = 'none'
item.setPointerCapture(e.pointerId)
})
chainContainer.addEventListener('pointermove', e => {
if (!dragged || !placeholder) return
e.preventDefault()
const dy = e.clientY - startY
itemMove(dragged, dy)
startY = e.clientY
const siblings = [...chainContainer.querySelectorAll('.fallback-chain-item:not([style*="position: fixed"])')]
for (const sibling of siblings) {
const rect = sibling.getBoundingClientRect()
if (e.clientY < rect.top + rect.height / 2) {
sibling.before(placeholder)
return
}
}
if (siblings.length) siblings[siblings.length - 1].after(placeholder)
})
function itemMove(el, dy) {
const top = parseFloat(el.style.top)
el.style.top = (top + dy) + 'px'
}
chainContainer.addEventListener('pointerup', e => {
if (!dragged || !placeholder) return
dragged.style.position = ''
dragged.style.left = ''
dragged.style.top = ''
dragged.style.width = ''
dragged.style.zIndex = ''
dragged.style.opacity = ''
dragged.style.pointerEvents = ''
placeholder.before(dragged)
placeholder.remove()
// 更新顺序
const newOrderIds = [...chainContainer.querySelectorAll('.fallback-chain-item')].map(el => el.dataset.id)
state.config.agents.defaults.model.fallbacks = newOrderIds
dragged = null
placeholder = null
renderDefaultBar(page, state) // 刷新索引数字
})
}
// 取消
container.querySelector('#btn-cancel-fallback').onclick = async () => {
state.showFallbackEditor = false
loadConfig(page, state)
}
// 保存
container.querySelector('#btn-save-fallback').onclick = async () => {
state.showFallbackEditor = false
await doAutoSave(state)
renderDefaultBar(page, state)
}
}
// 排序模型列表
@@ -189,7 +437,7 @@ function sortModels(models, sortBy) {
return sorted
}
// 渲染服务商列表渲染完后直接绑定事件
// 渲染服务商列表(渲染完后直接绑定事件)
function renderProviders(page, state) {
const listEl = page.querySelector('#providers-list')
const providers = state.config?.models?.providers || {}
@@ -262,11 +510,11 @@ function renderProviders(page, state) {
`
}).join('')
// innerHTML 完成后直接给每个按钮绑定 onclick
// innerHTML 完成后,直接给每个按钮绑定 onclick
bindProviderButtons(listEl, page, state)
}
// 渲染模型卡片支持搜索高亮和批量选择 checkbox
// 渲染模型卡片(支持搜索高亮和批量选择 checkbox)
function renderModelCards(providerKey, models, primary, search) {
if (!models.length) {
return `<div style="color:var(--text-tertiary);font-size:var(--font-size-sm);padding:8px 0">${t('models.noModel')}</div>`
@@ -281,7 +529,7 @@ function renderModelCards(providerKey, models, primary, search) {
const meta = []
if (name !== id) meta.push(name)
if (m.contextWindow) meta.push((m.contextWindow / 1000) + 'K ' + t('models.context'))
// 测试状态标签成功显示耗时失败显示不可用
// 测试状态标签:成功显示耗时,失败显示不可用
let latencyTag = ''
if (m.testStatus === 'fail') {
latencyTag = `<span style="font-size:var(--font-size-xs);padding:1px 6px;border-radius:var(--radius-sm);background:var(--error-muted, #fee2e2);color:var(--error)" title="${(m.testError || '').replace(/"/g, '&quot;')}">${t('models.unavailable')}</span>`
@@ -334,7 +582,7 @@ function findModelIdx(provider, modelId) {
// ===== 自动保存 + 撤销机制 =====
// 保存快照到撤销栈变更前调用
// 保存快照到撤销栈(变更前调用)
function pushUndo(state) {
state.undoStack.push(JSON.parse(JSON.stringify(state.config)))
if (state.undoStack.length > 20) state.undoStack.shift()
@@ -351,7 +599,7 @@ async function undo(page, state) {
toast(t('models.undone'), 'info')
}
// 自动保存防抖 300ms
// 自动保存(防抖 300ms)
let _saveTimer = null
let _batchTestAbort = null // 批量测试终止控制器
@@ -365,7 +613,7 @@ function autoSave(state) {
_saveTimer = setTimeout(() => doAutoSave(state), 300)
}
/** 已知的 API 类型错误→正确映射自动修复用户手动编辑或旧版本配置 */
/** 已知的 API 类型错误→正确映射,自动修复用户手动编辑或旧版本配置 */
const API_TYPE_FIXES = {
'google-gemini': 'google-generative-ai',
'gemini': 'google-generative-ai',
@@ -376,7 +624,7 @@ const API_TYPE_FIXES = {
}
const VALID_API_TYPES = new Set(API_TYPES.map(t => t.value))
/** 保存前规范化所有服务商的 baseUrl 和 API 类型确保 Gateway 能正确调用 */
/** 保存前规范化所有服务商的 baseUrl 和 API 类型,确保 Gateway 能正确调用 */
function normalizeProviderUrls(config) {
const providers = config?.models?.providers
if (!providers) return
@@ -387,14 +635,14 @@ function normalizeProviderUrls(config) {
if (API_TYPE_FIXES[lower]) {
p.api = API_TYPE_FIXES[lower]
} else if (!VALID_API_TYPES.has(lower)) {
console.warn(`[models] 未知 API 类型「${p.api}自动修正为 openai-completions`)
console.warn(`[models] 未知 API 类型「${p.api},自动修正为 openai-completions`)
p.api = 'openai-completions'
}
}
if (!p.baseUrl) continue
let url = p.baseUrl.replace(/\/+$/, '')
// 去掉尾部的已知端点路径用户可能粘贴了完整 URL
// 去掉尾部的已知端点路径(用户可能粘贴了完整 URL)
for (const suffix of ['/api/chat', '/api/generate', '/api/tags', '/api', '/chat/completions', '/completions', '/responses', '/messages', '/models']) {
if (url.endsWith(suffix)) { url = url.slice(0, -suffix.length); break }
}
@@ -403,15 +651,15 @@ function normalizeProviderUrls(config) {
if (apiType === 'anthropic-messages') {
if (!url.endsWith('/v1')) url += '/v1'
} else if (apiType !== 'google-generative-ai' && apiType !== 'ollama') {
// Ollama OpenAI 兼容模式端口检测11434 默认需要加 /v1ollama 原生 API 不需要
// Ollama OpenAI 兼容模式端口检测:11434 默认需要加 /v1(ollama 原生 API 不需要)
if (/:11434$/.test(url) && !url.endsWith('/v1')) url += '/v1'
// 不再强制追加 /v1尊重用户填写的 URL火山引擎等第三方用 /v3 等路径
// 不再强制追加 /v1,尊重用户填写的 URL(火山引擎等第三方用 /v3 等路径)
}
p.baseUrl = url
}
}
// 仅保存配置不重启 Gateway用于测试结果等元数据持久化
// 仅保存配置,不重启 Gateway(用于测试结果等元数据持久化)
async function saveConfigOnly(state) {
try {
const primary = getCurrentPrimary(state.config)
@@ -430,7 +678,7 @@ async function doAutoSave(state) {
normalizeProviderUrls(state.config)
await api.writeOpenclawConfig(state.config)
// 重启 Gateway 使配置生效Gateway 不支持 SIGHUP 热重载
// 重启 Gateway 使配置生效(Gateway 不支持 SIGHUP 热重载)
toast(t('models.configSavedRestarting'), 'info')
try {
await api.restartGateway()
@@ -466,7 +714,7 @@ function updateUndoBtn(page, state) {
btn.textContent = n ? t('models.undoN', { n }) : t('models.undo')
}
// 渲染完成后直接给每个 [data-action] 按钮绑定 onclick
// 渲染完成后,直接给每个 [data-action] 按钮绑定 onclick
function bindProviderButtons(listEl, page, state) {
// 绑定排序下拉框
listEl.querySelectorAll('select[data-action="sort-models"]').forEach(select => {
@@ -484,7 +732,7 @@ function bindProviderButtons(listEl, page, state) {
// 将排序固化到底层数据并保存
pushUndo(state)
provider.models = sortModels(provider.models, val)
// 恢复下拉框显示 "默认顺序"因为新顺序已经变成了默认顺序
// 恢复下拉框显示 "默认顺序",因为新顺序已经变成了默认顺序
state.sortBy = 'default'
renderProviders(page, state)
autoSave(state)
@@ -493,7 +741,7 @@ function bindProviderButtons(listEl, page, state) {
}
})
// 绑定拖拽排序Pointer 事件实现兼容 Tauri WebView2/WKWebView
// 绑定拖拽排序(Pointer 事件实现,兼容 Tauri WebView2/WKWebView)
listEl.querySelectorAll('.provider-models').forEach(container => {
let dragged = null
let placeholder = null
@@ -609,7 +857,7 @@ function bindProviderButtons(listEl, page, state) {
if (!provider) return
const card = btn.closest('.model-card')
// checkbox 改变时不需要阻止冒泡由 handleAction 内部处理
// checkbox 改变时不需要阻止冒泡,由 handleAction 内部处理
if (btn.type === 'checkbox') {
btn.onchange = (e) => {
handleAction(action, btn, card, section, providerKey, provider, page, state)
@@ -697,7 +945,7 @@ async function handleAction(action, btn, card, section, providerKey, provider, p
}
}
// 设置主模型仅修改 state不写入文件
// 设置主模型(仅修改 state,不写入文件)
function setPrimary(state, full) {
if (!state.config.agents) state.config.agents = {}
if (!state.config.agents.defaults) state.config.agents.defaults = {}
@@ -705,13 +953,13 @@ function setPrimary(state, full) {
state.config.agents.defaults.model.primary = full
}
// 应用默认模型primary + 其余自动成为备选
// 确保 primary 指向的模型仍然存在不存在则自动切到第一个可用模型
// 应用默认模型:primary + 其余自动成为备选
// 确保 primary 指向的模型仍然存在,不存在则自动切到第一个可用模型
function ensureValidPrimary(state) {
const primary = getCurrentPrimary(state.config)
const allModels = collectAllModels(state.config)
if (allModels.length === 0) {
// 所有模型都没了清空 primary
// 所有模型都没了,清空 primary
if (state.config.agents?.defaults?.model) {
state.config.agents.defaults.model.primary = ''
}
@@ -719,7 +967,7 @@ function ensureValidPrimary(state) {
}
const exists = allModels.some(m => m.full === primary)
if (!exists) {
// primary 指向已删除的模型自动切到第一个
// primary 指向已删除的模型,自动切到第一个
const newPrimary = allModels[0].full
setPrimary(state, newPrimary)
toast(t('models.primaryAutoSwitch', { model: newPrimary }), 'info')
@@ -734,8 +982,8 @@ function applyDefaultModel(state) {
if (!defaults.model) defaults.model = {}
defaults.model.primary = primary
// fallbacks / models 仅在为空时初始化首次安装友好不再每次保存都覆盖
// 避免用户精心维护的精简 fallback 链被重写且随模型增多不断膨胀 (fixes #190)
// fallbacks / models 仅在为空时初始化(首次安装友好),不再每次保存都覆盖
// 避免用户精心维护的精简 fallback 链被重写,且随模型增多不断膨胀 (fixes #190)
if (!defaults.model.fallbacks || defaults.model.fallbacks.length === 0) {
const allModels = collectAllModels(state.config)
defaults.model.fallbacks = allModels.filter(m => m.full !== primary).map(m => m.full)
@@ -748,9 +996,9 @@ function applyDefaultModel(state) {
defaults.models = modelsMap
}
// 注意不再强制同步到各 agent 的 model.primary
// 子 Agent 的模型覆盖是 OpenClaw 正常功能用户可通过对话为不同 Agent 设置不同模型
// 强制覆盖会导致 #142重开 ClawPanel 后子 Agent 模型配置被重置
// 注意:不再强制同步到各 agent 的 model.primary
// 子 Agent 的模型覆盖是 OpenClaw 正常功能(用户可通过对话为不同 Agent 设置不同模型)
// 强制覆盖会导致 #142:重开 ClawPanel 后子 Agent 模型配置被重置
}
// 顶部按钮事件
@@ -758,7 +1006,7 @@ function bindTopActions(page, state) {
page.querySelector('#btn-add-provider').onclick = () => addProvider(page, state)
page.querySelector('#btn-undo').onclick = () => undo(page, state)
// 晴辰云获取模型列表 → 弹窗让用户选择要添加的模型
// 晴辰云:获取模型列表 → 弹窗让用户选择要添加的模型
page.querySelector('#btn-qtcool-oneclick').onclick = async () => {
if (!state.config) { toast(t('models.configNotReady'), 'warning'); return }
@@ -873,7 +1121,7 @@ function bindTopActions(page, state) {
}
}
// 添加服务商带预设快捷选择
// 添加服务商(带预设快捷选择)
function addProvider(page, state) {
// 构建预设按钮 HTML
const presetsHtml = PROVIDER_PRESETS.filter(p => !p.hidden).map(p =>
@@ -933,7 +1181,7 @@ function addProvider(page, state) {
// 高亮选中的预设
overlay.querySelectorAll('.preset-btn').forEach(b => b.style.opacity = '0.5')
btn.style.opacity = '1'
// 显示服务商详情官网、描述
// 显示服务商详情(官网、描述)
const detailEl = overlay.querySelector('#preset-detail')
if (detailEl) {
if (preset.desc || preset.site) {
@@ -1003,7 +1251,7 @@ function editProvider(page, state, providerKey) {
})
}
// 添加模型带预设快捷选择
// 添加模型(带预设快捷选择)
function addModel(page, state, providerKey) {
const presets = MODEL_PRESETS[providerKey] || []
const existingIds = (state.config.models.providers[providerKey].models || [])
@@ -1020,7 +1268,7 @@ function addModel(page, state, providerKey) {
]
if (available.length) {
// 有预设可用构建自定义弹窗
// 有预设可用,构建自定义弹窗
const overlay = document.createElement('div')
overlay.className = 'modal-overlay'
@@ -1058,7 +1306,7 @@ function addModel(page, state, providerKey) {
autoSave(state)
})
// 预设按钮点击直接添加
// 预设按钮:点击直接添加
overlay.querySelectorAll('.preset-btn').forEach(btn => {
btn.onclick = () => {
const preset = available.find(p => p.id === btn.dataset.mid)
@@ -1075,7 +1323,7 @@ function addModel(page, state, providerKey) {
}
})
} else {
// 无预设直接弹普通 modal
// 无预设,直接弹普通 modal
showModal({
title: t('models.addModelTitle', { provider: providerKey }),
fields,
@@ -1091,7 +1339,7 @@ function addModel(page, state, providerKey) {
}
}
// 构建表单字段 HTML用于自定义弹窗
// 构建表单字段 HTML(用于自定义弹窗)
function buildFieldsHtml(fields) {
return fields.map(f => {
if (f.type === 'checkbox') {
@@ -1198,9 +1446,9 @@ async function handleBatchDelete(section, page, state, providerKey) {
toast(t('models.batchDeleted', { count: ids.length }), 'info')
}
// 批量测试勾选的模型没勾选则测试全部记录耗时和状态
// 批量测试:勾选的模型,没勾选则测试全部(记录耗时和状态)
async function handleBatchTest(section, state, providerKey) {
// 如果正在测试点击则终止
// 如果正在测试,点击则终止
if (_batchTestAbort) {
_batchTestAbort.abort = true
toast(t('models.stoppingBatchTest'), 'warning')
@@ -1269,7 +1517,7 @@ async function handleBatchTest(section, state, providerKey) {
// 恢复按钮
_batchTestAbort = null
// 重新查找按钮renderProviders 后 DOM 已更新
// 重新查找按钮(renderProviders 后 DOM 已更新)
const newSection = page?.querySelector(`[data-provider="${providerKey}"]`)
const newBtn = newSection?.querySelector('[data-action="batch-test"]')
if (newBtn) {
@@ -1382,7 +1630,7 @@ async function fetchRemoteModels(btn, page, state, providerKey) {
}
}
// 测试模型连通性记录耗时和状态
// 测试模型连通性(记录耗时和状态)
async function testModel(btn, state, providerKey, idx) {
const provider = state.config.models.providers[providerKey]
const model = provider.models[idx]
@@ -1403,13 +1651,13 @@ async function testModel(btn, state, providerKey, idx) {
model.testStatus = 'ok'
delete model.testError
}
// 包含 ⚠ 的是非致命错误429 等拆分显示
// 包含 ⚠ 的是非致命错误(429 等),拆分显示
if (reply.startsWith('⚠')) {
const lines = reply.split('\n')
const summary = lines[0]
const detail = lines.slice(1).join('\n').trim()
if (detail) {
const detailHtml = detail.replace(/</g, '&lt;').replace(/(https?:\/\/[^\s,,。;))'"&]+)/g, '<a href="$1" target="_blank" style="color:var(--primary);text-decoration:underline">$1</a>')
const detailHtml = detail.replace(/</g, '&lt;').replace(/(https?:\/\/[^\s,,。;))'"&]+)/g, '<a href="$1" target="_blank" style="color:var(--primary);text-decoration:underline">$1</a>')
toast(`<strong>${modelId}</strong> ${summary.replace(/</g, '&lt;')}<br><span style="font-size:11px;line-height:1.5;word-break:break-all">${detailHtml}</span>`, 'warning', { duration: 10000, html: true })
} else {
toast(`${modelId} ${summary}`, 'warning', { duration: 6000 })
@@ -1435,7 +1683,7 @@ async function testModel(btn, state, providerKey, idx) {
renderProviders(page, state)
renderDefaultBar(page, state)
}
// 持久化测试结果仅保存不重启 Gateway
// 持久化测试结果(仅保存,不重启 Gateway)
saveConfigOnly(state)
}
}