@mcviseron/dsh-qq-bridge 0.2.1 → 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/lib/client.js CHANGED
@@ -12,6 +12,8 @@ window.__ModuleLoader__.load({
12
12
  const React = require("react")
13
13
  const h = React.createElement
14
14
  const PANEL = "http://127.0.0.1:39062"
15
+ // 安装器在宿主插件里(Node 侧),不在机器人面板
16
+ const BRIDGE = "http://127.0.0.1:39061"
15
17
 
16
18
  const T = {
17
19
  page: { width: "100%", height: "100%", minHeight: 0, overflow: "auto", boxSizing: "border-box", padding: "24px clamp(16px,4vw,48px) 32px", color: "var(--dsw-alias-label-primary)", fontFamily: "var(--dsw-font-family, inherit)" },
@@ -30,9 +32,47 @@ window.__ModuleLoader__.load({
30
32
  labelBox: { display: "grid", gap: 2, minWidth: 0 },
31
33
  title: { fontSize: 13, color: "var(--dsw-alias-label-primary)" },
32
34
  hint: { fontSize: 12, color: "var(--dsw-alias-label-tertiary)" },
35
+ tabs: { display: "flex", gap: 8, marginBottom: 4 },
36
+ tab: { padding: "6px 14px", borderRadius: 999, border: "1px solid var(--dsw-alias-border-l2)", background: "transparent", color: "var(--dsw-alias-label-secondary)", fontSize: 13, cursor: "pointer" },
37
+ tabActive: { background: "var(--dsw-alias-label-primary)", borderColor: "var(--dsw-alias-label-primary)", color: "var(--dsw-alias-bg-layer-3)" },
38
+ grid: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(220px, 1fr))", gap: 12 },
39
+ kpiRow: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 12 },
40
+ kpi: { display: "grid", gap: 4, padding: "14px 16px", borderRadius: 12, border: "1px solid var(--dsw-alias-border-l2)", background: "var(--dsw-alias-bg-layer-1, rgba(255,255,255,0.04))" },
41
+ kpiLabel: { fontSize: 12, color: "var(--dsw-alias-label-tertiary)" },
42
+ kpiValue: { fontSize: 26, fontWeight: 650, letterSpacing: "-0.02em", color: "var(--dsw-alias-label-primary)", fontVariantNumeric: "tabular-nums" },
43
+ cardHead: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 6 },
44
+ legend: { display: "flex", gap: 10, flexWrap: "wrap" },
45
+ legendItem: { display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, color: "var(--dsw-alias-label-tertiary)" },
46
+ legendDot: { width: 8, height: 8, borderRadius: 999, display: "inline-block" },
47
+ ringBox: { display: "grid", justifyItems: "center", gap: 4 },
48
+ ringLabel: { fontSize: 13, fontWeight: 600, color: "var(--dsw-alias-label-primary)" },
49
+ barRow: { display: "grid", gridTemplateColumns: "minmax(64px,auto) 1fr 34px", alignItems: "center", gap: 8, fontSize: 12, whiteSpace: "nowrap" },
50
+ barLabel: { color: "var(--dsw-alias-label-tertiary)" },
51
+ barTrack: { height: 8, borderRadius: 999, background: "var(--dsw-alias-border-l2, rgba(255,255,255,0.12))", overflow: "hidden" },
52
+ barFill: { height: "100%", borderRadius: 999 },
53
+ barValue: { textAlign: "right", color: "var(--dsw-alias-label-secondary)", fontVariantNumeric: "tabular-nums" },
54
+ eventRow: { display: "grid", gridTemplateColumns: "42px 62px 1fr", gap: 8, fontSize: 12, lineHeight: 1.5 },
55
+ eventTime: { color: "var(--dsw-alias-label-tertiary)", fontVariantNumeric: "tabular-nums" },
56
+ eventKind: { color: "var(--dsw-alias-state-business-primary, #2f6bff)" },
57
+ eventText: { color: "var(--dsw-alias-label-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
58
+ footNote: { fontSize: 11, color: "var(--dsw-alias-label-tertiary)" },
59
+ memberRow: { display: "grid", gridTemplateColumns: "24px 1fr auto", alignItems: "center", gap: 8, fontSize: 12 },
60
+ memberAvatar: { width: 24, height: 24, borderRadius: 999, objectFit: "cover", display: "inline-block" },
61
+ memberName: { color: "var(--dsw-alias-label-secondary)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
62
+ memberTail: { color: "var(--dsw-alias-label-tertiary)", fontVariantNumeric: "tabular-nums" },
63
+ memberList: { maxHeight: 172, overflowY: "scroll", display: "flex", flexDirection: "column", gap: 6, paddingRight: 4 },
64
+ eventList: { maxHeight: 200, overflowY: "scroll", display: "flex", flexDirection: "column", gap: 4, paddingRight: 4 },
65
+ chipRow: { display: "flex", flexWrap: "wrap", gap: 6 },
66
+ chip: { padding: "2px 8px", borderRadius: 999, border: "1px solid var(--dsw-alias-border-l2)", fontSize: 11, color: "var(--dsw-alias-label-secondary)" },
67
+ card: { display: "grid", gap: 8, padding: "14px 16px", borderRadius: 12, border: "1px solid var(--dsw-alias-border-l2)", background: "var(--dsw-alias-bg-layer-1, rgba(255,255,255,0.04))" },
68
+ cardTitle: { fontSize: 13, fontWeight: 600, color: "var(--dsw-alias-label-primary)" },
69
+ cardRow: { display: "flex", justifyContent: "space-between", gap: 10, fontSize: 12 },
70
+ cardKey: { color: "var(--dsw-alias-label-tertiary)" },
71
+ cardValue: { color: "var(--dsw-alias-label-secondary)", fontVariantNumeric: "tabular-nums" },
33
72
  sectionTitle: { fontSize: 12, letterSpacing: "0.04em", color: "var(--dsw-alias-label-tertiary)", margin: "10px 0 2px" },
34
73
  input: { width: 132, padding: "5px 8px", border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 6, background: "var(--dsw-alias-bg-layer-3)", color: "var(--dsw-alias-label-primary)", font: "inherit", textAlign: "right" },
35
74
  inputWide: { width: 260, textAlign: "left" },
75
+ textarea: { width: "100%", minHeight: 120, padding: "8px 10px", border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 6, background: "var(--dsw-alias-bg-layer-3)", color: "var(--dsw-alias-label-primary)", font: "inherit", lineHeight: 1.6, resize: "vertical", boxSizing: "border-box", textAlign: "left" },
36
76
  btn: { padding: "6px 14px", border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 6, background: "transparent", color: "var(--dsw-alias-label-primary)", font: "inherit", cursor: "pointer" },
37
77
  btnPrimary: { background: "var(--dsw-alias-label-primary)", borderColor: "var(--dsw-alias-label-primary)", color: "var(--dsw-alias-bg-layer-3)" },
38
78
  actions: { display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" },
@@ -87,9 +127,13 @@ window.__ModuleLoader__.load({
87
127
  capture_enabled: ["允许截屏", "/截图、/窗口 是否可用"],
88
128
  auto_group: ["自动分组(每个会话独立工作区)", "关闭则所有会话共用同一个工作目录"],
89
129
  approval_inline_redraw: ["审批按钮就地重绘为“已允许”", "关闭后退回旧行为:额外发一条结论文字 + “已处理”卡片"],
130
+ kick_confirm: ["踢人二次审批", "开启后踢人前先在你的私聊弹一张确认卡片,点了才执行"],
131
+ interject_hook_only: ["插话只要命中钩子才判断", "开启后只有被点名/带问号/提到别名/长时间冷场才花一次判断;关闭则每攒够几条就判一次"],
132
+ judge_score_output: ["判断用打分制", "让模型先给 0~3 分的开口意愿,再按阈值决定发不发"],
133
+ persona_enabled: ["启用人设", "只在新会话的第一条消息里发一次;会话已有历史就不再重复"],
90
134
  }
91
135
 
92
- const SWITCHES = ["enabled","c2c_enabled","group_enabled","group_full_mode","group_at_only","md_auto","stream_enabled","ack_enabled","quote_enabled","capture_enabled","auto_group","approval_inline_redraw"]
136
+ const SWITCHES = ["enabled","c2c_enabled","group_enabled","group_full_mode","group_at_only","md_auto","stream_enabled","ack_enabled","quote_enabled","capture_enabled","auto_group","approval_inline_redraw","kick_confirm","interject_hook_only","judge_score_output","persona_enabled"]
93
137
  .map(function (key) { return [key, LABELS[key][0], LABELS[key][1]] })
94
138
 
95
139
  // 静默时段:开始/结束时间 + 最右侧开关,并实时显示"当前是否静默、下次切换"
@@ -120,6 +164,11 @@ window.__ModuleLoader__.load({
120
164
  ["image_max_mb","图片上限(MB)",1,20], ["rate_limit_per_hour","每会话每小时上限(0=不限)",0,240],
121
165
  ["stream_interval_ms","流式节流(毫秒)",50,2000], ["quote_context_chars","引用原文上限(字)",50,2000],
122
166
  ["pool_ttl_s","消息池保留(秒)",60,86400], ["pool_max","消息池上限(条)",10,1000],
167
+ ["metrics_keep_days","仪表盘数据保留(天)",1,365], ["interject_cold_s","冷场判定(秒,超过则有钩子)",60,7200],
168
+ ["send_file_timeout_s","发文件超时(秒)",10,300], ["stream_retry_s","流式降级后暂停(秒)",10,3600],
169
+ ["judge_join_threshold","开口阈值(0~3,越大越安静)",0,3],
170
+ ["judge_silent_streak","连续沉默几次后自动降一档",0,20],
171
+ ["judge_force_per_hour","每小时最多几次降档补开口",0,5],
123
172
  ]
124
173
 
125
174
  const TEXTS = [
@@ -139,6 +188,17 @@ window.__ModuleLoader__.load({
139
188
  const [logs, setLogs] = React.useState([])
140
189
  const [paused, setPaused] = React.useState(false)
141
190
  const [follow, setFollow] = React.useState(true)
191
+ const [tab, setTab] = React.useState("settings")
192
+ const [dash, setDash] = React.useState(null)
193
+ const [dashRange, setDashRange] = React.useState("hour")
194
+ const [install, setInstall] = React.useState(null)
195
+ const [installNote, setInstallNote] = React.useState("")
196
+ const [stickers, setStickers] = React.useState([])
197
+ const [stickerNote, setStickerNote] = React.useState("")
198
+ const [stickerDir, setStickerDir] = React.useState("")
199
+ const [renameFile, setRenameFile] = React.useState("")
200
+ const [renameValue, setRenameValue] = React.useState("")
201
+ const [deleteFile, setDeleteFile] = React.useState("")
142
202
  const logRef = React.useRef(null)
143
203
  React.useEffect(function () {
144
204
  const node = logRef.current
@@ -155,6 +215,58 @@ window.__ModuleLoader__.load({
155
215
  }, [call])
156
216
 
157
217
  React.useEffect(function () { load() }, [load])
218
+
219
+ // 装环境的状态轮询必须和其它 hook 一样在提前 return 之前声明,否则 hook 数量会变
220
+ const installCall = async function (body) {
221
+ const response = await fetch(BRIDGE + "/install", {
222
+ method: "POST",
223
+ headers: { "content-type": "application/json", "x-qqbridge-install": "1" },
224
+ body: JSON.stringify(body || {}),
225
+ })
226
+ return await response.json()
227
+ }
228
+ // 挂载时读一次;running 翻成 true 后持续轮询(首次挂载 running=false,旧写法会直接停掉不再更新)
229
+ const installRunning = install !== null && install.running === true
230
+ React.useEffect(function () {
231
+ let stop = false
232
+ const tick = async function () {
233
+ try {
234
+ const state = await installCall({ action: "status" })
235
+ if (stop) return
236
+ setInstall(state)
237
+ if (state.running === true) setTimeout(tick, 1000)
238
+ } catch (error) {
239
+ if (!stop) setInstallNote("连不上宿主插件(39061),确认插件已加载")
240
+ }
241
+ }
242
+ void tick()
243
+ return function () { stop = true }
244
+ }, [installRunning])
245
+ React.useEffect(function () {
246
+ if (tab !== "stickers") return undefined
247
+ let stop = false
248
+ call("/api/stickers").then(function (data) {
249
+ if (stop) return
250
+ setStickers(Array.isArray(data.stickers) ? data.stickers : [])
251
+ setStickerDir(String(data.dir || ""))
252
+ }).catch(function () { if (!stop) setStickerNote("表情包目录不可达") })
253
+ return function () { stop = true }
254
+ }, [tab, call])
255
+ React.useEffect(function () {
256
+ if (tab !== "dashboard") return undefined
257
+ let stop = false
258
+ const tick = async function () {
259
+ try {
260
+ const data = await call("/api/dashboard?range=" + dashRange)
261
+ if (!stop) setDash(data)
262
+ } catch (error) {
263
+ if (!stop) setDash({ offline: true })
264
+ }
265
+ }
266
+ tick()
267
+ const timer = setInterval(tick, 5000)
268
+ return function () { stop = true; clearInterval(timer) }
269
+ }, [tab, call, dashRange])
158
270
  React.useEffect(function () {
159
271
  const timer = setInterval(load, 8000)
160
272
  return function () { clearInterval(timer) }
@@ -176,7 +288,8 @@ window.__ModuleLoader__.load({
176
288
  }, [call, paused])
177
289
 
178
290
  if (state !== null && state.offline) {
179
- return h("div", { style: T.page }, h("div", { style: T.inner },
291
+ return h("div", { style: T.page },
292
+ h("div", { style: T.inner },
180
293
  h("div", { style: T.title }, "机器人的设置服务没有运行"),
181
294
  h("div", { style: T.hint }, "用 bot\\run-bot.bat 启动一次(或 python -u main.py --supervise),再点重试。"),
182
295
  h("div", { style: T.actions }, h("button", { style: T.btn, onClick: load }, "重试"))))
@@ -199,18 +312,508 @@ window.__ModuleLoader__.load({
199
312
  catch (error) { setMessage("保存失败") }
200
313
  setBusy(false)
201
314
  }
315
+ // 装环境:POST 给宿主插件的 /install,再轮询进度
316
+ const startInstall = async function () {
317
+ setInstallNote("")
318
+ try {
319
+ // 面板回传的 AppSecret 是打码值(pHjC****N6),别把它当真的传下去
320
+ const rawSecret = String(value("appsecret") === undefined ? "" : value("appsecret"))
321
+ const started = await installCall({
322
+ action: "start",
323
+ appid: value("appid"),
324
+ appsecret: rawSecret.indexOf("****") >= 0 ? "" : rawSecret,
325
+ autoGroupRoot: value("auto_group_root"),
326
+ })
327
+ if (started.ok !== true) { setInstallNote("启动安装失败:" + (started.error || "未知错误")); return }
328
+ setInstall(started.state || null)
329
+ } catch (error) {
330
+ setInstallNote("连不上宿主插件(39061),确认插件已加载")
331
+ }
332
+ }
333
+
202
334
  const manage = async function (action) {
203
335
  setBusy(true)
204
336
  try { const result = await call("/api/manage", { method: "POST", body: JSON.stringify({ action: action }) }); setMessage(result.message || action); await load() }
205
337
  catch (error) { setMessage("操作失败") }
206
338
  setBusy(false)
207
339
  }
340
+
341
+ const SCROLLBAR_CSS = [
342
+ '[data-qq-scroll]::-webkit-scrollbar{width:9px;height:9px}',
343
+ '[data-qq-scroll]::-webkit-scrollbar-track{background:rgba(0,0,0,0.04);border-radius:999px}',
344
+ '[data-qq-scroll]::-webkit-scrollbar-thumb{background:rgba(120,130,145,0.55);border-radius:999px;border:2px solid transparent;background-clip:padding-box}',
345
+ '[data-qq-scroll]::-webkit-scrollbar-thumb:hover{background:rgba(120,130,145,0.8);background-clip:padding-box}',
346
+ ].join('')
347
+
348
+ function bucketPlan(range) {
349
+ const now = Math.floor(Date.now() / 1000)
350
+ if (range === "today") {
351
+ const midnight = new Date(now * 1000)
352
+ midnight.setHours(0, 0, 0, 0)
353
+ const start = Math.floor(midnight.getTime() / 1000)
354
+ return { start: start, step: 60, count: Math.min(1440, Math.ceil((now - start) / 60) + 1) }
355
+ }
356
+ if (range === "7d") {
357
+ const step = 30 * 60
358
+ const start = Math.floor((now - 7 * 86400) / step) * step
359
+ return { start: start, step: step, count: Math.ceil((now - start) / step) + 1 }
360
+ }
361
+ const start = Math.floor((now - 60 * 60) / 60) * 60
362
+ return { start: start, step: 60, count: 60 }
363
+ }
364
+
365
+ function buildSeries(raw, keys, range) {
366
+ const plan = bucketPlan(range)
367
+ const byTime = new Map()
368
+ ;(raw || []).forEach(function (row) {
369
+ const bucket = Math.floor(Number(row.t) / plan.step) * plan.step
370
+ const cell = byTime.get(bucket) || {}
371
+ keys.forEach(function (key) { cell[key] = (cell[key] || 0) + Number(row[key] || 0) })
372
+ byTime.set(bucket, cell)
373
+ })
374
+ return Array.from({ length: plan.count }, function (_, index) {
375
+ const t = plan.start + index * plan.step
376
+ const cell = byTime.get(t) || {}
377
+ const point = { t: t }
378
+ keys.forEach(function (key) { point[key] = Number(cell[key] || 0) })
379
+ return point
380
+ })
381
+ }
382
+
383
+ function chartTick(tSec, spanSec) {
384
+ const d = new Date(Number(tSec) * 1000)
385
+ const pad = function (n) { return ("0" + n).slice(-2) }
386
+ if (spanSec > 86400) return (d.getMonth() + 1) + "-" + pad(d.getDate()) + " " + pad(d.getHours()) + "h"
387
+ return pad(d.getHours()) + ":" + pad(d.getMinutes())
388
+ }
389
+
390
+ function areaChart(rawPoints, keys, colors) {
391
+ // 7 天区间会产生上万条分钟点:抽稀到 ≤1000 条,形状不变,重绘不卡
392
+ let points = rawPoints
393
+ if (points.length > 1000) {
394
+ const stride = Math.ceil(points.length / 1000)
395
+ points = points.filter(function (_point, index) { return index % stride === 0 || index === points.length - 1 })
396
+ }
397
+ const width = 560
398
+ const height = 150
399
+ const left = 30
400
+ const right = 8
401
+ const top = 8
402
+ const bottom = 20
403
+ const plotW = width - left - right
404
+ const plotH = height - top - bottom
405
+ let max = 1
406
+ points.forEach(function (point) {
407
+ keys.forEach(function (key) { if (point[key] > max) max = point[key] })
408
+ })
409
+ const nice = Math.max(1, Math.ceil(max / 2) * 2)
410
+ const stamp = function (point) { return Number(point.t) || 0 }
411
+ let tMin = points.length ? Math.min.apply(null, points.map(stamp)) : 0
412
+ let tMax = points.length ? Math.max.apply(null, points.map(stamp)) : 60
413
+ if (tMax - tMin < 60) tMax = tMin + 60
414
+ const xAt = function (point) { return left + ((stamp(point) - tMin) / (tMax - tMin)) * plotW }
415
+ const yAt = function (value) { return top + plotH - ((Number(value) || 0) / nice) * plotH }
416
+ const children = [
417
+ h("rect", { key: "bg", x: 0, y: 0, width: width, height: height, fill: "transparent" }),
418
+ ]
419
+ ;[nice, Math.round(nice / 2), 0].forEach(function (value, index) {
420
+ const y = yAt(value)
421
+ children.push(h("line", {
422
+ key: "gy" + index, x1: left, y1: y, x2: left + plotW, y2: y,
423
+ stroke: "var(--dsw-alias-border-l2, #e3e6ea)", strokeWidth: 0.5,
424
+ }))
425
+ children.push(h("text", {
426
+ key: "gyt" + index, x: left - 5, y: y + 3, textAnchor: "end", fontSize: 9,
427
+ fill: "var(--dsw-alias-label-tertiary, #8b929c)",
428
+ }, String(value)))
429
+ })
430
+ const spanSec = tMax - tMin
431
+ for (let i = 0; i <= 4; i += 1) {
432
+ const x = left + (plotW / 4) * i
433
+ const tickTime = tMin + (spanSec / 4) * i
434
+ children.push(h("line", {
435
+ key: "gx" + i, x1: x, y1: top + plotH, x2: x, y2: top + plotH + 3,
436
+ stroke: "var(--dsw-alias-border-l3, #cfd4da)", strokeWidth: 0.5,
437
+ }))
438
+ children.push(h("text", {
439
+ key: "gxt" + i, x: x, y: height - 6,
440
+ textAnchor: i === 0 ? "start" : (i === 4 ? "end" : "middle"), fontSize: 9,
441
+ fill: "var(--dsw-alias-label-tertiary, #8b929c)",
442
+ }, chartTick(tickTime, spanSec)))
443
+ }
444
+ keys.forEach(function (key) {
445
+ const coords = points.map(function (point) {
446
+ return [xAt(point).toFixed(1), yAt(point[key]).toFixed(1)]
447
+ })
448
+ if (!coords.length) return
449
+ if (coords.length === 1) {
450
+ children.push(h("circle", { key: "p" + key, cx: coords[0][0], cy: coords[0][1], r: 2.5, fill: colors[key] }))
451
+ return
452
+ }
453
+ const d = coords.map(function (pair, index) {
454
+ return (index === 0 ? "M" : "L") + pair[0] + " " + pair[1]
455
+ }).join(" ")
456
+ const baseline = (top + plotH).toFixed(1)
457
+ children.push(h("path", {
458
+ key: "a" + key,
459
+ d: d + " L" + coords[coords.length - 1][0] + " " + baseline + " L" + coords[0][0] + " " + baseline + " Z",
460
+ fill: colors[key], opacity: 0.14,
461
+ }))
462
+ children.push(h("path", {
463
+ key: "l" + key, d: d, fill: "none", stroke: colors[key], strokeWidth: 2,
464
+ strokeLinejoin: "round", strokeLinecap: "round",
465
+ }))
466
+ })
467
+ return h("svg", { viewBox: "0 0 " + width + " " + height, style: { width: "100%", height: 150, display: "block" } }, children)
468
+ }
469
+
470
+ function ring(ratio, label, detail, color) {
471
+ const value = Math.max(0, Math.min(1, Number(ratio) || 0))
472
+ const radius = 26
473
+ const circumference = 2 * Math.PI * radius
474
+ const filled = circumference * value
475
+ return h("div", { style: T.ringBox },
476
+ h("svg", { viewBox: "0 0 72 72", style: { width: 72, height: 72 } },
477
+ h("circle", { cx: 36, cy: 36, r: radius, fill: "none", stroke: "var(--dsw-alias-border-l2, rgba(255,255,255,0.16))", strokeWidth: 7 }),
478
+ h("circle", {
479
+ cx: 36, cy: 36, r: radius, fill: "none", stroke: color, strokeWidth: 7, strokeLinecap: "round",
480
+ strokeDasharray: filled.toFixed(1) + " " + circumference.toFixed(1),
481
+ transform: "rotate(-90 36 36)",
482
+ }),
483
+ h("text", { x: 36, y: 41, textAnchor: "middle", fontSize: 15, fill: "var(--dsw-alias-label-primary)", fontWeight: 600 }, Math.round(value * 100) + "%")),
484
+ h("div", { style: T.ringLabel }, label),
485
+ h("div", { style: T.hint }, detail))
486
+ }
487
+
488
+ function kpi(label, value, sub) {
489
+ return h("div", { style: T.kpi },
490
+ h("div", { style: T.kpiLabel }, label),
491
+ h("div", { style: T.kpiValue }, value),
492
+ sub ? h("div", { style: T.hint }, sub) : null)
493
+ }
494
+
495
+ function barRow(label, value, max, color) {
496
+ const width = max > 0 ? Math.round((value / max) * 100) : 0
497
+ return h("div", { key: label, style: T.barRow },
498
+ h("span", { style: T.barLabel }, label),
499
+ h("div", { style: T.barTrack },
500
+ h("div", { style: Object.assign({}, T.barFill, { width: width + "%", background: color }) })),
501
+ h("span", { style: T.barValue }, String(value)))
502
+ }
503
+
504
+ function chartCard(title, legend, body) {
505
+ return h("div", { style: T.card },
506
+ h("div", { style: T.cardHead },
507
+ h("span", { style: T.cardTitle }, title),
508
+ h("span", { style: T.legend }, (legend || []).map(function (item) {
509
+ return h("span", { key: item.label, style: T.legendItem },
510
+ h("span", { style: Object.assign({}, T.legendDot, { background: item.color }) }),
511
+ item.label)
512
+ }))),
513
+ body)
514
+ }
515
+
516
+ const reloadStickers = async function () {
517
+ try {
518
+ const data = await call("/api/stickers")
519
+ setStickers(Array.isArray(data.stickers) ? data.stickers : [])
520
+ setStickerDir(String(data.dir || ""))
521
+ } catch (error) { setStickerNote("表情包目录不可达") }
522
+ }
523
+
524
+ const uploadSticker = function (event) {
525
+ const file = event.target.files && event.target.files[0]
526
+ if (!file) return
527
+ if (file.size > 4 * 1024 * 1024) { setStickerNote("图片超过 4MB"); return }
528
+ const reader = new FileReader()
529
+ reader.onload = async function () {
530
+ const name = String(file.name || "sticker").replace(/\.[^.]+$/, "")
531
+ try {
532
+ const result = await call("/api/stickers", { method: "POST", body: JSON.stringify({ action: "upload", name: name, data: String(reader.result) }) })
533
+ setStickerNote(result.ok ? "已上传:" + name : "上传失败:" + (result.error || ""))
534
+ await reloadStickers()
535
+ } catch (error) { setStickerNote("上传失败") }
536
+ }
537
+ reader.readAsDataURL(file)
538
+ event.target.value = ""
539
+ }
540
+
541
+ const stickerAction = async function (action, name, extra) {
542
+ try {
543
+ const result = await call("/api/stickers", { method: "POST", body: JSON.stringify(Object.assign({ action: action, name: name }, extra || {})) })
544
+ setStickerNote(result.ok ? (action === "delete" ? "已删除:" + name : "已改名") : "操作失败:" + (result.error || ""))
545
+ await reloadStickers()
546
+ } catch (error) { setStickerNote("操作失败") }
547
+ }
548
+
549
+ function stickersView() {
550
+ return h("div", { style: { display: "grid", gap: 14 } },
551
+ h("div", { style: T.actions },
552
+ h("label", { style: Object.assign({}, T.btn, T.btnPrimary, { cursor: "pointer" }) },
553
+ "上传表情包",
554
+ h("input", { type: "file", accept: "image/*", style: { display: "none" }, onChange: uploadSticker })),
555
+ h("button", { style: T.btn, onClick: reloadStickers }, "刷新"),
556
+ h("span", { style: T.hint }, stickers.length + " 个 · " + (stickerDir || "assets/stickers"))),
557
+ stickerNote ? h("div", { style: T.hint }, stickerNote) : null,
558
+ h("div", { style: T.grid },
559
+ ...(stickers.length === 0
560
+ ? [h("div", { style: T.card }, h("div", { style: T.hint }, "还没有表情包,点「上传表情包」加一个"))]
561
+ : stickers.map(function (item) {
562
+ return h("div", { key: item.file, style: Object.assign({}, T.card, { justifyItems: "center" }) },
563
+ h("img", {
564
+ src: PANEL + "/api/stickers?file=" + encodeURIComponent(item.file),
565
+ alt: item.name,
566
+ style: { width: "100%", maxHeight: 120, objectFit: "contain", borderRadius: 8 },
567
+ }),
568
+ renameFile === item.file
569
+ ? h("div", { style: { display: "grid", gap: 6, width: "100%" } },
570
+ h("input", {
571
+ style: Object.assign({}, T.input, { width: "100%", textAlign: "center" }),
572
+ value: renameValue,
573
+ autoFocus: true,
574
+ onChange: function (event) { setRenameValue(event.target.value) },
575
+ onKeyDown: function (event) {
576
+ if (event.key === "Enter" && renameValue.trim() && renameValue.trim() !== item.name) {
577
+ stickerAction("rename", item.name, { to: renameValue.trim() })
578
+ setRenameFile("")
579
+ }
580
+ if (event.key === "Escape") setRenameFile("")
581
+ },
582
+ }),
583
+ h("div", { style: T.actions },
584
+ h("button", {
585
+ style: Object.assign({}, T.btn, T.btnPrimary),
586
+ onClick: function () {
587
+ const next = renameValue.trim()
588
+ if (!next || next === item.name) { setRenameFile(""); return }
589
+ stickerAction("rename", item.name, { to: next })
590
+ setRenameFile("")
591
+ },
592
+ }, "保存"),
593
+ h("button", { style: T.btn, onClick: function () { setRenameFile("") } }, "取消")))
594
+ : h("div", { style: T.cardTitle }, item.name),
595
+ h("div", { style: T.hint }, Math.round(item.bytes / 1024) + " KB"),
596
+ h("div", { style: T.actions },
597
+ h("button", {
598
+ style: T.btn,
599
+ onClick: function () {
600
+ const syntax = "[[sticker: " + item.name + "]]"
601
+ try { navigator.clipboard.writeText(syntax) ; setStickerNote("已复制 " + syntax) } catch (error) { setStickerNote(syntax) }
602
+ },
603
+ }, "复制语法"),
604
+ h("button", {
605
+ style: T.btn,
606
+ onClick: function () {
607
+ setRenameFile(item.file)
608
+ setRenameValue(item.name)
609
+ setStickerNote("")
610
+ },
611
+ }, "改名"),
612
+ h("button", {
613
+ style: deleteFile === item.file ? Object.assign({}, T.btn, { color: "#ef4444", borderColor: "#ef4444" }) : T.btn,
614
+ onClick: function () {
615
+ if (deleteFile === item.file) {
616
+ setDeleteFile("")
617
+ stickerAction("delete", item.name)
618
+ } else {
619
+ setDeleteFile(item.file)
620
+ setStickerNote("再点一次「确认删除」移除 " + item.name)
621
+ }
622
+ },
623
+ }, deleteFile === item.file ? "确认删除" : "删除"))
624
+ )
625
+ }))),
626
+ h("div", { style: T.hint }, "模型在回复里写 " + "[[sticker: 名字]]" + " 就会发出对应的图;名字就是文件名去掉扩展名。"))
627
+ }
628
+ function dashboardView() {
629
+ if (!dash) return h("div", { style: T.card }, h("div", { style: T.hint }, "正在读取…"))
630
+ if (dash.offline) return h("div", { style: T.card }, h("div", { style: T.hint }, "面板不可达(守护进程没在跑)"))
631
+ const c = dash.counters || {}
632
+ const botInfo = dash.bot || {}
633
+ const queues = dash.queues || {}
634
+ const logs = dash.logs || {}
635
+ const uptime = Number(dash.uptime_s || 0)
636
+ const human = uptime > 0 ? Math.floor(uptime / 3600) + "h " + Math.floor((uptime % 3600) / 60) + "m" : "—"
637
+ const points = buildSeries(dash.series, ["c2c_msgs", "group_msgs", "judge_spoke", "streams"], dashRange)
638
+ const sumKey = function (key) {
639
+ return (points || []).reduce(function (acc, point) { return acc + Number(point[key] || 0) }, 0)
640
+ }
641
+ const rangeC2c = sumKey("c2c_msgs")
642
+ const rangeGroup = sumKey("group_msgs")
643
+ const rangeSpoke = sumKey("judge_spoke")
644
+ const rangeStreams = sumKey("streams")
645
+ const totalMsgs = (c.c2c_msgs || 0) + (c.group_msgs || 0)
646
+ const judged = c.judge_calls || 0
647
+ const spoke = c.judge_spoke || 0
648
+ const speakRate = judged > 0 ? spoke / judged : 0
649
+ const streamed = c.streams || 0
650
+ const fallbacks = c.stream_fallbacks || 0
651
+ const streamOk = streamed > 0 ? 1 - fallbacks / streamed : 1
652
+ const runtime = dash.runtime || {}
653
+ const actions = [
654
+ ["图片文件", c.files_image || 0, "var(--dsw-alias-state-business-primary, #2f6bff)"],
655
+ ["文档文件", c.files_doc || 0, "#0ea5e9"],
656
+ ["审批通过", c.approvals_allow || 0, "#22c55e"],
657
+ ["审批拒绝", c.approvals_deny || 0, "#ef4444"],
658
+ ["提问回答", c.questions_answered || 0, "#8b5cf6"],
659
+ ["提问超时", c.question_timeouts || 0, "#f97316"],
660
+ ["禁言", c.mutes || 0, "#f59e0b"],
661
+ ["解禁", c.unmutes || 0, "#14b8a6"],
662
+ ["踢人", c.kicks || 0, "#dc2626"],
663
+ ]
664
+ const actionMax = actions.reduce(function (acc, item) { return Math.max(acc, item[1]) }, 1)
665
+ const logText = Object.keys(logs).map(function (name) { return name.replace(".log", "") + " " + Math.round(logs[name] / 1024) + "KB" }).join(" · ") || "—"
666
+ return h("div", { style: { display: "grid", gap: 14 } },
667
+ h("div", { style: T.kpiRow },
668
+ kpi("运行时长", human, (botInfo.online ? "在线" : "离线") + " · pid " + (botInfo.pid || "—")),
669
+ kpi("消息(本区间)", rangeC2c + rangeGroup, "私聊 " + rangeC2c + " · 群 " + rangeGroup),
670
+ kpi("开口(本区间)", rangeSpoke, "累计 " + spoke + " 次 · 判断 " + judged),
671
+ kpi("流式(本区间)", rangeStreams, "累计 " + streamed + " 次 · 降级 " + fallbacks)),
672
+ h("div", { style: T.kpiRow },
673
+ kpi("累计消息", totalMsgs, "自首次运行起,重启不清零"),
674
+ kpi("累计开口", spoke, "共判断 " + judged + " 次"),
675
+ kpi("省下的调用", c.hook_skips || 0, "钩子预筛直接跳过"),
676
+ kpi("内存/错误", (dash.memory_mb ? dash.memory_mb + " MB" : "—") + " / " + (dash.errors || 0), "工作集 / 日志 ERROR 数")),
677
+ h("div", { style: T.actions },
678
+ [["hour", "近 60 分钟"], ["today", "今天"], ["7d", "近 7 天"]].map(function (item) {
679
+ return h("button", {
680
+ key: item[0],
681
+ style: dashRange === item[0] ? Object.assign({}, T.tab, T.tabActive) : T.tab,
682
+ onClick: function () { setDashRange(item[0]) },
683
+ }, item[1])
684
+ }),
685
+ h("span", { style: T.hint }, dashRange === "hour" ? "近 60 分钟,按分钟聚合" : "读取 state/metrics/*.jsonl,停机也留档")), chartCard(dashRange === "hour" ? "近 60 分钟活动" : dashRange === "today" ? "今天每分钟活动" : "近 7 天每 30 分钟活动", [
686
+ { label: "私聊", color: "#2f6bff" },
687
+ { label: "群聊", color: "#22c55e" },
688
+ { label: "开口", color: "#f59e0b" },
689
+ { label: "流式", color: "#a855f7" },
690
+ ], areaChart(points, ["c2c_msgs", "group_msgs", "judge_spoke", "streams"], {
691
+ c2c_msgs: "#2f6bff", group_msgs: "#22c55e", judge_spoke: "#f59e0b", streams: "#a855f7",
692
+ })),
693
+ h("div", { style: T.kpiRow },
694
+ h("div", { style: T.card }, ring(speakRate, "开口率", spoke + " / " + judged + " 次判断", "#f59e0b")),
695
+ h("div", { style: T.card }, ring(streamed > 0 ? streamOk : 0, streamed > 0 ? "流式成功率" : "流式(暂无数据)", streamed + " 次 · 降级 " + fallbacks, "#a855f7")),
696
+ h("div", { style: Object.assign({}, T.card, { gridColumn: "span 2" }) },
697
+ h("div", { style: T.cardTitle }, "动作分布"),
698
+ ...actions.map(function (item) { return barRow(item[0], item[1], actionMax, item[2]) }))),
699
+ h("div", { style: T.kpiRow },
700
+ kpi("队列残留", (queues.questions || 0) + (queues.admin || 0), "提问 " + (queues.questions || 0) + " · 管理 " + (queues.admin || 0)),
701
+ kpi("成员索引", dash.members || 0, "本群发过言的成员"),
702
+ kpi("日志体积", Math.round(Object.keys(logs).reduce(function (acc, k) { return acc + logs[k] }, 0) / 1024) + " KB", logText)),
703
+ h("div", { style: T.kpiRow },
704
+ kpi("内存占用", (dash.memory_mb ? dash.memory_mb + " MB" : "—"), "bot 进程工作集"),
705
+ kpi("日志错误", dash.errors || 0, "最近 300KB 内 [ERROR] 行"),
706
+ kpi("待处理", (runtime.inflight || 0) + (runtime.queued || 0) + (runtime.chatter || 0),
707
+ "在跑 " + (runtime.inflight || 0) + " · 排队 " + (runtime.queued || 0) + " · 待判 " + (runtime.chatter || 0)),
708
+ kpi("群图片/引用", (c.group_images || 0) + " / " + (c.quotes || 0), "含附件的群消息与引用次数")),
709
+ h("div", { style: T.kpiRow },
710
+ h("div", { style: T.card },
711
+ h("div", { style: T.cardTitle }, "最近事件"),
712
+ h("div", { style: T.eventList, "data-qq-scroll": "1" },
713
+ ...(dash.events && dash.events.length
714
+ ? dash.events.map(function (item, index) {
715
+ const when = new Date(Number(item.at) * 1000)
716
+ const hhmm = ("0" + when.getHours()).slice(-2) + ":" + ("0" + when.getMinutes()).slice(-2)
717
+ return h("div", { key: "ev" + index, style: T.eventRow },
718
+ h("span", { style: T.eventTime }, hhmm),
719
+ h("span", { style: T.eventKind }, String(item.kind || "")),
720
+ h("span", { style: T.eventText }, String(item.text || "")))
721
+ })
722
+ : [h("div", { style: T.hint }, "还没有事件")]))),
723
+ h("div", { style: T.card },
724
+ h("div", { style: T.cardTitle }, "群资料"),
725
+ ...(dash.groups_detail && dash.groups_detail.length
726
+ ? dash.groups_detail.flatMap(function (group) {
727
+ const rows = [
728
+ h("div", { key: group.openid + "-name", style: T.cardRow },
729
+ h("span", { style: T.cardKey }, "群名"),
730
+ h("span", { style: T.cardValue }, group.name || "—")),
731
+ h("div", { key: group.openid + "-members", style: T.cardRow },
732
+ h("span", { style: T.cardKey }, "成员数"),
733
+ h("span", { style: T.cardValue }, String(group.members || 0))),
734
+ ]
735
+ if (group.memo) {
736
+ rows.push(h("div", { key: group.openid + "-memo", style: T.hint }, group.memo))
737
+ }
738
+ if (group.class || (group.tags || []).length) {
739
+ rows.push(h("div", { key: group.openid + "-tags", style: T.chipRow },
740
+ ...[group.class].concat(group.tags || []).filter(Boolean).map(function (tag) {
741
+ return h("span", { key: group.openid + tag, style: T.chip }, tag)
742
+ })))
743
+ }
744
+ return rows
745
+ })
746
+ : [h("div", { style: T.hint }, "还没取到群资料(机器人收到群消息后会自动缓存)")])),
747
+ h("div", { style: T.card },
748
+ h("div", { style: T.cardTitle }, "群成员 · " + Object.keys(dash.members_detail || {}).reduce(function (sum, key) { return sum + ((dash.members_detail[key] || []).length) }, 0)),
749
+ ...Object.keys(dash.members_detail || {}).length
750
+ ? Object.keys(dash.members_detail || {}).flatMap(function (key) {
751
+ const groupName = (dash.group_names || {})[key.replace("group:", "")] || ""
752
+ const list = dash.members_detail[key] || []
753
+ const rows = [h("div", { key: key, style: T.footNote }, groupName ? groupName + " · " + key.replace("group:", "").slice(-8) : key.replace("group:", "").slice(-8))]
754
+ rows.push(h("div", { key: key + "-list", style: T.memberList, "data-qq-scroll": "1" },
755
+ ...(list.length
756
+ ? list.map(function (item) {
757
+ return h("div", { key: key + item.tail, style: T.memberRow },
758
+ item.avatar
759
+ ? h("img", { src: item.avatar, alt: item.tail, style: T.memberAvatar })
760
+ : h("span", { style: Object.assign({}, T.memberAvatar, { background: "var(--dsw-alias-border-l2)" }) }),
761
+ h("span", { style: T.memberName }, item.name || item.tail),
762
+ h("span", { style: T.memberTail }, item.name ? item.tail : ""))
763
+ })
764
+ : [h("div", { key: key + "-empty", style: T.hint }, "暂无")])))
765
+ if (list.length > 5) {
766
+ rows.push(h("div", { key: key + "-more", style: T.footNote }, "共 " + list.length + " 人 · 上下滚动查看全部"))
767
+ }
768
+ return rows
769
+ })
770
+ : [h("div", { style: T.hint }, "暂无")])),
771
+ h("div", { style: T.card },
772
+ h("div", { style: T.cardTitle }, "历史留档(state/metrics)"),
773
+ ...(dash.history && dash.history.length
774
+ ? dash.history.slice(-7).reverse().map(function (item) {
775
+ return h("div", { key: item.day, style: T.cardRow },
776
+ h("span", { style: T.cardKey }, item.day),
777
+ h("span", { style: T.cardValue }, item.minutes + " 分钟 · " + item.total + " 次事件"))
778
+ })
779
+ : [h("div", { style: T.hint }, "还没有归档文件(每分钟结束后自动写一行 JSONL)")])),
780
+ h("div", { style: T.footNote }, "计数与曲线跨重启保留(读 state/metrics),只有运行时长按本次启动计算。"))
781
+ }
208
782
  const dot = function (ok) {
209
783
  return h("span", { style: Object.assign({}, T.dot, { background: ok === true ? "var(--dsw-alias-state-success-primary, #35c759)" : ok === false ? "var(--dsw-alias-label-error, #e5534b)" : "var(--dsw-alias-label-tertiary, #888)" }) })
210
784
  }
211
785
 
786
+ const tabBar = h("div", { style: T.tabs },
787
+ h("button", { style: tab === "settings" ? Object.assign({}, T.tab, T.tabActive) : T.tab, onClick: function () { setTab("settings") } }, "设置"),
788
+ h("button", { style: tab === "dashboard" ? Object.assign({}, T.tab, T.tabActive) : T.tab, onClick: function () { setTab("dashboard") } }, "数据仪表盘"),
789
+ h("button", { style: tab === "stickers" ? Object.assign({}, T.tab, T.tabActive) : T.tab, onClick: function () { setTab("stickers") } }, "表情包"))
790
+
791
+ // 人设:一个大输入框一份,群聊与私聊分开
792
+ const personaBox = function (key, title, hint) {
793
+ return h("div", { key: key, style: T.card },
794
+ h("div", { style: T.cardHead },
795
+ h("span", { style: T.cardTitle }, title),
796
+ h("span", { style: T.hint }, hint)),
797
+ h("textarea", {
798
+ style: T.textarea,
799
+ rows: 8,
800
+ placeholder: "写这里,例如:你是一条叫「蓝色大肥鱼」的群宠,话短、带口癖「喵」,不主动聊政治和带节奏。",
801
+ value: value(key) === undefined ? "" : value(key),
802
+ onChange: function (event) { setValue(key, event.target.value) },
803
+ }))
804
+ }
805
+
806
+ if (tab === "dashboard") {
807
+ return h("div", { style: T.page }, h("style", { key: "qq-scroll-css" }, SCROLLBAR_CSS), h("div", { style: T.inner }, tabBar, dashboardView()))
808
+ }
809
+ if (tab === "stickers") {
810
+ return h("div", { style: T.page }, h("style", { key: "qq-scroll-css" }, SCROLLBAR_CSS), h("div", { style: T.inner }, tabBar, stickersView()))
811
+ }
812
+
212
813
  return h("div", { style: T.page },
814
+ h("style", { key: "qq-scroll-css" }, SCROLLBAR_CSS),
213
815
  h("div", { style: T.inner },
816
+ tabBar,
214
817
  h("div", { style: T.actions },
215
818
  h("span", { style: T.badge }, dot(!!bot.running), "进程 · " + (bot.running ? "运行中" : "已停止")),
216
819
  h("span", { style: T.badge }, dot(!!bot.online), "在线 · " + (bot.online ? "是" : "否")),
@@ -234,11 +837,40 @@ window.__ModuleLoader__.load({
234
837
  }
235
838
  },
236
839
  }, "打开分组文件夹")),
840
+ h("div", { style: T.sectionTitle }, "机器人环境(把 Python / SDK / 机器人代码一次配好)"),
841
+ h("div", { style: T.card },
842
+ h("div", { style: T.cardRow },
843
+ h("span", { style: T.cardKey }, "状态"),
844
+ h("span", { style: T.cardValue },
845
+ install === null ? "读取中…"
846
+ : install.running ? "正在配置…"
847
+ : (install.done && install.succeeded) ? "配置完成"
848
+ : install.installed ? "已配置" : "未用一键安装(按插件里的 pythonPath 启动)")),
849
+ install && install.installed
850
+ ? h("div", { style: T.hint }, "目录 " + install.installed.botDir + " · Python " + (install.installed.pythonVersion || "?"))
851
+ : h("div", { style: T.hint }, "点按钮:找系统 Python(3.10+)→ 建 venv → pip 装 aiohttp / Pillow / viseron-qqbotpy → 复制机器人代码 → 写配置 → 拉起守护进程"),
852
+ install && install.running && Array.isArray(install.steps)
853
+ ? h("div", { style: T.hint }, "第 " + (install.step + 1) + "/" + install.steps.length + " 步:" + install.steps[install.step])
854
+ : null,
855
+ install && install.error ? h("div", { style: T.hint }, "失败:" + install.error) : null,
856
+ installNote ? h("div", { style: T.hint }, installNote) : null,
857
+ h("div", { style: T.actions },
858
+ h("button", {
859
+ style: Object.assign({}, T.btn, T.btnPrimary),
860
+ disabled: busy || (install !== null && install.running === true),
861
+ onClick: function () { void startInstall() },
862
+ }, install && install.running ? "正在配置…" : "下载 / 配置机器人")),
863
+ install && Array.isArray(install.lines) && install.lines.length
864
+ ? h("pre", { style: T.log }, install.lines.slice(-60).join("\n"))
865
+ : null),
237
866
  h("div", { style: T.sectionTitle }, "开关"),
238
867
  SWITCHES.map(function (item) {
239
868
  return h(Row, { key: item[0], title: item[1], hint: item[2] },
240
869
  h(Switch, { checked: !!value(item[0]), label: item[1], disabled: busy, onChange: function (next) { setValue(item[0], next) } }))
241
870
  }),
871
+ h("div", { style: T.sectionTitle }, "人设(只在新会话的第一条消息里发一次)"),
872
+ personaBox("persona_group", "群聊人设", "群聊里带的人设;留空=不启用"),
873
+ personaBox("persona_c2c", "私聊人设", "单聊里带的人设;留空=不启用"),
242
874
  h("div", { style: T.sectionTitle }, "群聊节奏与发送"),
243
875
  h(QuietRow, {
244
876
  key: "quiet-hours",