@nestim/koishi-plugin-qqgm-webui 0.2.23 → 0.3.1
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 +66 -0
- package/README.md +41 -56
- package/index.js +172 -12
- package/lib/bot.js +44 -0
- package/lib/data.js +72 -13
- package/lib/logbuf.js +79 -0
- package/lib/plugin-config.js +288 -0
- package/package.json +33 -29
- package/public/app.js +1126 -241
- package/public/index.html +62 -148
- package/public/styles.css +118 -20
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
|
+
};
|
|
189
|
+
|
|
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
|
+
}
|
|
80
207
|
|
|
81
|
-
|
|
82
|
-
|
|
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,123 +278,345 @@ 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;
|
|
479
|
+
const memoryQuery = { scope: '', category: '', q: '', page: 1, pageSize: 20 };
|
|
123
480
|
|
|
124
481
|
function renderMemoryList(items) {
|
|
125
482
|
memoryItems = items || [];
|
|
126
483
|
const list = $('#memoryList');
|
|
127
484
|
if (!list) return;
|
|
128
485
|
if (!memoryItems.length) {
|
|
129
|
-
list.innerHTML = '<div class="memory-empty"><b>没有匹配的记忆</b><p
|
|
486
|
+
list.innerHTML = '<div class="memory-empty"><b>没有匹配的记忆</b><p>换个范围/分类,或调整搜索关键词。</p></div>';
|
|
130
487
|
return;
|
|
131
488
|
}
|
|
132
489
|
list.innerHTML = memoryItems.map((item, index) => `
|
|
133
490
|
<article class="memory-item" data-memory-index="${index}">
|
|
134
491
|
<div class="memory-head">
|
|
135
492
|
<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>
|
|
493
|
+
<span class="tag soft">${escHtml(item.category || '未分类')}</span>
|
|
137
494
|
<time>${new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })}</time>
|
|
138
495
|
</div>
|
|
139
|
-
<p>${
|
|
140
|
-
<div class="memory-foot"><code>${item.label || '记忆'}</code><span>#${item.id}</span><span class="memory-open">点击查看</span></div>
|
|
496
|
+
<p>${escHtml(item.content)}</p>
|
|
497
|
+
<div class="memory-foot"><code>${escHtml(item.label || '记忆')}</code><span>#${escHtml(item.id)}</span><span class="memory-open">点击查看</span></div>
|
|
141
498
|
</article>`).join('');
|
|
142
499
|
}
|
|
143
500
|
|
|
144
|
-
|
|
145
|
-
const
|
|
146
|
-
if (
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
501
|
+
function renderMemoryPager(data) {
|
|
502
|
+
const pager = $('#memoryPager');
|
|
503
|
+
if (!pager) return;
|
|
504
|
+
const pages = Number(data.pages) || 1;
|
|
505
|
+
const page = Number(data.page) || 1;
|
|
506
|
+
const size = Number(data.pageSize) || 20;
|
|
507
|
+
pager.innerHTML = `<div class="pager-info">筛选出 <b>${data.matched || 0}</b> 条 · 第 <b>${page}</b> / ${pages} 页</div>
|
|
508
|
+
<div class="pager-actions">
|
|
509
|
+
<select class="select tiny" id="memoryPageSize">${[10, 20, 50, 100].map((n) => `<option value="${n}" ${n === size ? 'selected' : ''}>${n} 条/页</option>`).join('')}</select>
|
|
510
|
+
<button class="btn ghost small" data-memory-page="${page - 1}" ${page <= 1 ? 'disabled' : ''}>上一页</button>
|
|
511
|
+
<button class="btn ghost small" data-memory-page="${page + 1}" ${page >= pages ? 'disabled' : ''}>下一页</button>
|
|
512
|
+
</div>`;
|
|
513
|
+
const count = $('#memoryCount');
|
|
514
|
+
if (count) count.textContent = `共 ${data.matched || 0} 条`;
|
|
158
515
|
}
|
|
159
516
|
|
|
160
|
-
|
|
517
|
+
function renderMemorySidebar(data) {
|
|
518
|
+
const scopes = $('#memoryScopes');
|
|
519
|
+
if (!scopes) return;
|
|
520
|
+
const activeScope = memoryQuery.scope;
|
|
521
|
+
const activeCategory = memoryQuery.category;
|
|
522
|
+
const buttons = [`<h3>范围</h3><button class="scope ${!activeScope && !activeCategory ? 'active' : ''}" data-scope="" data-category=""><span>全部</span><b>${data.total || 0}</b></button>`];
|
|
523
|
+
for (const item of data.scopes || []) {
|
|
524
|
+
const key = `${item.scope_kind}:${item.scope_id || ''}`;
|
|
525
|
+
const label = item.scope_kind === 'group' ? `群 ${item.scope_id}` : item.scope_kind === 'private' ? `私聊 ${item.scope_id}` : `全局 ${item.scope_id || ''}`;
|
|
526
|
+
buttons.push(`<button class="scope ${activeScope === key ? 'active' : ''}" data-scope="${key}"><span>${label}</span><b>${item.n}</b></button>`);
|
|
527
|
+
}
|
|
528
|
+
buttons.push('<h3 class="mt">分类</h3>');
|
|
529
|
+
buttons.push(`<button class="scope ${activeCategory === '' ? 'active' : ''}" data-category=""><span>全部分类</span><b>${data.scopeTotal || 0}</b></button>`);
|
|
530
|
+
for (const item of data.categories || []) {
|
|
531
|
+
const category = item.category || '未分类';
|
|
532
|
+
buttons.push(`<button class="scope ${activeCategory === category ? 'active' : ''}" data-category="${escHtml(category)}"><span>${escHtml(category)}</span><b>${item.n}</b></button>`);
|
|
533
|
+
}
|
|
534
|
+
scopes.innerHTML = buttons.join('');
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function renderMemoryHeader(data) {
|
|
538
|
+
const badge = $('.nav-badge');
|
|
539
|
+
if (badge) badge.textContent = String(data.total || 0);
|
|
540
|
+
const headP = $('#page-memory .page-head p');
|
|
541
|
+
if (headP) {
|
|
542
|
+
headP.textContent = data.useSqlite
|
|
543
|
+
? `当前 SQLite · ${data.total || 0} 条;切换前备份 koishi.yml`
|
|
544
|
+
: (data.md?.total
|
|
545
|
+
? `当前 MD · 识别到 ${data.md.total} 条旧记忆,可迁移到 SQLite`
|
|
546
|
+
: '当前 MD · 没有识别到旧记忆文件');
|
|
547
|
+
}
|
|
548
|
+
const pill = $('#memoryBackendPill');
|
|
549
|
+
if (pill) {
|
|
550
|
+
pill.textContent = data.useSqlite ? `当前:SQLite · ${data.total || 0} 条` : `当前:MD · ${data.total || 0} 条`;
|
|
551
|
+
pill.classList.toggle('sqlite', !!data.useSqlite);
|
|
552
|
+
}
|
|
553
|
+
const migrateBtn = $('#migrateMemory');
|
|
554
|
+
const switchSqliteBtn = $('#switchSqlite');
|
|
555
|
+
const switchBtn = $('#switchMd');
|
|
556
|
+
if (migrateBtn) migrateBtn.hidden = !(data.md?.total > 0);
|
|
557
|
+
if (switchSqliteBtn) switchSqliteBtn.hidden = !(data.backend === 'md' && (data.sqliteTotal || 0) > 0);
|
|
558
|
+
if (switchBtn) switchBtn.hidden = data.backend !== 'sqlite';
|
|
559
|
+
const note = $('#memoryBackend');
|
|
560
|
+
if (note) {
|
|
561
|
+
note.innerHTML = data.useSqlite
|
|
562
|
+
? '当前使用 SQLite;修改前会备份 <code>koishi.yml</code>,旧 MD 文件保留可回滚。'
|
|
563
|
+
: (data.md?.total
|
|
564
|
+
? `当前使用 MD,识别到 ${data.md.total} 条旧记忆、${data.md.files?.length || 0} 个文件。先点“迁移 MD → SQLite”导入,再点“切换到 SQLite”;迁移不会自动切换。`
|
|
565
|
+
: '默认使用 MD;没有识别到旧记忆文件。');
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
async function loadMemory(resetPage = false) {
|
|
570
|
+
if (resetPage) memoryQuery.page = 1;
|
|
571
|
+
const params = new URLSearchParams({
|
|
572
|
+
page: String(memoryQuery.page),
|
|
573
|
+
pageSize: String(memoryQuery.pageSize),
|
|
574
|
+
});
|
|
575
|
+
if (memoryQuery.scope) params.set('scope', memoryQuery.scope);
|
|
576
|
+
if (memoryQuery.category) params.set('category', memoryQuery.category);
|
|
577
|
+
if (memoryQuery.q) params.set('q', memoryQuery.q);
|
|
161
578
|
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();
|
|
579
|
+
const data = await apiGet(`api/memory?${params}`);
|
|
166
580
|
if (!data || !data.installed) return;
|
|
167
|
-
memoryItems = data.items || [];
|
|
168
581
|
memoryState = data;
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
if (migrateBtn) migrateBtn.hidden = !(data.md?.total > 0);
|
|
188
|
-
if (switchSqliteBtn) switchSqliteBtn.hidden = !(data.backend === 'md' && (data.sqliteTotal || 0) > 0);
|
|
189
|
-
if (switchBtn) switchBtn.hidden = data.backend !== 'sqlite';
|
|
190
|
-
const note = $('#memoryBackend');
|
|
191
|
-
if (note) {
|
|
192
|
-
note.innerHTML = data.useSqlite
|
|
193
|
-
? '当前使用 SQLite;修改前会备份 <code>koishi.yml</code>,旧 MD 文件保留可回滚。'
|
|
194
|
-
: (data.md?.total
|
|
195
|
-
? `当前使用 MD,识别到 ${data.md.total} 条旧记忆、${data.md.files?.length || 0} 个文件。先点“迁移 MD → SQLite”导入,再点“切换到 SQLite”;迁移不会自动切换。`
|
|
196
|
-
: '默认使用 MD;没有识别到旧记忆文件。');
|
|
197
|
-
}
|
|
198
|
-
const scopes = $('#memoryScopes');
|
|
199
|
-
if (scopes) {
|
|
200
|
-
const scopeButtons = [`<h3>范围</h3><button class="scope active" data-scope="" data-category=""><span>全部</span><b>${data.total || 0}</b></button>`];
|
|
201
|
-
for (const item of data.scopes || []) {
|
|
202
|
-
const label = item.scope_kind === 'group' ? `群 ${item.scope_id}` : item.scope_kind === 'private' ? `私聊 ${item.scope_id}` : `全局 ${item.scope_id || ''}`;
|
|
203
|
-
scopeButtons.push(`<button class="scope" data-scope="${item.scope_kind}:${item.scope_id || ''}"><span>${label}</span><b>${item.n}</b></button>`);
|
|
204
|
-
}
|
|
205
|
-
scopeButtons.push('<h3 class="mt">分类</h3>');
|
|
206
|
-
for (const item of data.categories || []) {
|
|
207
|
-
scopeButtons.push(`<button class="scope" data-category="${String(item.category).replace(/"/g, '"')}"><span>${item.category}</span><b>${item.n}</b></button>`);
|
|
208
|
-
}
|
|
209
|
-
scopes.innerHTML = scopeButtons.join('');
|
|
210
|
-
}
|
|
211
|
-
renderMemoryList(data.items);
|
|
212
|
-
} catch { /* 文件预览保留 mock */ }
|
|
582
|
+
memoryItems = data.items || [];
|
|
583
|
+
renderMemoryList(memoryItems);
|
|
584
|
+
renderMemoryPager(data);
|
|
585
|
+
renderMemorySidebar(data);
|
|
586
|
+
renderMemoryHeader(data);
|
|
587
|
+
} catch {
|
|
588
|
+
showToast('记忆库读取失败');
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
async function filterMemory(scope, category) {
|
|
593
|
+
memoryQuery.scope = scope || '';
|
|
594
|
+
memoryQuery.category = category || '';
|
|
595
|
+
await loadMemory(true);
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
async function initMemoryData() {
|
|
599
|
+
await loadMemory(true);
|
|
213
600
|
}
|
|
214
|
-
initMemoryData();
|
|
215
601
|
|
|
216
602
|
$('#memoryScopes')?.addEventListener('click', (event) => {
|
|
217
603
|
const btn = event.target.closest('.scope');
|
|
218
604
|
if (!btn) return;
|
|
219
605
|
if (btn.dataset.scope === undefined && btn.dataset.category === undefined) return;
|
|
220
|
-
filterMemory(btn.dataset.scope || '', btn.dataset.category || ''
|
|
606
|
+
filterMemory(btn.dataset.scope || '', btn.dataset.category || '').catch(() => {});
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
$('#memoryPager')?.addEventListener('click', (event) => {
|
|
610
|
+
const button = event.target.closest('[data-memory-page]');
|
|
611
|
+
if (!button || button.disabled) return;
|
|
612
|
+
memoryQuery.page = Number(button.dataset.memoryPage) || 1;
|
|
613
|
+
loadMemory();
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
$('#memoryPager')?.addEventListener('change', (event) => {
|
|
617
|
+
if (event.target.id !== 'memoryPageSize') return;
|
|
618
|
+
memoryQuery.pageSize = Number(event.target.value) || 20;
|
|
619
|
+
loadMemory(true);
|
|
221
620
|
});
|
|
222
621
|
|
|
223
622
|
function memoryScopeLabel(item) {
|
|
@@ -237,10 +636,12 @@ function openMemoryModal(index) {
|
|
|
237
636
|
$('#memoryModalSource').textContent = item.source === 'md' ? '来源:MD(只读;迁移到 SQLite 后可编辑)' : `来源:SQLite · #${item.id}`;
|
|
238
637
|
modal.hidden = false;
|
|
239
638
|
}
|
|
639
|
+
|
|
240
640
|
function closeMemoryModal() {
|
|
241
641
|
const modal = $('#memoryModal');
|
|
242
642
|
if (modal) modal.hidden = true;
|
|
243
643
|
}
|
|
644
|
+
|
|
244
645
|
$('#memoryList')?.addEventListener('click', (event) => {
|
|
245
646
|
const item = event.target.closest('[data-memory-index]');
|
|
246
647
|
if (item) openMemoryModal(Number(item.dataset.memoryIndex));
|
|
@@ -251,23 +652,11 @@ $('#memoryModal')?.addEventListener('click', (event) => {
|
|
|
251
652
|
if (event.target.id === 'memoryModal') closeMemoryModal();
|
|
252
653
|
});
|
|
253
654
|
|
|
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
655
|
$('#migrateMemory')?.addEventListener('click', async () => {
|
|
267
|
-
if (!confirm('把 Memory_*.md 导入 SQLite
|
|
656
|
+
if (!confirm('把 Memory_*.md 导入 SQLite?\n\n只导入,不切换后端;不会删除 MD,也不会自动重启。')) return;
|
|
268
657
|
try {
|
|
269
658
|
showToast('正在迁移…');
|
|
270
|
-
const data = await
|
|
659
|
+
const data = await apiPost('api/memory/migrate', { switchBackend: false });
|
|
271
660
|
showToast(`已导入 ${data.imported} 条到 SQLite;现在可以点“切换到 SQLite”`);
|
|
272
661
|
setTimeout(() => location.reload(), 1800);
|
|
273
662
|
} catch (error) {
|
|
@@ -282,12 +671,10 @@ $('#switchSqlite')?.addEventListener('click', async () => {
|
|
|
282
671
|
return;
|
|
283
672
|
}
|
|
284
673
|
const mdTotal = memoryState?.md?.total || 0;
|
|
285
|
-
const extra = mdTotal
|
|
286
|
-
|
|
287
|
-
: '';
|
|
288
|
-
if (!confirm(`切换主插件记忆后端到 sqlite?${extra}\\n\\n会先备份 koishi.yml,重启后生效。`)) return;
|
|
674
|
+
const extra = mdTotal ? `\n\n注意:还有 ${mdTotal} 条 MD 未确认迁移,切换后主插件只读 SQLite。` : '';
|
|
675
|
+
if (!confirm(`切换主插件记忆后端到 sqlite?${extra}\n\n会先备份 koishi.yml,重启后生效。`)) return;
|
|
289
676
|
try {
|
|
290
|
-
await
|
|
677
|
+
await apiPost('api/memory/config', { backend: 'sqlite' });
|
|
291
678
|
showToast('已切换,重启 Koishi 后生效');
|
|
292
679
|
setTimeout(() => location.reload(), 1600);
|
|
293
680
|
} catch (error) {
|
|
@@ -298,7 +685,7 @@ $('#switchSqlite')?.addEventListener('click', async () => {
|
|
|
298
685
|
$('#switchMd')?.addEventListener('click', async () => {
|
|
299
686
|
if (!confirm('把主插件记忆后端切回 md?SQLite 数据不会删除,可随时切回。')) return;
|
|
300
687
|
try {
|
|
301
|
-
await
|
|
688
|
+
await apiPost('api/memory/config', { backend: 'md' });
|
|
302
689
|
showToast('已切回 md,重启后生效');
|
|
303
690
|
setTimeout(() => location.reload(), 1500);
|
|
304
691
|
} catch (error) {
|
|
@@ -306,34 +693,44 @@ $('#switchMd')?.addEventListener('click', async () => {
|
|
|
306
693
|
}
|
|
307
694
|
});
|
|
308
695
|
|
|
696
|
+
// ---------------------------------------------------------------- 安装
|
|
697
|
+
|
|
309
698
|
async function installPackage(pkg) {
|
|
310
|
-
const token = new URLSearchParams(location.search).get('token') || '';
|
|
311
699
|
showToast(`正在安装 ${pkg}…`);
|
|
312
700
|
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}`);
|
|
701
|
+
await apiPost('api/install', { package: pkg });
|
|
320
702
|
showToast('安装完成,重启/重载插件后生效');
|
|
321
703
|
} catch (error) {
|
|
322
704
|
showToast(`安装失败:${String(error.message || error)}`);
|
|
323
705
|
}
|
|
324
706
|
}
|
|
707
|
+
|
|
325
708
|
$('#installMonitor')?.addEventListener('click', () => installPackage('@nestim/koishi-plugin-qqgm-monitor'));
|
|
326
709
|
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
710
|
+
$('#rescanPlugins')?.addEventListener('click', async () => {
|
|
711
|
+
try {
|
|
712
|
+
renderPlugins(await apiGet('api/plugins'));
|
|
713
|
+
showToast('已重新扫描');
|
|
714
|
+
} catch (error) {
|
|
715
|
+
showToast(`扫描失败:${String(error.message || error)}`);
|
|
716
|
+
}
|
|
717
|
+
});
|
|
330
718
|
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
|
|
334
|
-
|
|
719
|
+
document.addEventListener('click', (event) => {
|
|
720
|
+
const configButton = event.target.closest('[data-config-open]');
|
|
721
|
+
if (configButton) {
|
|
722
|
+
go('config');
|
|
723
|
+
openPluginConfig(configButton.dataset.configOpen);
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
const installButton = event.target.closest('[data-install-pkg]');
|
|
727
|
+
if (installButton) installPackage(installButton.dataset.installPkg);
|
|
728
|
+
});
|
|
335
729
|
|
|
336
|
-
|
|
730
|
+
// ---------------------------------------------------------------- 主插件配置
|
|
731
|
+
|
|
732
|
+
let mainSchema = null;
|
|
733
|
+
let activeMainGroup = 0;
|
|
337
734
|
|
|
338
735
|
function splitScored(raw) {
|
|
339
736
|
const text = String(raw == null ? '' : raw);
|
|
@@ -379,7 +776,7 @@ function collectList(root, field) {
|
|
|
379
776
|
return values;
|
|
380
777
|
}
|
|
381
778
|
|
|
382
|
-
function groupFieldHtml(field, value
|
|
779
|
+
function groupFieldHtml(field, value) {
|
|
383
780
|
const current = value == null ? '' : value;
|
|
384
781
|
if (field.type === 'boolean') {
|
|
385
782
|
return `<label class="group-field"><span>${escHtml(field.label)}</span>
|
|
@@ -400,12 +797,12 @@ function groupFieldHtml(field, value, index) {
|
|
|
400
797
|
<input type="${type}" data-group-field="${field.key}" data-group-kind="${type === 'number' ? 'number' : 'string'}" value="${escHtml(current)}" placeholder="留空=全局" /></label>`;
|
|
401
798
|
}
|
|
402
799
|
|
|
403
|
-
function groupCardHtml(field, group = {},
|
|
404
|
-
const body = (field.itemFields || []).map((item) => groupFieldHtml(item, group[item.key]
|
|
800
|
+
function groupCardHtml(field, group = {}, collapsed = true) {
|
|
801
|
+
const body = (field.itemFields || []).map((item) => groupFieldHtml(item, group[item.key])).join('');
|
|
405
802
|
return `<article class="group-rule" data-group-card>
|
|
406
803
|
<div class="group-rule-head">
|
|
407
804
|
<input class="group-rule-id" value="${escHtml(group.guildId || '')}" placeholder="群号" />
|
|
408
|
-
<button type="button" class="row-btn" data-toggle-group>${collapsed ? '
|
|
805
|
+
<button type="button" class="row-btn" data-toggle-group title="展开/收起">${collapsed ? '▸' : '▾'}</button>
|
|
409
806
|
<button type="button" class="row-btn" data-remove-group>×</button>
|
|
410
807
|
</div>
|
|
411
808
|
<div class="group-rule-body" ${collapsed ? 'hidden' : ''}>
|
|
@@ -419,9 +816,13 @@ function renderGroupRules(field, value) {
|
|
|
419
816
|
const groups = Array.isArray(value) ? value : [];
|
|
420
817
|
const enabled = groups.length > 0;
|
|
421
818
|
return `<div class="group-rules" data-group-rules>
|
|
422
|
-
<
|
|
819
|
+
<div class="group-rules-head">
|
|
820
|
+
<label class="switch"><input type="checkbox" data-group-enabled ${enabled ? 'checked' : ''} /><i></i><span>${enabled ? '按群号覆盖' : '未开启,使用全局配置'}</span></label>
|
|
821
|
+
<button type="button" class="link-btn" data-toggle-all-groups="collapse">全部收起</button>
|
|
822
|
+
</div>
|
|
823
|
+
<p class="group-rule-hint">每个群可以单独设置违禁词、白名单、禁止项与自动管控;没填的项跟随全局。</p>
|
|
423
824
|
<div class="group-rules-list" ${enabled ? '' : 'hidden'}>
|
|
424
|
-
${groups.map((group
|
|
825
|
+
${groups.map((group) => groupCardHtml(field, group, false)).join('')}
|
|
425
826
|
<button type="button" class="link-btn" data-add-group>+ 添加群规则</button>
|
|
426
827
|
</div>
|
|
427
828
|
</div>`;
|
|
@@ -454,6 +855,25 @@ function collectGroupRules(field, form) {
|
|
|
454
855
|
return groups;
|
|
455
856
|
}
|
|
456
857
|
|
|
858
|
+
const MAIN_GROUP_ICONS = {
|
|
859
|
+
基础设置: 'M4 6h16M4 12h10M4 18h7',
|
|
860
|
+
消息管控: 'M12 3 4 6v5c0 5 3.4 8.4 8 10 4.6-1.6 8-5 8-10V6l-8-3Z',
|
|
861
|
+
自动管控: 'M6 3h12l3 6-9 12L3 9l3-6Z',
|
|
862
|
+
记忆库: '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',
|
|
863
|
+
黑名单: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM5.6 5.6l12.8 12.8',
|
|
864
|
+
娱乐设置: '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',
|
|
865
|
+
群聊互动: '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',
|
|
866
|
+
自定义命令: 'M4 6h16M4 12h16M4 18h16M8 6v12',
|
|
867
|
+
'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',
|
|
868
|
+
权限设置: 'M7 11V8a5 5 0 0 1 10 0v3M5 11h14v10H5V11Zm7 4v2',
|
|
869
|
+
日志设置: 'M5 4h14v16H5V4Zm3 4 3 4-3 4m5 0h4',
|
|
870
|
+
};
|
|
871
|
+
|
|
872
|
+
function groupIcon(title) {
|
|
873
|
+
const path = MAIN_GROUP_ICONS[title] || 'M4 4h16v16H4V4Z';
|
|
874
|
+
return `<span class="plugin-ico group-ico"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
|
875
|
+
}
|
|
876
|
+
|
|
457
877
|
function openMainGroup(index) {
|
|
458
878
|
renderMainGroup(index);
|
|
459
879
|
}
|
|
@@ -465,7 +885,7 @@ function renderMainGroup(index) {
|
|
|
465
885
|
const form = $('#mainSchemaForm');
|
|
466
886
|
if (!form) return;
|
|
467
887
|
$$('#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>`
|
|
888
|
+
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
889
|
+ group.fields.map((field) => {
|
|
470
890
|
const value = mainSchema.values[field.key] ?? field.default;
|
|
471
891
|
let control = '';
|
|
@@ -496,7 +916,7 @@ function renderMainGroup(index) {
|
|
|
496
916
|
<div class="schema-field-control">${control}</div>
|
|
497
917
|
</div>`;
|
|
498
918
|
}).join('')
|
|
499
|
-
+
|
|
919
|
+
+ '<div class="form-foot"><span>保存只改本组字段;写前备份 koishi.yml,重启后生效</span></div>';
|
|
500
920
|
const save = $('#saveMainSchemaGroup');
|
|
501
921
|
if (save) save.onclick = () => saveMainGroup(group);
|
|
502
922
|
|
|
@@ -519,7 +939,7 @@ function renderMainGroup(index) {
|
|
|
519
939
|
const rules = addGroup.closest('[data-group-rules]');
|
|
520
940
|
const groupField = group.fields.find((item) => item.key === 'groupRules');
|
|
521
941
|
const list = rules?.querySelector('.group-rules-list');
|
|
522
|
-
if (list && groupField) list.insertAdjacentHTML('beforeend', groupCardHtml(groupField, {},
|
|
942
|
+
if (list && groupField) list.insertAdjacentHTML('beforeend', groupCardHtml(groupField, {}, false));
|
|
523
943
|
return;
|
|
524
944
|
}
|
|
525
945
|
const removeGroup = event.target.closest('[data-remove-group]');
|
|
@@ -529,8 +949,22 @@ function renderMainGroup(index) {
|
|
|
529
949
|
const body = toggleGroup.closest('[data-group-card]')?.querySelector('.group-rule-body');
|
|
530
950
|
if (body) {
|
|
531
951
|
body.hidden = !body.hidden;
|
|
532
|
-
toggleGroup.textContent = body.hidden ? '
|
|
952
|
+
toggleGroup.textContent = body.hidden ? '▸' : '▾';
|
|
533
953
|
}
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
const toggleAll = event.target.closest('[data-toggle-all-groups]');
|
|
957
|
+
if (toggleAll) {
|
|
958
|
+
const rules = toggleAll.closest('[data-group-rules]');
|
|
959
|
+
const collapse = toggleAll.dataset.toggleAllGroups === 'collapse';
|
|
960
|
+
rules?.querySelectorAll('[data-group-card]').forEach((card) => {
|
|
961
|
+
const body = card.querySelector('.group-rule-body');
|
|
962
|
+
const button = card.querySelector('[data-toggle-group]');
|
|
963
|
+
if (body) body.hidden = collapse;
|
|
964
|
+
if (button) button.textContent = collapse ? '▸' : '▾';
|
|
965
|
+
});
|
|
966
|
+
toggleAll.dataset.toggleAllGroups = collapse ? 'expand' : 'collapse';
|
|
967
|
+
toggleAll.textContent = collapse ? '全部展开' : '全部收起';
|
|
534
968
|
}
|
|
535
969
|
};
|
|
536
970
|
|
|
@@ -543,7 +977,7 @@ function renderMainGroup(index) {
|
|
|
543
977
|
if (text) text.textContent = event.target.checked ? '按群号覆盖' : '未开启,使用全局配置';
|
|
544
978
|
if (event.target.checked && list && !list.querySelector('[data-group-card]')) {
|
|
545
979
|
const groupField = group.fields.find((item) => item.key === 'groupRules');
|
|
546
|
-
if (groupField) list.insertAdjacentHTML('afterbegin', groupCardHtml(groupField, {},
|
|
980
|
+
if (groupField) list.insertAdjacentHTML('afterbegin', groupCardHtml(groupField, {}, false));
|
|
547
981
|
}
|
|
548
982
|
}
|
|
549
983
|
if (event.target.matches('.switch input')) {
|
|
@@ -565,7 +999,7 @@ async function saveMainGroup(group) {
|
|
|
565
999
|
values[field.key] = collectList(form.querySelector(`[data-list-key="${field.key}"]`), field);
|
|
566
1000
|
continue;
|
|
567
1001
|
}
|
|
568
|
-
const input = $(`[data-key="${field.key}"]
|
|
1002
|
+
const input = $(`[data-key="${field.key}"]`, form);
|
|
569
1003
|
if (!input) continue;
|
|
570
1004
|
if (field.type === 'boolean') values[field.key] = !!input.checked;
|
|
571
1005
|
else if (field.type === 'number') values[field.key] = Number(input.value);
|
|
@@ -575,13 +1009,7 @@ async function saveMainGroup(group) {
|
|
|
575
1009
|
} else values[field.key] = input.value;
|
|
576
1010
|
}
|
|
577
1011
|
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}`);
|
|
1012
|
+
const data = await apiPost('api/config/main', { values });
|
|
585
1013
|
showToast(`已保存 ${data.keys.length} 项,重启 Koishi 后生效`);
|
|
586
1014
|
} catch (error) {
|
|
587
1015
|
showToast(`保存失败:${String(error.message || error)}`);
|
|
@@ -590,87 +1018,544 @@ async function saveMainGroup(group) {
|
|
|
590
1018
|
|
|
591
1019
|
async function initMainSchema() {
|
|
592
1020
|
try {
|
|
593
|
-
|
|
594
|
-
if (!res.ok) return;
|
|
595
|
-
mainSchema = await res.json();
|
|
1021
|
+
mainSchema = await apiGet('api/config/main');
|
|
596
1022
|
if (!mainSchema.available) {
|
|
597
|
-
$('#mainSchemaForm')
|
|
1023
|
+
const form = $('#mainSchemaForm');
|
|
1024
|
+
if (form) form.innerHTML = '<div class="schema-loading">未找到主插件 Config Schema</div>';
|
|
598
1025
|
return;
|
|
599
1026
|
}
|
|
600
1027
|
const nav = $('#mainSchemaNav');
|
|
601
1028
|
if (nav) {
|
|
602
1029
|
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}"
|
|
1030
|
+
+ 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
1031
|
$$('#mainSchemaNav .config-plugin').forEach((btn) => btn.addEventListener('click', () => openMainGroup(Number(btn.dataset.mainGroup))));
|
|
605
1032
|
}
|
|
606
|
-
const params = new URLSearchParams(location.search);
|
|
607
1033
|
const groupParam = Number(params.get('group'));
|
|
608
1034
|
if (document.querySelector('#page-main-schema.active')) {
|
|
609
1035
|
openMainGroup(Number.isInteger(groupParam) && groupParam >= 0 && groupParam < mainSchema.groups.length ? groupParam : 0);
|
|
610
1036
|
}
|
|
611
1037
|
} catch { /* leave loading */ }
|
|
612
1038
|
}
|
|
613
|
-
initMainSchema();
|
|
614
1039
|
|
|
615
|
-
//
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
1040
|
+
// ---------------------------------------------------------------- 附属配置
|
|
1041
|
+
|
|
1042
|
+
const PLUGIN_ICONS = {
|
|
1043
|
+
'qqgm-monitor': ['blue', 'M4 19V5m0 14h16M8 16l3-5 3 2 4-7'],
|
|
1044
|
+
'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'],
|
|
1045
|
+
'qqgm-chat-style': ['orange', 'M4 5h16v11H8l-4 4V5Z'],
|
|
1046
|
+
'qqgm-private': ['purple', 'M4 5h16v12H8l-4 4V5Z'],
|
|
1047
|
+
'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'],
|
|
1048
|
+
'qqgm-webui': ['slate', 'M4 5h16v14H4V5Zm0 4h16M8 13h3m-3 3h6'],
|
|
1049
|
+
'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'],
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
function pluginIcon(item) {
|
|
1053
|
+
const [color, path] = PLUGIN_ICONS[item.id] || ['slate', 'M4 4h16v16H4V4Z'];
|
|
1054
|
+
return `<span class="plugin-ico ${color} plugin-ico-svg"><svg viewBox="0 0 24 24"><path d="${path}"/></svg></span>`;
|
|
619
1055
|
}
|
|
620
1056
|
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
1057
|
+
let pluginConfigList = null;
|
|
1058
|
+
let activePlugin = '';
|
|
1059
|
+
|
|
1060
|
+
async function initPluginConfig(force = false) {
|
|
1061
|
+
if (pluginConfigList && !force) {
|
|
1062
|
+
if (!activePlugin) {
|
|
1063
|
+
const list = pluginConfigList.plugins.filter((item) => item.id !== 'qq-group-manager');
|
|
1064
|
+
const first = list.find((item) => item.installed) || list[0];
|
|
1065
|
+
if (first) openPluginConfig(first.package);
|
|
1066
|
+
}
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
const nav = $('#pluginConfigNav');
|
|
1070
|
+
try {
|
|
1071
|
+
const data = await apiGet('api/config/plugins');
|
|
1072
|
+
pluginConfigList = data;
|
|
1073
|
+
const subPlugins = data.plugins.filter((item) => item.id !== 'qq-group-manager');
|
|
1074
|
+
const installed = subPlugins.filter((item) => item.installed);
|
|
1075
|
+
const missing = subPlugins.filter((item) => !item.installed);
|
|
1076
|
+
const button = (item) => `<button class="config-plugin ${item.package === activePlugin ? 'active' : ''}" data-package="${escHtml(item.package)}">
|
|
1077
|
+
${pluginIcon(item)}
|
|
1078
|
+
<div><b>${escHtml(item.id)}</b><small>${escHtml(item.title)} · ${item.installed ? (item.configured ? '已启用' : '未启用') : '未安装'}</small></div>
|
|
1079
|
+
</button>`;
|
|
1080
|
+
if (nav) {
|
|
1081
|
+
nav.innerHTML = '<div class="config-group-label">已安装</div>'
|
|
1082
|
+
+ (installed.map(button).join('') || '<div class="schema-loading">没有已安装的附属插件</div>')
|
|
1083
|
+
+ '<div class="config-group-label">未安装</div>'
|
|
1084
|
+
+ (missing.map(button).join('') || '<div class="schema-loading">全部已安装</div>');
|
|
1085
|
+
$$('#pluginConfigNav [data-package]').forEach((btn) => btn.addEventListener('click', () => openPluginConfig(btn.dataset.package)));
|
|
1086
|
+
}
|
|
1087
|
+
if (!activePlugin) {
|
|
1088
|
+
const first = installed[0] || data.plugins[0];
|
|
1089
|
+
if (first) openPluginConfig(first.package);
|
|
1090
|
+
}
|
|
1091
|
+
} catch (error) {
|
|
1092
|
+
if (nav) nav.innerHTML = `<div class="schema-loading">读取失败:${escHtml(error.message || error)}</div>`;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
const fieldRegistry = new Map();
|
|
1097
|
+
let fieldSeq = 0;
|
|
1098
|
+
|
|
1099
|
+
function registerField(field) {
|
|
1100
|
+
fieldSeq += 1;
|
|
1101
|
+
const id = `f${fieldSeq}`;
|
|
1102
|
+
fieldRegistry.set(id, field);
|
|
1103
|
+
return id;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
function listEditorHtml(field, value) {
|
|
1107
|
+
const values = Array.isArray(value) ? value : [];
|
|
1108
|
+
const rows = values.length
|
|
1109
|
+
? values.map((item) => {
|
|
1110
|
+
const [text, score] = splitScored(item);
|
|
1111
|
+
return listRowHtml(field.scored, text, score);
|
|
1112
|
+
}).join('')
|
|
1113
|
+
: listRowHtml(field.scored);
|
|
1114
|
+
return `<div class="list-editor" data-list-key="${field.key}" data-field-id="${registerField(field)}" data-list-scored="${field.scored ? '1' : '0'}">
|
|
1115
|
+
<div class="list-rows">${rows}</div>
|
|
1116
|
+
<button type="button" class="link-btn add-row" data-add-row>+ 添加一行</button>
|
|
1117
|
+
</div>`;
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function objectControlHtml(field, value) {
|
|
1121
|
+
const current = value == null ? (field.default ?? '') : value;
|
|
1122
|
+
if (field.type === 'boolean') {
|
|
1123
|
+
return `<label class="switch mini"><input type="checkbox" ${current ? 'checked' : ''} /><i></i><span>${current ? '开启' : '关闭'}</span></label>`;
|
|
1124
|
+
}
|
|
1125
|
+
if (field.type === 'union') {
|
|
1126
|
+
const options = (field.options || []).slice();
|
|
1127
|
+
if (current !== '' && !options.includes(String(current))) options.unshift(String(current));
|
|
1128
|
+
const empty = field.required ? '' : (current === '' ? '<option value="" selected>(留空)</option>' : '<option value="">(留空)</option>');
|
|
1129
|
+
return `<select>${empty}${options.map((opt) => `<option ${String(current) === String(opt) ? 'selected' : ''}>${escHtml(opt)}</option>`).join('')}</select>`;
|
|
1130
|
+
}
|
|
1131
|
+
if (field.type === 'number') {
|
|
1132
|
+
return `<input type="number" value="${current === '' ? '' : escHtml(current)}" />`;
|
|
1133
|
+
}
|
|
1134
|
+
if (field.list) return listEditorHtml(field, current);
|
|
1135
|
+
if (field.objectList) return objectListHtml(field, current);
|
|
1136
|
+
if (field.long) return `<textarea rows="4">${escHtml(current)}</textarea>`;
|
|
1137
|
+
return `<input type="text" value="${escHtml(current)}" />`;
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function objectRowHtml(field, item) {
|
|
1141
|
+
const data = item || {};
|
|
1142
|
+
const compact = field.itemFields.length <= 2
|
|
1143
|
+
&& field.itemFields.every((sub) => !sub.objectList && !(sub.objectFields && sub.objectFields.length));
|
|
1144
|
+
if (compact) {
|
|
1145
|
+
return `<div class="kv-row" data-object-row>
|
|
1146
|
+
${field.itemFields.map((sub) => `<label class="kv-cell" data-obj-field="${sub.key}"><span>${escHtml(sub.label || sub.key)}</span>${objectControlHtml(sub, data[sub.key])}</label>`).join('')}
|
|
1147
|
+
<button type="button" class="row-btn" data-remove-object title="删除">−</button>
|
|
1148
|
+
</div>`;
|
|
1149
|
+
}
|
|
1150
|
+
const titleField = field.itemFields[0];
|
|
1151
|
+
const rest = field.itemFields.slice(1);
|
|
1152
|
+
return `<article class="object-card" data-object-row>
|
|
1153
|
+
<div class="object-card-head">
|
|
1154
|
+
<input class="object-card-title" data-object-title value="${escHtml(data[titleField.key] ?? titleField.default ?? '')}" placeholder="${escHtml(titleField.label || titleField.key)}" />
|
|
1155
|
+
<button type="button" class="row-btn" data-toggle-object title="展开/收起">▸</button>
|
|
1156
|
+
<button type="button" class="row-btn" data-remove-object title="删除">×</button>
|
|
1157
|
+
</div>
|
|
1158
|
+
<div class="object-card-body" hidden>
|
|
1159
|
+
${rest.map((sub) => `<div class="obj-field ${sub.long || sub.list || sub.objectList ? 'block' : ''}" data-obj-field="${sub.key}">
|
|
1160
|
+
<span>${escHtml(sub.label || sub.key)}</span>
|
|
1161
|
+
<div class="obj-control">${objectControlHtml(sub, data[sub.key])}</div>
|
|
1162
|
+
</div>`).join('')}
|
|
1163
|
+
</div>
|
|
1164
|
+
</article>`;
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
function objectListHtml(field, value) {
|
|
1168
|
+
const items = Array.isArray(value) ? value : [];
|
|
1169
|
+
const rows = items.length ? items.map((item) => objectRowHtml(field, item)).join('') : objectRowHtml(field, {});
|
|
1170
|
+
return `<div class="object-list" data-object-key="${field.key}" data-field-id="${registerField(field)}">
|
|
1171
|
+
<div class="object-rows">${rows}</div>
|
|
1172
|
+
<button type="button" class="link-btn add-row" data-add-object>+ 添加${escHtml(field.label || '一条')}</button>
|
|
1173
|
+
</div>`;
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
function fieldControl(field, value) {
|
|
1177
|
+
const current = value == null ? (field.value ?? field.default ?? '') : value;
|
|
1178
|
+
if (field.type === 'boolean') {
|
|
1179
|
+
return `<label class="switch"><input type="checkbox" data-key="${field.key}" data-kind="boolean" ${current ? 'checked' : ''} /><i></i><span>${current ? '已开启' : '已关闭'}</span></label>`;
|
|
1180
|
+
}
|
|
1181
|
+
if (field.type === 'union') {
|
|
1182
|
+
const options = (field.options || []).slice();
|
|
1183
|
+
if (current !== '' && !options.includes(String(current))) options.unshift(String(current));
|
|
1184
|
+
if (!options.length) options.push(String(current));
|
|
1185
|
+
return `<select data-key="${field.key}" data-kind="string">${options.map((opt) => `<option ${String(current) === String(opt) ? 'selected' : ''}>${escHtml(opt)}</option>`).join('')}</select>`;
|
|
1186
|
+
}
|
|
1187
|
+
if (field.type === 'number') {
|
|
1188
|
+
return `<input type="number" data-key="${field.key}" data-kind="number" value="${escHtml(current ?? field.default ?? 0)}" />`;
|
|
1189
|
+
}
|
|
1190
|
+
if (field.list) return listEditorHtml(field, current);
|
|
1191
|
+
if (field.objectList) return objectListHtml(field, current);
|
|
1192
|
+
if (field.objectFields?.length) {
|
|
1193
|
+
return `<div class="object-fields" data-object-fields="${field.key}" data-field-id="${registerField(field)}">${field.objectFields.map((sub) => `<div class="obj-field ${sub.long ? 'block' : ''}" data-obj-field="${sub.key}"><span>${escHtml(sub.label || sub.key)}</span><div class="obj-control">${objectControlHtml(sub, current?.[sub.key])}</div></div>`).join('')}</div>`;
|
|
1194
|
+
}
|
|
1195
|
+
if (field.json) {
|
|
1196
|
+
const val = field.type === 'array' && !Array.isArray(current) ? [] : (current || (field.type === 'array' ? [] : {}));
|
|
1197
|
+
return `<textarea rows="4" class="json-input" data-key="${field.key}" data-kind="json">${escHtml(JSON.stringify(val, null, 2))}</textarea>`;
|
|
1198
|
+
}
|
|
1199
|
+
if (field.sensitive) {
|
|
1200
|
+
return `<div class="secret-field">
|
|
1201
|
+
<input type="password" data-key="${field.key}" data-kind="string" value="${escHtml(current ?? field.default ?? '')}" autocomplete="off" />
|
|
1202
|
+
<button type="button" class="eye-btn" data-eye title="显示/隐藏" aria-label="显示或隐藏">${EYE_ICON}</button>
|
|
1203
|
+
</div>`;
|
|
1204
|
+
}
|
|
1205
|
+
if (field.long) {
|
|
1206
|
+
return `<textarea rows="8" data-key="${field.key}" data-kind="string">${escHtml(current ?? field.default ?? '')}</textarea>`;
|
|
1207
|
+
}
|
|
1208
|
+
return `<input type="text" data-key="${field.key}" data-kind="string" value="${escHtml(current ?? field.default ?? '')}" />`;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
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>';
|
|
1212
|
+
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>';
|
|
1213
|
+
|
|
1214
|
+
function groupFields(fields) {
|
|
1215
|
+
const groups = new Map();
|
|
1216
|
+
for (const field of fields) {
|
|
1217
|
+
const key = field.group || '插件配置';
|
|
1218
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
1219
|
+
groups.get(key).push(field);
|
|
1220
|
+
}
|
|
1221
|
+
return [...groups.entries()];
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
async function openPluginConfig(pkg) {
|
|
1225
|
+
activePlugin = pkg;
|
|
1226
|
+
$$('#pluginConfigNav [data-package]').forEach((btn) => btn.classList.toggle('active', btn.dataset.package === pkg));
|
|
1227
|
+
const form = $('#pluginConfigForm');
|
|
1228
|
+
if (!form) return;
|
|
1229
|
+
form.innerHTML = '<div class="schema-loading">读取插件配置…</div>';
|
|
1230
|
+
let info;
|
|
1231
|
+
try {
|
|
1232
|
+
info = await apiGet(`api/config/plugin?name=${encodeURIComponent(pkg)}`);
|
|
1233
|
+
} catch (error) {
|
|
1234
|
+
form.innerHTML = `<div class="schema-loading">读取失败:${escHtml(error.message || error)}</div>`;
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
if (!info.installed) {
|
|
1238
|
+
const npm = `https://www.npmjs.com/package/${pkg}`;
|
|
1239
|
+
form.innerHTML = `<div class="empty-install">
|
|
1240
|
+
<div class="empty-icon">+</div>
|
|
1241
|
+
<h2>${escHtml(info.title || pkg)} 未安装</h2>
|
|
1242
|
+
<p>${escHtml(pkg)}</p>
|
|
1243
|
+
<div class="install-actions"><button class="btn primary" data-install="${escHtml(pkg)}">一键安装</button>
|
|
1244
|
+
<a class="btn ghost" href="${escHtml(npm)}" target="_blank" rel="noreferrer">npm</a></div>
|
|
1245
|
+
<code class="install-code">npm i ${escHtml(pkg)}</code>
|
|
1246
|
+
</div>`;
|
|
1247
|
+
form.querySelector('[data-install]')?.addEventListener('click', (event) => installPackage(event.target.dataset.install));
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
const badges = `<span class="status ${info.configured ? 'ok' : 'warn'}">${info.configured ? '已启用' : '未启用'}</span>`;
|
|
1251
|
+
fieldRegistry.clear();
|
|
1252
|
+
fieldSeq = 0;
|
|
1253
|
+
const fieldHtml = groupFields(info.fields).map(([group, fields]) => `<div class="form-section"><h3>${escHtml(group)}</h3>`
|
|
1254
|
+
+ fields.map((field) => {
|
|
1255
|
+
const wide = field.long || field.list || field.objectList;
|
|
1256
|
+
return `<div class="schema-field ${wide ? 'long' : ''}">
|
|
1257
|
+
<div class="schema-field-info">
|
|
1258
|
+
<div class="schema-field-title">${escHtml(field.label || field.key)}</div>
|
|
1259
|
+
${field.description ? `<p class="schema-field-desc">${escHtml(field.description)}</p>` : ''}
|
|
1260
|
+
<code class="schema-field-key">${escHtml(field.key)}${field.foreign ? ' · 主插件' : ''}</code>
|
|
1261
|
+
</div>
|
|
1262
|
+
<div class="schema-field-control" data-plugin-field="${field.key}" data-field-id="${registerField(field)}">${fieldControl(field, info.values[field.key])}</div>
|
|
1263
|
+
</div>`;
|
|
1264
|
+
}).join('')
|
|
1265
|
+
+ '</div>').join('');
|
|
1266
|
+
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>`
|
|
1267
|
+
+ (pkg === '@nestim/koishi-plugin-qqgm-memory' ? '<div class="sync-note" id="memorySyncNote">记忆后端状态读取中…</div>' : '')
|
|
1268
|
+
+ fieldHtml
|
|
1269
|
+
+ `<div class="form-foot"><span>保存前会备份 koishi.yml;带「主插件」标记的字段写到主插件配置块</span><div><button class="btn primary" id="savePluginConfig">保存</button></div></div>`;
|
|
1270
|
+
form.querySelector('#savePluginConfig')?.addEventListener('click', () => savePluginConfig(info));
|
|
1271
|
+
form.querySelectorAll('[data-eye]').forEach((btn) => btn.addEventListener('click', () => {
|
|
1272
|
+
const input = btn.parentElement?.querySelector('input');
|
|
1273
|
+
if (!input) return;
|
|
1274
|
+
const show = input.type === 'password';
|
|
1275
|
+
input.type = show ? 'text' : 'password';
|
|
1276
|
+
btn.innerHTML = show ? EYE_OFF_ICON : EYE_ICON;
|
|
1277
|
+
}));
|
|
1278
|
+
form.onclick = (event) => {
|
|
1279
|
+
const addRow = event.target.closest('[data-add-row]');
|
|
1280
|
+
if (addRow) {
|
|
1281
|
+
const editor = addRow.closest('.list-editor');
|
|
1282
|
+
const field = fieldRegistry.get(editor?.dataset.fieldId);
|
|
1283
|
+
if (editor && field) editor.querySelector('.list-rows').insertAdjacentHTML('beforeend', listRowHtml(field.scored));
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
const removeRow = event.target.closest('[data-remove-row]');
|
|
1287
|
+
if (removeRow) {
|
|
1288
|
+
const editor = removeRow.closest('.list-editor');
|
|
1289
|
+
removeRow.closest('.list-row')?.remove();
|
|
1290
|
+
if (editor && !editor.querySelector('.list-row')) {
|
|
1291
|
+
const field = fieldRegistry.get(editor.dataset.fieldId);
|
|
1292
|
+
editor.querySelector('.list-rows').innerHTML = listRowHtml(field ? field.scored : false);
|
|
1293
|
+
}
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
const addObject = event.target.closest('[data-add-object]');
|
|
1297
|
+
if (addObject) {
|
|
1298
|
+
const list = addObject.closest('[data-object-key]');
|
|
1299
|
+
const field = fieldRegistry.get(list?.dataset.fieldId);
|
|
1300
|
+
if (list && field) list.querySelector(':scope > .object-rows').insertAdjacentHTML('beforeend', objectRowHtml(field, {}));
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
const removeObject = event.target.closest('[data-remove-object]');
|
|
1304
|
+
if (removeObject) {
|
|
1305
|
+
removeObject.closest('[data-object-row]')?.remove();
|
|
1306
|
+
return;
|
|
1307
|
+
}
|
|
1308
|
+
const toggleObject = event.target.closest('[data-toggle-object]');
|
|
1309
|
+
if (toggleObject) {
|
|
1310
|
+
const body = toggleObject.closest('.object-card')?.querySelector('.object-card-body');
|
|
1311
|
+
if (!body) return;
|
|
1312
|
+
body.hidden = !body.hidden;
|
|
1313
|
+
toggleObject.textContent = body.hidden ? '▸' : '▾';
|
|
1314
|
+
}
|
|
1315
|
+
};
|
|
1316
|
+
form.onchange = (event) => {
|
|
1317
|
+
if (event.target.matches('.switch input')) {
|
|
1318
|
+
const text = event.target.parentElement?.querySelector('span');
|
|
1319
|
+
if (text) text.textContent = event.target.checked ? '已开启' : '已关闭';
|
|
1320
|
+
}
|
|
1321
|
+
};
|
|
1322
|
+
if (pkg === '@nestim/koishi-plugin-qqgm-memory') updateMemorySyncNote();
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
async function updateMemorySyncNote() {
|
|
1326
|
+
const note = $('#memorySyncNote');
|
|
1327
|
+
if (!note) return;
|
|
1328
|
+
try {
|
|
1329
|
+
const data = await apiGet('api/memory');
|
|
1330
|
+
const backend = data.backend === 'sqlite' ? 'SQLite' : 'MD';
|
|
1331
|
+
note.innerHTML = `主插件当前后端:<b>${backend}</b> · SQLite 里 ${data.sqliteTotal || 0} 条 · MD 识别 ${data.md?.total || 0} 条。`
|
|
1332
|
+
+ (data.backend === 'sqlite' ? ' 当前由 SQLite 提供数据。' : ' 切到 SQLite 前先迁移并备份 MD。');
|
|
1333
|
+
note.classList.toggle('ok', data.backend === 'sqlite');
|
|
1334
|
+
} catch {
|
|
1335
|
+
note.textContent = '记忆后端状态读取失败';
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
function collectSimpleValue(container, field) {
|
|
1340
|
+
if (!container) return undefined;
|
|
1341
|
+
if (field.type === 'boolean') {
|
|
1342
|
+
const checkbox = container.querySelector('input[type="checkbox"]');
|
|
1343
|
+
return checkbox ? !!checkbox.checked : undefined;
|
|
1344
|
+
}
|
|
1345
|
+
const input = container.querySelector('input, select, textarea');
|
|
1346
|
+
if (!input) return undefined;
|
|
1347
|
+
if (field.type === 'number') return input.value === '' ? undefined : Number(input.value);
|
|
1348
|
+
if (field.json) {
|
|
1349
|
+
try { return JSON.parse(input.value); }
|
|
1350
|
+
catch { throw new Error(`${field.label || field.key} 的 JSON 格式不对`); }
|
|
1351
|
+
}
|
|
1352
|
+
return input.value;
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
function collectObjectList(container, field) {
|
|
1356
|
+
if (!container) return [];
|
|
1357
|
+
const rows = [...container.querySelectorAll(':scope > .object-rows > [data-object-row]')];
|
|
1358
|
+
const result = [];
|
|
1359
|
+
for (const row of rows) {
|
|
1360
|
+
const item = {};
|
|
1361
|
+
const isCompact = row.classList.contains('kv-row');
|
|
1362
|
+
if (!isCompact && field.itemFields[0]) {
|
|
1363
|
+
const title = row.querySelector('.object-card-title');
|
|
1364
|
+
if (title) item[field.itemFields[0].key] = title.value;
|
|
1365
|
+
}
|
|
1366
|
+
const cells = isCompact
|
|
1367
|
+
? [...row.querySelectorAll(':scope > [data-obj-field]')]
|
|
1368
|
+
: [...row.querySelectorAll(':scope > .object-card-body > [data-obj-field]')];
|
|
1369
|
+
for (const cell of cells) {
|
|
1370
|
+
const sub = field.itemFields.find((entry) => entry.key === cell.dataset.objField);
|
|
1371
|
+
if (!sub) continue;
|
|
1372
|
+
let value;
|
|
1373
|
+
if (sub.list) value = collectList(cell.querySelector('[data-list-key]'), sub);
|
|
1374
|
+
else if (sub.objectList) value = collectObjectList(cell.querySelector('[data-object-key]'), sub);
|
|
1375
|
+
else value = collectSimpleValue(cell, sub);
|
|
1376
|
+
if (value !== undefined) item[sub.key] = value;
|
|
1377
|
+
}
|
|
1378
|
+
if (Object.keys(item).length) result.push(item);
|
|
1379
|
+
}
|
|
1380
|
+
return result;
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function collectObjectFields(container, field) {
|
|
1384
|
+
const item = {};
|
|
1385
|
+
for (const sub of field.objectFields || []) {
|
|
1386
|
+
const cell = container.querySelector(`:scope > [data-obj-field="${sub.key}"]`);
|
|
1387
|
+
if (!cell) continue;
|
|
1388
|
+
let value;
|
|
1389
|
+
if (sub.list) value = collectList(cell.querySelector('[data-list-key]'), sub);
|
|
1390
|
+
else if (sub.objectList) value = collectObjectList(cell.querySelector('[data-object-key]'), sub);
|
|
1391
|
+
else value = collectSimpleValue(cell, sub);
|
|
1392
|
+
if (value !== undefined) item[sub.key] = value;
|
|
1393
|
+
}
|
|
1394
|
+
return item;
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
function collectPluginValues(form, info) {
|
|
1398
|
+
const values = {};
|
|
1399
|
+
for (const field of info.fields) {
|
|
1400
|
+
const cell = form.querySelector(`[data-plugin-field="${field.key}"]`);
|
|
1401
|
+
if (!cell) continue;
|
|
1402
|
+
let value;
|
|
1403
|
+
if (field.list) value = collectList(cell.querySelector('[data-list-key]'), field);
|
|
1404
|
+
else if (field.objectList) value = collectObjectList(cell.querySelector('[data-object-key]'), field);
|
|
1405
|
+
else if (field.objectFields?.length) value = collectObjectFields(cell, field);
|
|
1406
|
+
else value = collectSimpleValue(cell, field);
|
|
1407
|
+
if (value !== undefined) values[field.key] = value;
|
|
1408
|
+
}
|
|
1409
|
+
return values;
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
async function savePluginConfig(info) {
|
|
1413
|
+
const form = $('#pluginConfigForm');
|
|
1414
|
+
let values;
|
|
1415
|
+
try {
|
|
1416
|
+
values = collectPluginValues(form, info);
|
|
1417
|
+
} catch (error) {
|
|
1418
|
+
showToast(String(error.message || error));
|
|
1419
|
+
return;
|
|
1420
|
+
}
|
|
1421
|
+
try {
|
|
1422
|
+
const data = await apiPost('api/config/plugin', { name: info.name, values });
|
|
1423
|
+
showToast(`已保存 ${data.keys.length} 项,重启 Koishi 后生效`);
|
|
1424
|
+
if (info.name === '@nestim/koishi-plugin-qqgm-memory') {
|
|
1425
|
+
updateMemorySyncNote();
|
|
1426
|
+
initMemoryData();
|
|
1427
|
+
}
|
|
1428
|
+
if (info.name === '@nestim/koishi-plugin-qqgm-webui' && Object.prototype.hasOwnProperty.call(values, 'token')) {
|
|
1429
|
+
showToast('令牌已保存:重启后请用新令牌访问当前地址');
|
|
1430
|
+
}
|
|
1431
|
+
refreshStatus();
|
|
1432
|
+
} catch (error) {
|
|
1433
|
+
showToast(`保存失败:${String(error.message || error)}`);
|
|
1434
|
+
}
|
|
630
1435
|
}
|
|
631
1436
|
|
|
632
|
-
//
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
1437
|
+
// ---------------------------------------------------------------- 日志
|
|
1438
|
+
|
|
1439
|
+
const logState = { paused: false, level: 'all', lines: [], timer: null };
|
|
1440
|
+
|
|
1441
|
+
function levelClass(level) {
|
|
1442
|
+
const value = String(level || '').toLowerCase();
|
|
1443
|
+
if (value === 'warn') return 'warn';
|
|
1444
|
+
if (value === 'error') return 'error';
|
|
1445
|
+
if (value === 'success') return 'success';
|
|
1446
|
+
if (value === 'debug') return 'debug';
|
|
1447
|
+
return 'info';
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function renderLogs() {
|
|
1451
|
+
const view = $('#logView');
|
|
1452
|
+
const meta = $('#logMeta');
|
|
1453
|
+
if (!view) return;
|
|
1454
|
+
const q = ($('#logSearch')?.value || '').trim().toLowerCase();
|
|
1455
|
+
const filtered = logState.lines.filter((line) => {
|
|
1456
|
+
if (logState.level !== 'all' && line.level !== logState.level) return false;
|
|
1457
|
+
if (q && !`${line.name} ${line.text}`.toLowerCase().includes(q)) return false;
|
|
1458
|
+
return true;
|
|
640
1459
|
});
|
|
1460
|
+
if (!filtered.length) {
|
|
1461
|
+
view.innerHTML = '<div class="log-empty">没有匹配的日志</div>';
|
|
1462
|
+
} else {
|
|
1463
|
+
const nearBottom = view.scrollHeight - view.scrollTop - view.clientHeight < 40;
|
|
1464
|
+
view.innerHTML = filtered.map((line) => `<div class="log-line">
|
|
1465
|
+
<time>${new Date(line.time).toLocaleTimeString('zh-CN', { hour12: false })}.${String(line.time % 1000).padStart(3, '0')}</time>
|
|
1466
|
+
<span class="lvl ${levelClass(line.level)}">${escHtml(String(line.level || 'info').toUpperCase())}</span>
|
|
1467
|
+
<span class="src">${escHtml(line.name || '-')}</span>
|
|
1468
|
+
<p>${escHtml(line.text || '')}</p>
|
|
1469
|
+
</div>`).join('');
|
|
1470
|
+
if (nearBottom) view.scrollTop = view.scrollHeight;
|
|
1471
|
+
}
|
|
1472
|
+
if (meta) {
|
|
1473
|
+
meta.textContent = `${filtered.length} / ${logState.lines.length} 条 · ${logState.paused ? '已暂停' : '自动刷新'}`;
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
function renderLogPause() {
|
|
1478
|
+
const btn = $('#logPause');
|
|
1479
|
+
if (btn) btn.textContent = logState.paused ? '继续' : '暂停';
|
|
641
1480
|
}
|
|
642
|
-
|
|
643
|
-
|
|
1481
|
+
|
|
1482
|
+
async function loadLogs(force = false) {
|
|
1483
|
+
if (!force && (logState.paused || !document.querySelector('#page-logs.active'))) return;
|
|
1484
|
+
try {
|
|
1485
|
+
const data = await apiGet('api/logs?lines=400');
|
|
1486
|
+
logState.lines = data.lines || [];
|
|
1487
|
+
renderLogs();
|
|
1488
|
+
} catch {
|
|
1489
|
+
const meta = $('#logMeta');
|
|
1490
|
+
if (meta) meta.textContent = '日志接口不可用';
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
$('#logChips')?.addEventListener('click', (event) => {
|
|
1495
|
+
const chip = event.target.closest('.chip');
|
|
1496
|
+
if (!chip) return;
|
|
1497
|
+
$$('#logChips .chip').forEach((item) => item.classList.remove('active'));
|
|
644
1498
|
chip.classList.add('active');
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
line.style.display = level === '全部' || lvl === level ? '' : 'none';
|
|
649
|
-
});
|
|
650
|
-
}));
|
|
1499
|
+
logState.level = chip.dataset.level || 'all';
|
|
1500
|
+
renderLogs();
|
|
1501
|
+
});
|
|
651
1502
|
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
1503
|
+
$('#logPause')?.addEventListener('click', () => {
|
|
1504
|
+
logState.paused = !logState.paused;
|
|
1505
|
+
renderLogPause();
|
|
1506
|
+
if (!logState.paused) loadLogs(true);
|
|
1507
|
+
else renderLogs();
|
|
1508
|
+
});
|
|
1509
|
+
|
|
1510
|
+
$('#logSearch')?.addEventListener('input', () => renderLogs());
|
|
657
1511
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
1512
|
+
setInterval(() => {
|
|
1513
|
+
if (!document.hidden && document.querySelector('#page-logs.active') && !logState.paused) loadLogs(true);
|
|
1514
|
+
}, 3000);
|
|
1515
|
+
|
|
1516
|
+
// ---------------------------------------------------------------- 记忆库搜索与其它
|
|
1517
|
+
|
|
1518
|
+
const memorySearch = $('#memorySearch');
|
|
1519
|
+
let memorySearchTimer = null;
|
|
1520
|
+
if (memorySearch) {
|
|
1521
|
+
memorySearch.addEventListener('input', () => {
|
|
1522
|
+
clearTimeout(memorySearchTimer);
|
|
1523
|
+
memorySearchTimer = setTimeout(() => {
|
|
1524
|
+
memoryQuery.q = memorySearch.value.trim();
|
|
1525
|
+
loadMemory(true);
|
|
1526
|
+
}, 300);
|
|
670
1527
|
});
|
|
671
1528
|
}
|
|
672
1529
|
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
1530
|
+
$('#memoryBackend')?.addEventListener('click', () => showToast('可在「附属配置 → qqgm-memory」里切换主插件后端'));
|
|
1531
|
+
|
|
1532
|
+
$('#refreshData')?.addEventListener('click', () => location.reload());
|
|
1533
|
+
|
|
1534
|
+
$('#exportSnapshot')?.addEventListener('click', async () => {
|
|
1535
|
+
try {
|
|
1536
|
+
const data = await apiGet('api/overview');
|
|
1537
|
+
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
|
|
1538
|
+
const a = document.createElement('a');
|
|
1539
|
+
a.href = URL.createObjectURL(blob);
|
|
1540
|
+
a.download = `qqgm-overview-${Date.now()}.json`;
|
|
1541
|
+
a.click();
|
|
1542
|
+
URL.revokeObjectURL(a.href);
|
|
1543
|
+
} catch (error) {
|
|
1544
|
+
showToast(`导出失败:${String(error.message || error)}`);
|
|
1545
|
+
}
|
|
1546
|
+
});
|
|
1547
|
+
|
|
1548
|
+
$('#refreshOverview')?.addEventListener('click', () => {
|
|
1549
|
+
initOverview();
|
|
1550
|
+
refreshStatus();
|
|
1551
|
+
loadTrend(Number($('#trendRange')?.value) || 7);
|
|
1552
|
+
showToast('已刷新');
|
|
1553
|
+
});
|
|
1554
|
+
|
|
1555
|
+
// ---------------------------------------------------------------- 启动
|
|
1556
|
+
|
|
1557
|
+
initOverview().then(() => loadTrend(Number($('#trendRange')?.value) || 7));
|
|
1558
|
+
initMemoryData();
|
|
1559
|
+
initMainSchema();
|
|
1560
|
+
initPluginConfig();
|
|
1561
|
+
loadLogs();
|