@mcviseron/dsh-qq-bridge 0.2.0 → 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
@@ -1,372 +1,1004 @@
1
- /**
2
- * dsh-qq-bridge 的浏览器半身:左侧导航栏「QQ 机器人」+ 整页设置/日志。
3
- * 全部改用内联样式:宿主 main 槽位不在同一个样式作用域,注入 <style> 不可靠。
4
- */
5
- window.__ModuleLoader__.load({
6
- id: "dsh-qq-bridge",
7
- factory: (require) => {
8
- var module = { exports: {} }
9
- var exports = module.exports
10
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
11
-
12
- const React = require("react")
13
- const h = React.createElement
14
- const PANEL = "http://127.0.0.1:39062"
15
-
16
- const T = {
17
- 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)" },
18
- inner: {
19
- width: "100%", maxWidth: 720, margin: "0 auto", display: "grid", gap: 14,
20
- // 磨砂玻璃底:页面浮在背景图之上时保证文字可读
21
- padding: "20px 22px", borderRadius: 16,
22
- border: "1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))",
23
- backgroundColor: "rgba(22, 24, 30, 0.62)",
24
- background: "color-mix(in srgb, var(--dsw-alias-bg-base, #14161c) 72%, transparent)",
25
- backdropFilter: "blur(18px) saturate(130%)",
26
- WebkitBackdropFilter: "blur(18px) saturate(130%)",
27
- boxShadow: "0 10px 30px rgba(0,0,0,0.24)",
28
- },
29
- row: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, padding: "9px 0", borderTop: "1px solid var(--dsw-alias-border-l2)" },
30
- labelBox: { display: "grid", gap: 2, minWidth: 0 },
31
- title: { fontSize: 13, color: "var(--dsw-alias-label-primary)" },
32
- hint: { fontSize: 12, color: "var(--dsw-alias-label-tertiary)" },
33
- sectionTitle: { fontSize: 12, letterSpacing: "0.04em", color: "var(--dsw-alias-label-tertiary)", margin: "10px 0 2px" },
34
- 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
- inputWide: { width: 260, textAlign: "left" },
36
- 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
- btnPrimary: { background: "var(--dsw-alias-label-primary)", borderColor: "var(--dsw-alias-label-primary)", color: "var(--dsw-alias-bg-layer-3)" },
38
- actions: { display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" },
39
- badge: { display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 9px", border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 999, fontSize: 12, color: "var(--dsw-alias-label-secondary)" },
40
- dot: { width: 7, height: 7, borderRadius: "50%" },
41
- log: { margin: 0, maxHeight: 300, overflow: "auto", padding: 10, border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 6, background: "var(--dsw-alias-bg-layer-3)", color: "var(--dsw-alias-label-secondary)", font: "12px/1.5 ui-monospace, Consolas, monospace", whiteSpace: "pre-wrap" },
42
- }
43
-
44
- function Switch(props) {
45
- return h("button", {
46
- type: "button", role: "switch", "aria-checked": props.checked ? "true" : "false",
47
- "aria-label": props.label, disabled: props.disabled,
48
- onClick: function () { props.onChange(!props.checked) },
49
- style: {
50
- position: "relative", flex: "0 0 auto", width: 38, height: 22, padding: 2, border: 0,
51
- borderRadius: 999, cursor: props.disabled ? "default" : "pointer", boxSizing: "border-box",
52
- // 用官方语义色:开启=业务主色,关闭=边框 L3(不再用不存在的 brand-primary 导致发白)
53
- background: props.checked
54
- ? "var(--dsw-alias-state-business-primary, #2f6bff)"
55
- : "var(--dsw-alias-border-l3, #5a6270)",
56
- boxShadow: props.checked ? "inset 0 0 0 1px rgba(255,255,255,0.12)" : "none",
57
- opacity: props.disabled ? 0.5 : 1,
58
- },
59
- }, h("span", {
60
- "aria-hidden": "true",
61
- style: {
62
- display: "block", width: 18, height: 18, borderRadius: "50%",
63
- background: props.checked ? "#fff" : "var(--dsw-alias-switch-thumb, #c9ccd6)",
64
- transform: props.checked ? "translateX(16px)" : "none", transition: "transform 120ms ease",
65
- },
66
- }))
67
- }
68
-
69
- function Row(props) {
70
- return h("div", { style: T.row },
71
- h("div", { style: T.labelBox },
72
- h("span", { style: T.title }, props.title),
73
- props.hint ? h("span", { style: T.hint }, props.hint) : null),
74
- props.children)
75
- }
76
-
77
- const LABELS = {
78
- enabled: ["接收消息(总)", "关掉后私聊与群聊都不响应"],
79
- c2c_enabled: ["私聊响应", ""],
80
- group_enabled: ["群聊响应", ""],
81
- group_full_mode: ["群全量消息", "需在开放平台开启全量接收"],
82
- group_at_only: ["群聊只处理 @ 我的消息", "开启后群里的普通发言一律丢弃(仅在拿到全量消息时才需要)"],
83
- md_auto: ["Markdown 自动发送", "回复像 Markdown 时用 msg_type=2"],
84
- stream_enabled: ["流式输出(仅私聊)", "平台只在单聊支持流式"],
85
- ack_enabled: ["“还在处理”占位提示", "会打断流式输出,默认关"],
86
- quote_enabled: ["识别引用消息", "引用时把被引用原文和来源一起带给模型"],
87
- capture_enabled: ["允许截屏", "/截图、/窗口 是否可用"],
88
- auto_group: ["自动分组(每个会话独立工作区)", "关闭则所有会话共用同一个工作目录"],
89
- approval_inline_redraw: ["审批按钮就地重绘为“已允许”", "关闭后退回旧行为:额外发一条结论文字 + “已处理”卡片"],
90
- }
91
-
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"]
93
- .map(function (key) { return [key, LABELS[key][0], LABELS[key][1]] })
94
-
95
- // 静默时段:开始/结束时间 + 最右侧开关,并实时显示"当前是否静默、下次切换"
96
- function parseQuiet(value) {
97
- const text = String(value || "23:30-07:00")
98
- const parts = text.split("-")
99
- const ok = parts.length === 2 && /^\d{1,2}:\d{2}$/.test(parts[0].trim()) && /^\d{1,2}:\d{2}$/.test(parts[1].trim())
100
- return ok ? [parts[0].trim(), parts[1].trim()] : ["23:30", "07:00"]
101
- }
102
- function minutesOf(text) { const p = text.split(":"); return Number(p[0]) * 60 + Number(p[1]) }
103
- function quietStatus(value) {
104
- const pair = parseQuiet(value)
105
- const start = minutesOf(pair[0])
106
- const end = minutesOf(pair[1])
107
- const now = new Date()
108
- const mins = now.getHours() * 60 + now.getMinutes()
109
- const inQuiet = start <= end ? (mins >= start && mins < end) : (mins >= start || mins < end)
110
- const next = inQuiet ? end : start
111
- const label = String(Math.floor(next / 60)).padStart(2, "0") + ":" + String(next % 60).padStart(2, "0")
112
- return { inQuiet, label }
113
- }
114
-
115
- const NUMBERS = [
116
- ["chatter_batch","攒够几条触发判断",1,30], ["chatter_max_s","最长等待(秒)",5,600],
117
- ["chatter_cooldown_s","判断后冷却(秒)",0,1800], ["bot_say_memory_s","「最近说过」记忆(秒)",30,3600],
118
- ["stuck_turn_s","回合卡死判定(秒)",30,1800], ["ack_delay_s","迟到提示延迟(秒)",0,120],
119
- ["debounce_ms","连发合并(毫秒)",0,5000], ["max_chars","单条最大字数",200,4000],
120
- ["image_max_mb","图片上限(MB)",1,20], ["rate_limit_per_hour","每会话每小时上限(0=不限)",0,240],
121
- ["stream_interval_ms","流式节流(毫秒)",50,2000], ["quote_context_chars","引用原文上限(字)",50,2000],
122
- ["pool_ttl_s","消息池保留(秒)",60,86400], ["pool_max","消息池上限(条)",10,1000],
123
- ]
124
-
125
- const TEXTS = [
126
- ["group_allowlist","群白名单(openid,逗号分隔)"],
127
- ["c2c_allowlist","私聊白名单(同上)"], ["bot_aliases","群内别名(逗号分隔)"],
128
- ["appid","APPID(留空=用 config.json)"],
129
- ["appsecret","APPSECRET(留空=不变,需重启)"],
130
- ["auto_group_root","自动分组根目录(如 D:\\dsh-qqbot-temp)"],
131
- ,
132
- ]
133
-
134
- function QQBridgePage() {
135
- const [state, setState] = React.useState(null)
136
- const [draft, setDraft] = React.useState({})
137
- const [message, setMessage] = React.useState("")
138
- const [busy, setBusy] = React.useState(false)
139
- const [logs, setLogs] = React.useState([])
140
- const [paused, setPaused] = React.useState(false)
141
- const [follow, setFollow] = React.useState(true)
142
- const logRef = React.useRef(null)
143
- React.useEffect(function () {
144
- const node = logRef.current
145
- if (node && follow) node.scrollTop = node.scrollHeight
146
- }, [logs, follow])
147
-
148
- const call = React.useCallback(async function (path, options) {
149
- const response = await fetch(PANEL + path, Object.assign({ headers: { "content-type": "application/json" } }, options || {}))
150
- return await response.json()
151
- }, [])
152
-
153
- const load = React.useCallback(async function () {
154
- try { setState(await call("/api/state")) } catch (error) { setState({ offline: true }) }
155
- }, [call])
156
-
157
- React.useEffect(function () { load() }, [load])
158
- React.useEffect(function () {
159
- const timer = setInterval(load, 8000)
160
- return function () { clearInterval(timer) }
161
- }, [load])
162
- React.useEffect(function () {
163
- if (paused) return undefined
164
- let stop = false
165
- const tick = async function () {
166
- try {
167
- const data = await call("/api/logs?lines=200")
168
- if (!stop) setLogs(Array.isArray(data.lines) ? data.lines : [])
169
- } catch (error) {
170
- if (!stop) setLogs(["(日志服务不可达)"])
171
- }
172
- }
173
- tick()
174
- const timer = setInterval(tick, 3000)
175
- return function () { stop = true; clearInterval(timer) }
176
- }, [call, paused])
177
-
178
- if (state !== null && state.offline) {
179
- return h("div", { style: T.page }, h("div", { style: T.inner },
180
- h("div", { style: T.title }, "机器人的设置服务没有运行"),
181
- h("div", { style: T.hint }, "用 bot\\run-bot.bat 启动一次(或 python -u main.py --supervise),再点重试。"),
182
- h("div", { style: T.actions }, h("button", { style: T.btn, onClick: load }, "重试"))))
183
- }
184
- if (state === null) return h("div", { style: T.page }, h("div", { style: T.inner }, h("div", { style: T.hint }, "读取中…")))
185
-
186
- const config = state.config || {}
187
- const bot = state.bot || {}
188
- const value = function (key) { return key in draft ? draft[key] : config[key] }
189
- const setValue = function (key, next) { const copy = Object.assign({}, draft); copy[key] = next; setDraft(copy) }
190
- const save = async function () {
191
- setBusy(true)
192
- try {
193
- const result = await call("/api/config", { method: "POST", body: JSON.stringify(draft) })
194
- const unknown = Array.isArray(result.unknown) ? result.unknown : []
195
- setDraft({})
196
- setMessage(unknown.length === 0 ? "已保存" : "部分未生效(键不在运行进程里):" + unknown.join(", ") + " —— 需要重启机器人进程")
197
- await load()
198
- }
199
- catch (error) { setMessage("保存失败") }
200
- setBusy(false)
201
- }
202
- const manage = async function (action) {
203
- setBusy(true)
204
- try { const result = await call("/api/manage", { method: "POST", body: JSON.stringify({ action: action }) }); setMessage(result.message || action); await load() }
205
- catch (error) { setMessage("操作失败") }
206
- setBusy(false)
207
- }
208
- const dot = function (ok) {
209
- 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
- }
211
-
212
- return h("div", { style: T.page },
213
- h("div", { style: T.inner },
214
- h("div", { style: T.actions },
215
- h("span", { style: T.badge }, dot(!!bot.running), "进程 · " + (bot.running ? "运行中" : "已停止")),
216
- h("span", { style: T.badge }, dot(!!bot.online), "在线 · " + (bot.online ? "是" : "否")),
217
- h("span", { style: T.badge }, dot(state.bridge === "ready"), "桥接 · " + (state.bridge || "?")),
218
- bot.pid ? h("span", { style: T.hint }, "pid " + bot.pid) : null),
219
- message ? h("div", { style: T.hint }, message) : null,
220
- h("div", { style: T.actions },
221
- h("button", { style: Object.assign({}, T.btn, T.btnPrimary), disabled: busy, onClick: function () { manage("start") } }, "启动"),
222
- h("button", { style: T.btn, disabled: busy, onClick: function () { manage("restart") } }, "重启"),
223
- h("button", { style: T.btn, disabled: busy, onClick: function () { manage("stop") } }, "关闭(不拉起)"),
224
- h("button", { style: T.btn, onClick: function () { window.open("https://q.qq.com/qqbot/", "_blank", "noopener") } }, "QQ 开放平台"),
225
- h("button", {
226
- style: T.btn,
227
- onClick: async function () {
228
- const target = String(config.auto_group_root || "D:\\dsh-qqbot-temp")
229
- try {
230
- const result = await call("/api/open-folder", { method: "POST", body: JSON.stringify({ path: target }) })
231
- setMessage(result.ok ? "已打开 " + target : "打不开:" + (result.error || target))
232
- } catch (error) {
233
- setMessage("打不开:" + target)
234
- }
235
- },
236
- }, "打开分组文件夹")),
237
- h("div", { style: T.sectionTitle }, "开关"),
238
- SWITCHES.map(function (item) {
239
- return h(Row, { key: item[0], title: item[1], hint: item[2] },
240
- h(Switch, { checked: !!value(item[0]), label: item[1], disabled: busy, onChange: function (next) { setValue(item[0], next) } }))
241
- }),
242
- h("div", { style: T.sectionTitle }, "群聊节奏与发送"),
243
- h(QuietRow, {
244
- key: "quiet-hours",
245
- value: value("quiet_hours"),
246
- checked: !!value("quiet_enabled"),
247
- disabled: busy,
248
- onChange: function (next) { setValue("quiet_hours", next) },
249
- onChange2: function (next) { setValue("quiet_enabled", next) },
250
- }),
251
- NUMBERS.map(function (item) {
252
- return h(Row, { key: item[0], title: item[1] },
253
- h("input", {
254
- type: "number", min: item[2], max: item[3], style: T.input,
255
- value: value(item[0]) === undefined ? "" : value(item[0]),
256
- onChange: function (event) { setValue(item[0], Number(event.target.value)) },
257
- }))
258
- }),
259
- h(ModeRow, {
260
- key: "group-mode",
261
- value: value("group_mode"),
262
- disabled: busy,
263
- onChange: function (next) { setValue("group_mode", next) },
264
- }), h("div", { style: T.sectionTitle }, "过滤与凭据"),
265
- TEXTS.map(function (item) {
266
- return h(Row, { key: item[0], title: item[1] },
267
- h("input", {
268
- type: item[0].indexOf("secret") >= 0 ? "password" : "text",
269
- placeholder: "不改", style: Object.assign({}, T.input, T.inputWide),
270
- value: value(item[0]) === undefined ? "" : value(item[0]),
271
- onChange: function (event) { setValue(item[0], event.target.value) },
272
- }))
273
- }),
274
- h("div", { style: T.actions },
275
- h("button", { style: Object.assign({}, T.btn, T.btnPrimary), disabled: busy, onClick: save }, "保存设置"),
276
- h("button", { style: T.btn, disabled: busy, onClick: function () { setDraft({}); load() } }, "重新读取")),
277
- h("div", { style: T.sectionTitle }, "运行日志(最近 200 行)"),
278
- h("div", { style: T.actions },
279
- h("button", { style: T.btn, onClick: function () { setPaused(!paused) } }, paused ? "继续刷新" : "暂停刷新"),
280
- h("button", {
281
- style: Object.assign({}, T.btn, follow ? { borderColor: "var(--dsw-alias-state-business-primary, #2f6bff)", color: "var(--dsw-alias-state-business-primary, #2f6bff)" } : {}),
282
- onClick: function () { setFollow(!follow) },
283
- }, follow ? "跟随中" : "已暂停跟随"),
284
- h("button", { style: T.btn, onClick: function () { setLogs([]) } }, "清屏")),
285
- h("pre", {
286
- style: T.log,
287
- ref: logRef,
288
- onScroll: function (event) {
289
- const node = event.target
290
- // 手动往上翻就暂停跟随;回到底部自动恢复
291
- setFollow(node.scrollHeight - node.scrollTop - node.clientHeight < 24)
292
- },
293
- }, logs.join("\n") || "(暂无日志)")
294
- ))
295
- }
296
-
297
- function QuietRow(props) {
298
- const value = String(props.value || "23:30-07:00")
299
- const pair = parseQuiet(value)
300
- const status = quietStatus(value)
301
- const setRange = function (index, next) {
302
- const parts = parseQuiet(value).slice()
303
- parts[index] = next || parts[index]
304
- props.onChange(parts[0] + "-" + parts[1])
305
- }
306
- const timeInput = function (index, label) {
307
- return h("span", { style: { display: "inline-flex", alignItems: "center", gap: 6 } },
308
- h("span", { style: T.hint }, label),
309
- h("input", {
310
- type: "time", value: pair[index], style: Object.assign({}, T.input, { width: 108, textAlign: "center" }),
311
- onChange: function (event) { setRange(index, event.target.value) },
312
- }))
313
- }
314
- return h("div", { style: Object.assign({}, T.row, { alignItems: "flex-start" }) },
315
- h("div", { style: T.labelBox },
316
- h("span", { style: T.title }, "静默时段(晚间群聊闲聊不回)"),
317
- h("span", { style: T.hint }, "按本机时间:静默时段内群里不主动插话,@ 与私聊照常回复"),
318
- h("span", { style: T.hint }, (status.inQuiet ? "当前为静默" : "当前不在静默") + " · 下次切换 " + status.label),
319
- h("div", { style: Object.assign({}, T.actions, { marginTop: 8 }) },
320
- timeInput(0, "开始"), h("span", { style: T.hint }, "至"), timeInput(1, "结束"))),
321
- h(Switch, { checked: !!props.checked, label: "静默时段生效", disabled: props.disabled, onChange: props.onChange2 }))
322
- }
323
-
324
- // 群聊主动消息模式:下拉式二选一(方案 A / 方案 B)
325
- function ModeRow(props) {
326
- const current = String(props.value || "A").toUpperCase() === "B" ? "B" : "A"
327
- const options = [
328
- ["A", "方案 A", "群里先攒几条消息,再由主会话判断要不要说话;跟它已有的对话上下文连着,插话会更自然。"],
329
- ["B", "方案 B", "用一个独立的判断会话先决定“说 / 不说”;决定要说时,把群聊记录原样交给主模型。判断与主对话隔离。"],
330
- ]
331
- const pill = function (key, label, hint) {
332
- const active = current === key
333
- return h("button", {
334
- key: key,
335
- type: "button",
336
- disabled: props.disabled,
337
- onClick: function () { props.onChange(key) },
338
- style: {
339
- padding: "6px 16px", borderRadius: 999, cursor: props.disabled ? "default" : "pointer", font: "inherit",
340
- border: "1px solid " + (active ? "var(--dsw-alias-label-primary, #fff)" : "var(--dsw-alias-border-l2)"),
341
- background: active ? "var(--dsw-alias-label-primary, #fff)" : "transparent",
342
- color: active ? "var(--dsw-alias-bg-layer-3, #1b1d23)" : "var(--dsw-alias-label-secondary)",
343
- },
344
- }, label)
345
- }
346
- const pick = options.filter(function (item) { return item[0] === current })[0]
347
- return h("div", { style: Object.assign({}, T.row, { alignItems: "flex-start" }) },
348
- h("div", { style: T.labelBox },
349
- h("span", { style: T.title }, "群聊主动消息模式"),
350
- h("span", { style: T.hint }, pick[2])),
351
- h("div", { style: Object.assign({}, T.actions, { flex: "0 0 auto" }) },
352
- options.map(function (item) { return pill(item[0], item[1], item[2]) })))
353
- }
354
-
355
- function SidebarIcon() {
356
- return h("span", { "aria-hidden": "true", style: { fontSize: 15, lineHeight: 1 } }, "🐟")
357
- }
358
-
359
- exports.inject = ["slots"]
360
- exports.apply = function apply(ctx) {
361
- ctx.slots.inject("sidebar.panellist", function () {
362
- const unregister = ctx.slots.register({ name: "sidebar.panellist", id: "qq-bridge", order: 120, label: function () { return "QQ 机器人" } }, SidebarIcon)
363
- return function () { unregister() }
364
- })
365
- ctx.slots.inject("main", function () {
366
- const unregister = ctx.slots.register({ name: "main", key: "qq-bridge", order: 120, label: function () { return "QQ 机器人" } }, QQBridgePage)
367
- return function () { unregister() }
368
- })
369
- }
370
- return module.exports
371
- },
372
- })
1
+ /**
2
+ * dsh-qq-bridge 的浏览器半身:左侧导航栏「QQ 机器人」+ 整页设置/日志。
3
+ * 全部改用内联样式:宿主 main 槽位不在同一个样式作用域,注入 <style> 不可靠。
4
+ */
5
+ window.__ModuleLoader__.load({
6
+ id: "dsh-qq-bridge",
7
+ factory: (require) => {
8
+ var module = { exports: {} }
9
+ var exports = module.exports
10
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
11
+
12
+ const React = require("react")
13
+ const h = React.createElement
14
+ const PANEL = "http://127.0.0.1:39062"
15
+ // 安装器在宿主插件里(Node 侧),不在机器人面板
16
+ const BRIDGE = "http://127.0.0.1:39061"
17
+
18
+ const T = {
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)" },
20
+ inner: {
21
+ width: "100%", maxWidth: 720, margin: "0 auto", display: "grid", gap: 14,
22
+ // 磨砂玻璃底:页面浮在背景图之上时保证文字可读
23
+ padding: "20px 22px", borderRadius: 16,
24
+ border: "1px solid var(--dsw-alias-border-l2, rgba(255,255,255,0.14))",
25
+ backgroundColor: "rgba(22, 24, 30, 0.62)",
26
+ background: "color-mix(in srgb, var(--dsw-alias-bg-base, #14161c) 72%, transparent)",
27
+ backdropFilter: "blur(18px) saturate(130%)",
28
+ WebkitBackdropFilter: "blur(18px) saturate(130%)",
29
+ boxShadow: "0 10px 30px rgba(0,0,0,0.24)",
30
+ },
31
+ row: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, padding: "9px 0", borderTop: "1px solid var(--dsw-alias-border-l2)" },
32
+ labelBox: { display: "grid", gap: 2, minWidth: 0 },
33
+ title: { fontSize: 13, color: "var(--dsw-alias-label-primary)" },
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" },
72
+ sectionTitle: { fontSize: 12, letterSpacing: "0.04em", color: "var(--dsw-alias-label-tertiary)", margin: "10px 0 2px" },
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" },
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" },
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" },
77
+ btnPrimary: { background: "var(--dsw-alias-label-primary)", borderColor: "var(--dsw-alias-label-primary)", color: "var(--dsw-alias-bg-layer-3)" },
78
+ actions: { display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" },
79
+ badge: { display: "inline-flex", alignItems: "center", gap: 6, padding: "3px 9px", border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 999, fontSize: 12, color: "var(--dsw-alias-label-secondary)" },
80
+ dot: { width: 7, height: 7, borderRadius: "50%" },
81
+ log: { margin: 0, maxHeight: 300, overflow: "auto", padding: 10, border: "1px solid var(--dsw-alias-border-l2)", borderRadius: 6, background: "var(--dsw-alias-bg-layer-3)", color: "var(--dsw-alias-label-secondary)", font: "12px/1.5 ui-monospace, Consolas, monospace", whiteSpace: "pre-wrap" },
82
+ }
83
+
84
+ function Switch(props) {
85
+ return h("button", {
86
+ type: "button", role: "switch", "aria-checked": props.checked ? "true" : "false",
87
+ "aria-label": props.label, disabled: props.disabled,
88
+ onClick: function () { props.onChange(!props.checked) },
89
+ style: {
90
+ position: "relative", flex: "0 0 auto", width: 38, height: 22, padding: 2, border: 0,
91
+ borderRadius: 999, cursor: props.disabled ? "default" : "pointer", boxSizing: "border-box",
92
+ // 用官方语义色:开启=业务主色,关闭=边框 L3(不再用不存在的 brand-primary 导致发白)
93
+ background: props.checked
94
+ ? "var(--dsw-alias-state-business-primary, #2f6bff)"
95
+ : "var(--dsw-alias-border-l3, #5a6270)",
96
+ boxShadow: props.checked ? "inset 0 0 0 1px rgba(255,255,255,0.12)" : "none",
97
+ opacity: props.disabled ? 0.5 : 1,
98
+ },
99
+ }, h("span", {
100
+ "aria-hidden": "true",
101
+ style: {
102
+ display: "block", width: 18, height: 18, borderRadius: "50%",
103
+ background: props.checked ? "#fff" : "var(--dsw-alias-switch-thumb, #c9ccd6)",
104
+ transform: props.checked ? "translateX(16px)" : "none", transition: "transform 120ms ease",
105
+ },
106
+ }))
107
+ }
108
+
109
+ function Row(props) {
110
+ return h("div", { style: T.row },
111
+ h("div", { style: T.labelBox },
112
+ h("span", { style: T.title }, props.title),
113
+ props.hint ? h("span", { style: T.hint }, props.hint) : null),
114
+ props.children)
115
+ }
116
+
117
+ const LABELS = {
118
+ enabled: ["接收消息(总)", "关掉后私聊与群聊都不响应"],
119
+ c2c_enabled: ["私聊响应", ""],
120
+ group_enabled: ["群聊响应", ""],
121
+ group_full_mode: ["群全量消息", "需在开放平台开启全量接收"],
122
+ group_at_only: ["群聊只处理 @ 我的消息", "开启后群里的普通发言一律丢弃(仅在拿到全量消息时才需要)"],
123
+ md_auto: ["Markdown 自动发送", "回复像 Markdown 时用 msg_type=2"],
124
+ stream_enabled: ["流式输出(仅私聊)", "平台只在单聊支持流式"],
125
+ ack_enabled: ["“还在处理”占位提示", "会打断流式输出,默认关"],
126
+ quote_enabled: ["识别引用消息", "引用时把被引用原文和来源一起带给模型"],
127
+ capture_enabled: ["允许截屏", "/截图、/窗口 是否可用"],
128
+ auto_group: ["自动分组(每个会话独立工作区)", "关闭则所有会话共用同一个工作目录"],
129
+ approval_inline_redraw: ["审批按钮就地重绘为“已允许”", "关闭后退回旧行为:额外发一条结论文字 + “已处理”卡片"],
130
+ kick_confirm: ["踢人二次审批", "开启后踢人前先在你的私聊弹一张确认卡片,点了才执行"],
131
+ interject_hook_only: ["插话只要命中钩子才判断", "开启后只有被点名/带问号/提到别名/长时间冷场才花一次判断;关闭则每攒够几条就判一次"],
132
+ judge_score_output: ["判断用打分制", "让模型先给 0~3 分的开口意愿,再按阈值决定发不发"],
133
+ persona_enabled: ["启用人设", "只在新会话的第一条消息里发一次;会话已有历史就不再重复"],
134
+ }
135
+
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"]
137
+ .map(function (key) { return [key, LABELS[key][0], LABELS[key][1]] })
138
+
139
+ // 静默时段:开始/结束时间 + 最右侧开关,并实时显示"当前是否静默、下次切换"
140
+ function parseQuiet(value) {
141
+ const text = String(value || "23:30-07:00")
142
+ const parts = text.split("-")
143
+ const ok = parts.length === 2 && /^\d{1,2}:\d{2}$/.test(parts[0].trim()) && /^\d{1,2}:\d{2}$/.test(parts[1].trim())
144
+ return ok ? [parts[0].trim(), parts[1].trim()] : ["23:30", "07:00"]
145
+ }
146
+ function minutesOf(text) { const p = text.split(":"); return Number(p[0]) * 60 + Number(p[1]) }
147
+ function quietStatus(value) {
148
+ const pair = parseQuiet(value)
149
+ const start = minutesOf(pair[0])
150
+ const end = minutesOf(pair[1])
151
+ const now = new Date()
152
+ const mins = now.getHours() * 60 + now.getMinutes()
153
+ const inQuiet = start <= end ? (mins >= start && mins < end) : (mins >= start || mins < end)
154
+ const next = inQuiet ? end : start
155
+ const label = String(Math.floor(next / 60)).padStart(2, "0") + ":" + String(next % 60).padStart(2, "0")
156
+ return { inQuiet, label }
157
+ }
158
+
159
+ const NUMBERS = [
160
+ ["chatter_batch","攒够几条触发判断",1,30], ["chatter_max_s","最长等待(秒)",5,600],
161
+ ["chatter_cooldown_s","判断后冷却(秒)",0,1800], ["bot_say_memory_s","「最近说过」记忆(秒)",30,3600],
162
+ ["stuck_turn_s","回合卡死判定(秒)",30,1800], ["ack_delay_s","迟到提示延迟(秒)",0,120],
163
+ ["debounce_ms","连发合并(毫秒)",0,5000], ["max_chars","单条最大字数",200,4000],
164
+ ["image_max_mb","图片上限(MB)",1,20], ["rate_limit_per_hour","每会话每小时上限(0=不限)",0,240],
165
+ ["stream_interval_ms","流式节流(毫秒)",50,2000], ["quote_context_chars","引用原文上限(字)",50,2000],
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],
172
+ ]
173
+
174
+ const TEXTS = [
175
+ ["group_allowlist","群白名单(openid,逗号分隔)"],
176
+ ["c2c_allowlist","私聊白名单(同上)"], ["bot_aliases","群内别名(逗号分隔)"],
177
+ ["appid","APPID(留空=用 config.json)"],
178
+ ["appsecret","APPSECRET(留空=不变,需重启)"],
179
+ ["auto_group_root","自动分组根目录(如 D:\\dsh-qqbot-temp)"],
180
+ ,
181
+ ]
182
+
183
+ function QQBridgePage() {
184
+ const [state, setState] = React.useState(null)
185
+ const [draft, setDraft] = React.useState({})
186
+ const [message, setMessage] = React.useState("")
187
+ const [busy, setBusy] = React.useState(false)
188
+ const [logs, setLogs] = React.useState([])
189
+ const [paused, setPaused] = React.useState(false)
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("")
202
+ const logRef = React.useRef(null)
203
+ React.useEffect(function () {
204
+ const node = logRef.current
205
+ if (node && follow) node.scrollTop = node.scrollHeight
206
+ }, [logs, follow])
207
+
208
+ const call = React.useCallback(async function (path, options) {
209
+ const response = await fetch(PANEL + path, Object.assign({ headers: { "content-type": "application/json" } }, options || {}))
210
+ return await response.json()
211
+ }, [])
212
+
213
+ const load = React.useCallback(async function () {
214
+ try { setState(await call("/api/state")) } catch (error) { setState({ offline: true }) }
215
+ }, [call])
216
+
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])
270
+ React.useEffect(function () {
271
+ const timer = setInterval(load, 8000)
272
+ return function () { clearInterval(timer) }
273
+ }, [load])
274
+ React.useEffect(function () {
275
+ if (paused) return undefined
276
+ let stop = false
277
+ const tick = async function () {
278
+ try {
279
+ const data = await call("/api/logs?lines=200")
280
+ if (!stop) setLogs(Array.isArray(data.lines) ? data.lines : [])
281
+ } catch (error) {
282
+ if (!stop) setLogs(["(日志服务不可达)"])
283
+ }
284
+ }
285
+ tick()
286
+ const timer = setInterval(tick, 3000)
287
+ return function () { stop = true; clearInterval(timer) }
288
+ }, [call, paused])
289
+
290
+ if (state !== null && state.offline) {
291
+ return h("div", { style: T.page },
292
+ h("div", { style: T.inner },
293
+ h("div", { style: T.title }, "机器人的设置服务没有运行"),
294
+ h("div", { style: T.hint }, "用 bot\\run-bot.bat 启动一次(或 python -u main.py --supervise),再点重试。"),
295
+ h("div", { style: T.actions }, h("button", { style: T.btn, onClick: load }, "重试"))))
296
+ }
297
+ if (state === null) return h("div", { style: T.page }, h("div", { style: T.inner }, h("div", { style: T.hint }, "读取中…")))
298
+
299
+ const config = state.config || {}
300
+ const bot = state.bot || {}
301
+ const value = function (key) { return key in draft ? draft[key] : config[key] }
302
+ const setValue = function (key, next) { const copy = Object.assign({}, draft); copy[key] = next; setDraft(copy) }
303
+ const save = async function () {
304
+ setBusy(true)
305
+ try {
306
+ const result = await call("/api/config", { method: "POST", body: JSON.stringify(draft) })
307
+ const unknown = Array.isArray(result.unknown) ? result.unknown : []
308
+ setDraft({})
309
+ setMessage(unknown.length === 0 ? "已保存" : "部分未生效(键不在运行进程里):" + unknown.join(", ") + " —— 需要重启机器人进程")
310
+ await load()
311
+ }
312
+ catch (error) { setMessage("保存失败") }
313
+ setBusy(false)
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
+
334
+ const manage = async function (action) {
335
+ setBusy(true)
336
+ try { const result = await call("/api/manage", { method: "POST", body: JSON.stringify({ action: action }) }); setMessage(result.message || action); await load() }
337
+ catch (error) { setMessage("操作失败") }
338
+ setBusy(false)
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
+ }
782
+ const dot = function (ok) {
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)" }) })
784
+ }
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
+
813
+ return h("div", { style: T.page },
814
+ h("style", { key: "qq-scroll-css" }, SCROLLBAR_CSS),
815
+ h("div", { style: T.inner },
816
+ tabBar,
817
+ h("div", { style: T.actions },
818
+ h("span", { style: T.badge }, dot(!!bot.running), "进程 · " + (bot.running ? "运行中" : "已停止")),
819
+ h("span", { style: T.badge }, dot(!!bot.online), "在线 · " + (bot.online ? "是" : "否")),
820
+ h("span", { style: T.badge }, dot(state.bridge === "ready"), "桥接 · " + (state.bridge || "?")),
821
+ bot.pid ? h("span", { style: T.hint }, "pid " + bot.pid) : null),
822
+ message ? h("div", { style: T.hint }, message) : null,
823
+ h("div", { style: T.actions },
824
+ h("button", { style: Object.assign({}, T.btn, T.btnPrimary), disabled: busy, onClick: function () { manage("start") } }, "启动"),
825
+ h("button", { style: T.btn, disabled: busy, onClick: function () { manage("restart") } }, "重启"),
826
+ h("button", { style: T.btn, disabled: busy, onClick: function () { manage("stop") } }, "关闭(不拉起)"),
827
+ h("button", { style: T.btn, onClick: function () { window.open("https://q.qq.com/qqbot/", "_blank", "noopener") } }, "QQ 开放平台"),
828
+ h("button", {
829
+ style: T.btn,
830
+ onClick: async function () {
831
+ const target = String(config.auto_group_root || "D:\\dsh-qqbot-temp")
832
+ try {
833
+ const result = await call("/api/open-folder", { method: "POST", body: JSON.stringify({ path: target }) })
834
+ setMessage(result.ok ? "已打开 " + target : "打不开:" + (result.error || target))
835
+ } catch (error) {
836
+ setMessage("打不开:" + target)
837
+ }
838
+ },
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),
866
+ h("div", { style: T.sectionTitle }, "开关"),
867
+ SWITCHES.map(function (item) {
868
+ return h(Row, { key: item[0], title: item[1], hint: item[2] },
869
+ h(Switch, { checked: !!value(item[0]), label: item[1], disabled: busy, onChange: function (next) { setValue(item[0], next) } }))
870
+ }),
871
+ h("div", { style: T.sectionTitle }, "人设(只在新会话的第一条消息里发一次)"),
872
+ personaBox("persona_group", "群聊人设", "群聊里带的人设;留空=不启用"),
873
+ personaBox("persona_c2c", "私聊人设", "单聊里带的人设;留空=不启用"),
874
+ h("div", { style: T.sectionTitle }, "群聊节奏与发送"),
875
+ h(QuietRow, {
876
+ key: "quiet-hours",
877
+ value: value("quiet_hours"),
878
+ checked: !!value("quiet_enabled"),
879
+ disabled: busy,
880
+ onChange: function (next) { setValue("quiet_hours", next) },
881
+ onChange2: function (next) { setValue("quiet_enabled", next) },
882
+ }),
883
+ NUMBERS.map(function (item) {
884
+ return h(Row, { key: item[0], title: item[1] },
885
+ h("input", {
886
+ type: "number", min: item[2], max: item[3], style: T.input,
887
+ value: value(item[0]) === undefined ? "" : value(item[0]),
888
+ onChange: function (event) { setValue(item[0], Number(event.target.value)) },
889
+ }))
890
+ }),
891
+ h(ModeRow, {
892
+ key: "group-mode",
893
+ value: value("group_mode"),
894
+ disabled: busy,
895
+ onChange: function (next) { setValue("group_mode", next) },
896
+ }), h("div", { style: T.sectionTitle }, "过滤与凭据"),
897
+ TEXTS.map(function (item) {
898
+ return h(Row, { key: item[0], title: item[1] },
899
+ h("input", {
900
+ type: item[0].indexOf("secret") >= 0 ? "password" : "text",
901
+ placeholder: "不改", style: Object.assign({}, T.input, T.inputWide),
902
+ value: value(item[0]) === undefined ? "" : value(item[0]),
903
+ onChange: function (event) { setValue(item[0], event.target.value) },
904
+ }))
905
+ }),
906
+ h("div", { style: T.actions },
907
+ h("button", { style: Object.assign({}, T.btn, T.btnPrimary), disabled: busy, onClick: save }, "保存设置"),
908
+ h("button", { style: T.btn, disabled: busy, onClick: function () { setDraft({}); load() } }, "重新读取")),
909
+ h("div", { style: T.sectionTitle }, "运行日志(最近 200 行)"),
910
+ h("div", { style: T.actions },
911
+ h("button", { style: T.btn, onClick: function () { setPaused(!paused) } }, paused ? "继续刷新" : "暂停刷新"),
912
+ h("button", {
913
+ style: Object.assign({}, T.btn, follow ? { borderColor: "var(--dsw-alias-state-business-primary, #2f6bff)", color: "var(--dsw-alias-state-business-primary, #2f6bff)" } : {}),
914
+ onClick: function () { setFollow(!follow) },
915
+ }, follow ? "跟随中" : "已暂停跟随"),
916
+ h("button", { style: T.btn, onClick: function () { setLogs([]) } }, "清屏")),
917
+ h("pre", {
918
+ style: T.log,
919
+ ref: logRef,
920
+ onScroll: function (event) {
921
+ const node = event.target
922
+ // 手动往上翻就暂停跟随;回到底部自动恢复
923
+ setFollow(node.scrollHeight - node.scrollTop - node.clientHeight < 24)
924
+ },
925
+ }, logs.join("\n") || "(暂无日志)")
926
+ ))
927
+ }
928
+
929
+ function QuietRow(props) {
930
+ const value = String(props.value || "23:30-07:00")
931
+ const pair = parseQuiet(value)
932
+ const status = quietStatus(value)
933
+ const setRange = function (index, next) {
934
+ const parts = parseQuiet(value).slice()
935
+ parts[index] = next || parts[index]
936
+ props.onChange(parts[0] + "-" + parts[1])
937
+ }
938
+ const timeInput = function (index, label) {
939
+ return h("span", { style: { display: "inline-flex", alignItems: "center", gap: 6 } },
940
+ h("span", { style: T.hint }, label),
941
+ h("input", {
942
+ type: "time", value: pair[index], style: Object.assign({}, T.input, { width: 108, textAlign: "center" }),
943
+ onChange: function (event) { setRange(index, event.target.value) },
944
+ }))
945
+ }
946
+ return h("div", { style: Object.assign({}, T.row, { alignItems: "flex-start" }) },
947
+ h("div", { style: T.labelBox },
948
+ h("span", { style: T.title }, "静默时段(晚间群聊闲聊不回)"),
949
+ h("span", { style: T.hint }, "按本机时间:静默时段内群里不主动插话,@ 与私聊照常回复"),
950
+ h("span", { style: T.hint }, (status.inQuiet ? "当前为静默" : "当前不在静默") + " · 下次切换 " + status.label),
951
+ h("div", { style: Object.assign({}, T.actions, { marginTop: 8 }) },
952
+ timeInput(0, "开始"), h("span", { style: T.hint }, "至"), timeInput(1, "结束"))),
953
+ h(Switch, { checked: !!props.checked, label: "静默时段生效", disabled: props.disabled, onChange: props.onChange2 }))
954
+ }
955
+
956
+ // 群聊主动消息模式:下拉式二选一(方案 A / 方案 B)
957
+ function ModeRow(props) {
958
+ const current = String(props.value || "A").toUpperCase() === "B" ? "B" : "A"
959
+ const options = [
960
+ ["A", "方案 A", "群里先攒几条消息,再由主会话判断要不要说话;跟它已有的对话上下文连着,插话会更自然。"],
961
+ ["B", "方案 B", "用一个独立的判断会话先决定“说 / 不说”;决定要说时,把群聊记录原样交给主模型。判断与主对话隔离。"],
962
+ ]
963
+ const pill = function (key, label, hint) {
964
+ const active = current === key
965
+ return h("button", {
966
+ key: key,
967
+ type: "button",
968
+ disabled: props.disabled,
969
+ onClick: function () { props.onChange(key) },
970
+ style: {
971
+ padding: "6px 16px", borderRadius: 999, cursor: props.disabled ? "default" : "pointer", font: "inherit",
972
+ border: "1px solid " + (active ? "var(--dsw-alias-label-primary, #fff)" : "var(--dsw-alias-border-l2)"),
973
+ background: active ? "var(--dsw-alias-label-primary, #fff)" : "transparent",
974
+ color: active ? "var(--dsw-alias-bg-layer-3, #1b1d23)" : "var(--dsw-alias-label-secondary)",
975
+ },
976
+ }, label)
977
+ }
978
+ const pick = options.filter(function (item) { return item[0] === current })[0]
979
+ return h("div", { style: Object.assign({}, T.row, { alignItems: "flex-start" }) },
980
+ h("div", { style: T.labelBox },
981
+ h("span", { style: T.title }, "群聊主动消息模式"),
982
+ h("span", { style: T.hint }, pick[2])),
983
+ h("div", { style: Object.assign({}, T.actions, { flex: "0 0 auto" }) },
984
+ options.map(function (item) { return pill(item[0], item[1], item[2]) })))
985
+ }
986
+
987
+ function SidebarIcon() {
988
+ return h("span", { "aria-hidden": "true", style: { fontSize: 15, lineHeight: 1 } }, "🐟")
989
+ }
990
+
991
+ exports.inject = ["slots"]
992
+ exports.apply = function apply(ctx) {
993
+ ctx.slots.inject("sidebar.panellist", function () {
994
+ const unregister = ctx.slots.register({ name: "sidebar.panellist", id: "qq-bridge", order: 120, label: function () { return "QQ 机器人" } }, SidebarIcon)
995
+ return function () { unregister() }
996
+ })
997
+ ctx.slots.inject("main", function () {
998
+ const unregister = ctx.slots.register({ name: "main", key: "qq-bridge", order: 120, label: function () { return "QQ 机器人" } }, QQBridgePage)
999
+ return function () { unregister() }
1000
+ })
1001
+ }
1002
+ return module.exports
1003
+ },
1004
+ })