加入自动生成标题功能支持
This commit is contained in:
@@ -32,7 +32,7 @@ const DEFAULTS = {
|
||||
// 只在回合循环结束、finalize 之后检查,AI↔工具交互过程中绝不触发;压缩回合自身不再复查(防递归)。
|
||||
// 满足条件后延迟 1.5s 再推送(避开超长回合刚结束时前端收尾渲染的高峰;期间会话有变动则撤回提议)。
|
||||
// 改后重启生效。
|
||||
agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2, language: '中文', auto_compress_tokens: 60000 },
|
||||
agent: { temperature: 1.0, max_tool_iterations: 50, max_retries: 2, language: 'Simplified Chinese', auto_compress_tokens: 60000 },
|
||||
// 大图上传预处理:图片文件超过 threshold_kb 时,浏览器端询问用户后用 canvas 压缩
|
||||
// (长边 ≤ max_dim,JPEG quality)再上传,减轻服务器带宽与存储压力。参数经 /api/system/status 下发给前端。
|
||||
upload: { image_compress_threshold_kb: 1536, image_max_dim: 2000, image_quality: 0.85 },
|
||||
|
||||
+38
-4
@@ -2,7 +2,7 @@
|
||||
// 单进程内存模型:JS 单线程 + better-sqlite3 同步 API,不存在跨进程竞争。
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { buildMessages, callModel, encodeBlocks, compressPromptText, historyTranscript } = require('./llm');
|
||||
const { buildMessages, callModel, encodeBlocks, compressPromptText, historyTranscript, titleMessages } = require('./llm');
|
||||
const { executeTool, resolveInTask } = require('./tools/executor');
|
||||
const mcp = require('./mcp');
|
||||
const log = require('./log');
|
||||
@@ -11,6 +11,7 @@ const TOOL_DEFINITIONS = require('./tools/definitions.json');
|
||||
|
||||
let cfg, db, bus;
|
||||
const runs = new Map(); // session_id -> {cancelled, procs:Set, abortController, looping:boolean}
|
||||
const titling = new Set(); // 正在生成标题的会话(防重入;标题落库后靠 title 非空自然不再触发)
|
||||
|
||||
// ---------- 小工具 ----------
|
||||
const now = () => Date.now();
|
||||
@@ -410,6 +411,42 @@ function finalize(sessionId, run) {
|
||||
runs.delete(sessionId);
|
||||
bus.emit(sessionId, 'done', { status: 'held' });
|
||||
emitStatus(sessionId);
|
||||
maybeGenerateTitle(sessionId, s);
|
||||
}
|
||||
|
||||
// 首次交互结束后自动生成会话标题:fire-and-forget,不阻塞回合收尾。
|
||||
// 不带 system prompt:历史 user/assistant 原文 + 末尾一条标题指令 user(见 llm.titleMessages),
|
||||
// 用会话当前 model_id 发一次不传 tools 的调用。失败静默(title 仍空,下个回合结束自动重试)。
|
||||
function maybeGenerateTitle(sessionId, s) {
|
||||
try {
|
||||
if (s.title) return;
|
||||
const modelId = s.model_id;
|
||||
if (!modelId || titling.has(sessionId)) return;
|
||||
titling.add(sessionId);
|
||||
const messages = titleMessages(loadHistory(sessionId), cfg.agent.language);
|
||||
callModel(cfg, modelId, messages, null, {})
|
||||
.then(r => {
|
||||
const title = cleanTitle(r && r.content);
|
||||
if (!title) return;
|
||||
touch(sessionId, { title });
|
||||
bus.emit(sessionId, 'title', { title }); // 前端监听:刷新详情页标题 + 重拉会话列表
|
||||
log.info('task', sessionId + ' 自动生成标题「' + title + '」');
|
||||
})
|
||||
.catch(err => log.warn('task', sessionId + ' 生成标题失败:' + String(err && err.message || err)))
|
||||
.finally(() => titling.delete(sessionId));
|
||||
} catch (e) {
|
||||
titling.delete(sessionId);
|
||||
log.warn('task', sessionId + ' 生成标题异常:' + String(e && e.message || e));
|
||||
}
|
||||
}
|
||||
|
||||
// 清洗模型返回的标题:压成单行、去包裹引号,截断到 60 字(手动重命名上限 100,留余量)。
|
||||
function cleanTitle(raw) {
|
||||
let t = String(raw || '').replace(/\s+/g, ' ').trim();
|
||||
const q = ['"', '\'', '“', '”', '‘', '’', '「', '」', '『', '』', '《', '》'];
|
||||
while (t.length > 2 && q.includes(t[0])) t = t.slice(1).trimStart();
|
||||
while (t.length > 1 && q.includes(t[t.length - 1])) t = t.slice(0, -1).trimEnd();
|
||||
return t.slice(0, 60);
|
||||
}
|
||||
|
||||
async function runLoopInner(sessionId, run) {
|
||||
@@ -779,9 +816,6 @@ function postUserMessage(sessionId, content, opts) {
|
||||
const session = getSession(sessionId);
|
||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||
const messageId = saveMessage(sessionId, { role: 'user', content });
|
||||
if (!session.title) {
|
||||
touch(sessionId, { title: content.slice(0, 24) });
|
||||
}
|
||||
// 预建/更新 run 记录,记下本轮的 deepThink(被 runLoop / callModel 读取)
|
||||
const run = getRun(sessionId, true);
|
||||
run.deepThink = !!(opts && opts.deepThink);
|
||||
|
||||
+25
-1
@@ -51,6 +51,30 @@ function compressPromptText(conversation) {
|
||||
return COMPRESS_PROMPT_TEMPLATE + '\n\n## 对话记录\n' + rec;
|
||||
}
|
||||
|
||||
// 自动生成会话标题提示词(templates/title-prompt.txt):会话建立后第 1 次交互完成时触发。
|
||||
// 与压缩回合不同,这里**不带 system prompt**:直接复用历史里的 user/assistant 文本消息,
|
||||
// 末尾追加一条 user(本模板,{{language}} 占位符替换为配置语言),见 titleMessages。
|
||||
const TITLE_PROMPT_TEMPLATE = fs.readFileSync(path.join(__dirname, 'templates', 'title-prompt.txt'), 'utf8');
|
||||
|
||||
// 拼标题回合的 messages:历史原样(只留 user/assistant 纯文本行)+ 末尾一条标题指令 user。
|
||||
// 与 historyTranscript 同取舍:archived 行不进;__blocks__ 哨兵 JSON 还原为文字,图片以 [图片] 占位;
|
||||
// 含 tool_calls 的 assistant 行无文本内容则跳过,tool 回执行整体跳过(只要对话主干)。
|
||||
function titleMessages(history, language) {
|
||||
const messages = [];
|
||||
for (const row of history || []) {
|
||||
if (row.type === 'archived') continue;
|
||||
if (row.role !== 'user' && row.role !== 'assistant') continue;
|
||||
let content = row.content || '';
|
||||
const blocks = decodeBlocks(content);
|
||||
if (blocks) content = blocks.map(b => (b && b.type === 'text' ? b.text : '[图片]')).join('\n');
|
||||
if (!content.trim()) continue;
|
||||
messages.push({ role: row.role, content });
|
||||
}
|
||||
const lang = String(language || '').trim() || 'the same language as the conversation';
|
||||
messages.push({ role: 'user', content: TITLE_PROMPT_TEMPLATE.replaceAll('{{language}}', () => lang) });
|
||||
return messages;
|
||||
}
|
||||
|
||||
// system prompt 完全静态:所有会话共用同一份内容,利于上游前缀缓存。
|
||||
function buildSystemPrompt() {
|
||||
return SYSTEM_PROMPT_TEMPLATE;
|
||||
@@ -386,4 +410,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||
}
|
||||
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, encodeBlocks, decodeBlocks, compressPromptText, historyTranscript };
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, encodeBlocks, decodeBlocks, compressPromptText, historyTranscript, titleMessages };
|
||||
|
||||
@@ -2125,6 +2125,12 @@
|
||||
updateScrollBottomBtn();
|
||||
loadSessionList();
|
||||
});
|
||||
// 服务端首次交互后自动生成的标题(finalize 后约 1s 到达):即时刷新顶栏 + 重拉会话列表(PC 常驻侧边栏/移动抽屉)
|
||||
es.addEventListener('title', ev => {
|
||||
const d = JSON.parse(ev.data);
|
||||
if (d && d.title) { state.sessionTitle = d.title; renderHeader(); }
|
||||
loadSessionList();
|
||||
});
|
||||
es.addEventListener('error', ev => {
|
||||
removeTyping();
|
||||
try {
|
||||
|
||||
@@ -1,184 +0,0 @@
|
||||
// Agent 任务台前端核心(2.0):共享工具函数 + 底部导航路由。
|
||||
// 页面拆分:core.js(本文件)/ tasks.js / skills.js / models.js / settings.js。
|
||||
// 约定:各业务文件把自身注册进 window.tabModules[tabName] = { onShow() {...} },
|
||||
// 路由在对应 Tab 每次显示时调用其 onShow()。
|
||||
'use strict';
|
||||
|
||||
if (typeof marked !== 'undefined') {
|
||||
marked.setOptions({ breaks: true, gfm: true });
|
||||
}
|
||||
|
||||
// 全局共享状态(目前主要被 tasks.js 使用;core 仅用 sessionId 处理 Tab 切换时的聊天收尾)
|
||||
const state = {
|
||||
sessionId: null,
|
||||
status: '',
|
||||
es: null,
|
||||
streamEl: null,
|
||||
streamText: '',
|
||||
turnEl: null,
|
||||
toolCards: {},
|
||||
filePanelOpen: false,
|
||||
pendingDeleteId: null,
|
||||
pendingEl: null,
|
||||
pendingTimer: null,
|
||||
pendingStart: 0,
|
||||
streaming: false, // AI 是否正在输出(用于滚动到底部按钮显示加载提示)
|
||||
};
|
||||
|
||||
window.tabModules = window.tabModules || {};
|
||||
|
||||
// ---------- API ----------
|
||||
async function req(method, url, body, isForm) {
|
||||
const opt = { method, headers: {} };
|
||||
if (body && !isForm) {
|
||||
opt.headers['Content-Type'] = 'application/json';
|
||||
opt.body = JSON.stringify(body);
|
||||
} else if (body && isForm) {
|
||||
opt.body = body;
|
||||
}
|
||||
const res = await fetch(url, opt);
|
||||
if (res.status === 401) { location.href = '/login'; throw new Error('未登录'); }
|
||||
if (!res.ok) {
|
||||
let msg = 'HTTP ' + res.status;
|
||||
try { msg = (await res.json()).error || msg; } catch (_) {}
|
||||
const err = new Error(msg);
|
||||
err.status = res.status; // 供调用方区分 409(重启保护/重名)等状态
|
||||
throw err;
|
||||
}
|
||||
return res.json();
|
||||
}
|
||||
|
||||
// ---------- 工具函数 ----------
|
||||
function $(id) { return document.getElementById(id); }
|
||||
function esc(s) { const d = document.createElement('div'); d.textContent = s == null ? '' : String(s); return d.innerHTML; }
|
||||
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 fmtTime(ts) {
|
||||
if (!ts) return '';
|
||||
const d = new Date(ts);
|
||||
const p = n => String(n).padStart(2, '0');
|
||||
const now = new Date();
|
||||
const hm = p(d.getHours()) + ':' + p(d.getMinutes());
|
||||
if (now.toDateString() === d.toDateString()) return hm;
|
||||
const md = (d.getMonth() + 1) + '/' + d.getDate();
|
||||
// 跨天带日期,跨年再带年份
|
||||
return (d.getFullYear() === now.getFullYear() ? md : d.getFullYear() + '/' + md) + ' ' + hm;
|
||||
}
|
||||
// 剪贴板:优先 navigator.clipboard(https/localhost),失败时降级 execCommand。
|
||||
// 降级用 readonly textarea + 只 select 不 focus:不选焦点,手机上不弹软键盘。
|
||||
async function copyText(text) {
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; }
|
||||
} catch (_) { /* 落入降级 */ }
|
||||
try {
|
||||
const ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
ta.setAttribute('readonly', '');
|
||||
ta.style.position = 'fixed'; ta.style.top = '0'; ta.style.left = '-9999px';
|
||||
ta.style.opacity = '0';
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
ta.setSelectionRange(0, ta.value.length);
|
||||
const ok = document.execCommand('copy');
|
||||
document.body.removeChild(ta);
|
||||
return ok;
|
||||
} catch (_) { return false; }
|
||||
}
|
||||
function toast(msg) {
|
||||
const el = $('toast');
|
||||
el.textContent = msg;
|
||||
el.classList.remove('hidden');
|
||||
clearTimeout(toast._t);
|
||||
toast._t = setTimeout(() => el.classList.add('hidden'), 2500);
|
||||
}
|
||||
|
||||
// ---------- 统一弹窗(替代原生 confirm/prompt;同屏仅弹一个) ----------
|
||||
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);
|
||||
}
|
||||
// 确认框:resolve(true/false);danger=true 时确定钮红色
|
||||
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); }
|
||||
// 输入框:resolve(字符串) 或取消 resolve(null);opts.type 可指定 password 等输入类型
|
||||
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); }
|
||||
(function () {
|
||||
const inp = document.getElementById('prompt-input');
|
||||
if (inp) inp.addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); promptOk(); }
|
||||
});
|
||||
})();
|
||||
|
||||
// ---------- 底部导航路由(hash) ----------
|
||||
const TABS = ['tasks', 'skills', 'models', 'settings'];
|
||||
|
||||
function currentTabFromHash() {
|
||||
const m = /^#\/(\w+)/.exec(location.hash || '');
|
||||
const t = m && m[1];
|
||||
return TABS.indexOf(t) >= 0 ? t : 'tasks';
|
||||
}
|
||||
|
||||
function showTab(name) {
|
||||
for (const t of TABS) {
|
||||
const el = $('tab-' + t);
|
||||
if (el) el.classList.toggle('hidden', t !== name);
|
||||
}
|
||||
for (const a of document.querySelectorAll('.tab-item')) {
|
||||
a.classList.toggle('active', a.dataset.tab === name);
|
||||
}
|
||||
const mod = window.tabModules[name];
|
||||
if (mod && typeof mod.onShow === 'function') {
|
||||
try { mod.onShow(); } catch (e) { console.error('[tab ' + name + '] onShow 失败', e); }
|
||||
}
|
||||
}
|
||||
|
||||
function initRouter() {
|
||||
for (const a of document.querySelectorAll('.tab-item')) {
|
||||
a.addEventListener('click', () => {
|
||||
// 点当前已激活的 Tab 不会触发 hashchange:若正停在聊天详情,直接返回列表
|
||||
if (a.dataset.tab === currentTabFromHash() && state.sessionId && window.ui) ui.backToList();
|
||||
});
|
||||
}
|
||||
window.addEventListener('hashchange', () => {
|
||||
// 跨 Tab 导航(含浏览器返回键)时,先收尾打开中的聊天详情
|
||||
if (state.sessionId && window.ui) ui.backToList();
|
||||
showTab(currentTabFromHash());
|
||||
});
|
||||
}
|
||||
|
||||
function boot() {
|
||||
initRouter();
|
||||
showTab(currentTabFromHash());
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', boot);
|
||||
@@ -1,361 +0,0 @@
|
||||
// 模型 Tab(阶段 5):模型池状态 + 模型增 / 改 / 删(仅写 config.yml,到「设置」页重启才生效)。
|
||||
// 配置为 platforms 层级(平台 → models + keys):url/type/models 在平台层,api_key/concurrency 在 Key 层,
|
||||
// 同一份 models 被该平台下所有 key 共用。模型项 {id, display_name, vision, enable, ...};id 只需同平台内唯一
|
||||
// (内部唯一键 = 平台名/模型id,effective.models 的 id 即该键、mid 为原始模型名)。
|
||||
// 页面 PATCH 用 platforms[i].models[k] 定位(key_index 不进入路径,因为模型与 key 解耦);
|
||||
// 新增一律走 append(只动目标数组,脱敏 key 绝不整体回写文件);已有 Key 的 api_key 修改请走配置原文编辑器。
|
||||
// 展示层暂按「平台名 + 脱敏 Key」分组(cf. models.js modelGroupHtml):每组都展示该平台下所有 models
|
||||
// (key 间重复),等后续 UI 重构再去重;余额按 key 拆开,每个 key 一行。
|
||||
'use strict';
|
||||
|
||||
window.tabModules = window.tabModules || {};
|
||||
|
||||
let cfgPlatforms = []; // effective.platforms(服务端已对 api_key 脱敏)
|
||||
let cfgModels = []; // 打平后的 effective.models(含 platform_index/key_index/model_index)
|
||||
// 注:同一 (name/id) 在 cfgModels 里出现 N 次(N=key 数),key_index 区分 key 副本
|
||||
let runtimeById = {}; // 运行池状态,按 id 关联
|
||||
let modelsPendingRestart = false;
|
||||
let moeIdx = -1; // 当前编辑弹窗对应的打平下标;-1 = 新增
|
||||
let expandedGroups = {}; // 模型池分组展开态,key =「pi-ki」;余额按 key 拆,分组即 Key 槽位,默认折叠
|
||||
let balanceByGroup = {}; // 余额查询结果缓存,key =「pi-ki」;切 Tab/写配置时清空
|
||||
let balanceRequested = {}; // 本 Tab 会话内该分组是否已自动查过(首次展开只自动查一次)
|
||||
let balanceTypes = []; // 后端已接入余额查询的平台类型(GET /api/config 的 balance_types)
|
||||
|
||||
// api_key 脱敏显示:sk-***1234 样式。后端 GET effective 已脱敏,这里仅兜底(幂等)。
|
||||
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 用量紧凑显示:1.2k / 9.1M 这种 human-friendly 量级,一眼看出多少。
|
||||
// <1000 原样;1k~1M 用 k(1 位小数,去尾零);≥1M 用 M。0 显示为 0。
|
||||
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';
|
||||
}
|
||||
|
||||
// ---------- 模型池卡片:按「平台 + Key」分组 ----------
|
||||
// 余额由 platform.name + key 决定,故父级 = 平台名 · 脱敏 key,子级 = 该 Key 下的模型;默认折叠。
|
||||
|
||||
function toggleModelGroup(gk) {
|
||||
const on = !expandedGroups[gk];
|
||||
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);
|
||||
// 首次展开自动查一次余额(mbal 存在 = 该类型已接入);标记随切 Tab 重置,
|
||||
// 故每次切到模型 Tab 后,每个分组只自动查一次,反复折叠展开不重复请求
|
||||
if (on && !balanceRequested[gk] && $('mbal-' + gk)) {
|
||||
const parts = gk.split('-');
|
||||
fetchBalance(gk, Number(parts[0]), Number(parts[1]), false);
|
||||
}
|
||||
}
|
||||
|
||||
// 单个模型的子卡片;余额是 Key 级概念,统一在分组头显示,模型卡不再重复。
|
||||
function modelCardHtml(m) {
|
||||
const run = runtimeById[m.id];
|
||||
// 运行池里没有 = 配置新增但还没重启生效
|
||||
const stateHtml = run
|
||||
? '<span class="model-card-state ' + (run.is_busy ? 'busy' : 'idle') + '">' + (run.is_busy ? '占用中' : '空闲') + '</span>'
|
||||
: '<span class="model-card-state pending">待重启</span>';
|
||||
return '<div class="model-card">' +
|
||||
'<div class="model-card-head">' +
|
||||
'<span class="model-card-name" title="点击编辑" onclick="modelsUI.openEdit(\'' + encodeURIComponent(m.id) + '\')">' + esc(m.display_name || m.mid || m.id) + '</span>' +
|
||||
// 模型 id / 会话号紧跟名字同行,卡片更紧凑
|
||||
'<span class="model-card-meta">' + esc(m.mid || m.id) +
|
||||
(run && run.is_busy && run.current_session_id ? ' · 会话 ' + esc(run.current_session_id) : '') + '</span>' +
|
||||
stateHtml +
|
||||
'</div>' +
|
||||
// token 紧凑显示:输入 / 输出
|
||||
'<div class="cfg-kv"><label>今日 token</label><b title="输入 / 输出">' + (run ? fmtTok(run.today_prompt) + ' / ' + fmtTok(run.today_completion) : '--') + '</b></div>' +
|
||||
'<div class="cfg-kv"><label>累计 token</label><b title="输入 / 输出">' + (run ? fmtTok(run.total_prompt) + ' / ' + fmtTok(run.total_completion) : '--') + '</b></div>' +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
// 余额展示文案与悬停详情(查询成功后才有值,默认 --)
|
||||
function balText(gk) {
|
||||
const b = 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 = 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) {
|
||||
balanceRequested[gk] = true; // 无论成败,本 Tab 会话不再自动重查(手动刷新不受限)
|
||||
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 || {};
|
||||
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) {
|
||||
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 = '<svg viewBox="0 0 24 24"><polyline points="23 4 23 10 17 10"></polyline><path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path></svg>';
|
||||
|
||||
function modelGroupHtml(pi, ki) {
|
||||
const p = cfgPlatforms[pi] || {};
|
||||
const k = (p.keys || [])[ki] || {};
|
||||
const gk = pi + '-' + ki;
|
||||
// 该平台下所有 models(不按 key_index 过滤;key 间会重复展示,等后续 UI 重构再去重)
|
||||
const models = cfgModels.filter(m => m.platform_index === pi && m.key_index === ki);
|
||||
// 同 id 在 cfgModels 里出现 N 次(每个 key 副本),卡片只画一次以避免视觉重复;
|
||||
// 取该 key 副本下首条即可(同 id 字段相同,渲染无差异)。
|
||||
const seen = new Set();
|
||||
const dedup = [];
|
||||
for (const m of models) { if (!seen.has(m.id)) { seen.add(m.id); dedup.push(m); } }
|
||||
const open = !!expandedGroups[gk];
|
||||
// 仅已接入余额查询的类型显示余额行(未接入的显示出来也只会是报错,不如不显示)
|
||||
const hasBal = balanceTypes.indexOf(String(p.type || '')) >= 0;
|
||||
return '<div class="model-group' + (open ? ' open' : '') + '" id="mgrp-' + gk + '">' +
|
||||
'<div class="model-group-head" onclick="modelsUI.toggleGroup(\'' + gk + '\')">' +
|
||||
'<svg class="model-group-caret" viewBox="0 0 24 24"><polyline points="9 6 15 12 9 18"></polyline></svg>' +
|
||||
'<span class="model-group-name">' + esc(p.name || ('平台' + pi)) + '</span>' +
|
||||
'<span class="model-group-key">' + esc(k.api_key ? maskKey(k.api_key) : '无 key') + '</span>' +
|
||||
'<span class="model-group-meta">' + dedup.length + ' 模型</span>' +
|
||||
'</div>' +
|
||||
'<div class="model-group-body' + (open ? '' : ' hidden') + '">' +
|
||||
(hasBal ?
|
||||
'<div class="model-group-bal">' +
|
||||
'<span id="mbal-' + gk + '" title="' + esc(balTitle(gk)) + '">' + balText(gk) + '</span>' +
|
||||
'<button class="mbal-refresh" id="mbrg-' + gk + '" title="重新查询余额" onclick="modelsUI.refreshBalance(event,' + pi + ',' + ki + ')">' + BAL_REFRESH_SVG + '</button>' +
|
||||
'</div>' : '') +
|
||||
(dedup.length ? dedup.map(modelCardHtml).join('') : '<div class="model-group-empty">该 Key 下暂无模型</div>') +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
async function loadModelCards() {
|
||||
const el = $('model-cards');
|
||||
if (!el) return;
|
||||
try {
|
||||
const [rt, cg] = await Promise.all([req('GET', '/api/models'), req('GET', '/api/config')]);
|
||||
runtimeById = {};
|
||||
for (const m of rt || []) runtimeById[m.id] = m;
|
||||
cfgPlatforms = (cg.effective && cg.effective.platforms) || [];
|
||||
cfgModels = (cg.effective && cg.effective.models) || [];
|
||||
balanceTypes = cg.balance_types || [];
|
||||
if (!cfgModels.length) {
|
||||
el.innerHTML = '<div class="empty-tip">尚未配置模型,点右上角 + 添加。</div>';
|
||||
return;
|
||||
}
|
||||
let html = '';
|
||||
cfgPlatforms.forEach((p, pi) => (p.keys || []).forEach((k, ki) => {
|
||||
html += modelGroupHtml(pi, ki);
|
||||
}));
|
||||
el.innerHTML = html +
|
||||
(modelsPendingRestart
|
||||
? '<div class="empty-tip">已写入 config.yml,到「设置」页重启服务后生效。</div>'
|
||||
: '<div class="empty-tip">token 格式为「输入 / 输出」;余额在分组首次展开时自动查询,点刷新图标可重查;改动写入 config.yml,重启服务后生效。</div>');
|
||||
} catch (e) {
|
||||
el.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function idxOf(id) {
|
||||
for (let i = 0; i < cfgModels.length; i++) if (cfgModels[i].id === id) return i;
|
||||
return -1;
|
||||
}
|
||||
function afterWrite() {
|
||||
modelsPendingRestart = true;
|
||||
balanceByGroup = {}; // 配置变了,旧余额不再对应现有 pi/ki 槽位
|
||||
balanceRequested = {};
|
||||
toast('已写入 config.yml,到「设置」页重启后生效');
|
||||
loadModelCards();
|
||||
}
|
||||
|
||||
// ---------- 编辑/新增弹窗 ----------
|
||||
// Key 标签:「平台名 · sk-***1234」;下拉里用它标识可挂模型的目标 Key(新增模式下展示,实际模型与 key 解耦,
|
||||
// 所有 key 都共享 platforms.models)。
|
||||
function keyLabel(pi, ki) {
|
||||
const p = cfgPlatforms[pi] || {};
|
||||
const k = (p.keys || [])[ki] || {};
|
||||
return (p.name || ('平台' + pi)) + ' · ' + (k.api_key ? maskKey(k.api_key) : '无 key');
|
||||
}
|
||||
|
||||
function targetOptions() {
|
||||
let html = '';
|
||||
cfgPlatforms.forEach((p, pi) => {
|
||||
const n = (p.models || []).length;
|
||||
html += '<option value="plat:' + pi + '">' +
|
||||
esc(p.name || ('平台' + pi)) + '(' + n + ' 模型)</option>';
|
||||
});
|
||||
html += '<option value="newkey">+ 在已有平台下新增 Key</option>';
|
||||
html += '<option value="newplat">+ 新增平台</option>';
|
||||
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 = cfgPlatforms.map((p, i) =>
|
||||
'<option value="' + i + '">' + esc(p.name || ('平台' + i)) + '</option>').join('');
|
||||
}
|
||||
|
||||
function openModelEditor(rawId) {
|
||||
const add = rawId == null;
|
||||
moeIdx = add ? -1 : idxOf(decodeURIComponent(rawId));
|
||||
if (!add && moeIdx < 0) return toast('模型不存在');
|
||||
const m = add ? null : cfgModels[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 解耦后,移动模型 = 改 platforms[pi],已不支持)
|
||||
const p = cfgPlatforms[m.platform_index] || {};
|
||||
tgt.innerHTML = '<option value="plat:' + m.platform_index + '">' + esc(p.name || ('平台' + m.platform_index)) + '</option>';
|
||||
tgt.disabled = true;
|
||||
}
|
||||
tgt.onchange = onTargetChange;
|
||||
onTargetChange(); // add 模式默认 plat:0 → 两组附加字段都隐藏
|
||||
$('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/type 在平台层,api_key/concurrency 在 Key 层,这里不动。
|
||||
const model = {
|
||||
id,
|
||||
display_name: $('moe-name').value.trim() || id,
|
||||
vision: $('moe-vision').checked,
|
||||
};
|
||||
const add = moeIdx < 0;
|
||||
let body;
|
||||
if (!add) {
|
||||
// 编辑:改到 platforms[pi].models[mi](与 key 解耦,所有 key 共享同一份 models)
|
||||
const m = cfgModels[moeIdx];
|
||||
body = { path: ['platforms', m.platform_index, 'models', m.model_index], value: model };
|
||||
} else {
|
||||
const t = $('moe-target').value;
|
||||
// id 唯一性只看同平台(内部键 = 平台名/模型id);不同平台可同名。
|
||||
let platIdx = -1;
|
||||
if (t === 'newkey') platIdx = parseInt($('moe-nk-plat').value, 10);
|
||||
else if (t.indexOf('plat:') === 0) platIdx = Number(t.split(':')[1]);
|
||||
if (platIdx >= 0) {
|
||||
const p = cfgPlatforms[platIdx] || {};
|
||||
if (cfgModels.some(x => x.platform === p.name && x.mid === id)) {
|
||||
return toast('平台「' + (p.name || '') + '」下已有模型 id:' + id);
|
||||
}
|
||||
}
|
||||
if (t === 'newplat') {
|
||||
const url = $('moe-np-url').value.trim().replace(/\/+$/, '');
|
||||
if (!url) return toast('请填写平台上游地址');
|
||||
// append 一整个新平台:含一份 models 和一个 key;key 明文只在此时输入一次。
|
||||
body = { op: 'append', path: ['platforms'], value: {
|
||||
name: $('moe-np-name').value.trim(),
|
||||
url,
|
||||
type: $('moe-np-type').value.trim(),
|
||||
models: [model],
|
||||
keys: [{ api_key: $('moe-np-key').value.trim(), concurrency: parseInt($('moe-np-con').value, 10) || 1 }],
|
||||
} };
|
||||
} else if (t === 'newkey') {
|
||||
if (!(platIdx >= 0)) return toast('请选择平台');
|
||||
// append 一个新 Key 到已有平台(models 与 key 解耦,这里只追加 key,不重复 model)
|
||||
body = { op: 'append', path: ['platforms', platIdx, 'keys'], value: {
|
||||
api_key: $('moe-nk-key').value.trim(), concurrency: parseInt($('moe-nk-con').value, 10) || 1 } };
|
||||
// 紧接着把模型 append 到 platforms[platIdx].models
|
||||
await req('PATCH', '/api/config', body);
|
||||
try {
|
||||
await req('PATCH', '/api/config', { op: 'append', path: ['platforms', platIdx, 'models'], value: model });
|
||||
} catch (e) { throw e; }
|
||||
closeModelEditor();
|
||||
afterWrite();
|
||||
return;
|
||||
} else {
|
||||
// plat:pi → append 模型到 platforms[pi].models
|
||||
body = { op: 'append', path: ['platforms', platIdx, 'models'], value: model };
|
||||
}
|
||||
}
|
||||
try {
|
||||
await req('PATCH', '/api/config', body);
|
||||
closeModelEditor();
|
||||
afterWrite();
|
||||
} catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function delModelFromModal() {
|
||||
if (moeIdx < 0) return;
|
||||
const m = cfgModels[moeIdx];
|
||||
closeModelEditor();
|
||||
// 唯一性:同 id 在 cfgModels 里出现 N 次(N=key 数);删之前确认至少还剩一个平台的模型数 > 0
|
||||
const otherIds = new Set(cfgModels.filter(x => x.id !== m.id).map(x => x.id));
|
||||
if (otherIds.size < 1) return toast('至少要保留一个模型');
|
||||
const ok = await confirmModal('删除模型', '删除模型「' + (m.display_name || m.id) + '」?将从 platforms 中移除该模型项(该平台下所有 key 都不再可用此模型)。', '删除', true);
|
||||
if (!ok) return;
|
||||
try {
|
||||
// delete 到 platforms[pi].models[mi](与 key 解耦);YAML 数组删项会自动收紧,不影响其他行注释。
|
||||
await req('PATCH', '/api/config', { path: ['platforms', m.platform_index, 'models', m.model_index], op: 'delete' });
|
||||
SET.deletedModels[m.id] = true; // 重启前后端仍会返回该模型,本地标记隐藏
|
||||
afterWrite();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
window.modelsUI = {
|
||||
openAdd: function () { openModelEditor(null); },
|
||||
openEdit: openModelEditor,
|
||||
close: closeModelEditor,
|
||||
save: saveModelEditor,
|
||||
del: delModelFromModal,
|
||||
onTargetChange: onTargetChange,
|
||||
toggleGroup: toggleModelGroup,
|
||||
refreshBalance: refreshBalance,
|
||||
};
|
||||
|
||||
tabModules.models = {
|
||||
// 每次切到模型 Tab:余额结果与「本 Tab 已自动查过」标记一并重置,
|
||||
// 分组首次点开时重新自动查一次(对应需求:每次切 Tab 后只首次点开自动更新)
|
||||
onShow() { balanceByGroup = {}; balanceRequested = {}; loadModelCards(); },
|
||||
};
|
||||
@@ -1,290 +0,0 @@
|
||||
// 设置 Tab(阶段 5):账号 / 服务状态与重启 / config.yml 表单化编辑。
|
||||
// 语义:所有写入 = 服务端校验 → 写盘;多数改动需「重启服务」生效(本项目不做热重载)。
|
||||
// 表单值展示的是「当前生效值」;改完未重启前显示旧值属正常,保存按钮统一写盘。
|
||||
// 模型池 / 登录账号 / MCP / 路径类配置不在本页编辑,请用顶栏「配置文件」图标改原文。
|
||||
'use strict';
|
||||
|
||||
window.tabModules = window.tabModules || {};
|
||||
|
||||
let effCfg = null; // 当前生效配置(GET /api/config 的 effective)
|
||||
let cfgOrig = ''; // 原文编辑器打开/上次保存内容(脏检测)
|
||||
const pendingKeys = new Set(); // 本次会话已写盘、但尚未通过重启生效的顶层段
|
||||
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
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);
|
||||
}
|
||||
// 属性上下文转义(esc 不处理引号)
|
||||
function att(s) { return esc(s).replace(/"/g, '"'); }
|
||||
|
||||
// ---------- 表单 schema:path 点分路径;type:int|float ----------
|
||||
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 '<div class="cfg-kv"><label>' + esc(label) + '</label><b>' + esc(dispVal(v)) + '</b></div>';
|
||||
}
|
||||
|
||||
// 用户信息卡(仅启用认证时显示,页面顶部):Google 风双字母头像 + 用户名 + 操作按钮。
|
||||
// 头像字母/配色均前端本地生成,无外部依赖。
|
||||
const AVATAR_COLORS = ['#4285F4', '#EA4335', '#FBBC05', '#34A853', '#5C6BC0', '#00897B', '#8E24AA', '#F4511E'];
|
||||
|
||||
// 取用户名前两个字符:首字母大写、次字母小写(kicer→Ki);单字符只显一个;
|
||||
// 中文取前两字,charAt 大小写对汉字无副作用,无需特判
|
||||
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 userCard(me) {
|
||||
return '<div class="settings-card user-card">' +
|
||||
'<div class="user-avatar" style="background:' + avatarColor(me) + '">' + esc(userInitials(me)) + '</div>' +
|
||||
'<div class="user-name">' + esc(me) + '</div>' +
|
||||
'<div class="user-acts">' +
|
||||
'<button class="ghost-btn" onclick="cfgUI.changePassword()">修改密码</button>' +
|
||||
'<button class="ghost-btn" onclick="ui.logout()">退出登录</button>' +
|
||||
'</div></div>';
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
function svcCard(st) {
|
||||
let html = '<div class="settings-card"><h4>服务状态' +
|
||||
(pendingKeys.size ? ' <span class="badge held">待重启生效</span>' : '') + '</h4>';
|
||||
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.data_root);
|
||||
html += kvPlain('技能目录', st.skills_root);
|
||||
html += kvPlain('命令执行', st.executor_url ? st.executor_url + '(远端)' : '本地');
|
||||
if (pendingKeys.size) html += kvPlain('待生效改动', Array.from(pendingKeys).join(', '));
|
||||
html += '<button class="primary-btn" id="restart-btn" style="width:100%;margin-top:8px" onclick="cfgUI.restart()">重启服务</button>' +
|
||||
'<div class="cfg-note">配置改动重启后生效;重启约需十几秒,期间页面暂不可用。非 Docker 部署不会自动拉起。</div></div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function cfgInput(it) {
|
||||
const cur = getByPath(effCfg, it.path);
|
||||
const v = cur == null ? '' : String(cur);
|
||||
if (it.type === 'text') {
|
||||
return '<div class="cfg-kv"><label>' + esc(it.label) + '</label>' +
|
||||
'<input class="cfg-input" type="text"' +
|
||||
' data-path="' + att(it.path) + '" data-type="text" data-label="' + att(it.label) + '" data-orig="' + att(v) + '"' +
|
||||
' value="' + att(v) + '" placeholder="如:中文 / English"></div>';
|
||||
}
|
||||
const step = it.type === 'float' ? ' step="any"' : ' step="1"';
|
||||
return '<div class="cfg-kv"><label>' + esc(it.label) + '</label>' +
|
||||
'<input class="cfg-input" type="number"' + step +
|
||||
' inputmode="decimal"' +
|
||||
' data-path="' + att(it.path) + '" data-type="' + it.type + '" data-label="' + att(it.label) + '" data-orig="' + att(v) + '"' +
|
||||
' value="' + att(v) + '"></div>';
|
||||
}
|
||||
|
||||
function formCard() {
|
||||
let html = '';
|
||||
for (const g of CFG_FORM) {
|
||||
html += '<div class="settings-card"><h4>' + esc(g.group) + '</h4>';
|
||||
html += g.items.map(cfgInput).join('');
|
||||
html += '</div>';
|
||||
}
|
||||
html += '<button class="primary-btn" id="cfg-save-btn" style="width:100%" onclick="cfgUI.saveForm()">更新配置</button>' +
|
||||
'<div class="cfg-note" style="margin-bottom:12px">更新即写入 config.yml(注释保留);多数配置需重启服务后生效。' +
|
||||
'模型、账号、MCP 等请用右上角配置文件编辑。</div>';
|
||||
return html;
|
||||
}
|
||||
|
||||
async function loadSettings() {
|
||||
bindDirtyMark();
|
||||
const el = $('cfg-sections');
|
||||
if (!el) return;
|
||||
el.innerHTML = '<div class="empty-tip">加载中…</div>';
|
||||
try {
|
||||
const [st, cg, me] = await Promise.all([
|
||||
req('GET', '/api/system/status'),
|
||||
req('GET', '/api/config'),
|
||||
req('GET', '/api/me').catch(function () { return { user: null }; }), // 未启用认证时无此路由
|
||||
]);
|
||||
effCfg = cg.effective || {};
|
||||
el.innerHTML = (st.auth_enabled && me && me.user ? userCard(me.user) : '') + svcCard(st) + formCard();
|
||||
} catch (e) {
|
||||
el.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// 未保存改动标红:委托监听(#cfg-sections 容器常驻,innerHTML 重建不影响)
|
||||
let dirtyBound = false;
|
||||
function bindDirtyMark() {
|
||||
if (dirtyBound) return;
|
||||
const box = $('cfg-sections');
|
||||
if (!box) return;
|
||||
dirtyBound = true;
|
||||
box.addEventListener('input', function (ev) {
|
||||
const inp = ev.target;
|
||||
if (inp.classList && inp.classList.contains('cfg-input')) {
|
||||
inp.classList.toggle('cfg-dirty', inp.value.trim() !== inp.dataset.orig);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 表单保存(收集与打开时不同的项,逐项 PATCH) ----------
|
||||
async function saveForm() {
|
||||
const inputs = document.querySelectorAll('#cfg-sections .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 => pendingKeys.add(k));
|
||||
}
|
||||
toast('已保存 ' + edits.length + ' 项' + (lastChanged.length ? ',重启后生效' : ''));
|
||||
} catch (e) {
|
||||
toast('保存失败:' + e.message);
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
loadSettings();
|
||||
}
|
||||
|
||||
// ---------- 重启 ----------
|
||||
async function restart() {
|
||||
if (!await confirmModal('重启服务', '重启服务使新配置生效?正在执行的 AI 会话会被打断。', '重启')) return;
|
||||
try {
|
||||
await req('POST', '/api/system/restart');
|
||||
} catch (e) {
|
||||
if (e.status === 409 && /个任务.*执行中/.test(e.message)) {
|
||||
// 仅「有会话在跑」值得二次确认强打;配置不合法等 409 强打也无法启动,直接报给用户
|
||||
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 原文编辑器(顶栏图标打开) ----------
|
||||
async function openCfgEditor() {
|
||||
try {
|
||||
const cg = await req('GET', '/api/config');
|
||||
cfgOrig = cg.text;
|
||||
$('cfg-editor-area').value = cg.text;
|
||||
$('cfg-editor-err').classList.add('hidden');
|
||||
$('cfg-editor').classList.remove('hidden');
|
||||
} catch (e) { toast('读取失败:' + e.message); }
|
||||
}
|
||||
async function saveCfgEditor() {
|
||||
const text = $('cfg-editor-area').value;
|
||||
const errEl = $('cfg-editor-err');
|
||||
errEl.classList.add('hidden');
|
||||
try {
|
||||
await req('POST', '/api/config/validate', { text }); // 先干跑,错误信息更友好
|
||||
const r = await req('PUT', '/api/config', { text });
|
||||
cfgOrig = text;
|
||||
(r.changed || []).forEach(k => pendingKeys.add(k));
|
||||
toast('配置已保存');
|
||||
$('cfg-editor').classList.add('hidden');
|
||||
loadSettings(); // 保存成功直接退出编辑页
|
||||
} catch (e) {
|
||||
errEl.textContent = '校验失败:' + e.message;
|
||||
errEl.classList.remove('hidden');
|
||||
toast('配置不合法,未写入');
|
||||
}
|
||||
}
|
||||
async function closeCfgEditor() {
|
||||
if ($('cfg-editor-area').value !== cfgOrig &&
|
||||
!await confirmModal('未保存的修改', '有未保存的修改,确定关闭并丢弃?', '关闭', true)) return;
|
||||
$('cfg-editor').classList.add('hidden');
|
||||
loadSettings(); // 原文可能改了生效值相关的显示,回到本页时刷新
|
||||
}
|
||||
|
||||
window.cfgUI = {
|
||||
saveForm: saveForm,
|
||||
changePassword: changePassword,
|
||||
restart: restart,
|
||||
open: openCfgEditor,
|
||||
save: saveCfgEditor,
|
||||
close: closeCfgEditor,
|
||||
};
|
||||
|
||||
tabModules.settings = {
|
||||
onShow() { loadSettings(); },
|
||||
};
|
||||
@@ -1,248 +0,0 @@
|
||||
// 技能 Tab:SKILL 管理(技能增删改 + 技能内文件管理)。
|
||||
// 只做文件管理,不执行技能;技能是否生效由用户在任务里自行测试。
|
||||
// 视图:列表(list) / 技能详情(detail) / 文件编辑器(editor,全屏覆盖本 Tab)。
|
||||
'use strict';
|
||||
|
||||
window.tabModules = window.tabModules || {};
|
||||
|
||||
// 当前技能名(详情/编辑视图有效)与编辑器状态
|
||||
let curSkill = null;
|
||||
let editorPath = null; // 正在编辑的文件相对路径
|
||||
let editorOrig = ''; // 打开/上次保存时的内容,用于脏检测
|
||||
|
||||
// ---------- 视图切换 ----------
|
||||
function setSkillsView(v) {
|
||||
$('skills-back-btn').classList.toggle('hidden', v === 'list');
|
||||
$('skill-new-btn').classList.toggle('hidden', v !== 'list');
|
||||
$('skill-upload-btn').classList.toggle('hidden', v !== 'detail');
|
||||
$('skills-list').classList.toggle('hidden', v !== 'list');
|
||||
$('skill-detail').classList.toggle('hidden', v !== 'detail');
|
||||
$('skill-editor').classList.toggle('hidden', v !== 'editor');
|
||||
}
|
||||
|
||||
// ---------- 列表 ----------
|
||||
async function loadSkillList() {
|
||||
curSkill = null;
|
||||
setSkillsView('list');
|
||||
$('skills-title').textContent = '技能管理';
|
||||
const el = $('skills-list');
|
||||
el.innerHTML = '<div class="empty-tip">加载中…</div>';
|
||||
try {
|
||||
const rows = await req('GET', '/api/skills');
|
||||
if (!rows.length) {
|
||||
el.innerHTML = '<div class="empty-tip">还没有技能,点右上角 + 新建一个。</div>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = rows.map(s => {
|
||||
const a = encodeURIComponent(s.name);
|
||||
return '<div class="session-card" onclick="skillsUI.open(\'' + a + '\')">' +
|
||||
'<div class="session-main">' +
|
||||
'<div class="session-name">' + esc(s.name) +
|
||||
(s.has_md ? '' : ' <span class="badge cancelled">缺 SKILL.md</span>') +
|
||||
(s.entry ? ' <span class="badge active">' + s.entry + ' 入口</span>' : '') +
|
||||
'</div>' +
|
||||
'<div class="skill-desc">' + esc(s.description || '') + '</div>' +
|
||||
'<div class="session-meta"><span>' + s.file_count + ' 个文件</span>' +
|
||||
'<span>' + fmtSize(s.size) + '</span>' +
|
||||
(s.mtime ? '<span>' + fmtTime(s.mtime) + '</span>' : '') + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="card-acts">' +
|
||||
'<button class="card-act" onclick="event.stopPropagation();skillsUI.renameSkill(\'' + a + '\')">改名</button>' +
|
||||
'<button class="card-act del" onclick="event.stopPropagation();skillsUI.deleteSkill(\'' + a + '\')">删除</button>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}).join('');
|
||||
} catch (e) {
|
||||
el.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 详情(文件列表) ----------
|
||||
async function loadSkillDetail() {
|
||||
if (!curSkill) return loadSkillList();
|
||||
const el = $('skill-detail');
|
||||
el.innerHTML = '<div class="empty-tip">加载中…</div>';
|
||||
try {
|
||||
const d = await req('GET', '/api/skills/' + encodeURIComponent(curSkill));
|
||||
$('skills-title').textContent = d.name;
|
||||
const newBtn = '<button class="primary-btn" style="width:100%;margin-top:10px" onclick="skillsUI.newFile()">+ 新建文件</button>';
|
||||
if (!d.files.length) {
|
||||
el.innerHTML = '<div class="skill-files"><div class="empty-tip">技能目录是空的</div></div>' + newBtn;
|
||||
return;
|
||||
}
|
||||
el.innerHTML = '<div class="skill-files">' + d.files.map(f => {
|
||||
const a = encodeURIComponent(f.filename);
|
||||
return '<div class="file-row" onclick="skillsUI.editFile(\'' + a + '\')">' +
|
||||
'<svg class="file-ico" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>' +
|
||||
'<span class="file-name">' + esc(f.filename) + '</span>' +
|
||||
'<span class="file-size">' + fmtSize(f.size) + '</span>' +
|
||||
'<button class="file-act" onclick="event.stopPropagation();skillsUI.editFile(\'' + a + '\')">编辑</button>' +
|
||||
'<button class="file-act del" onclick="event.stopPropagation();skillsUI.deleteFile(\'' + a + '\')">删除</button>' +
|
||||
'</div>';
|
||||
}).join('') + '</div>' + newBtn;
|
||||
} catch (e) {
|
||||
el.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
|
||||
}
|
||||
}
|
||||
|
||||
async function openSkill(name) {
|
||||
curSkill = decodeURIComponent(name);
|
||||
setSkillsView('detail');
|
||||
await loadSkillDetail();
|
||||
}
|
||||
|
||||
function backFromSkill() {
|
||||
// 编辑器内的返回由 closeEditor 处理;这里只处理顶部返回(先提醒未保存)
|
||||
loadSkillList();
|
||||
}
|
||||
|
||||
// ---------- 技能增删改 ----------
|
||||
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);
|
||||
// 新建后直接进入详情,方便继续编辑 SKILL.md
|
||||
await openSkill(encodeURIComponent(name));
|
||||
} catch (e) { toast('创建失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function renameSkill(nameEnc) {
|
||||
const name = nameEnc ? decodeURIComponent(nameEnc) : 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 (curSkill === name) { curSkill = newName; await loadSkillDetail(); }
|
||||
else await loadSkillList();
|
||||
} catch (e) { toast('重命名失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function deleteSkill(nameEnc) {
|
||||
const name = nameEnc ? decodeURIComponent(nameEnc) : curSkill;
|
||||
if (!name) return;
|
||||
if (!await confirmModal('删除技能', '确定删除技能「' + name + '」?目录下所有文件将不可恢复。', '删除', true)) return;
|
||||
try {
|
||||
await req('DELETE', '/api/skills/' + encodeURIComponent(name));
|
||||
toast('已删除 ' + name);
|
||||
if (curSkill === name) curSkill = null;
|
||||
loadSkillList();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
// ---------- 技能内文件 ----------
|
||||
async function openFileEditor(path) {
|
||||
const rel = decodeURIComponent(path);
|
||||
try {
|
||||
const f = await req('GET', '/api/skills/' + encodeURIComponent(curSkill) + '/file?path=' + encodeURIComponent(rel));
|
||||
editorPath = f.path; editorOrig = f.content;
|
||||
$('skill-editor-name').textContent = curSkill + ' / ' + f.path;
|
||||
$('skill-editor-area').value = f.content;
|
||||
setSkillsView('editor');
|
||||
} catch (e) { toast('打开失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function saveSkillFile() {
|
||||
if (!curSkill || editorPath == null) return;
|
||||
const content = $('skill-editor-area').value;
|
||||
try {
|
||||
await req('PUT', '/api/skills/' + encodeURIComponent(curSkill) + '/file', { path: editorPath, content });
|
||||
editorOrig = content;
|
||||
toast('已保存 ' + editorPath);
|
||||
// 保存成功直接退出编辑页回文件列表
|
||||
editorPath = null;
|
||||
setSkillsView('detail');
|
||||
loadSkillDetail();
|
||||
} catch (e) { toast('保存失败:' + e.message); }
|
||||
}
|
||||
|
||||
async function closeSkillEditor() {
|
||||
if ($('skill-editor-area').value !== editorOrig &&
|
||||
!await confirmModal('未保存的修改', '有未保存的修改,确定关闭编辑器并丢弃?', '关闭', true)) return;
|
||||
editorPath = null; editorOrig = '';
|
||||
setSkillsView('detail');
|
||||
loadSkillDetail();
|
||||
}
|
||||
|
||||
async function newSkillFile() {
|
||||
if (!curSkill) return;
|
||||
const p = await promptModal('新建文件', '相对技能目录的路径,可含子目录(如 scripts/run.sh)', '');
|
||||
if (p == null) return;
|
||||
const rel = p.trim();
|
||||
if (!rel) { toast('路径为空'); return; }
|
||||
editorPath = rel; editorOrig = '';
|
||||
$('skill-editor-name').textContent = curSkill + ' / ' + rel + '(新建)';
|
||||
$('skill-editor-area').value = '';
|
||||
setSkillsView('editor');
|
||||
$('skill-editor-area').focus();
|
||||
}
|
||||
|
||||
async function deleteSkillFile(path) {
|
||||
const rel = decodeURIComponent(path);
|
||||
if (!await confirmModal('删除文件', '删除文件 ' + rel + ' ?', '删除', true)) return;
|
||||
try {
|
||||
await req('DELETE', '/api/skills/' + encodeURIComponent(curSkill) + '/file?path=' + encodeURIComponent(rel));
|
||||
toast('已删除');
|
||||
loadSkillDetail();
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
// 单文件上传;重名默认 409,询问后带 overwrite 重试
|
||||
async function uploadSkillFile(ev) {
|
||||
const input = ev.target;
|
||||
const file = input.files && input.files[0];
|
||||
input.value = '';
|
||||
if (!file || !curSkill) return;
|
||||
const send = async function (overwrite) {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
return req('POST', '/api/skills/' + encodeURIComponent(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);
|
||||
}
|
||||
}
|
||||
loadSkillDetail();
|
||||
}
|
||||
|
||||
window.skillsUI = {
|
||||
back: backFromSkill,
|
||||
open: openSkill,
|
||||
openCreate: openCreateSkill,
|
||||
closeCreate: closeCreateSkill,
|
||||
createSkill: createSkill,
|
||||
renameSkill: renameSkill,
|
||||
deleteSkill: deleteSkill,
|
||||
editFile: openFileEditor,
|
||||
saveFile: saveSkillFile,
|
||||
closeEditor: closeSkillEditor,
|
||||
newFile: newSkillFile,
|
||||
deleteFile: deleteSkillFile,
|
||||
onUpload: uploadSkillFile,
|
||||
};
|
||||
|
||||
tabModules.skills = {
|
||||
onShow() { loadSkillList(); },
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
Generate a concise title for this conversation in {{language}}, omitting punctuation.
|
||||
Aim for 3-7 words, or 6-14 Chinese characters if the title is in Chinese.
|
||||
Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`.
|
||||
If the conversation is about a specific subject, include it in the title.
|
||||
Be descriptive. DO NOT speak in the first person.
|
||||
@@ -12,6 +12,7 @@ services:
|
||||
- ./skills:/workspace/skills # 技能目录:所有任务/会话共享同一份技能
|
||||
- ./data:/workspace/data # 持久化:数据目录
|
||||
- ./config.yml:/app/config.yml # 允许设置页写配置(写前服务端会校验)
|
||||
- ./app/server:/app/server
|
||||
environment:
|
||||
- PORT=8090
|
||||
- AGENT_CONFIG=/app/config.yml
|
||||
@@ -20,8 +21,12 @@ services:
|
||||
# 调用鉴权 token:两侧同一值。从 .env 读取(已 gitignore),不再硬编码进仓库;
|
||||
# 未设置则 compose 直接报错,避免静默无鉴权。生成:openssl rand -hex 32
|
||||
- EXECUTOR_TOKEN=${EXECUTOR_TOKEN:?EXECUTOR_TOKEN not set - see .env.example}
|
||||
- VIRTUAL_HOST=agent.ai.foresh.com
|
||||
- VIRTUAL_PORT=8090
|
||||
- CERT_NAME=default
|
||||
networks:
|
||||
- agent-mcp-net
|
||||
- my-app-network
|
||||
|
||||
# 技能准备(一次性,跑完退出):把各技能的“运行期可变”依赖落到宿主 ./skills——
|
||||
# requirements.txt → 先离线探测,只把镜像缺的包装进共享 deps 目录(镜像已带的不重复装);
|
||||
@@ -131,3 +136,5 @@ networks:
|
||||
agent-mcp-net:
|
||||
name: agent-mcp-net
|
||||
driver: bridge
|
||||
my-app-network:
|
||||
external: true
|
||||
|
||||
Reference in New Issue
Block a user