@nestim/koishi-plugin-qqgm-webui 0.2.23 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +39 -56
- package/index.js +170 -11
- package/lib/bot.js +44 -0
- package/lib/data.js +49 -8
- package/lib/logbuf.js +79 -0
- package/lib/plugin-config.js +236 -0
- package/package.json +33 -29
- package/public/app.js +815 -187
- package/public/index.html +60 -145
- package/public/styles.css +89 -19
package/public/app.js
CHANGED
|
@@ -1,15 +1,41 @@
|
|
|
1
1
|
const titles = {
|
|
2
|
-
overview:
|
|
3
|
-
plugins:
|
|
4
|
-
monitor:
|
|
5
|
-
memory:
|
|
6
|
-
'main-schema':
|
|
7
|
-
config:
|
|
8
|
-
logs:
|
|
2
|
+
overview: '总览',
|
|
3
|
+
plugins: '插件',
|
|
4
|
+
monitor: '监控',
|
|
5
|
+
memory: '记忆库',
|
|
6
|
+
'main-schema': '主插件配置',
|
|
7
|
+
config: '附属配置',
|
|
8
|
+
logs: '日志',
|
|
9
9
|
};
|
|
10
10
|
|
|
11
11
|
const $ = (sel, root = document) => root.querySelector(sel);
|
|
12
12
|
const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
|
|
13
|
+
const params = new URLSearchParams(location.search);
|
|
14
|
+
const token = params.get('token') || '';
|
|
15
|
+
|
|
16
|
+
function apiPath(path) {
|
|
17
|
+
if (!token) return path;
|
|
18
|
+
return `${path}${path.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function apiGet(path) {
|
|
22
|
+
const res = await fetch(apiPath(path), { cache: 'no-store' });
|
|
23
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
24
|
+
return res.json();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function apiPost(path, body) {
|
|
28
|
+
const res = await fetch(apiPath(path), {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: { 'content-type': 'application/json' },
|
|
31
|
+
body: JSON.stringify(body || {}),
|
|
32
|
+
});
|
|
33
|
+
const data = await res.json().catch(() => ({}));
|
|
34
|
+
if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
35
|
+
return data;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const escHtml = (text) => String(text == null ? '' : text).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
13
39
|
|
|
14
40
|
function showToast(text) {
|
|
15
41
|
const el = $('#toast');
|
|
@@ -17,10 +43,35 @@ function showToast(text) {
|
|
|
17
43
|
el.textContent = text;
|
|
18
44
|
el.classList.add('show');
|
|
19
45
|
clearTimeout(showToast.timer);
|
|
20
|
-
showToast.timer = setTimeout(() => el.classList.remove('show'),
|
|
46
|
+
showToast.timer = setTimeout(() => el.classList.remove('show'), 2200);
|
|
21
47
|
}
|
|
22
48
|
|
|
49
|
+
// ---------------------------------------------------------------- 布局与导航
|
|
50
|
+
|
|
51
|
+
const sidebar = $('#sidebar');
|
|
52
|
+
const backdrop = $('#sidebarBackdrop');
|
|
53
|
+
|
|
54
|
+
function openNav() {
|
|
55
|
+
sidebar?.classList.add('open');
|
|
56
|
+
if (backdrop) backdrop.hidden = false;
|
|
57
|
+
document.body.classList.add('nav-open');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function closeNav() {
|
|
61
|
+
sidebar?.classList.remove('open');
|
|
62
|
+
if (backdrop) backdrop.hidden = true;
|
|
63
|
+
document.body.classList.remove('nav-open');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
$('#menuBtn')?.addEventListener('click', openNav);
|
|
67
|
+
$('#navClose')?.addEventListener('click', closeNav);
|
|
68
|
+
backdrop?.addEventListener('click', closeNav);
|
|
69
|
+
window.addEventListener('keydown', (event) => {
|
|
70
|
+
if (event.key === 'Escape') closeNav();
|
|
71
|
+
});
|
|
72
|
+
|
|
23
73
|
function go(page) {
|
|
74
|
+
if (!titles[page]) return;
|
|
24
75
|
const monitorNav = $('.nav-item[data-page="monitor"]');
|
|
25
76
|
if (page === 'monitor' && monitorNav && monitorNav.classList.contains('disabled')) {
|
|
26
77
|
showToast('安装 qqgm-monitor 后可用');
|
|
@@ -29,34 +80,88 @@ function go(page) {
|
|
|
29
80
|
$$('.nav-item').forEach((item) => item.classList.toggle('active', item.dataset.page === page));
|
|
30
81
|
$$('.nav-sub').forEach((item) => item.classList.toggle('active', item.dataset.page === page));
|
|
31
82
|
$$('.page').forEach((item) => item.classList.toggle('active', item.id === `page-${page}`));
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
const
|
|
35
|
-
if (
|
|
36
|
-
|
|
83
|
+
const title = $('#pageTitle');
|
|
84
|
+
if (title) title.textContent = titles[page];
|
|
85
|
+
const content = $('.content');
|
|
86
|
+
if (content) content.scrollTop = 0;
|
|
87
|
+
if (window.innerWidth <= 820) closeNav();
|
|
88
|
+
if (page === 'logs') {
|
|
89
|
+
logState.paused = false;
|
|
90
|
+
renderLogPause();
|
|
91
|
+
loadLogs(true);
|
|
92
|
+
}
|
|
93
|
+
if (page === 'memory') initMemoryData();
|
|
94
|
+
if (page === 'monitor') initMonitor();
|
|
95
|
+
if (page === 'config') initPluginConfig();
|
|
96
|
+
if (page === 'main-schema' && mainSchema) openMainGroup(activeMainGroup || 0);
|
|
37
97
|
}
|
|
38
98
|
|
|
39
99
|
$$('.nav-item').forEach((item) => item.addEventListener('click', () => go(item.dataset.page)));
|
|
40
|
-
$$('.nav-sub').forEach((item) => item.addEventListener('click', () =>
|
|
41
|
-
const page = item.dataset.page;
|
|
42
|
-
go(page);
|
|
43
|
-
if (page === 'main-schema' && mainSchema) openMainGroup(activeMainGroup || 0);
|
|
44
|
-
}));
|
|
100
|
+
$$('.nav-sub').forEach((item) => item.addEventListener('click', () => go(item.dataset.page)));
|
|
45
101
|
$$('[data-nav]').forEach((item) => item.addEventListener('click', (event) => {
|
|
46
102
|
event.preventDefault();
|
|
47
103
|
go(item.dataset.nav);
|
|
48
104
|
}));
|
|
49
105
|
$$('[data-toast]').forEach((item) => item.addEventListener('click', () => showToast(item.dataset.toast)));
|
|
50
106
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
107
|
+
const initialPage = params.get('page');
|
|
108
|
+
if (initialPage && titles[initialPage]) go(initialPage);
|
|
109
|
+
|
|
110
|
+
// ---------------------------------------------------------------- 真实 Bot 状态
|
|
111
|
+
|
|
112
|
+
let lastStatus = null;
|
|
113
|
+
|
|
114
|
+
function statusTooltip(status) {
|
|
115
|
+
if (!status || !status.bots) return '无法读取 Bot 状态';
|
|
116
|
+
if (!status.bots.length) return '没有已连接的 Bot:检查 adapter 是否启用';
|
|
117
|
+
return status.bots.map((bot) => `${bot.platform || 'bot'} · ${bot.selfId || '?'} · ${bot.statusText}`).join('\n');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function renderStatus(status) {
|
|
121
|
+
lastStatus = status;
|
|
122
|
+
const pill = $('#botStatus');
|
|
123
|
+
if (pill) {
|
|
124
|
+
const online = !!(status && status.onlineNow);
|
|
125
|
+
pill.classList.toggle('online', online);
|
|
126
|
+
pill.classList.toggle('offline', !online);
|
|
127
|
+
const label = pill.querySelector('b');
|
|
128
|
+
if (label) {
|
|
129
|
+
const text = online ? `Bot 在线 ${status.online}/${status.total}` : (status && status.total ? `Bot 离线 0/${status.total}` : 'Bot 未连接');
|
|
130
|
+
label.textContent = text;
|
|
131
|
+
}
|
|
132
|
+
pill.title = statusTooltip(status);
|
|
133
|
+
}
|
|
134
|
+
const sysBots = $('#sysBots');
|
|
135
|
+
if (sysBots) sysBots.textContent = status ? `${status.online} / ${status.total}` : '-';
|
|
136
|
+
const sysOnline = $('#sysOnline');
|
|
137
|
+
if (sysOnline) sysOnline.textContent = status && status.onlineNow ? '系统在线' : '系统离线';
|
|
138
|
+
const sysPulse = $('#sysPulse');
|
|
139
|
+
if (sysPulse) sysPulse.classList.toggle('off', !(status && status.onlineNow));
|
|
140
|
+
const platforms = [...new Set((status?.bots || []).map((bot) => bot.platform).filter(Boolean))];
|
|
141
|
+
const sysMeta = $('#sysMeta');
|
|
142
|
+
if (sysMeta) {
|
|
143
|
+
const up = status?.uptimeSec ? `${Math.floor(status.uptimeSec / 3600)}h${Math.floor((status.uptimeSec % 3600) / 60)}m` : '-';
|
|
144
|
+
sysMeta.textContent = `${platforms.join(' / ') || '未连接'} · 运行 ${up}`;
|
|
145
|
+
}
|
|
146
|
+
const statusBots = $('#statusBots');
|
|
147
|
+
if (statusBots) statusBots.textContent = `Bot ${status ? `${status.online}/${status.total}` : '-'}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function refreshStatus() {
|
|
151
|
+
try {
|
|
152
|
+
renderStatus(await apiGet('api/status'));
|
|
153
|
+
} catch {
|
|
154
|
+
renderStatus(null);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
refreshStatus();
|
|
159
|
+
setInterval(() => {
|
|
160
|
+
if (!document.hidden) refreshStatus();
|
|
161
|
+
}, 20_000);
|
|
162
|
+
|
|
163
|
+
// ---------------------------------------------------------------- 总览
|
|
58
164
|
|
|
59
|
-
// monitor installed / not installed preview
|
|
60
165
|
function setMonitorState(on) {
|
|
61
166
|
const monitor = $('#overview-monitor');
|
|
62
167
|
const welcome = $('#overview-welcome');
|
|
@@ -65,28 +170,100 @@ function setMonitorState(on) {
|
|
|
65
170
|
welcome.hidden = on;
|
|
66
171
|
const nav = $('.nav-item[data-page="monitor"]');
|
|
67
172
|
if (nav) nav.classList.toggle('disabled', !on);
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
$('#demoNoMonitor')?.addEventListener('click', () => setMonitorState(false));
|
|
176
|
+
$('#demoMonitor')?.addEventListener('click', () => setMonitorState(true));
|
|
177
|
+
if (params.get('monitor') === '0') setMonitorState(false);
|
|
178
|
+
|
|
179
|
+
const ERROR_TEXT = {
|
|
180
|
+
empty: '空响应',
|
|
181
|
+
timeout: '超时',
|
|
182
|
+
auth: '鉴权失败',
|
|
183
|
+
rate_limit: '限流',
|
|
184
|
+
http_5xx: '服务端错误',
|
|
185
|
+
http_4xx: '请求错误',
|
|
186
|
+
exception: '异常',
|
|
187
|
+
error: '失败',
|
|
188
|
+
};
|
|
80
189
|
|
|
81
|
-
|
|
82
|
-
|
|
190
|
+
function renderRecentCalls(list) {
|
|
191
|
+
const body = $('#recentCallsBody');
|
|
192
|
+
if (!body || !Array.isArray(list)) return;
|
|
193
|
+
body.innerHTML = list.map((call) => {
|
|
194
|
+
const source = call.kind === 'private' ? '私聊' : call.kind === 'memory' ? '记忆' : call.kind === 'idle' ? '主动话题' : `群 ${call.group_id || '-'}`;
|
|
195
|
+
const tokens = `${(((Number(call.prompt_tokens) || 0) + (Number(call.completion_tokens) || 0)) / 1000).toFixed(1)}k`;
|
|
196
|
+
const time = new Date(call.started_at).toLocaleTimeString('zh-CN', { hour12: false });
|
|
197
|
+
const status = call.status === 'ok'
|
|
198
|
+
? '<span class="status ok">成功</span>'
|
|
199
|
+
: `<span class="status fail">${escHtml(ERROR_TEXT[call.error_kind] || call.error_kind || '失败')}</span>`;
|
|
200
|
+
return `<tr><td>${time}</td><td><span class="tag ${call.kind === 'private' ? 'private' : call.kind === 'memory' ? 'memory' : 'group'}">${escHtml(source)}</span></td><td>${escHtml(call.model || '-')}</td><td>${tokens}</td><td>${((Number(call.model_ms) || 0) / 1000).toFixed(1)}s</td><td>${status}</td></tr>`;
|
|
201
|
+
}).join('');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function pluginConfigured(item) {
|
|
205
|
+
return item.configured !== undefined ? item.configured : !!item.enabled;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function pluginState(item) {
|
|
209
|
+
if (!item.installed) return { cls: 'warn', text: '未安装' };
|
|
210
|
+
if (pluginConfigured(item)) return { cls: 'ok', text: '运行中' };
|
|
211
|
+
return { cls: 'warn', text: '未启用' };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function pluginCardHtml(item) {
|
|
215
|
+
const state = pluginState(item);
|
|
216
|
+
return `<article class="plugin-card">
|
|
217
|
+
<div class="plugin-card-top">${pluginIcon(item)}<div><h3>${escHtml(item.id)}</h3><p>${escHtml(item.package)}</p></div><span class="status ${state.cls}">${state.text}</span></div>
|
|
218
|
+
<div class="plugin-meta"><span>v${escHtml(item.version || '—')}</span><span>${escHtml(item.title)}</span><span>${pluginConfigured(item) ? '已写入 koishi.yml' : (item.installed ? '未启用' : '未安装')}</span></div>
|
|
219
|
+
<p class="plugin-desc">${escHtml(item.description || '')}</p>
|
|
220
|
+
<div class="plugin-actions">
|
|
221
|
+
${item.installed && pluginConfigured(item) ? `<button class="btn small" data-config-open="${escHtml(item.package)}">配置</button>` : ''}
|
|
222
|
+
${item.installed ? '' : `<button class="btn small" data-install-pkg="${escHtml(item.package)}">安装</button>`}
|
|
223
|
+
</div>
|
|
224
|
+
</article>`;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function renderPlugins(data) {
|
|
228
|
+
const list = (data?.list || []).filter((item) => item.id !== 'qq-group-manager');
|
|
229
|
+
const mini = $('#pluginMiniList');
|
|
230
|
+
if (mini) {
|
|
231
|
+
mini.innerHTML = list.filter((item) => item.installed).map((item) => `<div class="plugin-line">
|
|
232
|
+
${pluginIcon(item)}
|
|
233
|
+
<div><b>${escHtml(item.id)}</b><small>${escHtml(item.title)} · v${escHtml(item.version || '—')}</small></div>
|
|
234
|
+
<i class="${pluginConfigured(item) ? 'on' : 'off'}"></i>
|
|
235
|
+
</div>`).join('') || '<div class="schema-loading">没有已安装的附属插件</div>';
|
|
236
|
+
}
|
|
237
|
+
const count = $('#pluginMiniCount');
|
|
238
|
+
if (count) count.textContent = `自动识别 · ${list.filter((item) => item.installed).length} 个`;
|
|
239
|
+
const grid = $('#pluginGrid');
|
|
240
|
+
if (grid) {
|
|
241
|
+
const cards = list.map(pluginCardHtml).join('');
|
|
242
|
+
const addCard = '<article class="plugin-card add"><div class="add-inner"><span>+</span><b>安装附属插件</b><p>从 npm 安装后重启 Koishi</p><a class="btn small ghost" href="https://www.npmjs.com/search?q=%40nestim%2Fkoishi-plugin" target="_blank" rel="noreferrer">去 npm 看看</a></div></article>';
|
|
243
|
+
grid.innerHTML = cards + addCard;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function initOverview() {
|
|
83
248
|
try {
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
|
|
88
|
-
if (!data || !data.monitor) return;
|
|
249
|
+
const data = await apiGet('api/overview');
|
|
250
|
+
if (!data) return;
|
|
251
|
+
if (data.plugins) renderPlugins(data.plugins);
|
|
252
|
+
if (!data.monitor) return;
|
|
89
253
|
setMonitorState(!!data.monitor.installed);
|
|
254
|
+
if (data.status) renderStatus(data.status);
|
|
255
|
+
const headP = $('#page-overview .page-head p');
|
|
256
|
+
if (headP) {
|
|
257
|
+
const now = new Date();
|
|
258
|
+
headP.textContent = `今天 ${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} · 数据来自 qqgm-monitor SQLite`;
|
|
259
|
+
}
|
|
260
|
+
const plugins = data.plugins || {};
|
|
261
|
+
const main = plugins.main || {};
|
|
262
|
+
if (main.version) {
|
|
263
|
+
$$('.overview-meta').forEach((el) => {
|
|
264
|
+
el.textContent = `@nestim/koishi-plugin-qq-group-manager v${main.version} · 作者 Miseat`;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
90
267
|
if (!data.monitor.installed) return;
|
|
91
268
|
const calls = data.monitor.calls || {};
|
|
92
269
|
const cards = $$('#overview-monitor .metric-value');
|
|
@@ -101,22 +278,201 @@ async function initRealData() {
|
|
|
101
278
|
if (foots[1] && calls.calls) {
|
|
102
279
|
foots[1].textContent = `失败率 ${((calls.fail || 0) / calls.calls * 100).toFixed(1)}% · 解析 ${calls.parse_fail || 0} · 超时 ${calls.timeout || 0}`;
|
|
103
280
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
281
|
+
renderRecentCalls(data.monitor.recent);
|
|
282
|
+
const statusCalls = $('#statusCalls');
|
|
283
|
+
if (statusCalls) statusCalls.textContent = `${calls.calls || 0} calls today`;
|
|
284
|
+
} catch { /* 未登录/文件预览时保留静态示例 */ }
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// ---------------------------------------------------------------- 调用趋势
|
|
288
|
+
|
|
289
|
+
function smoothPath(points) {
|
|
290
|
+
if (!points.length) return '';
|
|
291
|
+
if (points.length === 1) return `M${points[0].x} ${points[0].y}`;
|
|
292
|
+
let d = `M${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
|
|
293
|
+
for (let i = 0; i < points.length - 1; i += 1) {
|
|
294
|
+
const p0 = points[Math.max(0, i - 1)];
|
|
295
|
+
const p1 = points[i];
|
|
296
|
+
const p2 = points[i + 1];
|
|
297
|
+
const p3 = points[Math.min(points.length - 1, i + 2)];
|
|
298
|
+
const c1x = p1.x + (p2.x - p0.x) / 6;
|
|
299
|
+
const c1y = p1.y + (p2.y - p0.y) / 6;
|
|
300
|
+
const c2x = p2.x - (p3.x - p1.x) / 6;
|
|
301
|
+
const c2y = p2.y - (p3.y - p1.y) / 6;
|
|
302
|
+
d += ` C${c1x.toFixed(1)} ${c1y.toFixed(1)} ${c2x.toFixed(1)} ${c2y.toFixed(1)} ${p2.x.toFixed(1)} ${p2.y.toFixed(1)}`;
|
|
303
|
+
}
|
|
304
|
+
return d;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function renderTrend(points, days) {
|
|
308
|
+
const svg = $('#trendChart');
|
|
309
|
+
const axis = $('#trendAxis');
|
|
310
|
+
const sub = $('#trendSub');
|
|
311
|
+
if (!svg || !points.length) return;
|
|
312
|
+
const W = 720;
|
|
313
|
+
const H = 210;
|
|
314
|
+
const top = 24;
|
|
315
|
+
const bottom = 26;
|
|
316
|
+
const maxCalls = Math.max(1, ...points.map((p) => p.calls));
|
|
317
|
+
const maxTokens = Math.max(1, ...points.map((p) => p.tokens));
|
|
318
|
+
const xOf = (i) => (points.length === 1 ? W / 2 : (i * W) / (points.length - 1));
|
|
319
|
+
const yOf = (value, max) => H - bottom - (value / max) * (H - top - bottom);
|
|
320
|
+
const callPts = points.map((p, i) => ({ x: xOf(i), y: yOf(p.calls, maxCalls) }));
|
|
321
|
+
const tokenPts = points.map((p, i) => ({ x: xOf(i), y: yOf(p.tokens, maxTokens) }));
|
|
322
|
+
const callD = smoothPath(callPts);
|
|
323
|
+
const areaD = `${callD} L${W} ${H - bottom} L0 ${H - bottom} Z`;
|
|
324
|
+
const dots = days <= 7
|
|
325
|
+
? callPts.map((p) => `<circle cx="${p.x.toFixed(1)}" cy="${p.y.toFixed(1)}" r="3"/>`).join('')
|
|
326
|
+
: '';
|
|
327
|
+
svg.innerHTML = `<defs><linearGradient id="g1" x1="0" x2="0" y1="0" y2="1"><stop offset="0" stop-color="#5b8def" stop-opacity=".22"/><stop offset="1" stop-color="#5b8def" stop-opacity="0"/></linearGradient></defs>
|
|
328
|
+
<g class="grid-lines"><line x1="0" y1="40" x2="720" y2="40"/><line x1="0" y1="90" x2="720" y2="90"/><line x1="0" y1="140" x2="720" y2="140"/><line x1="0" y1="190" x2="720" y2="190"/></g>
|
|
329
|
+
<path class="area" d="${areaD}"/>
|
|
330
|
+
<path class="line blue" d="${callD}"/>
|
|
331
|
+
<path class="line cyan dashed" d="${smoothPath(tokenPts)}"/>
|
|
332
|
+
<g class="dots">${dots}</g>`;
|
|
333
|
+
if (axis) {
|
|
334
|
+
const every = points.length <= 8 ? 1 : Math.ceil(points.length / 7);
|
|
335
|
+
axis.style.gridTemplateColumns = `repeat(${points.length}, 1fr)`;
|
|
336
|
+
axis.innerHTML = points.map((p, i) => `<span>${i % every === 0 || i === points.length - 1 ? escHtml(p.label) : ''}</span>`).join('');
|
|
337
|
+
}
|
|
338
|
+
if (sub) sub.textContent = `最近 ${days} 天 · 调用次数 / token`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
let trendToken = 0;
|
|
342
|
+
async function loadTrend(days) {
|
|
343
|
+
const mine = ++trendToken;
|
|
344
|
+
try {
|
|
345
|
+
const data = await apiGet(`api/monitor/trend?days=${days}`);
|
|
346
|
+
if (mine !== trendToken) return;
|
|
347
|
+
if (!data || !data.installed || !data.points?.length) return;
|
|
348
|
+
renderTrend(data.points, Number(data.days) || days);
|
|
349
|
+
} catch { /* 保留示例曲线 */ }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
$('#trendRange')?.addEventListener('change', (event) => {
|
|
353
|
+
const days = Number(event.target.value) || 7;
|
|
354
|
+
loadTrend(days);
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// ---------------------------------------------------------------- 监控页
|
|
358
|
+
|
|
359
|
+
function fmtDuration(ms) {
|
|
360
|
+
if (ms == null || !Number.isFinite(Number(ms))) return '—';
|
|
361
|
+
const value = Number(ms);
|
|
362
|
+
if (value >= 1000) return `${(value / 1000).toFixed(1)}s`;
|
|
363
|
+
return `${Math.round(value)}ms`;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function latencyText(part) {
|
|
367
|
+
if (!part || part.p50 == null) return '—';
|
|
368
|
+
return `${fmtDuration(part.p50)} / ${fmtDuration(part.p95)} / ${fmtDuration(part.p99)}`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function renderMonitor(data, days) {
|
|
372
|
+
const calls = data.calls || {};
|
|
373
|
+
const total = Number(calls.calls) || 0;
|
|
374
|
+
const fail = Number(calls.fail) || 0;
|
|
375
|
+
const tokens = (Number(calls.prompt) || 0) + (Number(calls.completion) || 0);
|
|
376
|
+
const label = days === 1 ? '今日' : `最近 ${days} 天`;
|
|
377
|
+
const rangeLabel = $('#monitorRangeLabel');
|
|
378
|
+
if (rangeLabel) rangeLabel.textContent = label;
|
|
379
|
+
const callsEl = $('#monitorCalls');
|
|
380
|
+
if (callsEl) callsEl.textContent = String(total);
|
|
381
|
+
const tokensEl = $('#monitorTokens');
|
|
382
|
+
if (tokensEl) tokensEl.textContent = `Token ${(tokens / 1000).toFixed(1)}k · ${calls.cost ? `成本 ¥${Number(calls.cost).toFixed(2)}` : '成本未配置'}`;
|
|
383
|
+
const rate = total ? ((fail / total) * 100).toFixed(1) : '0.0';
|
|
384
|
+
const rateEl = $('#monitorFailRate');
|
|
385
|
+
if (rateEl) rateEl.textContent = `${rate}%`;
|
|
386
|
+
const failEl = $('#monitorFail');
|
|
387
|
+
if (failEl) failEl.innerHTML = `${fail} <small>次</small>`;
|
|
388
|
+
const failFoot = $('#monitorFailFoot');
|
|
389
|
+
if (failFoot) failFoot.textContent = `解析 ${calls.parse_fail || 0} · 超时 ${calls.timeout || 0} · 其他 ${Math.max(0, fail - (calls.parse_fail || 0) - (calls.timeout || 0))}`;
|
|
390
|
+
const costEl = $('#monitorCost');
|
|
391
|
+
if (costEl) costEl.textContent = calls.cost ? `¥${Number(calls.cost).toFixed(2)}` : '—';
|
|
392
|
+
const balanceEl = $('#monitorBalance');
|
|
393
|
+
if (balanceEl) {
|
|
394
|
+
balanceEl.textContent = data.balance
|
|
395
|
+
? `余额 ${data.balance.currency === 'CNY' || !data.balance.currency ? '¥' : ''}${Number(data.balance.total || 0).toFixed(2)}`
|
|
396
|
+
: '余额未知';
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const groups = data.groups || [];
|
|
400
|
+
const groupBody = $('#monitorGroups');
|
|
401
|
+
if (groupBody) {
|
|
402
|
+
groupBody.innerHTML = groups.length ? groups.map((group) => {
|
|
403
|
+
const groupFail = Number(group.fail) || 0;
|
|
404
|
+
const groupCalls = Number(group.calls) || 0;
|
|
405
|
+
const groupRate = groupCalls ? ((groupFail / groupCalls) * 100).toFixed(1) : '0.0';
|
|
406
|
+
return `<tr><td>${escHtml(group.group_id)}</td><td>${groupCalls}</td><td>${groupFail}</td><td><span class="status ${groupFail ? 'fail' : 'ok'}">${groupRate}%</span></td><td>${((Number(group.tokens) || 0) / 1000).toFixed(1)}k</td></tr>`;
|
|
407
|
+
}).join('') : '<tr><td colspan="5">暂无数据</td></tr>';
|
|
408
|
+
}
|
|
409
|
+
const groupCount = $('#monitorGroupCount');
|
|
410
|
+
if (groupCount) groupCount.textContent = `${groups.length} 个群`;
|
|
411
|
+
|
|
412
|
+
const latency = data.latency || {};
|
|
413
|
+
const latencyBox = $('#monitorLatency');
|
|
414
|
+
if (latencyBox) {
|
|
415
|
+
latencyBox.innerHTML = `
|
|
416
|
+
<div><span>E2E</span><b>${latencyText(latency.e2e)}</b><small>收到→发出</small></div>
|
|
417
|
+
<div><span>模型</span><b>${latencyText(latency.model)}</b><small>API 调用</small></div>
|
|
418
|
+
<div><span>渲染</span><b>${latencyText(latency.render)}</b><small>过滤/表情</small></div>
|
|
419
|
+
<div><span>发送</span><b>${latencyText(latency.send)}</b><small>OneBot</small></div>`;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const recent = data.recent || [];
|
|
423
|
+
const recentBody = $('#monitorRecent');
|
|
424
|
+
if (recentBody) {
|
|
425
|
+
recentBody.innerHTML = recent.length ? recent.map((call) => {
|
|
426
|
+
const source = call.kind === 'private' ? '私聊' : call.kind === 'memory' ? '记忆' : call.kind === 'idle' ? '主动话题' : `群 ${call.group_id || '-'}`;
|
|
427
|
+
const status = call.status === 'ok'
|
|
428
|
+
? '<span class="status ok">成功</span>'
|
|
429
|
+
: `<span class="status fail">${escHtml(ERROR_TEXT[call.error_kind] || call.error_kind || '失败')}</span>`;
|
|
430
|
+
const text = `${source} ${call.model || ''} ${call.status}`;
|
|
431
|
+
return `<tr data-search="${escHtml(text.toLowerCase())}"><td>${new Date(call.started_at).toLocaleTimeString('zh-CN', { hour12: false })}</td><td><code>${escHtml(String(call.trace_id || '').slice(-8))}</code></td><td>${escHtml(source)}</td><td>${escHtml(call.model || '-')}</td><td>${((Number(call.prompt_tokens) || 0) / 1000).toFixed(1)}k / ${call.completion_tokens || 0}</td><td>${fmtDuration(call.model_ms)}</td><td>${status}</td></tr>`;
|
|
432
|
+
}).join('') : '<tr><td colspan="7">暂无数据</td></tr>';
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async function initMonitor(days) {
|
|
437
|
+
const range = days || Number($('#monitorRange')?.value) || 1;
|
|
438
|
+
try {
|
|
439
|
+
const data = await apiGet(`api/monitor?days=${range}`);
|
|
440
|
+
if (!data || !data.installed) {
|
|
441
|
+
showToast('安装并启用 qqgm-monitor 后才有数据');
|
|
442
|
+
return;
|
|
116
443
|
}
|
|
117
|
-
|
|
444
|
+
renderMonitor(data, range);
|
|
445
|
+
} catch (error) {
|
|
446
|
+
showToast(`监控数据读取失败:${String(error.message || error)}`);
|
|
447
|
+
}
|
|
118
448
|
}
|
|
119
|
-
|
|
449
|
+
|
|
450
|
+
$('#monitorRange')?.addEventListener('change', (event) => initMonitor(Number(event.target.value) || 1));
|
|
451
|
+
|
|
452
|
+
$('#monitorSearch')?.addEventListener('input', (event) => {
|
|
453
|
+
const q = String(event.target.value || '').trim().toLowerCase();
|
|
454
|
+
$$('#monitorRecent tr').forEach((row) => {
|
|
455
|
+
if (!row.dataset.search) return;
|
|
456
|
+
row.style.display = !q || row.dataset.search.includes(q) ? '' : 'none';
|
|
457
|
+
});
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
$('#monitorExport')?.addEventListener('click', async () => {
|
|
461
|
+
try {
|
|
462
|
+
const days = Number($('#monitorRange')?.value) || 1;
|
|
463
|
+
const data = await apiGet(`api/monitor?days=${days}`);
|
|
464
|
+
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
|
465
|
+
const a = document.createElement('a');
|
|
466
|
+
a.href = URL.createObjectURL(blob);
|
|
467
|
+
a.download = `qqgm-monitor-${days}d-${Date.now()}.json`;
|
|
468
|
+
a.click();
|
|
469
|
+
URL.revokeObjectURL(a.href);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
showToast(`导出失败:${String(error.message || error)}`);
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
|
|
475
|
+
// ---------------------------------------------------------------- 记忆库
|
|
120
476
|
|
|
121
477
|
let memoryItems = [];
|
|
122
478
|
let memoryState = null;
|
|
@@ -133,24 +489,20 @@ function renderMemoryList(items) {
|
|
|
133
489
|
<article class="memory-item" data-memory-index="${index}">
|
|
134
490
|
<div class="memory-head">
|
|
135
491
|
<span class="tag ${item.scope_kind === 'private' ? 'private' : 'group'}">${item.scope_kind === 'group' ? '群' : item.scope_kind === 'private' ? '私聊' : '全局'} ${item.scope_id || ''}</span>
|
|
136
|
-
<span class="tag soft">${item.category || '未分类'}</span>
|
|
492
|
+
<span class="tag soft">${escHtml(item.category || '未分类')}</span>
|
|
137
493
|
<time>${new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })}</time>
|
|
138
494
|
</div>
|
|
139
|
-
<p>${
|
|
140
|
-
<div class="memory-foot"><code>${item.label || '记忆'}</code><span>#${item.id}</span><span class="memory-open">点击查看</span></div>
|
|
495
|
+
<p>${escHtml(item.content)}</p>
|
|
496
|
+
<div class="memory-foot"><code>${escHtml(item.label || '记忆')}</code><span>#${escHtml(item.id)}</span><span class="memory-open">点击查看</span></div>
|
|
141
497
|
</article>`).join('');
|
|
142
498
|
}
|
|
143
499
|
|
|
144
500
|
async function filterMemory(scope, category, activeButton) {
|
|
145
|
-
const
|
|
146
|
-
if (scope)
|
|
147
|
-
if (category)
|
|
148
|
-
const token = new URLSearchParams(location.search).get('token') || '';
|
|
149
|
-
if (token) params.set('token', token);
|
|
501
|
+
const search = new URLSearchParams({ limit: '200' });
|
|
502
|
+
if (scope) search.set('scope', scope);
|
|
503
|
+
if (category) search.set('category', category);
|
|
150
504
|
try {
|
|
151
|
-
const
|
|
152
|
-
if (!res.ok) return;
|
|
153
|
-
const data = await res.json();
|
|
505
|
+
const data = await apiGet(`api/memory?${search}`);
|
|
154
506
|
renderMemoryList(data.items || []);
|
|
155
507
|
$$('#memoryScopes .scope').forEach((btn) => btn.classList.remove('active'));
|
|
156
508
|
if (activeButton) activeButton.classList.add('active');
|
|
@@ -159,10 +511,7 @@ async function filterMemory(scope, category, activeButton) {
|
|
|
159
511
|
|
|
160
512
|
async function initMemoryData() {
|
|
161
513
|
try {
|
|
162
|
-
const
|
|
163
|
-
const res = await fetch(`api/memory?limit=20${token ? `&token=${encodeURIComponent(token)}` : ''}`, { cache: 'no-store' });
|
|
164
|
-
if (!res.ok) return;
|
|
165
|
-
const data = await res.json();
|
|
514
|
+
const data = await apiGet('api/memory?limit=20');
|
|
166
515
|
if (!data || !data.installed) return;
|
|
167
516
|
memoryItems = data.items || [];
|
|
168
517
|
memoryState = data;
|
|
@@ -197,21 +546,20 @@ async function initMemoryData() {
|
|
|
197
546
|
}
|
|
198
547
|
const scopes = $('#memoryScopes');
|
|
199
548
|
if (scopes) {
|
|
200
|
-
const
|
|
549
|
+
const buttons = [`<h3>范围</h3><button class="scope active" data-scope="" data-category=""><span>全部</span><b>${data.total || 0}</b></button>`];
|
|
201
550
|
for (const item of data.scopes || []) {
|
|
202
551
|
const label = item.scope_kind === 'group' ? `群 ${item.scope_id}` : item.scope_kind === 'private' ? `私聊 ${item.scope_id}` : `全局 ${item.scope_id || ''}`;
|
|
203
|
-
|
|
552
|
+
buttons.push(`<button class="scope" data-scope="${item.scope_kind}:${item.scope_id || ''}"><span>${label}</span><b>${item.n}</b></button>`);
|
|
204
553
|
}
|
|
205
|
-
|
|
554
|
+
buttons.push('<h3 class="mt">分类</h3>');
|
|
206
555
|
for (const item of data.categories || []) {
|
|
207
|
-
|
|
556
|
+
buttons.push(`<button class="scope" data-category="${escHtml(item.category)}"><span>${escHtml(item.category)}</span><b>${item.n}</b></button>`);
|
|
208
557
|
}
|
|
209
|
-
scopes.innerHTML =
|
|
558
|
+
scopes.innerHTML = buttons.join('');
|
|
210
559
|
}
|
|
211
560
|
renderMemoryList(data.items);
|
|
212
|
-
} catch { /*
|
|
561
|
+
} catch { /* 文件预览保留静态示例 */ }
|
|
213
562
|
}
|
|
214
|
-
initMemoryData();
|
|
215
563
|
|
|
216
564
|
$('#memoryScopes')?.addEventListener('click', (event) => {
|
|
217
565
|
const btn = event.target.closest('.scope');
|
|
@@ -237,10 +585,12 @@ function openMemoryModal(index) {
|
|
|
237
585
|
$('#memoryModalSource').textContent = item.source === 'md' ? '来源:MD(只读;迁移到 SQLite 后可编辑)' : `来源:SQLite · #${item.id}`;
|
|
238
586
|
modal.hidden = false;
|
|
239
587
|
}
|
|
588
|
+
|
|
240
589
|
function closeMemoryModal() {
|
|
241
590
|
const modal = $('#memoryModal');
|
|
242
591
|
if (modal) modal.hidden = true;
|
|
243
592
|
}
|
|
593
|
+
|
|
244
594
|
$('#memoryList')?.addEventListener('click', (event) => {
|
|
245
595
|
const item = event.target.closest('[data-memory-index]');
|
|
246
596
|
if (item) openMemoryModal(Number(item.dataset.memoryIndex));
|
|
@@ -251,23 +601,11 @@ $('#memoryModal')?.addEventListener('click', (event) => {
|
|
|
251
601
|
if (event.target.id === 'memoryModal') closeMemoryModal();
|
|
252
602
|
});
|
|
253
603
|
|
|
254
|
-
async function memoryPost(path, body) {
|
|
255
|
-
const token = new URLSearchParams(location.search).get('token') || '';
|
|
256
|
-
const res = await fetch(`${path}${token ? `?token=${encodeURIComponent(token)}` : ''}`, {
|
|
257
|
-
method: 'POST',
|
|
258
|
-
headers: { 'content-type': 'application/json' },
|
|
259
|
-
body: JSON.stringify(body || {}),
|
|
260
|
-
});
|
|
261
|
-
const data = await res.json();
|
|
262
|
-
if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
263
|
-
return data;
|
|
264
|
-
}
|
|
265
|
-
|
|
266
604
|
$('#migrateMemory')?.addEventListener('click', async () => {
|
|
267
|
-
if (!confirm('把 Memory_*.md 导入 SQLite
|
|
605
|
+
if (!confirm('把 Memory_*.md 导入 SQLite?\n\n只导入,不切换后端;不会删除 MD,也不会自动重启。')) return;
|
|
268
606
|
try {
|
|
269
607
|
showToast('正在迁移…');
|
|
270
|
-
const data = await
|
|
608
|
+
const data = await apiPost('api/memory/migrate', { switchBackend: false });
|
|
271
609
|
showToast(`已导入 ${data.imported} 条到 SQLite;现在可以点“切换到 SQLite”`);
|
|
272
610
|
setTimeout(() => location.reload(), 1800);
|
|
273
611
|
} catch (error) {
|
|
@@ -282,12 +620,10 @@ $('#switchSqlite')?.addEventListener('click', async () => {
|
|
|
282
620
|
return;
|
|
283
621
|
}
|
|
284
622
|
const mdTotal = memoryState?.md?.total || 0;
|
|
285
|
-
const extra = mdTotal
|
|
286
|
-
|
|
287
|
-
: '';
|
|
288
|
-
if (!confirm(`切换主插件记忆后端到 sqlite?${extra}\\n\\n会先备份 koishi.yml,重启后生效。`)) return;
|
|
623
|
+
const extra = mdTotal ? `\n\n注意:还有 ${mdTotal} 条 MD 未确认迁移,切换后主插件只读 SQLite。` : '';
|
|
624
|
+
if (!confirm(`切换主插件记忆后端到 sqlite?${extra}\n\n会先备份 koishi.yml,重启后生效。`)) return;
|
|
289
625
|
try {
|
|
290
|
-
await
|
|
626
|
+
await apiPost('api/memory/config', { backend: 'sqlite' });
|
|
291
627
|
showToast('已切换,重启 Koishi 后生效');
|
|
292
628
|
setTimeout(() => location.reload(), 1600);
|
|
293
629
|
} catch (error) {
|
|
@@ -298,7 +634,7 @@ $('#switchSqlite')?.addEventListener('click', async () => {
|
|
|
298
634
|
$('#switchMd')?.addEventListener('click', async () => {
|
|
299
635
|
if (!confirm('把主插件记忆后端切回 md?SQLite 数据不会删除,可随时切回。')) return;
|
|
300
636
|
try {
|
|
301
|
-
await
|
|
637
|
+
await apiPost('api/memory/config', { backend: 'md' });
|
|
302
638
|
showToast('已切回 md,重启后生效');
|
|
303
639
|
setTimeout(() => location.reload(), 1500);
|
|
304
640
|
} catch (error) {
|
|
@@ -306,34 +642,44 @@ $('#switchMd')?.addEventListener('click', async () => {
|
|
|
306
642
|
}
|
|
307
643
|
});
|
|
308
644
|
|
|
645
|
+
// ---------------------------------------------------------------- 安装
|
|
646
|
+
|
|
309
647
|
async function installPackage(pkg) {
|
|
310
|
-
const token = new URLSearchParams(location.search).get('token') || '';
|
|
311
648
|
showToast(`正在安装 ${pkg}…`);
|
|
312
649
|
try {
|
|
313
|
-
|
|
314
|
-
method: 'POST',
|
|
315
|
-
headers: { 'content-type': 'application/json' },
|
|
316
|
-
body: JSON.stringify({ package: pkg }),
|
|
317
|
-
});
|
|
318
|
-
const data = await res.json();
|
|
319
|
-
if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
650
|
+
await apiPost('api/install', { package: pkg });
|
|
320
651
|
showToast('安装完成,重启/重载插件后生效');
|
|
321
652
|
} catch (error) {
|
|
322
653
|
showToast(`安装失败:${String(error.message || error)}`);
|
|
323
654
|
}
|
|
324
655
|
}
|
|
656
|
+
|
|
325
657
|
$('#installMonitor')?.addEventListener('click', () => installPackage('@nestim/koishi-plugin-qqgm-monitor'));
|
|
326
658
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
659
|
+
$('#rescanPlugins')?.addEventListener('click', async () => {
|
|
660
|
+
try {
|
|
661
|
+
renderPlugins(await apiGet('api/plugins'));
|
|
662
|
+
showToast('已重新扫描');
|
|
663
|
+
} catch (error) {
|
|
664
|
+
showToast(`扫描失败:${String(error.message || error)}`);
|
|
665
|
+
}
|
|
666
|
+
});
|
|
330
667
|
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
668
|
+
document.addEventListener('click', (event) => {
|
|
669
|
+
const configButton = event.target.closest('[data-config-open]');
|
|
670
|
+
if (configButton) {
|
|
671
|
+
go('config');
|
|
672
|
+
openPluginConfig(configButton.dataset.configOpen);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
const installButton = event.target.closest('[data-install-pkg]');
|
|
676
|
+
if (installButton) installPackage(installButton.dataset.installPkg);
|
|
677
|
+
});
|
|
335
678
|
|
|
336
|
-
|
|
679
|
+
// ---------------------------------------------------------------- 主插件配置
|
|
680
|
+
|
|
681
|
+
let mainSchema = null;
|
|
682
|
+
let activeMainGroup = 0;
|
|
337
683
|
|
|
338
684
|
function splitScored(raw) {
|
|
339
685
|
const text = String(raw == null ? '' : raw);
|
|
@@ -379,7 +725,7 @@ function collectList(root, field) {
|
|
|
379
725
|
return values;
|
|
380
726
|
}
|
|
381
727
|
|
|
382
|
-
function groupFieldHtml(field, value
|
|
728
|
+
function groupFieldHtml(field, value) {
|
|
383
729
|
const current = value == null ? '' : value;
|
|
384
730
|
if (field.type === 'boolean') {
|
|
385
731
|
return `<label class="group-field"><span>${escHtml(field.label)}</span>
|
|
@@ -400,8 +746,8 @@ function groupFieldHtml(field, value, index) {
|
|
|
400
746
|
<input type="${type}" data-group-field="${field.key}" data-group-kind="${type === 'number' ? 'number' : 'string'}" value="${escHtml(current)}" placeholder="留空=全局" /></label>`;
|
|
401
747
|
}
|
|
402
748
|
|
|
403
|
-
function groupCardHtml(field, group = {},
|
|
404
|
-
const body = (field.itemFields || []).map((item) => groupFieldHtml(item, group[item.key]
|
|
749
|
+
function groupCardHtml(field, group = {}, collapsed = true) {
|
|
750
|
+
const body = (field.itemFields || []).map((item) => groupFieldHtml(item, group[item.key])).join('');
|
|
405
751
|
return `<article class="group-rule" data-group-card>
|
|
406
752
|
<div class="group-rule-head">
|
|
407
753
|
<input class="group-rule-id" value="${escHtml(group.guildId || '')}" placeholder="群号" />
|
|
@@ -421,7 +767,7 @@ function renderGroupRules(field, value) {
|
|
|
421
767
|
return `<div class="group-rules" data-group-rules>
|
|
422
768
|
<label class="switch"><input type="checkbox" data-group-enabled ${enabled ? 'checked' : ''} /><i></i><span>${enabled ? '按群号覆盖' : '未开启,使用全局配置'}</span></label>
|
|
423
769
|
<div class="group-rules-list" ${enabled ? '' : 'hidden'}>
|
|
424
|
-
${groups.map((group
|
|
770
|
+
${groups.map((group) => groupCardHtml(field, group, true)).join('')}
|
|
425
771
|
<button type="button" class="link-btn" data-add-group>+ 添加群规则</button>
|
|
426
772
|
</div>
|
|
427
773
|
</div>`;
|
|
@@ -454,6 +800,25 @@ function collectGroupRules(field, form) {
|
|
|
454
800
|
return groups;
|
|
455
801
|
}
|
|
456
802
|
|
|
803
|
+
const MAIN_GROUP_ICONS = {
|
|
804
|
+
基础设置: 'M4 6h16M4 12h10M4 18h7',
|
|
805
|
+
消息管控: 'M12 3 4 6v5c0 5 3.4 8.4 8 10 4.6-1.6 8-5 8-10V6l-8-3Z',
|
|
806
|
+
自动管控: 'M6 3h12l3 6-9 12L3 9l3-6Z',
|
|
807
|
+
记忆库: 'M6 4h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Zm2 4h8M8 12h8M8 16h5',
|
|
808
|
+
黑名单: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM5.6 5.6l12.8 12.8',
|
|
809
|
+
娱乐设置: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM8.5 10h.01M15.5 10h.01M8.5 15c1 1.2 2.2 1.8 3.5 1.8s2.5-.6 3.5-1.8',
|
|
810
|
+
群聊互动: 'M16 20v-2a4 4 0 0 0-4-4H7a4 4 0 0 0-4 4v2M9.5 10a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7ZM21 20v-2a4 4 0 0 0-3-3.9M16.5 3.2a3.5 3.5 0 0 1 0 6.6',
|
|
811
|
+
自定义命令: 'M4 6h16M4 12h16M4 18h16M8 6v12',
|
|
812
|
+
'AI 回复': 'M12 3v3m0 12v3M3 12h3m12 0h3M6 6l2 2m8 8 2 2M18 6l-2 2M8 16l-2 2M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z',
|
|
813
|
+
权限设置: 'M7 11V8a5 5 0 0 1 10 0v3M5 11h14v10H5V11Zm7 4v2',
|
|
814
|
+
日志设置: 'M5 4h14v16H5V4Zm3 4 3 4-3 4m5 0h4',
|
|
815
|
+
};
|
|
816
|
+
|
|
817
|
+
function groupIcon(title) {
|
|
818
|
+
const path = MAIN_GROUP_ICONS[title] || 'M4 4h16v16H4V4Z';
|
|
819
|
+
return `<span class="plugin-ico group-ico"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
|
820
|
+
}
|
|
821
|
+
|
|
457
822
|
function openMainGroup(index) {
|
|
458
823
|
renderMainGroup(index);
|
|
459
824
|
}
|
|
@@ -465,7 +830,7 @@ function renderMainGroup(index) {
|
|
|
465
830
|
const form = $('#mainSchemaForm');
|
|
466
831
|
if (!form) return;
|
|
467
832
|
$$('#mainSchemaNav .config-plugin').forEach((btn, i) => btn.classList.toggle('active', i === index));
|
|
468
|
-
form.innerHTML = `<div class="form-head"><div><h2>${group.title}</h2><p>${group.fields.length} 个字段 · 与 Koishi 配置页同源</p></div><span class="status ok">运行中</span></div>`
|
|
833
|
+
form.innerHTML = `<div class="form-head"><div><h2>${escHtml(group.title)}</h2><p>${group.fields.length} 个字段 · 与 Koishi 配置页同源</p></div><span class="status ok">运行中</span></div>`
|
|
469
834
|
+ group.fields.map((field) => {
|
|
470
835
|
const value = mainSchema.values[field.key] ?? field.default;
|
|
471
836
|
let control = '';
|
|
@@ -496,7 +861,7 @@ function renderMainGroup(index) {
|
|
|
496
861
|
<div class="schema-field-control">${control}</div>
|
|
497
862
|
</div>`;
|
|
498
863
|
}).join('')
|
|
499
|
-
+
|
|
864
|
+
+ '<div class="form-foot"><span>保存只改本组字段;写前备份 koishi.yml,重启后生效</span></div>';
|
|
500
865
|
const save = $('#saveMainSchemaGroup');
|
|
501
866
|
if (save) save.onclick = () => saveMainGroup(group);
|
|
502
867
|
|
|
@@ -519,7 +884,7 @@ function renderMainGroup(index) {
|
|
|
519
884
|
const rules = addGroup.closest('[data-group-rules]');
|
|
520
885
|
const groupField = group.fields.find((item) => item.key === 'groupRules');
|
|
521
886
|
const list = rules?.querySelector('.group-rules-list');
|
|
522
|
-
if (list && groupField) list.insertAdjacentHTML('beforeend', groupCardHtml(groupField, {},
|
|
887
|
+
if (list && groupField) list.insertAdjacentHTML('beforeend', groupCardHtml(groupField, {}, false));
|
|
523
888
|
return;
|
|
524
889
|
}
|
|
525
890
|
const removeGroup = event.target.closest('[data-remove-group]');
|
|
@@ -543,7 +908,7 @@ function renderMainGroup(index) {
|
|
|
543
908
|
if (text) text.textContent = event.target.checked ? '按群号覆盖' : '未开启,使用全局配置';
|
|
544
909
|
if (event.target.checked && list && !list.querySelector('[data-group-card]')) {
|
|
545
910
|
const groupField = group.fields.find((item) => item.key === 'groupRules');
|
|
546
|
-
if (groupField) list.insertAdjacentHTML('afterbegin', groupCardHtml(groupField, {},
|
|
911
|
+
if (groupField) list.insertAdjacentHTML('afterbegin', groupCardHtml(groupField, {}, false));
|
|
547
912
|
}
|
|
548
913
|
}
|
|
549
914
|
if (event.target.matches('.switch input')) {
|
|
@@ -565,7 +930,7 @@ async function saveMainGroup(group) {
|
|
|
565
930
|
values[field.key] = collectList(form.querySelector(`[data-list-key="${field.key}"]`), field);
|
|
566
931
|
continue;
|
|
567
932
|
}
|
|
568
|
-
const input = $(`[data-key="${field.key}"]
|
|
933
|
+
const input = $(`[data-key="${field.key}"]`, form);
|
|
569
934
|
if (!input) continue;
|
|
570
935
|
if (field.type === 'boolean') values[field.key] = !!input.checked;
|
|
571
936
|
else if (field.type === 'number') values[field.key] = Number(input.value);
|
|
@@ -575,13 +940,7 @@ async function saveMainGroup(group) {
|
|
|
575
940
|
} else values[field.key] = input.value;
|
|
576
941
|
}
|
|
577
942
|
try {
|
|
578
|
-
const
|
|
579
|
-
method: 'POST',
|
|
580
|
-
headers: { 'content-type': 'application/json' },
|
|
581
|
-
body: JSON.stringify({ values }),
|
|
582
|
-
});
|
|
583
|
-
const data = await res.json();
|
|
584
|
-
if (!res.ok || !data.ok) throw new Error(data.error || `HTTP ${res.status}`);
|
|
943
|
+
const data = await apiPost('api/config/main', { values });
|
|
585
944
|
showToast(`已保存 ${data.keys.length} 项,重启 Koishi 后生效`);
|
|
586
945
|
} catch (error) {
|
|
587
946
|
showToast(`保存失败:${String(error.message || error)}`);
|
|
@@ -590,35 +949,317 @@ async function saveMainGroup(group) {
|
|
|
590
949
|
|
|
591
950
|
async function initMainSchema() {
|
|
592
951
|
try {
|
|
593
|
-
|
|
594
|
-
if (!res.ok) return;
|
|
595
|
-
mainSchema = await res.json();
|
|
952
|
+
mainSchema = await apiGet('api/config/main');
|
|
596
953
|
if (!mainSchema.available) {
|
|
597
|
-
$('#mainSchemaForm')
|
|
954
|
+
const form = $('#mainSchemaForm');
|
|
955
|
+
if (form) form.innerHTML = '<div class="schema-loading">未找到主插件 Config Schema</div>';
|
|
598
956
|
return;
|
|
599
957
|
}
|
|
600
958
|
const nav = $('#mainSchemaNav');
|
|
601
959
|
if (nav) {
|
|
602
960
|
nav.innerHTML = '<div class="config-group-label">配置分组</div>'
|
|
603
|
-
+ mainSchema.groups.map((group, index) => `<button class="config-plugin ${index === 0 ? 'active' : ''}" data-main-group="${index}"
|
|
961
|
+
+ mainSchema.groups.map((group, index) => `<button class="config-plugin ${index === 0 ? 'active' : ''}" data-main-group="${index}">${groupIcon(group.title)}<div><b>${escHtml(group.title)}</b><small>${group.fields.length} 项</small></div></button>`).join('');
|
|
604
962
|
$$('#mainSchemaNav .config-plugin').forEach((btn) => btn.addEventListener('click', () => openMainGroup(Number(btn.dataset.mainGroup))));
|
|
605
963
|
}
|
|
606
|
-
const params = new URLSearchParams(location.search);
|
|
607
964
|
const groupParam = Number(params.get('group'));
|
|
608
965
|
if (document.querySelector('#page-main-schema.active')) {
|
|
609
966
|
openMainGroup(Number.isInteger(groupParam) && groupParam >= 0 && groupParam < mainSchema.groups.length ? groupParam : 0);
|
|
610
967
|
}
|
|
611
968
|
} catch { /* leave loading */ }
|
|
612
969
|
}
|
|
613
|
-
initMainSchema();
|
|
614
970
|
|
|
615
|
-
//
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
971
|
+
// ---------------------------------------------------------------- 附属配置
|
|
972
|
+
|
|
973
|
+
const PLUGIN_ICONS = {
|
|
974
|
+
'qqgm-monitor': ['blue', 'M4 19V5m0 14h16M8 16l3-5 3 2 4-7'],
|
|
975
|
+
'qqgm-meme': ['green', 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM8.5 10h.01M15.5 10h.01M8.5 15c1 1.2 2.2 1.8 3.5 1.8s2.5-.6 3.5-1.8'],
|
|
976
|
+
'qqgm-chat-style': ['orange', 'M4 5h16v11H8l-4 4V5Z'],
|
|
977
|
+
'qqgm-private': ['purple', 'M4 5h16v12H8l-4 4V5Z'],
|
|
978
|
+
'qqgm-memory': ['slate', 'M6 4h12a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2Zm2 4h8M8 12h8M8 16h5'],
|
|
979
|
+
'qqgm-webui': ['slate', 'M4 5h16v14H4V5Zm0 4h16M8 13h3m-3 3h6'],
|
|
980
|
+
'qq-group-manager': ['slate', 'M12 15.5A3.5 3.5 0 1 0 12 8.5a3.5 3.5 0 0 0 0 7Zm7-3.5c0-.6-.06-1.16-.18-1.7l2.02-1.58-2-3.46-2.38.96a8.2 8.2 0 0 0-2.94-1.7L14.2 2h-4.4l-.32 2.52a8.2 8.2 0 0 0-2.94 1.7l-2.38-.96-2 3.46 2.02 1.58A8.6 8.6 0 0 0 4 12c0 .6.06 1.16.18 1.7l-2.02 1.58 2 3.46 2.38-.96a8.2 8.2 0 0 0 2.94 1.7L9.8 22h4.4l.32-2.52a8.2 8.2 0 0 0 2.94-1.7l2.38.96 2-3.46-2.02-1.58c.12-.54.18-1.1.18-1.7Z'],
|
|
981
|
+
};
|
|
982
|
+
|
|
983
|
+
function pluginIcon(item) {
|
|
984
|
+
const [color, path] = PLUGIN_ICONS[item.id] || ['slate', 'M4 4h16v16H4V4Z'];
|
|
985
|
+
return `<span class="plugin-ico ${color} plugin-ico-svg"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
let pluginConfigList = null;
|
|
989
|
+
let activePlugin = '';
|
|
990
|
+
|
|
991
|
+
async function initPluginConfig(force = false) {
|
|
992
|
+
if (pluginConfigList && !force) {
|
|
993
|
+
if (!activePlugin) {
|
|
994
|
+
const list = pluginConfigList.plugins.filter((item) => item.id !== 'qq-group-manager');
|
|
995
|
+
const first = list.find((item) => item.installed) || list[0];
|
|
996
|
+
if (first) openPluginConfig(first.package);
|
|
997
|
+
}
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
const nav = $('#pluginConfigNav');
|
|
1001
|
+
try {
|
|
1002
|
+
const data = await apiGet('api/config/plugins');
|
|
1003
|
+
pluginConfigList = data;
|
|
1004
|
+
const subPlugins = data.plugins.filter((item) => item.id !== 'qq-group-manager');
|
|
1005
|
+
const installed = subPlugins.filter((item) => item.installed);
|
|
1006
|
+
const missing = subPlugins.filter((item) => !item.installed);
|
|
1007
|
+
const button = (item) => `<button class="config-plugin ${item.package === activePlugin ? 'active' : ''}" data-package="${escHtml(item.package)}">
|
|
1008
|
+
${pluginIcon(item)}
|
|
1009
|
+
<div><b>${escHtml(item.id)}</b><small>${escHtml(item.title)} · ${item.installed ? (item.configured ? '已启用' : '未启用') : '未安装'}</small></div>
|
|
1010
|
+
</button>`;
|
|
1011
|
+
if (nav) {
|
|
1012
|
+
nav.innerHTML = '<div class="config-group-label">已安装</div>'
|
|
1013
|
+
+ (installed.map(button).join('') || '<div class="schema-loading">没有已安装的附属插件</div>')
|
|
1014
|
+
+ '<div class="config-group-label">未安装</div>'
|
|
1015
|
+
+ (missing.map(button).join('') || '<div class="schema-loading">全部已安装</div>');
|
|
1016
|
+
$$('#pluginConfigNav [data-package]').forEach((btn) => btn.addEventListener('click', () => openPluginConfig(btn.dataset.package)));
|
|
1017
|
+
}
|
|
1018
|
+
if (!activePlugin) {
|
|
1019
|
+
const first = installed[0] || data.plugins[0];
|
|
1020
|
+
if (first) openPluginConfig(first.package);
|
|
1021
|
+
}
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
if (nav) nav.innerHTML = `<div class="schema-loading">读取失败:${escHtml(error.message || error)}</div>`;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
function fieldControl(field, value) {
|
|
1028
|
+
const current = value == null ? (field.value ?? field.default ?? '') : value;
|
|
1029
|
+
if (field.type === 'boolean') {
|
|
1030
|
+
return `<label class="switch"><input type="checkbox" data-key="${field.key}" data-kind="boolean" ${current ? 'checked' : ''} /><i></i><span>${current ? '已开启' : '已关闭'}</span></label>`;
|
|
1031
|
+
}
|
|
1032
|
+
if (field.type === 'union') {
|
|
1033
|
+
const options = (field.options || []).slice();
|
|
1034
|
+
if (current !== '' && !options.includes(String(current))) options.unshift(String(current));
|
|
1035
|
+
if (!options.length) options.push(String(current));
|
|
1036
|
+
return `<select data-key="${field.key}" data-kind="string">${options.map((opt) => `<option ${String(current) === String(opt) ? 'selected' : ''}>${escHtml(opt)}</option>`).join('')}</select>`;
|
|
1037
|
+
}
|
|
1038
|
+
if (field.type === 'number') {
|
|
1039
|
+
return `<input type="number" data-key="${field.key}" data-kind="number" value="${escHtml(current ?? field.default ?? 0)}" />`;
|
|
1040
|
+
}
|
|
1041
|
+
if (field.json) {
|
|
1042
|
+
const val = field.type === 'array' && !Array.isArray(current) ? [] : (current || (field.type === 'array' ? [] : {}));
|
|
1043
|
+
return `<textarea rows="4" class="json-input" data-key="${field.key}" data-kind="json">${escHtml(JSON.stringify(val, null, 2))}</textarea>`;
|
|
1044
|
+
}
|
|
1045
|
+
if (field.sensitive) {
|
|
1046
|
+
return `<div class="secret-field">
|
|
1047
|
+
<input type="password" data-key="${field.key}" data-kind="string" value="${escHtml(current ?? field.default ?? '')}" autocomplete="off" />
|
|
1048
|
+
<button type="button" class="eye-btn" data-eye title="显示/隐藏" aria-label="显示或隐藏">${EYE_ICON}</button>
|
|
1049
|
+
</div>`;
|
|
1050
|
+
}
|
|
1051
|
+
if (field.long) {
|
|
1052
|
+
return `<textarea rows="6" data-key="${field.key}" data-kind="string">${escHtml(current ?? field.default ?? '')}</textarea>`;
|
|
1053
|
+
}
|
|
1054
|
+
return `<input type="text" data-key="${field.key}" data-kind="string" value="${escHtml(current ?? field.default ?? '')}" />`;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
const EYE_ICON = '<svg viewBox="0 0 24 24"><path d="M2 12s3.6-6 10-6 10 6 10 6-3.6 6-10 6S2 12 2 12Z"/><circle cx="12" cy="12" r="2.6"/></svg>';
|
|
1058
|
+
const EYE_OFF_ICON = '<svg viewBox="0 0 24 24"><path d="M3 3l18 18M10.6 6.2A9.8 9.8 0 0 1 12 6c6.4 0 10 6 10 6a17 17 0 0 1-2.5 3.2M6.6 6.7A16.7 16.7 0 0 0 2 12s3.6 6 10 6c1.6 0 3-.4 4.3-1"/></svg>';
|
|
1059
|
+
|
|
1060
|
+
function groupFields(fields) {
|
|
1061
|
+
const groups = new Map();
|
|
1062
|
+
for (const field of fields) {
|
|
1063
|
+
const key = field.group || '插件配置';
|
|
1064
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
1065
|
+
groups.get(key).push(field);
|
|
1066
|
+
}
|
|
1067
|
+
return [...groups.entries()];
|
|
619
1068
|
}
|
|
620
1069
|
|
|
621
|
-
|
|
1070
|
+
async function openPluginConfig(pkg) {
|
|
1071
|
+
activePlugin = pkg;
|
|
1072
|
+
$$('#pluginConfigNav [data-package]').forEach((btn) => btn.classList.toggle('active', btn.dataset.package === pkg));
|
|
1073
|
+
const form = $('#pluginConfigForm');
|
|
1074
|
+
if (!form) return;
|
|
1075
|
+
form.innerHTML = '<div class="schema-loading">读取插件配置…</div>';
|
|
1076
|
+
let info;
|
|
1077
|
+
try {
|
|
1078
|
+
info = await apiGet(`api/config/plugin?name=${encodeURIComponent(pkg)}`);
|
|
1079
|
+
} catch (error) {
|
|
1080
|
+
form.innerHTML = `<div class="schema-loading">读取失败:${escHtml(error.message || error)}</div>`;
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
if (!info.installed) {
|
|
1084
|
+
const npm = `https://www.npmjs.com/package/${pkg}`;
|
|
1085
|
+
form.innerHTML = `<div class="empty-install">
|
|
1086
|
+
<div class="empty-icon">+</div>
|
|
1087
|
+
<h2>${escHtml(info.title || pkg)} 未安装</h2>
|
|
1088
|
+
<p>${escHtml(pkg)}</p>
|
|
1089
|
+
<div class="install-actions"><button class="btn primary" data-install="${escHtml(pkg)}">一键安装</button>
|
|
1090
|
+
<a class="btn ghost" href="${escHtml(npm)}" target="_blank" rel="noreferrer">npm</a></div>
|
|
1091
|
+
<code class="install-code">npm i ${escHtml(pkg)}</code>
|
|
1092
|
+
</div>`;
|
|
1093
|
+
form.querySelector('[data-install]')?.addEventListener('click', (event) => installPackage(event.target.dataset.install));
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
const badges = `<span class="status ${info.configured ? 'ok' : 'warn'}">${info.configured ? '已启用' : '未启用'}</span>`;
|
|
1097
|
+
const fieldHtml = groupFields(info.fields).map(([group, fields]) => `<div class="form-section"><h3>${escHtml(group)}</h3>`
|
|
1098
|
+
+ fields.map((field) => `<div class="schema-field ${field.long ? 'long' : ''}">
|
|
1099
|
+
<div class="schema-field-info">
|
|
1100
|
+
<div class="schema-field-title">${escHtml(field.label || field.key)}</div>
|
|
1101
|
+
${field.description ? `<p class="schema-field-desc">${escHtml(field.description)}</p>` : ''}
|
|
1102
|
+
<code class="schema-field-key">${escHtml(field.key)}${field.foreign ? ' · 主插件' : ''}</code>
|
|
1103
|
+
</div>
|
|
1104
|
+
<div class="schema-field-control">${fieldControl(field, info.values[field.key])}</div>
|
|
1105
|
+
</div>`).join('')
|
|
1106
|
+
+ '</div>').join('');
|
|
1107
|
+
form.innerHTML = `<div class="form-head"><div><h2>${escHtml(info.title || info.name)}</h2><p>${escHtml(info.name)} · v${escHtml(info.version || '未知')}${info.instance ? ` · ${escHtml(info.instance)}` : ''}</p></div>${badges}</div>`
|
|
1108
|
+
+ (pkg === '@nestim/koishi-plugin-qqgm-memory' ? '<div class="sync-note" id="memorySyncNote">记忆后端状态读取中…</div>' : '')
|
|
1109
|
+
+ fieldHtml
|
|
1110
|
+
+ `<div class="form-foot"><span>保存前会备份 koishi.yml;带「主插件」标记的字段写到主插件配置块</span><div><button class="btn primary" id="savePluginConfig">保存</button></div></div>`;
|
|
1111
|
+
form.querySelector('#savePluginConfig')?.addEventListener('click', () => savePluginConfig(info));
|
|
1112
|
+
form.querySelectorAll('[data-eye]').forEach((btn) => btn.addEventListener('click', () => {
|
|
1113
|
+
const input = btn.parentElement?.querySelector('input');
|
|
1114
|
+
if (!input) return;
|
|
1115
|
+
const show = input.type === 'password';
|
|
1116
|
+
input.type = show ? 'text' : 'password';
|
|
1117
|
+
btn.innerHTML = show ? EYE_OFF_ICON : EYE_ICON;
|
|
1118
|
+
}));
|
|
1119
|
+
form.onchange = (event) => {
|
|
1120
|
+
if (event.target.matches('.switch input')) {
|
|
1121
|
+
const text = event.target.parentElement?.querySelector('span');
|
|
1122
|
+
if (text) text.textContent = event.target.checked ? '已开启' : '已关闭';
|
|
1123
|
+
}
|
|
1124
|
+
};
|
|
1125
|
+
if (pkg === '@nestim/koishi-plugin-qqgm-memory') updateMemorySyncNote();
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
async function updateMemorySyncNote() {
|
|
1129
|
+
const note = $('#memorySyncNote');
|
|
1130
|
+
if (!note) return;
|
|
1131
|
+
try {
|
|
1132
|
+
const data = await apiGet('api/memory');
|
|
1133
|
+
const backend = data.backend === 'sqlite' ? 'SQLite' : 'MD';
|
|
1134
|
+
note.innerHTML = `主插件当前后端:<b>${backend}</b> · SQLite 里 ${data.sqliteTotal || 0} 条 · MD 识别 ${data.md?.total || 0} 条。`
|
|
1135
|
+
+ (data.backend === 'sqlite' ? ' 当前由 SQLite 提供数据。' : ' 切到 SQLite 前先迁移并备份 MD。');
|
|
1136
|
+
note.classList.toggle('ok', data.backend === 'sqlite');
|
|
1137
|
+
} catch {
|
|
1138
|
+
note.textContent = '记忆后端状态读取失败';
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
function collectPluginValues(form, info) {
|
|
1143
|
+
const values = {};
|
|
1144
|
+
for (const field of info.fields) {
|
|
1145
|
+
const input = form.querySelector(`[data-key="${field.key}"]`);
|
|
1146
|
+
if (!input) continue;
|
|
1147
|
+
if (field.type === 'boolean') values[field.key] = !!input.checked;
|
|
1148
|
+
else if (field.type === 'number') values[field.key] = Number(input.value);
|
|
1149
|
+
else if (field.json) {
|
|
1150
|
+
try { values[field.key] = JSON.parse(input.value); }
|
|
1151
|
+
catch { throw new Error(`${field.label || field.key} 的 JSON 格式不对`); }
|
|
1152
|
+
} else values[field.key] = input.value;
|
|
1153
|
+
}
|
|
1154
|
+
return values;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
async function savePluginConfig(info) {
|
|
1158
|
+
const form = $('#pluginConfigForm');
|
|
1159
|
+
let values;
|
|
1160
|
+
try {
|
|
1161
|
+
values = collectPluginValues(form, info);
|
|
1162
|
+
} catch (error) {
|
|
1163
|
+
showToast(String(error.message || error));
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
try {
|
|
1167
|
+
const data = await apiPost('api/config/plugin', { name: info.name, values });
|
|
1168
|
+
showToast(`已保存 ${data.keys.length} 项,重启 Koishi 后生效`);
|
|
1169
|
+
if (info.name === '@nestim/koishi-plugin-qqgm-memory') {
|
|
1170
|
+
updateMemorySyncNote();
|
|
1171
|
+
initMemoryData();
|
|
1172
|
+
}
|
|
1173
|
+
if (info.name === '@nestim/koishi-plugin-qqgm-webui' && Object.prototype.hasOwnProperty.call(values, 'token')) {
|
|
1174
|
+
showToast('令牌已保存:重启后请用新令牌访问当前地址');
|
|
1175
|
+
}
|
|
1176
|
+
refreshStatus();
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
showToast(`保存失败:${String(error.message || error)}`);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// ---------------------------------------------------------------- 日志
|
|
1183
|
+
|
|
1184
|
+
const logState = { paused: false, level: 'all', lines: [], timer: null };
|
|
1185
|
+
|
|
1186
|
+
function levelClass(level) {
|
|
1187
|
+
const value = String(level || '').toLowerCase();
|
|
1188
|
+
if (value === 'warn') return 'warn';
|
|
1189
|
+
if (value === 'error') return 'error';
|
|
1190
|
+
if (value === 'success') return 'success';
|
|
1191
|
+
if (value === 'debug') return 'debug';
|
|
1192
|
+
return 'info';
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
function renderLogs() {
|
|
1196
|
+
const view = $('#logView');
|
|
1197
|
+
const meta = $('#logMeta');
|
|
1198
|
+
if (!view) return;
|
|
1199
|
+
const q = ($('#logSearch')?.value || '').trim().toLowerCase();
|
|
1200
|
+
const filtered = logState.lines.filter((line) => {
|
|
1201
|
+
if (logState.level !== 'all' && line.level !== logState.level) return false;
|
|
1202
|
+
if (q && !`${line.name} ${line.text}`.toLowerCase().includes(q)) return false;
|
|
1203
|
+
return true;
|
|
1204
|
+
});
|
|
1205
|
+
if (!filtered.length) {
|
|
1206
|
+
view.innerHTML = '<div class="log-empty">没有匹配的日志</div>';
|
|
1207
|
+
} else {
|
|
1208
|
+
const nearBottom = view.scrollHeight - view.scrollTop - view.clientHeight < 40;
|
|
1209
|
+
view.innerHTML = filtered.map((line) => `<div class="log-line">
|
|
1210
|
+
<time>${new Date(line.time).toLocaleTimeString('zh-CN', { hour12: false })}.${String(line.time % 1000).padStart(3, '0')}</time>
|
|
1211
|
+
<span class="lvl ${levelClass(line.level)}">${escHtml(String(line.level || 'info').toUpperCase())}</span>
|
|
1212
|
+
<span class="src">${escHtml(line.name || '-')}</span>
|
|
1213
|
+
<p>${escHtml(line.text || '')}</p>
|
|
1214
|
+
</div>`).join('');
|
|
1215
|
+
if (nearBottom) view.scrollTop = view.scrollHeight;
|
|
1216
|
+
}
|
|
1217
|
+
if (meta) {
|
|
1218
|
+
meta.textContent = `${filtered.length} / ${logState.lines.length} 条 · ${logState.paused ? '已暂停' : '自动刷新'}`;
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
function renderLogPause() {
|
|
1223
|
+
const btn = $('#logPause');
|
|
1224
|
+
if (btn) btn.textContent = logState.paused ? '继续' : '暂停';
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
async function loadLogs(force = false) {
|
|
1228
|
+
if (!force && (logState.paused || !document.querySelector('#page-logs.active'))) return;
|
|
1229
|
+
try {
|
|
1230
|
+
const data = await apiGet('api/logs?lines=400');
|
|
1231
|
+
logState.lines = data.lines || [];
|
|
1232
|
+
renderLogs();
|
|
1233
|
+
} catch {
|
|
1234
|
+
const meta = $('#logMeta');
|
|
1235
|
+
if (meta) meta.textContent = '日志接口不可用';
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
$('#logChips')?.addEventListener('click', (event) => {
|
|
1240
|
+
const chip = event.target.closest('.chip');
|
|
1241
|
+
if (!chip) return;
|
|
1242
|
+
$$('#logChips .chip').forEach((item) => item.classList.remove('active'));
|
|
1243
|
+
chip.classList.add('active');
|
|
1244
|
+
logState.level = chip.dataset.level || 'all';
|
|
1245
|
+
renderLogs();
|
|
1246
|
+
});
|
|
1247
|
+
|
|
1248
|
+
$('#logPause')?.addEventListener('click', () => {
|
|
1249
|
+
logState.paused = !logState.paused;
|
|
1250
|
+
renderLogPause();
|
|
1251
|
+
if (!logState.paused) loadLogs(true);
|
|
1252
|
+
else renderLogs();
|
|
1253
|
+
});
|
|
1254
|
+
|
|
1255
|
+
$('#logSearch')?.addEventListener('input', () => renderLogs());
|
|
1256
|
+
|
|
1257
|
+
setInterval(() => {
|
|
1258
|
+
if (!document.hidden && document.querySelector('#page-logs.active') && !logState.paused) loadLogs(true);
|
|
1259
|
+
}, 3000);
|
|
1260
|
+
|
|
1261
|
+
// ---------------------------------------------------------------- 记忆库搜索与其它
|
|
1262
|
+
|
|
622
1263
|
const memorySearch = $('#memorySearch');
|
|
623
1264
|
if (memorySearch) {
|
|
624
1265
|
memorySearch.addEventListener('input', () => {
|
|
@@ -629,48 +1270,35 @@ if (memorySearch) {
|
|
|
629
1270
|
});
|
|
630
1271
|
}
|
|
631
1272
|
|
|
632
|
-
|
|
633
|
-
const logSearch = $('#logSearch');
|
|
634
|
-
if (logSearch) {
|
|
635
|
-
logSearch.addEventListener('input', () => {
|
|
636
|
-
const q = logSearch.value.trim().toLowerCase();
|
|
637
|
-
$$('.log-line').forEach((line) => {
|
|
638
|
-
line.style.display = line.textContent.toLowerCase().includes(q) ? '' : 'none';
|
|
639
|
-
});
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
$$('.chip').forEach((chip) => chip.addEventListener('click', () => {
|
|
643
|
-
$$('.chip').forEach((x) => x.classList.remove('active'));
|
|
644
|
-
chip.classList.add('active');
|
|
645
|
-
const level = chip.textContent.trim().toLowerCase();
|
|
646
|
-
$$('.log-line').forEach((line) => {
|
|
647
|
-
const lvl = $('.lvl', line)?.textContent.trim().toLowerCase() || '';
|
|
648
|
-
line.style.display = level === '全部' || lvl === level ? '' : 'none';
|
|
649
|
-
});
|
|
650
|
-
}));
|
|
1273
|
+
$('#memoryBackend')?.addEventListener('click', () => showToast('可在「附属配置 → qqgm-memory」里切换主插件后端'));
|
|
651
1274
|
|
|
652
|
-
|
|
653
|
-
$$('.scope').forEach((item) => item.addEventListener('click', () => {
|
|
654
|
-
$$('.scope').forEach((x) => x.classList.remove('active'));
|
|
655
|
-
item.classList.add('active');
|
|
656
|
-
}));
|
|
1275
|
+
$('#refreshData')?.addEventListener('click', () => location.reload());
|
|
657
1276
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
}
|
|
1277
|
+
$('#exportSnapshot')?.addEventListener('click', async () => {
|
|
1278
|
+
try {
|
|
1279
|
+
const data = await apiGet('api/overview');
|
|
1280
|
+
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
|
1281
|
+
const a = document.createElement('a');
|
|
1282
|
+
a.href = URL.createObjectURL(blob);
|
|
1283
|
+
a.download = `qqgm-overview-${Date.now()}.json`;
|
|
1284
|
+
a.click();
|
|
1285
|
+
URL.revokeObjectURL(a.href);
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
showToast(`导出失败:${String(error.message || error)}`);
|
|
1288
|
+
}
|
|
1289
|
+
});
|
|
672
1290
|
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
1291
|
+
$('#refreshOverview')?.addEventListener('click', () => {
|
|
1292
|
+
initOverview();
|
|
1293
|
+
refreshStatus();
|
|
1294
|
+
loadTrend(Number($('#trendRange')?.value) || 7);
|
|
1295
|
+
showToast('已刷新');
|
|
1296
|
+
});
|
|
1297
|
+
|
|
1298
|
+
// ---------------------------------------------------------------- 启动
|
|
1299
|
+
|
|
1300
|
+
initOverview().then(() => loadTrend(Number($('#trendRange')?.value) || 7));
|
|
1301
|
+
initMemoryData();
|
|
1302
|
+
initMainSchema();
|
|
1303
|
+
initPluginConfig();
|
|
1304
|
+
loadLogs();
|