From c7cd341cc7ba1365170b918149032c72947e8587 Mon Sep 17 00:00:00 2001 From: kicer Date: Thu, 3 Sep 2026 13:04:58 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0v2=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/server/public/css/v2.css | 217 ++++++++ app/server/public/v2.html | 1012 +++++++++++++++++++++++++++++++++- 2 files changed, 1226 insertions(+), 3 deletions(-) diff --git a/app/server/public/css/v2.css b/app/server/public/css/v2.css index ce719be..3db4f6b 100644 --- a/app/server/public/css/v2.css +++ b/app/server/public/css/v2.css @@ -309,3 +309,220 @@ footer { flex: none; padding: 8px 12px calc(10px + env(safe-area-inset-bottom, 0 /* ================= 工具调用行(v2 轻量展示,替代工具卡片) ================= */ .tool-line { font-size: 12px; color: var(--gray); line-height: 1.6; padding: 2px 0; } + +/* ================= 设置区(覆盖层页面;卡片/表单样式搬自 style.css 适配 v2 变量) ================= */ +#settings-page { + position: absolute; inset: 0; z-index: 60; + background: var(--page); + display: flex; flex-direction: column; +} +.header-right { flex: none; min-width: 40px; display: flex; align-items: center; justify-content: flex-end; gap: 2px; } +.header-right .icon-btn, .header-right label.icon-btn { color: var(--ink); } +.header-right .icon-btn:active, .header-right label.icon-btn:active { background: var(--surface); } +label.icon-btn { cursor: pointer; } +#set-body { flex: 1; min-height: 0; background: var(--surface); display: flex; flex-direction: column; } +.set-scroll { flex: 1; min-height: 0; overflow-y: auto; padding: 12px 12px calc(16px + env(safe-area-inset-bottom, 0px)); } +.empty-tip { color: var(--gray-light); text-align: center; padding: 18px; font-size: 13px; } + +/* ---------- 设置主页卡片 ---------- */ +.set-home { display: flex; flex-direction: column; gap: 12px; } +.set-card { + display: flex; align-items: center; gap: 14px; width: 100%; text-align: left; + background: var(--page); border: 1px solid var(--border); border-radius: 16px; padding: 15px 16px; +} +.set-card:active { background: var(--surface); } +.set-ico { + width: 42px; height: 42px; border-radius: 12px; flex: none; + display: flex; align-items: center; justify-content: center; + background: var(--active-soft); color: var(--active); +} +.set-tt { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.set-name { font-size: 15px; font-weight: 600; } +.set-desc { font-size: 12px; color: var(--gray); } +.set-arrow { color: var(--gray-light); } + +/* ---------- 抽屉底部用户区:整行可点 ---------- */ +.drawer-user { cursor: pointer; } +.drawer-user:active { background: var(--surface); } + +/* ---------- 通用白卡与设置表单(搬自 style.css 设置页) ---------- */ +.settings-card { + background: var(--page); border: 1px solid var(--border); border-radius: 12px; + padding: 10px 14px 12px; margin-bottom: 12px; +} +.settings-card h4 { font-size: 14px; color: var(--ink); margin: 4px 0 2px; display: flex; align-items: center; gap: 8px; } +.cfg-kv { + display: flex; align-items: baseline; gap: 10px; + font-size: 13px; padding: 7px 0; border-bottom: 1px dashed var(--border); +} +.cfg-kv:last-of-type { border-bottom: none; } +.cfg-kv label { color: var(--gray); flex: none; max-width: 42%; } +.cfg-kv b { + font-weight: 500; flex: 1; text-align: right; color: var(--ink); + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + font-variant-numeric: tabular-nums; +} +.cfg-note { font-size: 11.5px; color: var(--gray-light); line-height: 1.5; margin-top: 6px; } +.cfg-input { + flex: 1; min-width: 0; text-align: right; font-size: 13px; color: var(--ink); + background: var(--surface); border: 1px solid transparent; border-radius: 8px; + padding: 6px 10px; font-variant-numeric: tabular-nums; font-family: inherit; + -webkit-appearance: none; appearance: none; +} +.cfg-input:focus { border-color: var(--active); background: #fff; } +.cfg-input::-webkit-outer-spin-button, .cfg-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } +.cfg-input.cfg-dirty { color: #c0392b; border-color: #e8b4b0; background: #fdf3f2; } +.cfg-err { + margin: 0 0 8px; padding: 8px 12px; border-radius: 8px; + background: #fdecea; color: #a3352a; font-size: 12.5px; + white-space: pre-wrap; word-break: break-all; +} + +/* ---------- 账户卡(搬自 index 用户卡) ---------- */ +.user-card { display: flex; flex-direction: column; align-items: center; padding: 20px 16px 16px; } +.user-avatar { + width: 64px; height: 64px; border-radius: 50%; border: none; + color: #fff; font-size: 26px; font-weight: 600; letter-spacing: 1px; + display: flex; align-items: center; justify-content: center; + box-shadow: 0 2px 6px rgba(30, 40, 90, 0.18); user-select: none; +} +.set-user-name { margin-top: 10px; font-size: 16px; font-weight: 600; word-break: break-all; text-align: center; } +.user-acts { display: flex; gap: 10px; width: 100%; max-width: 360px; margin-top: 14px; } +.user-acts .ghost-btn { flex: 1; } + +/* ---------- 徽章 ---------- */ +.badge { font-size: 11px; padding: 1px 7px; border-radius: 8px; white-space: nowrap; } +.badge.active { background: #e3f2e6; color: #217a34; } +.badge.held { background: #fff4dc; color: #a06a00; } +.badge.cancelled { background: #fdecea; color: #b3382c; } + +/* ---------- 列表卡(技能)与操作钮 ---------- */ +.session-card { + background: var(--page); border: 1px solid var(--border); border-radius: 12px; + padding: 12px 14px; margin-bottom: 10px; + display: flex; align-items: center; gap: 10px; cursor: pointer; +} +.session-card:active { background: var(--surface); } +.session-main { flex: 1; overflow: hidden; } +.session-name { font-weight: 600; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.session-meta { font-size: 12px; color: var(--gray); margin-top: 3px; display: flex; gap: 8px; flex-wrap: wrap; } +.skill-desc { + font-size: 12px; color: var(--gray); margin-top: 3px; + display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; +} +.card-acts { display: flex; flex-direction: column; gap: 10px; align-items: flex-end; flex-shrink: 0; } +.card-act { background: var(--active-soft); color: var(--active); border: none; border-radius: 8px; font-size: 12px; padding: 5px 10px; cursor: pointer; } +.card-act.del { background: #fdecea; color: #c0392b; } +.card-act:active { opacity: 0.7; } + +/* ---------- 技能详情文件列表 ---------- */ +.skill-files { background: var(--page); border: 1px solid var(--border); border-radius: 12px; padding: 6px 8px; } +.skill-files .file-row { + display: flex; align-items: center; gap: 8px; padding: 8px; + border-radius: 8px; font-size: 13.5px; cursor: pointer; + border-bottom: 1px dashed var(--border); +} +.skill-files .file-row:last-child { border-bottom: none; } +.skill-files .file-row:active { background: var(--surface); } +.skill-files .file-ico { + width: 16px; height: 16px; flex-shrink: 0; + stroke: #7f8db0; fill: none; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; +} +.skill-files .file-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; } +.skill-files .file-size { background: var(--surface); color: var(--gray); font-size: 11px; padding: 2px 8px; border-radius: 9px; flex: none; } +.skill-files .file-act { background: var(--active-soft); color: var(--active); border: none; border-radius: 7px; padding: 4px 9px; font-size: 13px; flex: none; cursor: pointer; } +.skill-files .file-act.del { background: #fdecea; color: #c0392b; } + +/* ---------- 模型池分组与卡片 ---------- */ +.model-group { background: var(--page); border: 1px solid var(--border); border-radius: 12px; margin-bottom: 10px; overflow: hidden; } +.model-group-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; cursor: pointer; user-select: none; } +.model-group-head:active { opacity: 0.7; } +.model-group-caret { + width: 15px; height: 15px; flex-shrink: 0; + stroke: #7f8db0; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; + transition: transform 0.15s ease; +} +.model-group.open .model-group-caret { transform: rotate(90deg); } +.model-group-name { font-weight: 600; font-size: 14.5px; } +.model-group-key { + font-size: 11.5px; color: var(--gray); word-break: break-all; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +.model-group-meta { margin-left: auto; flex-shrink: 0; font-size: 12px; color: var(--gray); white-space: nowrap; } +.model-group-body { padding: 0 10px 10px; border-top: 1px dashed var(--border); } +.model-group-bal { display: flex; align-items: center; justify-content: flex-end; gap: 6px; padding: 10px 4px 0; font-size: 12.5px; color: #556; } +.mbal-refresh { border: none; background: none; padding: 2px; margin: 0; cursor: pointer; display: flex; color: #7f8db0; } +.mbal-refresh svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.mbal-refresh:active { opacity: 0.6; } +.mbal-refresh.spin svg { animation: mbal-spin 0.8s linear infinite; } +@keyframes mbal-spin { to { transform: rotate(360deg); } } +.model-group-empty { font-size: 12px; color: var(--gray-light); padding: 12px 4px 2px; text-align: center; } +.model-card { background: #fafbfd; border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; margin: 10px 0 0; } +.model-card:last-child { margin-bottom: 2px; } +.model-card-head { display: flex; align-items: baseline; gap: 8px; } +.model-card-name { font-weight: 600; font-size: 15px; flex-shrink: 0; cursor: pointer; } +.model-card-name:active { opacity: 0.55; } +.model-card-meta { font-size: 12px; color: var(--gray); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.model-card-state { font-size: 11px; padding: 2px 8px; border-radius: 9px; flex-shrink: 0; } +.model-card-state.idle { background: #e3f2e6; color: #217a34; } +.model-card-state.busy { background: #fdecea; color: #b3382c; } +.model-card-state.pending { background: #fff4dc; color: #a06a00; } + +/* ---------- 编辑器页(config.yml 原文 / 技能文件) ---------- */ +.set-editor { + flex: 1; min-height: 0; display: flex; flex-direction: column; + padding: 10px 12px calc(12px + env(safe-area-inset-bottom, 0px)); +} +.set-editor textarea { + flex: 1; width: 100%; resize: none; background: #fff; color: var(--ink); + border: 1px solid #dde1ea; border-radius: 10px; padding: 10px 12px; + font-size: 12.5px; line-height: 1.55; tab-size: 4; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Courier New", monospace; + white-space: pre; overflow: auto; +} + +/* ---------- 按钮与弹窗(搬自 style.css,按 v2 调性去渐变) ---------- */ +.primary-btn { + width: 100%; background: var(--active); color: #fff; border: none; border-radius: 10px; + padding: 11px; font-size: 15px; font-weight: 600; cursor: pointer; +} +.primary-btn:active { opacity: 0.9; } +.primary-btn:disabled { opacity: 0.5; cursor: default; } +.ghost-btn { + background: var(--surface); color: #445; border: 1px solid #dde; border-radius: 10px; + padding: 11px; font-size: 15px; cursor: pointer; +} +.ghost-btn:active { background: #e8eaf0; } +.ghost-btn.danger { background: #fdf3f2; color: #c0392b; border-color: #eac2bd; } +.btn-row { display: flex; gap: 10px; } +.btn-row .primary-btn { flex: 1; } +.modal-overlay { + position: fixed; inset: 0; background: rgba(20, 25, 50, 0.45); + display: flex; align-items: center; justify-content: center; z-index: 100; +} +.modal { + background: var(--page); border-radius: 14px; padding: 20px; width: 84%; max-width: 360px; + position: relative; max-height: 88%; overflow-y: auto; +} +.modal h3 { margin-bottom: 12px; font-size: 16px; } +.modal input { + width: 100%; border: 1px solid #dde1ea; border-radius: 10px; + padding: 10px 12px; font-size: 15px; margin-bottom: 10px; background: #fff; color: var(--ink); +} +.modal input:focus { border-color: var(--active); } +.modal input:disabled { background: var(--surface); color: var(--gray-light); } +.modal select { + width: 100%; border: 1px solid #dde1ea; border-radius: 10px; + padding: 10px 12px; font-size: 15px; margin-bottom: 10px; + background: #fff; color: var(--ink); appearance: none; -webkit-appearance: none; +} +.modal select:focus { border-color: var(--active); } +.modal-close-btn { + position: absolute; right: 10px; top: 10px; + background: none; border: none; cursor: pointer; color: var(--gray-light); + width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; +} +.modal-close-btn svg { width: 18px; height: 18px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; } +.modal .modal-text { font-size: 14px; color: #556; margin-bottom: 12px; white-space: pre-wrap; } +.modal .del-dir { display: flex; align-items: center; gap: 7px; font-size: 14px; color: var(--ink); margin-bottom: 14px; cursor: pointer; } +.modal .del-dir input { width: 16px; height: 16px; padding: 0; margin: 0; flex: none; accent-color: var(--active); } diff --git a/app/server/public/v2.html b/app/server/public/v2.html index 6eada62..5ac0eab 100644 --- a/app/server/public/v2.html +++ b/app/server/public/v2.html @@ -79,7 +79,7 @@
-
+
A
Agent 用户
+ + + + + + + + + + + + + + +
@@ -107,12 +191,18 @@ * POST /api/sessions/:id/files 附件上传(multipart) * GET /api/sessions/:id/stream SSE 流式输出 * + * 设置区(侧边栏用户区整行点击进入;页面搬自 index.html,未新增任何接口): + * GET /api/system/status | POST /api/system/restart[?force=true] 服务·状态与重启 + * GET/PUT/PATCH /api/config | POST /api/config/validate 系统配置 / 原文编辑 / 模型增删改 + * GET /api/models | GET /api/platforms/balance 模型·模型池与余额 + * GET/POST/PUT/DELETE /api/skills[/:name][/file|/upload|/rename] 技能·技能与文件管理 + * GET /api/me | POST /api/password | GET /logout 账户·信息/改密/退出 + * * 后端已有但 v2 尚未接入 UI 的接口(先列出,不实现): * PATCH /api/sessions/:id 重命名(后端已支持) * POST /api/sessions/:id/stop | /release | /bind 终止/断开/绑定模型 * DELETE /api/sessions/:id/messages 清空会话内容 * GET /api/sessions/:id/files/download-token?path= 文件下载 - * GET /api/models | /api/system/status 模型池 / 系统状态 * * 无后端支撑、仅前端占位的概念(先不实现): * · 「文秘助理 / 识图专家」模式 —— 后端无 mode 字段,当前仅影响提示文案 @@ -661,11 +751,927 @@ openDrawer(false); }); - $('user-more-btn').addEventListener('click', () => toast('更多设置:待接入')); + // 抽屉底部用户区:整行点击 → 设置主页(逻辑见文末「设置区」一节) + $('drawer-user').addEventListener('click', () => { + openDrawer(false); + showSettings(); + }); // ---------- 顶栏 ---------- $('new-chat-btn').addEventListener('click', newChat); + // ============================================================================ + // 设置区(侧边栏用户区点击进入;页面搬自 index.html,接口全部复用既有 /api) + // ---------------------------------------------------------------------------- + // · 覆盖层 #settings-page:顶栏「左返回 + 中标题 + 右操作」,风格与对话页一致; + // 导航走 SET.stack 页面栈,返回弹一层、栈空即关闭;不再有底部导航。 + // · 页面:home 设置主页卡片 / account 账户 / service 服务(状态+配置) / + // cfg-editor config.yml 原文 / skills 列表 / skill-detail 详情 / + // skill-editor 技能文件编辑 / models 模型池。 + // ============================================================================ + + const SET = { + stack: [], + pendingKeys: new Set(), // 已写盘、尚未重启生效的顶层配置段 + effCfg: null, cfgOrig: '', + curSkill: null, // 技能详情/编辑视图对应的技能名 + editorPath: null, editorOrig: '', editorText: '', editorLabel: '', + // 模型池(搬自 models.js) + cfgPlatforms: [], cfgModels: [], runtimeById: {}, modelsPendingRestart: false, + moeIdx: -1, expandedGroups: {}, balanceByGroup: {}, balanceRequested: {}, balanceTypes: [], + }; + let setTok = 0; // 异步渲染防竞态令牌 + + // ---------- 通用小工具(搬自 core.js / settings.js) ---------- + const sleep = ms => new Promise(r => setTimeout(r, ms)); + function fmtSize(n) { + if (n == null) return ''; + if (n < 1024) return n + ' B'; + if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'; + return (n / 1024 / 1024).toFixed(1) + ' MB'; + } + function att(s) { return esc(s).replace(/"/g, '"'); } // 属性上下文转义(esc 不处理引号) + function getByPath(obj, p) { + return String(p).split('.').reduce((o, k) => (o == null ? undefined : o[k]), obj); + } + function fmtUptime(ms) { + const s = Math.floor((ms || 0) / 1000); + const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60); + if (d) return d + ' 天 ' + h + ' 小时'; + if (h) return h + ' 小时 ' + m + ' 分'; + if (m) return m + ' 分 ' + (s % 60) + ' 秒'; + return s + ' 秒'; + } + function dispVal(v) { + if (v === undefined || v === null || v === '') return '(未设置)'; + if (typeof v === 'boolean') return v ? '是' : '否'; + return String(v); + } + + // ---------- 统一确认/输入弹窗(搬自 core.js;会话删除仍用原生 confirm) ---------- + let _dlgResolve = null; + function _dlgSettle(val) { + $('confirm-modal').classList.add('hidden'); + $('prompt-modal').classList.add('hidden'); + const r = _dlgResolve; + _dlgResolve = null; + if (r) r(val); + } + function confirmModal(title, text, okText, danger) { + return new Promise(resolve => { + _dlgResolve = resolve; + $('confirm-title').textContent = title || '请确认'; + $('confirm-text').textContent = text || ''; + const ok = $('confirm-ok-btn'); + ok.textContent = okText || '确定'; + ok.style.background = danger ? 'linear-gradient(135deg,#a3352a,#d2483c)' : ''; + $('confirm-modal').classList.remove('hidden'); + }); + } + function confirmClose(v) { _dlgSettle(v); } + function promptModal(title, placeholder, initial, opts) { + return new Promise(resolve => { + _dlgResolve = resolve; + $('prompt-title').textContent = title || '请输入'; + const inp = $('prompt-input'); + inp.placeholder = placeholder || ''; + inp.value = initial || ''; + inp.type = opts && opts.type ? opts.type : 'text'; + $('prompt-modal').classList.remove('hidden'); + setTimeout(() => inp.focus(), 60); + }); + } + function promptOk() { _dlgSettle($('prompt-input').value); } + function promptCancel() { _dlgSettle(null); } + $('prompt-input').addEventListener('keydown', e => { + if (e.key === 'Enter') { e.preventDefault(); promptOk(); } + }); + + // ---------- 页面栈与顶栏 ---------- + function setTop() { return SET.stack[SET.stack.length - 1] || 'home'; } + function showSettings() { SET.stack = ['home']; $('settings-page').classList.remove('hidden'); renderSetPage(); } + function closeSettings() { SET.stack = []; $('settings-page').classList.add('hidden'); } + function setPush(p) { SET.stack.push(p); renderSetPage(); } + function setPopRaw() { SET.stack.pop(); renderSetPage(); } + function onSetBack() { + const p = setTop(); + if (p === 'skill-editor') return sUI.closeEditor(); + if (p === 'cfg-editor') return sUI.closeCfg(); + if (SET.stack.length > 1) setPopRaw(); else closeSettings(); + } + $('set-back-btn').addEventListener('click', onSetBack); + + function setTitle(t) { $('set-title').textContent = t; } + function setActions(html) { $('set-actions').innerHTML = html || ''; } + function setBody(html) { $('set-body').innerHTML = html; } + + function renderSetPage() { + const tok = ++setTok; + const p = setTop(); + const ctx = () => tok === setTok && setTop() === p; // 异步回包时页面可能已切走 + if (p === 'home') return setPageHome(ctx); + if (p === 'account') return setPageAccount(ctx); + if (p === 'service') return setPageService(ctx); + if (p === 'cfg-editor') return setPageCfgEditor(ctx); + if (p === 'skills') return setPageSkills(ctx); + if (p === 'skill-detail') return setPageSkillDetail(ctx); + if (p === 'skill-editor') return setPageSkillEditor(ctx); + if (p === 'models') return setPageModels(ctx); + } + // 主页卡片跳转与配置表单脏值标红(容器常驻,各自委托一次) + $('set-body').addEventListener('click', e => { + const card = e.target.closest('.set-card'); + if (card && card.dataset.go) setPush(card.dataset.go); + }); + $('set-body').addEventListener('input', e => { + const inp = e.target; + if (inp.classList && inp.classList.contains('cfg-input')) { + inp.classList.toggle('cfg-dirty', inp.value.trim() !== inp.dataset.orig); + } + }); + + // ---------- 页:设置主页(卡片入口) ---------- + const SET_CARDS = [ + { go: 'account', name: '账户', desc: '修改密码 · 退出登录', + icon: '' }, + { go: 'service', name: '服务', desc: '服务状态 · 系统配置', + icon: '' }, + { go: 'skills', name: '技能', desc: '技能管理 · 技能文件编辑', + icon: '' }, + { go: 'models', name: '模型', desc: '模型池状态 · 增删改', + icon: '' }, + ]; + function setPageHome(ctx) { + setTitle('设置'); + setActions(''); + setBody('
' + SET_CARDS.map(c => + '').join('') + '
'); + } + + // ---------- 页:账户(修改密码 / 退出登录) ---------- + const AVATAR_COLORS = ['#4285F4', '#EA4335', '#FBBC05', '#34A853', '#5C6BC0', '#00897B', '#8E24AA', '#F4511E']; + function userInitials(name) { + const s = String(name || '').trim(); + if (!s) return '?'; + const two = s.slice(0, 2); + return two.charAt(0).toUpperCase() + (two.length > 1 ? two.charAt(1).toLowerCase() : ''); + } + function avatarColor(name) { + let h = 0; + for (const ch of String(name || '')) h = (h * 31 + ch.codePointAt(0)) >>> 0; + return AVATAR_COLORS[h % AVATAR_COLORS.length]; + } + function userCardHtml(me) { + return '
' + + '
' + esc(userInitials(me)) + '
' + + '
' + esc(me) + '
' + + '
' + + '' + + '' + + '
'; + } + async function setPageAccount(ctx) { + setTitle('账户'); + setActions(''); + setBody('
加载中…
'); + try { + const [st, me] = await Promise.all([ + req('GET', '/api/system/status'), + req('GET', '/api/me').catch(function () { return { user: null }; }), // 未启用认证时无此路由 + ]); + if (!ctx()) return; + if (!st.auth_enabled || !me || !me.user) { + setBody('
未启用登录认证,无账户设置。
'); + return; + } + setBody('
' + userCardHtml(me.user) + '
'); + } catch (e) { + if (ctx()) setBody('
加载失败:' + esc(e.message) + '
'); + } + } + async function changePassword() { + try { + const newP = await promptModal('修改密码', '新密码,至少 6 位', '', { type: 'password' }); + if (newP == null) return; + if (newP.length < 6) { toast('新密码至少 6 位'); return; } + await req('POST', '/api/password', { new_password: newP }); + toast('密码已修改,立即生效'); + } catch (e) { toast('修改失败:' + e.message); } + } + + // ---------- 页:服务(服务状态 + 系统配置;搬自 settings.js) ---------- + const CFG_FORM = [ + { group: 'Agent 会话', items: [ + { path: 'agent.temperature', label: '温度 temperature', type: 'float' }, + { path: 'agent.max_tool_iterations', label: '单会话最大工具轮次', type: 'int' }, + { path: 'agent.max_retries', label: '上游失败重试次数', type: 'int' }, + { path: 'agent.language', label: '回复语言(留空不限)', type: 'text' }, + ] }, + { group: '终端工具', items: [ + { path: 'terminal.default_timeout_ms', label: '命令默认超时(ms)', type: 'int' }, + { path: 'terminal.max_output_chars', label: '输出最大字符数', type: 'int' }, + ] }, + { group: '技能', items: [ + { path: 'skills.timeout_ms', label: '技能执行超时(ms)', type: 'int' }, + ] }, + { group: '图片上传压缩(浏览器端)', items: [ + { path: 'upload.image_compress_threshold_kb', label: '大图阈值(KB)', type: 'int' }, + { path: 'upload.image_max_dim', label: '压缩后长边上限(px)', type: 'int' }, + { path: 'upload.image_quality', label: 'JPEG 质量(0~1)', type: 'float' }, + ] }, + { group: '模型租约(会话结束后的保持)', items: [ + { path: 'model_hold.idle_release_ms', label: '无人观看释放(ms)', type: 'int' }, + { path: 'model_hold.active_max_ms', label: '最长保持(ms)', type: 'int' }, + { path: 'model_hold.sweep_ms', label: '巡检间隔(ms)', type: 'int' }, + ] }, + ]; + function kvPlain(label, v) { + return '
' + esc(dispVal(v)) + '
'; + } + function svcCardHtml(st) { + let html = '

服务状态' + + (SET.pendingKeys.size ? ' 待重启生效' : '') + '

'; + html += kvPlain('版本 / Node', st.version + ' / ' + st.node); + html += kvPlain('已运行', fmtUptime(st.uptime_ms) + '(启动于 ' + new Date(st.started_at).toLocaleString() + ')'); + html += kvPlain('端口', st.port); + html += kvPlain('配置文件', st.config_path); + html += kvPlain('工作区', st.workspace_root); + html += kvPlain('技能目录', st.skills_root); + if (SET.pendingKeys.size) html += kvPlain('待生效改动', Array.from(SET.pendingKeys).join(', ')); + html += '' + + '
配置改动重启后生效;重启约需十几秒,期间页面暂不可用。非 Docker 部署不会自动拉起。
'; + return html; + } + function cfgInputHtml(it) { + const cur = getByPath(SET.effCfg, it.path); + const v = cur == null ? '' : String(cur); + if (it.type === 'text') { + return '
' + + '
'; + } + const step = it.type === 'float' ? ' step="any"' : ' step="1"'; + return '
' + + '
'; + } + function formCardHtml() { + let html = ''; + for (const g of CFG_FORM) { + html += '

' + esc(g.group) + '

'; + html += g.items.map(cfgInputHtml).join(''); + html += '
'; + } + html += '' + + '
更新即写入 config.yml(注释保留);多数配置需重启服务后生效。' + + '模型、账号、MCP 等请用右上角配置文件编辑。
'; + return html; + } + async function setPageService(ctx) { + setTitle('服务'); + setActions(''); + setBody('
加载中…
'); + try { + const [st, cg] = await Promise.all([ + req('GET', '/api/system/status'), + req('GET', '/api/config'), + ]); + if (!ctx()) return; + SET.effCfg = cg.effective || {}; + const el = $('svc-body'); + if (el) el.innerHTML = svcCardHtml(st) + formCardHtml(); + } catch (e) { + if (ctx()) setBody('
加载失败:' + esc(e.message) + '
'); + } + } + // 表单保存:收集与打开时不同的项,逐项 PATCH(搬自 settings.js saveForm) + async function saveForm() { + const inputs = document.querySelectorAll('#set-body .cfg-input'); + const edits = []; + for (const inp of inputs) { + const v = inp.value.trim(); + if (v === inp.dataset.orig) continue; + let val = v; + if (inp.dataset.type === 'int' || inp.dataset.type === 'float') { + val = Number(v); + if (v === '' || !isFinite(val)) { toast('「' + inp.dataset.label + '」需填数字'); return; } + if (inp.dataset.type === 'int' && !Number.isInteger(val)) { toast('「' + inp.dataset.label + '」需为整数'); return; } + } + edits.push({ path: inp.dataset.path, value: val }); + } + if (!edits.length) { toast('没有改动'); return; } + const btn = $('cfg-save-btn'); + if (btn) btn.disabled = true; + let lastChanged = []; + try { + for (const e of edits) { + const r = await req('PATCH', '/api/config', { path: e.path, value: e.value }); + lastChanged = r.changed || []; + lastChanged.forEach(k => SET.pendingKeys.add(k)); + } + toast('已保存 ' + edits.length + ' 项' + (lastChanged.length ? ',重启后生效' : '')); + } catch (e) { + toast('保存失败:' + e.message); + } finally { + if (btn) btn.disabled = false; + } + renderSetPage(); + } + // 重启服务(搬自 settings.js restart) + async function restart() { + if (!await confirmModal('重启服务', '重启服务使新配置生效?正在执行的 AI 会话会被打断。', '重启')) return; + try { + await req('POST', '/api/system/restart'); + } catch (e) { + // 仅「有会话在跑」值得二次确认强打;配置不合法等 409 强打也无法启动,直接报给用户 + if (e.status === 409 && /个任务.*执行中/.test(e.message)) { + if (!await confirmModal('有任务在跑', e.message, '强制重启', true)) return; + try { await req('POST', '/api/system/restart?force=true'); } + catch (e2) { toast('重启失败:' + e2.message); return; } + } else { toast('重启失败:' + e.message); return; } + } + const btn = $('restart-btn'); + if (btn) { btn.disabled = true; btn.textContent = '重启中,请勿关闭页面…'; } + toast('服务重启中…'); + for (let i = 0; i < 90; i++) { + await sleep(1000); + try { const r = await fetch('/api/health'); if (r.ok) { location.reload(); return; } } catch (_) {} + } + toast('90 秒内未恢复,请检查容器状态(非 Docker 部署需手动启动)'); + if (btn) { btn.disabled = false; btn.textContent = '重启服务'; } + } + + // ---------- 页:config.yml 原文编辑器(搬自 settings.js) ---------- + function openCfgEditor() { setPush('cfg-editor'); } + async function setPageCfgEditor(ctx) { + setTitle('config.yml 原文'); + setActions(''); + setBody('
' + + '
'); + try { + const cg = await req('GET', '/api/config'); + if (!ctx()) return; + SET.cfgOrig = cg.text; + $('set-editor-area').value = cg.text; + } catch (e) { + // 读取失败不能留下空编辑器:保存会把空文本写回配置,改展示错误态 + if (ctx()) setBody('
读取失败:' + esc(e.message) + '
'); + } + } + async function saveCfg() { + const area = $('set-editor-area'); + if (!area) { toast('配置未加载'); return; } + const text = area.value; + const errEl = $('cfg-editor-err'); + if (errEl) errEl.classList.add('hidden'); + try { + await req('POST', '/api/config/validate', { text }); // 先干跑,错误信息更友好 + const r = await req('PUT', '/api/config', { text }); + SET.cfgOrig = text; + (r.changed || []).forEach(k => SET.pendingKeys.add(k)); + toast('配置已保存'); + setPopRaw(); // 保存成功直接退出编辑页,回服务页即刷新生效值展示 + } catch (e) { + if (errEl) { errEl.textContent = '校验失败:' + e.message; errEl.classList.remove('hidden'); } + toast('配置不合法,未写入'); + } + } + async function closeCfg() { + const area = $('set-editor-area'); + if (area && area.value !== SET.cfgOrig && + !await confirmModal('未保存的修改', '有未保存的修改,确定关闭并丢弃?', '关闭', true)) return; + setPopRaw(); + } + + // ---------- 页:技能(列表/详情/文件编辑;搬自 skills.js) ---------- + async function setPageSkills(ctx) { + SET.curSkill = null; + setTitle('技能管理'); + setActions(''); + setBody('
加载中…
'); + try { + const rows = await req('GET', '/api/skills'); + if (!ctx()) return; + const el = $('skills-list'); + if (!el) return; + if (!rows.length) { + el.innerHTML = '
还没有技能,点右上角 + 新建一个。
'; + return; + } + el.innerHTML = rows.map(s => { + const a = encodeURIComponent(s.name); + return '
' + + '
' + + '
' + esc(s.name) + + (s.has_md ? '' : ' 缺 SKILL.md') + + (s.entry ? ' ' + s.entry + ' 入口' : '') + + '
' + + '
' + esc(s.description || '') + '
' + + '
' + s.file_count + ' 个文件' + + '' + fmtSize(s.size) + '' + + (s.mtime ? '' + fmtTime(s.mtime) + '' : '') + '
' + + '
' + + '
' + + '' + + '' + + '
' + + '
'; + }).join(''); + } catch (e) { + if (ctx()) setBody('
加载失败:' + esc(e.message) + '
'); + } + } + async function openSkill(nameEnc) { + SET.curSkill = decodeURIComponent(nameEnc); + setPush('skill-detail'); + } + async function setPageSkillDetail(ctx) { + if (!SET.curSkill) { if (SET.stack.length > 1) setPopRaw(); return; } + setTitle(SET.curSkill); + setActions(''); + setBody('
加载中…
'); + try { + const d = await req('GET', '/api/skills/' + encodeURIComponent(SET.curSkill)); + if (!ctx()) return; + setTitle(d.name); + const el = $('skill-detail'); + if (!el) return; + const newBtn = ''; + if (!d.files.length) { + el.innerHTML = '
技能目录是空的
' + newBtn; + return; + } + el.innerHTML = '
' + d.files.map(f => { + const a = encodeURIComponent(f.filename); + return '
' + + '' + + '' + esc(f.filename) + '' + + '' + fmtSize(f.size) + '' + + '' + + '' + + '
'; + }).join('') + '
' + newBtn; + } catch (e) { + if (ctx()) setBody('
加载失败:' + esc(e.message) + '
'); + } + } + function setPageSkillEditor(ctx) { + setTitle(SET.editorLabel || '编辑文件'); + setActions(''); + setBody('
'); + $('set-editor-area').value = SET.editorText; + } + async function openSkillFile(pathEnc) { + const rel = decodeURIComponent(pathEnc); + try { + const f = await req('GET', '/api/skills/' + encodeURIComponent(SET.curSkill) + '/file?path=' + encodeURIComponent(rel)); + SET.editorPath = f.path; SET.editorOrig = f.content; + SET.editorText = f.content; + SET.editorLabel = SET.curSkill + ' / ' + f.path; + setPush('skill-editor'); + } catch (e) { toast('打开失败:' + e.message); } + } + async function newSkillFile() { + if (!SET.curSkill) return; + const p = await promptModal('新建文件', '相对技能目录的路径,可含子目录(如 scripts/run.sh)', ''); + if (p == null) return; + const rel = p.trim(); + if (!rel) { toast('路径为空'); return; } + SET.editorPath = rel; SET.editorOrig = ''; + SET.editorText = ''; + SET.editorLabel = SET.curSkill + ' / ' + rel + '(新建)'; + setPush('skill-editor'); + } + async function saveSkillFile() { + if (!SET.curSkill || SET.editorPath == null) return; + const content = $('set-editor-area').value; + try { + await req('PUT', '/api/skills/' + encodeURIComponent(SET.curSkill) + '/file', { path: SET.editorPath, content }); + SET.editorOrig = content; + toast('已保存 ' + SET.editorPath); + SET.editorPath = null; + setPopRaw(); // 保存成功直接退出编辑页,回详情即刷新文件列表 + } catch (e) { toast('保存失败:' + e.message); } + } + async function closeSkillEditor() { + const area = $('set-editor-area'); + if (area && area.value !== SET.editorOrig && + !await confirmModal('未保存的修改', '有未保存的修改,确定关闭编辑器并丢弃?', '关闭', true)) return; + SET.editorPath = null; SET.editorOrig = ''; SET.editorText = ''; + setPopRaw(); + } + async function deleteSkillFile(pathEnc) { + const rel = decodeURIComponent(pathEnc); + if (!await confirmModal('删除文件', '删除文件 ' + rel + ' ?', '删除', true)) return; + try { + await req('DELETE', '/api/skills/' + encodeURIComponent(SET.curSkill) + '/file?path=' + encodeURIComponent(rel)); + toast('已删除'); + renderSetPage(); + } catch (e) { toast('删除失败:' + e.message); } + } + // 单文件上传;重名默认 409,询问后带 overwrite 重试(搬自 skills.js) + async function uploadSkillFile(ev) { + const input = ev.target; + const file = input.files && input.files[0]; + input.value = ''; + if (!file || !SET.curSkill) return; + const send = async function (overwrite) { + const fd = new FormData(); + fd.append('file', file); + return req('POST', '/api/skills/' + encodeURIComponent(SET.curSkill) + '/upload' + (overwrite ? '?overwrite=true' : ''), fd, true); + }; + try { + await send(false); + toast('已上传 ' + file.name); + } catch (e) { + if (/已存在/.test(e.message)) { + if (!await confirmModal('文件已存在', file.name + ' 已存在,覆盖?', '覆盖')) return; + try { await send(true); toast('已覆盖 ' + file.name); } + catch (e2) { toast('上传失败:' + e2.message); } + } else { + toast('上传失败:' + e.message); + } + } + renderSetPage(); + } + function openCreateSkill() { + $('skill-new-name').value = ''; + $('skill-new-desc').value = ''; + $('skill-create-modal').classList.remove('hidden'); + $('skill-new-name').focus(); + } + function closeCreateSkill() { $('skill-create-modal').classList.add('hidden'); } + async function createSkill() { + const name = $('skill-new-name').value.trim(); + if (!name) { toast('请填写技能名'); return; } + try { + await req('POST', '/api/skills', { name, description: $('skill-new-desc').value.trim() }); + closeCreateSkill(); + toast('已创建 ' + name); + SET.curSkill = name; + setPush('skill-detail'); // 新建后直接进详情,方便继续编辑 SKILL.md + } catch (e) { toast('创建失败:' + e.message); } + } + async function renameSkill(nameEnc) { + const name = nameEnc ? decodeURIComponent(nameEnc) : SET.curSkill; + if (!name) return; + const nn = await promptModal('重命名技能', '新的技能名', name); + if (nn == null) return; + const newName = nn.trim(); + if (!newName || newName === name) return; + try { + await req('POST', '/api/skills/' + encodeURIComponent(name) + '/rename', { newName }); + toast('已重命名为 ' + newName); + if (SET.curSkill === name) SET.curSkill = newName; + renderSetPage(); + } catch (e) { toast('重命名失败:' + e.message); } + } + async function deleteSkill(nameEnc) { + const name = nameEnc ? decodeURIComponent(nameEnc) : SET.curSkill; + if (!name) return; + if (!await confirmModal('删除技能', '确定删除技能「' + name + '」?目录下所有文件将不可恢复。', '删除', true)) return; + try { + await req('DELETE', '/api/skills/' + encodeURIComponent(name)); + toast('已删除 ' + name); + if (SET.curSkill === name) SET.curSkill = null; + if (setTop() === 'skill-detail') setPopRaw(); else renderSetPage(); + } catch (e) { toast('删除失败:' + e.message); } + } + + // ---------- 页:模型池(状态 + 增/改/删;搬自 models.js) ---------- + // api_key 脱敏显示兼容后端已脱敏结果(幂等) + function maskKey(k) { + k = k || ''; + if (k.includes('***')) return k; + if (k.length > 8) return k.slice(0, 3) + '***' + k.slice(-4); + if (k.length > 0) return '***' + k.slice(-2); + return ''; + } + // token 用量紧凑显示:<1000 原样;k(1 位小数去尾零);≥1M 用 M + function fmtTok(n) { + n = Number(n) || 0; + if (n < 1000) return String(n); + if (n < 1000000) { const v = (n / 1000).toFixed(1).replace(/\.0$/, ''); return v + 'k'; } + const v = (n / 1000000).toFixed(1).replace(/\.0$/, ''); + return v + 'M'; + } + function balText(gk) { + const b = SET.balanceByGroup[gk]; + if (!b) return '余额 --'; + if (b.error) return '余额 查询失败'; + return '余额 ' + (b.total_balance == null ? '--' : b.total_balance) + (b.currency ? ' ' + esc(b.currency) : ''); + } + function balTitle(gk) { + const b = SET.balanceByGroup[gk]; + if (!b) return ''; + if (b.error) return '查询失败:' + b.error; + const parts = []; + if (b.available === false) parts.push('上游报告余额不可用'); + if (b.granted_balance != null) parts.push('赠送 ' + b.granted_balance); + if (b.topped_up_balance != null) parts.push('充值 ' + b.topped_up_balance); + return parts.join(' · '); + } + async function fetchBalance(gk, pi, ki, manual) { + SET.balanceRequested[gk] = true; // 无论成败,本页会话不再自动重查(手动刷新不受限) + const btn = $('mbrg-' + gk); + if (btn) btn.classList.add('spin'); + const el = $('mbal-' + gk); + if (el) el.textContent = '余额 …'; + try { + const r = await req('GET', '/api/platforms/balance?pi=' + pi + '&ki=' + ki); + const b = r.balance || {}; + SET.balanceByGroup[gk] = { + total_balance: b.total_balance, currency: b.currency, + granted_balance: b.granted_balance, topped_up_balance: b.topped_up_balance, + available: b.is_available, + }; + } catch (e) { + SET.balanceByGroup[gk] = { error: e.message }; + if (manual) toast('查余额失败:' + e.message); // 自动查询失败只落悬停详情,不打扰 + } + if (btn) btn.classList.remove('spin'); + const el2 = $('mbal-' + gk); + if (el2) { el2.textContent = balText(gk); el2.title = balTitle(gk); } + } + // 点刷新图标:无视「本页已查过」标记,总是重新请求 + function refreshBalance(ev, pi, ki) { + if (ev) ev.stopPropagation(); // 冒泡到分组头会误触折叠/展开 + fetchBalance(pi + '-' + ki, pi, ki, true); + } + const BAL_REFRESH_SVG = ''; + function toggleModelGroup(gk) { + const on = !SET.expandedGroups[gk]; + SET.expandedGroups[gk] = on; + const el = $('mgrp-' + gk); + if (!el) return; + el.classList.toggle('open', on); + const body = el.querySelector('.model-group-body'); + if (body) body.classList.toggle('hidden', !on); + // 首次展开自动查一次余额(余额由平台名+key 决定);标记随每次进入本页重置 + if (on && !SET.balanceRequested[gk] && $('mbal-' + gk)) { + const parts = gk.split('-'); + fetchBalance(gk, Number(parts[0]), Number(parts[1]), false); + } + } + // 单个模型的子卡片;余额是 Key 级概念,统一在分组头显示 + function modelCardHtml(m) { + const run = SET.runtimeById[m.id]; + // 运行池里没有 = 配置新增但还没重启生效 + const stateHtml = run + ? '' + (run.is_busy ? '占用中' : '空闲') + '' + : '待重启'; + return '
' + + '
' + + '' + esc(m.display_name || m.mid || m.id) + '' + + '' + esc(m.mid || m.id) + + (run && run.is_busy && run.current_session_id ? ' · 会话 ' + esc(run.current_session_id) : '') + '' + + stateHtml + + '
' + + '
' + (run ? fmtTok(run.today_prompt) + ' / ' + fmtTok(run.today_completion) : '--') + '
' + + '
' + (run ? fmtTok(run.total_prompt) + ' / ' + fmtTok(run.total_completion) : '--') + '
' + + '
'; + } + function modelGroupHtml(pi, ki) { + const p = SET.cfgPlatforms[pi] || {}; + const k = (p.keys || [])[ki] || {}; + const gk = pi + '-' + ki; + const models = SET.cfgModels.filter(m => m.platform_index === pi && m.key_index === ki); + const open = !!SET.expandedGroups[gk]; + // 仅已接入余额查询的类型显示余额行(未接入的显示出来也只会是报错,不如不显示) + const hasBal = SET.balanceTypes.indexOf(String(p.type || '')) >= 0; + return '
' + + '
' + + '' + + '' + esc(p.name || ('平台' + pi)) + '' + + '' + esc(k.api_key ? maskKey(k.api_key) : '无 key') + '' + + '' + models.length + ' 模型' + + '
' + + '
' + + (hasBal ? + '
' + + '' + balText(gk) + '' + + '' + + '
' : '') + + (models.length ? models.map(modelCardHtml).join('') : '
该 Key 下暂无模型
') + + '
' + + '
'; + } + async function loadModelCards(ctx) { + const el = $('model-cards'); + if (!el || (ctx && !ctx())) return; + try { + const [rt, cg] = await Promise.all([req('GET', '/api/models'), req('GET', '/api/config')]); + if (ctx && !ctx()) return; + if (!$('model-cards')) return; // 异步期间已离开本页 + SET.runtimeById = {}; + for (const m of rt || []) SET.runtimeById[m.id] = m; + SET.cfgPlatforms = (cg.effective && cg.effective.platforms) || []; + SET.cfgModels = (cg.effective && cg.effective.models) || []; + SET.balanceTypes = cg.balance_types || []; + const box = $('model-cards'); + if (!SET.cfgModels.length) { + box.innerHTML = '
尚未配置模型,点右上角 + 添加。
'; + return; + } + let html = ''; + SET.cfgPlatforms.forEach((p, pi) => (p.keys || []).forEach((k, ki) => { + html += modelGroupHtml(pi, ki); + })); + box.innerHTML = html + + (SET.modelsPendingRestart + ? '
已写入 config.yml,到「服务」页重启服务后生效。
' + : '
token 格式为「输入 / 输出」;余额在分组首次展开时自动查询,点刷新图标可重查;改动写入 config.yml,重启服务后生效。
'); + } catch (e) { + const box = $('model-cards'); + if (box && (!ctx || ctx())) box.innerHTML = '
加载失败:' + esc(e.message) + '
'; + } + } + function setPageModels(ctx) { + setTitle('模型池'); + setActions(''); + setBody('
加载中…
'); + // 每次进入本页:余额结果与「已自动查过」标记重置(同 index 的 Tab onShow) + SET.balanceByGroup = {}; + SET.balanceRequested = {}; + loadModelCards(ctx); + } + function idxOf(id) { + for (let i = 0; i < SET.cfgModels.length; i++) if (SET.cfgModels[i].id === id) return i; + return -1; + } + function afterWrite() { + SET.modelsPendingRestart = true; + SET.balanceByGroup = {}; // 配置变了,旧余额不再对应现有 pi/ki 槽位 + SET.balanceRequested = {}; + toast('已写入 config.yml,到「服务」页重启后生效'); + loadModelCards(); + } + // Key 标签:「平台名 · sk-***1234」;下拉里用它标识可挂模型的目标 Key。 + function keyLabel(pi, ki) { + const p = SET.cfgPlatforms[pi] || {}; + const k = (p.keys || [])[ki] || {}; + return (p.name || ('平台' + pi)) + ' · ' + (k.api_key ? maskKey(k.api_key) : '无 key'); + } + function targetOptions() { + let html = ''; + SET.cfgPlatforms.forEach((p, pi) => (p.keys || []).forEach((k, ki) => { + html += ''; + })); + html += ''; + html += ''; + return html; + } + // 切换「新增 Key / 新增平台」时显隐对应字段。 + function onTargetChange() { + const t = $('moe-target').value || ''; + $('moe-newkey-wrap').classList.toggle('hidden', t !== 'newkey'); + $('moe-newplat-wrap').classList.toggle('hidden', t !== 'newplat'); + } + function fillNewKeyPlatforms() { + $('moe-nk-plat').innerHTML = SET.cfgPlatforms.map((p, i) => + '').join(''); + } + function openModelEditor(rawId) { + const add = rawId == null; + SET.moeIdx = add ? -1 : idxOf(decodeURIComponent(rawId)); + if (!add && SET.moeIdx < 0) return toast('模型不存在'); + const m = add ? null : SET.cfgModels[SET.moeIdx]; + $('moe-title').textContent = add ? '添加模型' : '编辑模型'; + const idIn = $('moe-id'); + idIn.value = m ? (m.mid || m.id) : ''; + idIn.disabled = !add; // 编辑时禁改 id(历史会话按「平台名/模型id」绑定,改 id 等于换模型) + $('moe-name').value = m ? (m.display_name || '') : ''; + $('moe-vision').checked = m ? !!m.vision : false; + const tgt = $('moe-target'); + if (add) { + tgt.disabled = false; + tgt.innerHTML = targetOptions(); + fillNewKeyPlatforms(); + } else { + // 编辑时锁定目标为本模型所属 Key(移动模型 = 删除后重建,不支持就地挪) + tgt.innerHTML = ''; + tgt.disabled = true; + } + tgt.onchange = onTargetChange; + onTargetChange(); // add 模式默认 exist → 两组附加字段都隐藏 + $('moe-del-btn').classList.toggle('hidden', add); + $('model-edit-modal').classList.remove('hidden'); + } + function closeModelEditor() { $('model-edit-modal').classList.add('hidden'); } + async function saveModelEditor() { + const id = $('moe-id').value.trim(); + if (!id) return toast('请填写 id'); + // 模型项本身只含 id/display_name/vision;url/key/concurrency 在平台/Key 层,这里不动。 + const model = { + id, + display_name: $('moe-name').value.trim() || id, + vision: $('moe-vision').checked, + }; + const add = SET.moeIdx < 0; + let body; + if (!add) { + // 编辑:精确改到 platforms[pi].keys[ki].models[mi] + const m = SET.cfgModels[SET.moeIdx]; + body = { path: ['platforms', m.platform_index, 'keys', m.key_index, 'models', m.model_index], value: model }; + } else { + const t = $('moe-target').value; + // id 唯一性只看同平台(内部键 = 平台名/模型id);不同平台可同名。 + let platName = ''; + if (t === 'newkey') platName = (SET.cfgPlatforms[parseInt($('moe-nk-plat').value, 10)] || {}).name || ''; + else if (t.indexOf('exist:') === 0) platName = (SET.cfgPlatforms[Number(t.split(':')[1])] || {}).name || ''; + if (platName && SET.cfgModels.some(x => x.platform === platName && x.mid === id)) return toast('平台「' + platName + '」下已有模型 id:' + id); + if (t === 'newplat') { + const url = $('moe-np-url').value.trim().replace(/\/+$/, ''); + if (!url) return toast('请填写平台上游地址'); + // append 一整个新平台:含一个新 Key + 这个模型;key 明文只在此时输入一次。 + body = { op: 'append', path: ['platforms'], value: { + name: $('moe-np-name').value.trim(), + url, + type: $('moe-np-type').value.trim() || 'openai', + keys: [{ api_key: $('moe-np-key').value.trim(), concurrency: parseInt($('moe-np-con').value, 10) || 1, models: [model] }], + } }; + } else if (t === 'newkey') { + const pi = parseInt($('moe-nk-plat').value, 10); + if (!(pi >= 0)) return toast('请选择平台'); + // append 一个新 Key 到已有平台;模型挂在它下面。 + body = { op: 'append', path: ['platforms', pi, 'keys'], value: { + api_key: $('moe-nk-key').value.trim(), concurrency: parseInt($('moe-nk-con').value, 10) || 1, models: [model] } }; + } else { + // exist:pi:ki → append 模型到已有 Key 的 models 数组 + const parts = t.split(':'); + body = { op: 'append', path: ['platforms', Number(parts[1]), 'keys', Number(parts[2]), 'models'], value: model }; + } + } + try { + await req('PATCH', '/api/config', body); + closeModelEditor(); + afterWrite(); + } catch (e) { toast('保存失败:' + e.message); } + } + async function delModelFromModal() { + if (SET.moeIdx < 0) return; + const m = SET.cfgModels[SET.moeIdx]; + closeModelEditor(); + if (SET.cfgModels.length <= 1) return toast('至少要保留一个模型'); + const ok = await confirmModal('删除模型', '删除模型「' + (m.display_name || m.id) + '」?将从 platforms 中移除该模型项。', '删除', true); + if (!ok) return; + try { + // delete 到 platforms[pi].keys[ki].models[mi];YAML 数组删项会自动收紧,不影响其他行注释。 + await req('PATCH', '/api/config', { path: ['platforms', m.platform_index, 'keys', m.key_index, 'models', m.model_index], op: 'delete' }); + afterWrite(); + } catch (e) { toast('删除失败:' + e.message); } + } + + // ---------- 设置区对外接口(动态卡片里的 onclick 均指向这里) ---------- + window.sUI = { + // 账户 + changePassword: changePassword, + logout: function () { location.href = '/logout'; }, + // 服务 + saveForm: saveForm, + restart: restart, + openCfg: openCfgEditor, + saveCfg: saveCfg, + closeCfg: closeCfg, + // 技能 + open: openSkill, + openCreate: openCreateSkill, + closeCreate: closeCreateSkill, + createSkill: createSkill, + renameSkill: renameSkill, + deleteSkill: deleteSkill, + editFile: openSkillFile, + saveFile: saveSkillFile, + closeEditor: closeSkillEditor, + newFile: newSkillFile, + deleteFile: deleteSkillFile, + onUpload: uploadSkillFile, + // 模型 + openAdd: function () { openModelEditor(null); }, + mEdit: openModelEditor, + mClose: closeModelEditor, + mSave: saveModelEditor, + mDel: delModelFromModal, + toggleGroup: toggleModelGroup, + refreshBalance: refreshBalance, + }; + // ---------- 初始化 ---------- selectMode('secretary'); // 默认选中【文秘助理】 setView('welcome');