@morgan9668/dsh-llm-gateway 1.2.1 → 1.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/client.js ADDED
@@ -0,0 +1,1202 @@
1
+ /**
2
+ * @morgan9668/dsh-llm-gateway — 浏览器半身(设置页 + 闪动覆层)。
3
+ *
4
+ * 三件事必须完全对齐(照 dsh-our-free-model / dsh-task-notify 的可用实现):
5
+ * 1. slot 名是 `settings.section`,用 `id`(不是 key),配 `order` 与 `label`;
6
+ * 2. `inject = ['slots', 'locale']`,数组形式;
7
+ * 3. 模块导出走 `module.exports`,文件末尾 `return module.exports`。
8
+ *
9
+ * 数据读写走插件自己的同源路由 `/api/llm-gateway/*`:这些路由由宿主进程的
10
+ * webServer 提供,和页面同源,不依赖 configForms 那套 scope 绑定。
11
+ *
12
+ * 为什么设置存的是插件自己的文件而不是它的 config:改 config 会让插件
13
+ * reconcile(server.close() 重启),跑到一半的外部客户端请求会被掐断。
14
+ * 见 Host 侧 src/notify/store.js 的说明。
15
+ */
16
+
17
+ window.__ModuleLoader__.load({
18
+ id: '@morgan9668/dsh-llm-gateway',
19
+ factory: require => {
20
+ const module = { exports: {} }
21
+ const exports = module.exports
22
+
23
+ const React = require('react')
24
+ const h = React.createElement
25
+ const { useState, useEffect, useCallback } = React
26
+
27
+ /** 与 Host 的 patch row id 一致。 */
28
+ const NS = 'llm-gateway'
29
+ /** 同源 API 前缀,必须与 index.js 的路由一致。 */
30
+ const API = '/api/llm-gateway'
31
+
32
+ const DICT = {
33
+ // 导航名必须同时覆盖「网关」和「通知」:侧栏里紧挨着还有
34
+ // dsh-task-notify 的「任务完成通知」,只写「DSH 大模型网关」的话,
35
+ // 用户想「不再收到通知」时只会点那一页,在这里永远找不到开关。
36
+ zh: { nav: '网关与通知' },
37
+ en: { nav: 'Gateway & notifications' },
38
+ }
39
+
40
+ /**
41
+ * 闪动的透明度峰值。
42
+ *
43
+ * 不做到 1:整块盖死会让通知期间完全读不了字,用户点开设置页时反而
44
+ * 不知道刚发生了什么。这个值足够一眼看见,又不至于把正文吃掉。
45
+ * 它同时被 keyframes 与「减少动态效果」的静态罩子使用,改这里就够。
46
+ */
47
+ const FLASH_PEAK = 0.72
48
+
49
+ /** 闪动事件里允许的取值边界,与 Host 的 config.js 保持一致。 */
50
+ const LIMITS = {
51
+ flashes: { min: 1, max: 60, fallback: 18 },
52
+ seconds: { min: 1, max: 80, fallback: 6 },
53
+ settle: { min: 0, max: 300, fallback: 12 },
54
+ }
55
+ const DEFAULT_COLOR = '#22c55e'
56
+
57
+ /**
58
+ * 结局的取值与中文名。
59
+ *
60
+ * key 必须与 Host 侧 `src/notify/config.js` 的 REASON_CHOICES 一致——
61
+ * 那边的 REASON_CHOICES 只有 key,这里补上给人看的字。
62
+ */
63
+ const REASON_LABELS = [
64
+ ['completed', '完成'],
65
+ ['error', '失败'],
66
+ ['blocked', '被阻塞'],
67
+ ['max-tokens', '超长截断'],
68
+ ['aborted', '被中止'],
69
+ ]
70
+
71
+ /**
72
+ * 与 Host 侧 normalizeColor 同构的颜色收敛。
73
+ *
74
+ * 客户端也要有一份,因为「输入框里正在打的值」还没经过服务端,而色块
75
+ * 得立刻跟着变。两份规则不一致时表现是:色块亮着、保存后却不生效。
76
+ */
77
+ const COLOR_SHAPES = [
78
+ /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,
79
+ /^(?:rgb|rgba|hsl|hsla)\(\s*[0-9.,%\s/+-]+\)$/i,
80
+ ]
81
+
82
+ function normalizeColor(raw, fallback = DEFAULT_COLOR) {
83
+ const value = typeof raw === 'string' ? raw.trim() : ''
84
+ if (value === '') return fallback
85
+ return COLOR_SHAPES.some(shape => shape.test(value)) ? value.toLowerCase() : fallback
86
+ }
87
+
88
+ /** 把 rgb()/hsl() 折算成六位十六进制,仅用于给 <input type="color"> 定位。 */
89
+ function toHexForPicker(value, fallback = DEFAULT_COLOR) {
90
+ const text = normalizeColor(value, fallback)
91
+ if (/^#[0-9a-f]{3}$/i.test(text)) {
92
+ return `#${text[1]}${text[1]}${text[2]}${text[2]}${text[3]}${text[3]}`.toLowerCase()
93
+ }
94
+ if (/^#[0-9a-f]{6}$/i.test(text)) return text.toLowerCase()
95
+ if (/^#[0-9a-f]{4}$/i.test(text)) {
96
+ return `#${text[1]}${text[1]}${text[2]}${text[2]}${text[3]}${text[3]}`.toLowerCase()
97
+ }
98
+ if (/^#[0-9a-f]{8}$/i.test(text)) return `#${text.slice(1, 7)}`.toLowerCase()
99
+ return fallback
100
+ }
101
+
102
+ const clampInt = (value, min, max, fallback) => {
103
+ const numeric = Number(value)
104
+ if (!Number.isFinite(numeric)) return fallback
105
+ return Math.min(max, Math.max(min, Math.round(numeric)))
106
+ }
107
+
108
+ /* --------------------------- 闪动控制器 --------------------------- */
109
+
110
+ /**
111
+ * 一条闪动事件 → 主线程上一段动画。
112
+ *
113
+ * 单独抽出来是为了让「自动闪动」和设置页的「预览」走完全相同的代码,
114
+ * 免得预览好看、真到回合结束却是另一回事。
115
+ */
116
+ function flashSpec(payload) {
117
+ const flashes = clampInt(payload?.flashes, LIMITS.flashes.min, LIMITS.flashes.max, LIMITS.flashes.fallback)
118
+ const seconds = clampInt(payload?.durationSeconds, LIMITS.seconds.min, LIMITS.seconds.max, LIMITS.seconds.fallback)
119
+ return {
120
+ key: String(payload?.id ?? `${Date.now()}`),
121
+ flashes,
122
+ seconds,
123
+ color: normalizeColor(payload?.color),
124
+ // 总时长均分给每一次:6 秒 18 次 = 每 333ms 一个完整明暗周期。
125
+ periodMs: Math.max(16, Math.round((seconds * 1000) / flashes)),
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 订阅 Host 的闪动事件流,把事件交给当前挂着的 overlay。
131
+ *
132
+ * 这里刻意什么都不渲染:控制器只持有「最近一次闪动」,渲染由 overlay
133
+ * 负责。控制器活得比任何一次设置页开关都久,所以即使用户没打开设置页,
134
+ * 网关请求结束或会话回合结束时也照样会闪。
135
+ */
136
+ function createFlashStore() {
137
+ let current = null
138
+ const listeners = new Set()
139
+
140
+ const publish = () => {
141
+ for (const listener of [...listeners]) {
142
+ try {
143
+ listener(current)
144
+ } catch {
145
+ /* 一个订阅者坏了不该拖垮其它订阅者 */
146
+ }
147
+ }
148
+ }
149
+
150
+ return {
151
+ get() {
152
+ return current
153
+ },
154
+ fire(payload) {
155
+ const next = flashSpec(payload)
156
+ // 同一个 id 只闪一次:EventSource 断线重连会重发最后一段帧。
157
+ if (current !== null && current.key === next.key) return
158
+ current = next
159
+ publish()
160
+ },
161
+ clear() {
162
+ current = null
163
+ publish()
164
+ },
165
+ subscribe(listener) {
166
+ listeners.add(listener)
167
+ return () => listeners.delete(listener)
168
+ },
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 把闪动事件流接上。
174
+ *
175
+ * EventSource 默认无限重连会一直占着连接池,所以连续失败到上限先关掉,
176
+ * 再按退避(30s 起、翻倍、封顶 5 分钟)重开——永久关闭会让闪屏在宿主
177
+ * 重启或休眠之后整体静默失效,而只有刷新页面才能救回来。
178
+ */
179
+ function subscribeFlashStream(store) {
180
+ if (typeof EventSource !== 'function') return () => {}
181
+ let disposed = false
182
+ let source
183
+ let retryTimer
184
+ let retries = 0
185
+
186
+ const open = () => {
187
+ if (disposed) return
188
+ source = new EventSource(`${API}/events`)
189
+ let errors = 0
190
+ source.onopen = () => {
191
+ errors = 0
192
+ retries = 0
193
+ }
194
+ source.onerror = () => {
195
+ errors += 1
196
+ if (errors < 5) return
197
+ try {
198
+ source.close()
199
+ } catch {
200
+ /* 已关闭 */
201
+ }
202
+ if (disposed || retryTimer !== undefined) return
203
+ retryTimer = setTimeout(() => {
204
+ retryTimer = undefined
205
+ open()
206
+ }, Math.min(30_000 * 2 ** retries, 300_000))
207
+ retries += 1
208
+ }
209
+ source.addEventListener('flash', event => {
210
+ errors = 0
211
+ try {
212
+ store.fire(JSON.parse(event.data))
213
+ } catch {
214
+ /* 坏帧丢掉即可,闪屏不是关键路径 */
215
+ }
216
+ })
217
+ }
218
+
219
+ open()
220
+ return () => {
221
+ disposed = true
222
+ if (retryTimer !== undefined) {
223
+ clearTimeout(retryTimer)
224
+ retryTimer = undefined
225
+ }
226
+ try {
227
+ source?.close()
228
+ } catch {
229
+ /* 已关闭 */
230
+ }
231
+ }
232
+ }
233
+
234
+ /* ----------------------------- 样式 ----------------------------- */
235
+
236
+ /* 全部走宿主主题变量,字面颜色只出现在「就绪/已开启」这种状态色上。 */
237
+ const CSS = `
238
+ .lg-card { font-family: inherit; color: var(--dsw-alias-label-primary, inherit); }
239
+ .lg-row { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
240
+ .lg-label { font-size: 13px; opacity: .8; }
241
+ .lg-input { width: 100%; box-sizing: border-box; padding: 8px 10px; font-size: 13px;
242
+ font-family: inherit; color: inherit; border-radius: 6px; outline: none;
243
+ background: var(--dsw-alias-bg-layer-2, rgba(128,128,128,.1));
244
+ border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
245
+ .lg-input:disabled { opacity: .5; }
246
+ .lg-block { border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.22));
247
+ border-radius: 8px; padding: 14px 16px; margin: 12px 0; }
248
+ .lg-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; }
249
+ .lg-name { font-size: 14px; font-weight: 600; }
250
+ .lg-badge { font-size: 11px; padding: 2px 8px; border-radius: 999px;
251
+ border: 1px solid currentColor; opacity: .8; }
252
+ .lg-badge.on { color: var(--dsw-alias-state-success-primary, #1a9d55); }
253
+ .lg-hint { font-size: 12px; opacity: .62; line-height: 1.65; margin: 4px 0 10px; }
254
+ .lg-field { margin-bottom: 10px; }
255
+ .lg-field > .lg-label { display: block; margin-bottom: 4px; font-size: 12px; opacity: .72; }
256
+ .lg-btn { padding: 8px 16px; font-size: 13px; font-family: inherit; color: #fff;
257
+ background: var(--dsw-alias-brand-primary, #2b7fff); border: none; border-radius: 6px;
258
+ cursor: pointer; white-space: nowrap; flex: none; }
259
+ /* 原生 checkbox 在深色主题下偏亮,一行 accent-color 就够。 */
260
+ .lg-row input[type="checkbox"] { accent-color: var(--dsw-alias-brand-primary, #2b7fff); }
261
+ .lg-btn:disabled { opacity: .6; cursor: default; }
262
+ .lg-status { font-size: 12.5px; margin-top: 10px; line-height: 1.6; }
263
+ .lg-ok { color: var(--dsw-alias-state-success-primary, #1a9d55); }
264
+ .lg-bad { color: var(--dsw-alias-state-error-primary, #d64545); }
265
+ .lg-warn { color: var(--dsw-alias-state-warn-primary, #c9821a); }
266
+ .lg-title { font-size: 16px; font-weight: 600; margin: 0 0 4px; }
267
+ .lg-sub { font-size: 12.5px; opacity: .65; margin: 0; line-height: 1.6; }
268
+ .lg-header { display: block; margin-bottom: 14px; }
269
+
270
+ /* 网关状态条:一行只读事实,不参与任何编辑。 */
271
+ /* 双通知警示条:左边框用警告色,一眼能看出这不是普通说明文字。 */
272
+ .lg-warnbar { display: flex; gap: 6px; flex-wrap: wrap; align-items: baseline;
273
+ font-size: 12.5px; line-height: 1.65; margin: 2px 0 10px; padding: 8px 10px;
274
+ border-radius: 6px; border-left: 3px solid var(--dsw-alias-state-warn-primary, #c9821a);
275
+ background: var(--dsw-alias-bg-layer-2, rgba(128,128,128,.08)); }
276
+ .lg-warnbar strong { color: var(--dsw-alias-state-warn-primary, #c9821a); flex: none; }
277
+
278
+ /* 总开关关掉时,底下的设置全部暂时无意义:整体压暗,让用户一眼看出
279
+ 「不是这些开关坏了,是它们现在不算数」。 */
280
+ .lg-card.off .lg-block { opacity: .55; }
281
+
282
+ .lg-statusbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
283
+ font-size: 12.5px; padding: 8px 12px; border-radius: 8px;
284
+ background: var(--dsw-alias-bg-layer-1, rgba(128,128,128,.08));
285
+ border: 1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.18)); }
286
+ .lg-dot { width: 7px; height: 7px; border-radius: 999px; flex: none; }
287
+ .lg-dot.on { background: var(--dsw-alias-state-success-primary, #1a9d55); }
288
+ .lg-dot.off { background: var(--dsw-alias-state-error-primary, #d64545); }
289
+ .lg-dot.idle { background: var(--dsw-alias-state-idle-primary, #8a8a8a); }
290
+
291
+ /* 顶栏:总开关 + 子代理 + 发送测试 同一行;按钮 auto 外边距推到最右,
292
+ 折行后仍是右对齐,不会忽然跑到中间去。 */
293
+ .lg-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 22px; margin: 0 0 10px; }
294
+ .lg-toolbar > .lg-row { margin-bottom: 0; flex: none; }
295
+ .lg-toolbar > .lg-btn { margin-left: auto; }
296
+
297
+ /* 触发源:两个勾选并排,各自一行说明。 */
298
+ .lg-sources { display: flex; flex-wrap: wrap; gap: 4px 26px; }
299
+ .lg-source { flex: 1 1 220px; min-width: 0; }
300
+ .lg-source > .lg-row { margin-bottom: 0; }
301
+
302
+ /* 三项配置并排一行:次数 / 时长 / 颜色。 */
303
+ .lg-controls { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 18px; margin: 0 0 2px; }
304
+ .lg-seg { display: flex; align-items: center; gap: 6px; flex: none; }
305
+ .lg-seg > .lg-label { display: inline-block; margin: 0; font-size: 12px; opacity: .72; white-space: nowrap; flex: none; }
306
+ .lg-num { width: 56px; flex: none; text-align: center; padding: 6px 8px; }
307
+ .lg-seg-text { font-size: 12px; opacity: .6; flex: none; }
308
+ .lg-swatch { width: 26px; height: 26px; flex: none; padding: 0; cursor: pointer;
309
+ border-radius: 5px; overflow: hidden; background: none;
310
+ border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
311
+ .lg-swatch input { width: 150%; height: 150%; margin: -25%; padding: 0; border: none;
312
+ cursor: pointer; background: none; }
313
+ .lg-color-code { width: 104px; flex: none; padding: 6px 8px; }
314
+
315
+ /* 预览按钮用次级样式,避免和「发送测试」抢注意力。 */
316
+ .lg-btn-ghost { padding: 5px 12px; font-size: 12.5px; font-family: inherit; color: inherit;
317
+ background: transparent; border-radius: 6px; cursor: pointer; flex: none; white-space: nowrap;
318
+ border: 1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); }
319
+ .lg-btn-ghost:hover { background: rgba(128, 128, 128, .1); }
320
+ .lg-btn-ghost:disabled { opacity: .55; cursor: default; }
321
+
322
+ .lg-row-split { display: flex; align-items: center; justify-content: space-between;
323
+ gap: 16px; margin-bottom: 10px; }
324
+ .lg-row-split > .lg-row { margin-bottom: 0; flex: 1 1 auto; min-width: 0; }
325
+
326
+ /* ── 闪动覆层 ──────────────────────────────────────────────────── */
327
+
328
+ /* 铺满整个框架、盖在所有面板之上,但不吃任何鼠标事件:
329
+ 闪 18 次的过程中用户照样能点按钮、能打字。 */
330
+ .lg-flash-veil { position: absolute; inset: 0; z-index: 60; pointer-events: none;
331
+ display: none; background-color: #22c55e; }
332
+
333
+ /* 一次「闪动」= 白 → 指定色 → 淡出 的一个完整周期。
334
+ 次数 × 周期时长 = 总时长,两个数字都由 Host 算好后内联下发。 */
335
+ @keyframes lg-flash-cycle {
336
+ 0% { opacity: 0; }
337
+ 22% { opacity: ${FLASH_PEAK}; }
338
+ 50% { opacity: ${FLASH_PEAK}; }
339
+ 88% { opacity: ${FLASH_PEAK}; }
340
+ 100% { opacity: 0; }
341
+ }
342
+ .lg-flash-veil.on { display: block; animation-name: lg-flash-cycle;
343
+ animation-timing-function: ease-in-out; animation-fill-mode: both; }
344
+
345
+ /* 系统开了「减少动态效果」就不闪,只留一层短暂的静态罩子。
346
+ 硬闪对前庭敏感人群不友好,这个让步比「照配置闪」更重要。 */
347
+ @media (prefers-reduced-motion: reduce) {
348
+ .lg-flash-veil.on { animation: none; opacity: ${FLASH_PEAK * 0.49}; }
349
+ }
350
+ `
351
+
352
+ /* ---------------------------- 小工具 ---------------------------- */
353
+
354
+ function useStyles() {
355
+ useEffect(() => {
356
+ const style = document.createElement('style')
357
+ style.setAttribute('data-plugin', 'dsh-llm-gateway')
358
+ style.textContent = CSS
359
+ document.head.appendChild(style)
360
+ return () => style.remove()
361
+ }, [])
362
+ }
363
+
364
+ async function callApi(path, init) {
365
+ const response = await fetch(API + path, {
366
+ credentials: 'same-origin',
367
+ cache: 'no-store',
368
+ headers: { 'content-type': 'application/json' },
369
+ ...init,
370
+ })
371
+ const data = await response.json().catch(() => ({}))
372
+ if (!response.ok && data?.error === undefined) {
373
+ throw new Error(`HTTP ${response.status}`)
374
+ }
375
+ return data
376
+ }
377
+
378
+ /* ---------------------------- 控件 ---------------------------- */
379
+
380
+ /**
381
+ * 闪动覆层。
382
+ *
383
+ * 只渲染一层 absolute + inset:0 的罩子,不碰 document.body、不改主题变量、
384
+ * 不替换任何宿主节点——这是 UI 插件里唯一安全的全屏画法。播放结束后把
385
+ * 状态清掉,罩子回到 display:none,而不是留一个透明的全屏节点在页面上。
386
+ */
387
+ function FlashVeil({ store }) {
388
+ const [spec, setSpec] = useState(null)
389
+
390
+ useEffect(() => {
391
+ let timer
392
+ const unsubscribe = store.subscribe(next => {
393
+ if (next === null) {
394
+ setSpec(null)
395
+ return
396
+ }
397
+ if (timer !== undefined) clearTimeout(timer)
398
+ setSpec(next)
399
+ timer = setTimeout(() => setSpec(null), next.periodMs * next.flashes + 120)
400
+ })
401
+ return () => {
402
+ unsubscribe()
403
+ if (timer !== undefined) clearTimeout(timer)
404
+ }
405
+ }, [store])
406
+
407
+ return h('div', {
408
+ // key 里带上每次都不同的标记:同一次闪动不重挂,新的闪动强制重挂,
409
+ // 否则正在播放的动画不会重启,第二次闪动会被静默吞掉。
410
+ key: spec === null ? 'idle' : spec.key,
411
+ className: spec === null ? 'lg-flash-veil' : 'lg-flash-veil on',
412
+ 'aria-hidden': 'true',
413
+ style: spec === null
414
+ ? undefined
415
+ : {
416
+ backgroundColor: spec.color,
417
+ animationDuration: `${spec.periodMs}ms`,
418
+ animationIterationCount: String(spec.flashes),
419
+ },
420
+ })
421
+ }
422
+
423
+ /** 勾选行。`title` 给「说明太长、一行放不下」的场合用。 */
424
+ function Toggle({ label, checked, onChange, disabled, title }) {
425
+ return h(
426
+ 'label',
427
+ { className: 'lg-row', title: title ?? undefined, style: { cursor: disabled ? 'default' : 'pointer' } },
428
+ h('input', {
429
+ type: 'checkbox',
430
+ checked: checked === true,
431
+ disabled,
432
+ onChange: event => onChange(event.target.checked),
433
+ }),
434
+ h('span', { className: 'lg-label' }, label),
435
+ )
436
+ }
437
+
438
+ /** 文本框:失焦或回车才提交。 */
439
+ function Field({ label, value, placeholder, onCommit, disabled }) {
440
+ const [draft, setDraft] = useState(value ?? '')
441
+ useEffect(() => {
442
+ setDraft(value ?? '')
443
+ }, [value])
444
+ return h(
445
+ 'div',
446
+ { className: 'lg-field' },
447
+ h('span', { className: 'lg-label' }, label),
448
+ h('input', {
449
+ className: 'lg-input',
450
+ value: draft,
451
+ placeholder: placeholder ?? '',
452
+ disabled,
453
+ spellCheck: false,
454
+ onChange: event => setDraft(event.target.value),
455
+ onBlur: () => {
456
+ if (draft !== (value ?? '')) onCommit(draft.trim())
457
+ },
458
+ onKeyDown: event => {
459
+ if (event.key === 'Enter') event.currentTarget.blur()
460
+ },
461
+ }),
462
+ )
463
+ }
464
+
465
+ /**
466
+ * 数字输入:标签在左、框在右,整段并排塞进一行。
467
+ *
468
+ * 不在每个按键上提交——用户从 18 改到 40 会路过 1、4,中间每个值都触发
469
+ * 一次写盘 + 一次「保存中」,等于让界面跟着手抖。
470
+ */
471
+ function NumberField({ label, value, min, max, unitText, onCommit, onDraft, disabled }) {
472
+ const [draft, setDraft] = useState(String(value ?? ''))
473
+ useEffect(() => {
474
+ setDraft(String(value ?? ''))
475
+ }, [value])
476
+
477
+ const commit = () => {
478
+ const parsed = Number(draft)
479
+ if (!Number.isFinite(parsed)) {
480
+ setDraft(String(value ?? ''))
481
+ return
482
+ }
483
+ const next = Math.min(max, Math.max(min, Math.round(parsed)))
484
+ setDraft(String(next))
485
+ if (next !== value) onCommit(next)
486
+ }
487
+
488
+ return h(
489
+ 'div',
490
+ { className: 'lg-seg' },
491
+ h('span', { className: 'lg-label' }, label),
492
+ h('input', {
493
+ className: 'lg-input lg-num',
494
+ type: 'number',
495
+ inputMode: 'numeric',
496
+ min,
497
+ max,
498
+ value: draft,
499
+ disabled,
500
+ 'aria-label': label,
501
+ onChange: event => {
502
+ setDraft(event.target.value)
503
+ // 草稿也上报一份:设置页的「闪一下试试」要的是输入框里的值,
504
+ // 不是上次保存的值。没有这条,用户把 18 改成 30 再点预览,
505
+ // 看到的是 18 次的效果,会以为「改了没用」。
506
+ onDraft?.(event.target.value)
507
+ },
508
+ onBlur: commit,
509
+ onKeyDown: event => {
510
+ if (event.key === 'Enter') event.currentTarget.blur()
511
+ },
512
+ }),
513
+ h('span', { className: 'lg-seg-text', title: `${min}–${max}` }, unitText),
514
+ )
515
+ }
516
+
517
+ /**
518
+ * 颜色:原生色板 + 手填色值,并排一行。
519
+ *
520
+ * 色板只认自己的格式,所以 rgb()/hsl() 会先折算成十六进制再喂给它;
521
+ * 文本框保留用户原样输入,存下去的是校验过的原文。
522
+ */
523
+ function ColorField({ value, onCommit, onDraft, disabled }) {
524
+ const [draft, setDraft] = useState(value ?? DEFAULT_COLOR)
525
+ useEffect(() => {
526
+ setDraft(value ?? DEFAULT_COLOR)
527
+ }, [value])
528
+
529
+ const valid = COLOR_SHAPES.some(shape => shape.test(draft.trim()))
530
+ const shown = valid ? draft.trim() : DEFAULT_COLOR
531
+
532
+ const commit = text => {
533
+ const next = normalizeColor(text)
534
+ setDraft(next)
535
+ if (next !== value) onCommit(next)
536
+ }
537
+
538
+ return h(
539
+ 'div',
540
+ { className: 'lg-seg' },
541
+ h('span', { className: 'lg-label' }, '颜色'),
542
+ h(
543
+ 'label',
544
+ { className: 'lg-swatch', title: '点开取色器' },
545
+ h('input', {
546
+ type: 'color',
547
+ value: toHexForPicker(shown),
548
+ disabled,
549
+ 'aria-label': '闪动颜色',
550
+ onChange: event => commit(event.target.value),
551
+ }),
552
+ ),
553
+ h('input', {
554
+ className: 'lg-input lg-color-code',
555
+ value: draft,
556
+ disabled,
557
+ spellCheck: false,
558
+ placeholder: '#22c55e',
559
+ 'aria-label': '闪动颜色色值',
560
+ 'aria-invalid': valid ? undefined : 'true',
561
+ // 认不出时描红边框:一行里没地方放错误文案,边框是最省的提示。
562
+ style: valid ? undefined : { borderColor: 'var(--dsw-alias-state-error-primary, #d64545)' },
563
+ onChange: event => {
564
+ setDraft(event.target.value)
565
+ onDraft?.(event.target.value)
566
+ },
567
+ onBlur: () => commit(draft),
568
+ onKeyDown: event => {
569
+ if (event.key === 'Enter') event.currentTarget.blur()
570
+ },
571
+ }),
572
+ )
573
+ }
574
+
575
+ /* -------------------------- 设置页面 -------------------------- */
576
+
577
+ function SettingsPage() {
578
+ useStyles()
579
+ const [settings, setSettings] = useState(null)
580
+ const [status, setStatus] = useState(null)
581
+ const [error, setError] = useState('')
582
+ const [saving, setSaving] = useState(false)
583
+ /**
584
+ * 保存结果用显式状态描颜色,不用字符串前缀猜。
585
+ *
586
+ * 之前的写法是 `saveMsg.startsWith('已生效') ? 'ok' : 'bad'`,而「写盘
587
+ * 失败」的文案正好以「已生效」开头,于是磁盘写失败被染成成功绿——
588
+ * 下次启动配置丢失时用户会坚定地认为「保存明明成功了」。
589
+ */
590
+ const [saveMsg, setSaveMsg] = useState({ kind: '', text: '' })
591
+ const [testing, setTesting] = useState(false)
592
+ const [testMsg, setTestMsg] = useState('')
593
+ const [previewing, setPreviewing] = useState(false)
594
+ const [previewMsg, setPreviewMsg] = useState('')
595
+ /**
596
+ * 内部通知三项的「正在编辑」草稿。
597
+ *
598
+ * 必须是页面级的:这三个值原本各自活在 NumberField / ColorField 的
599
+ * 局部 state 里,「闪一下试试」读不到它们,只能读到上次保存的配置。
600
+ * 结果就是预览看到的永远是旧参数——而预览的全部意义就是「先看再决定
601
+ * 要不要保存」。
602
+ */
603
+ const [inAppDraft, setInAppDraft] = useState({})
604
+
605
+ const load = useCallback(async () => {
606
+ try {
607
+ const data = await callApi('/settings')
608
+ setSettings(data.settings ?? {})
609
+ setStatus(data.status ?? null)
610
+ setError('')
611
+ } catch (e) {
612
+ setError(`读取配置失败:${e.message}`)
613
+ }
614
+ }, [])
615
+
616
+ useEffect(() => {
617
+ void load()
618
+ }, [load])
619
+
620
+ /** 按 path 写一个字段,服务端返回新配置与网关状态。 */
621
+ const setPath = useCallback(async (path, value) => {
622
+ setSaving(true)
623
+ setSaveMsg({ kind: 'warn', text: '保存中…' })
624
+ try {
625
+ const data = await callApi('/settings', {
626
+ method: 'POST',
627
+ body: JSON.stringify({ path, value }),
628
+ })
629
+ if (data.settings !== undefined) setSettings(data.settings)
630
+ if (data.status !== undefined) setStatus(data.status)
631
+ setSaveMsg(data.saved === false
632
+ ? { kind: 'warn', text: `已生效,但写入文件失败:${data.error ?? '未知原因'}(重开 DSH 后会丢失)` }
633
+ : { kind: 'ok', text: '已保存,立即生效(网关不重启)' })
634
+ } catch (e) {
635
+ setSaveMsg({ kind: 'bad', text: `保存失败:${e.message}` })
636
+ } finally {
637
+ setSaving(false)
638
+ }
639
+ }, [])
640
+
641
+ const runTest = useCallback(async () => {
642
+ setTesting(true)
643
+ setTestMsg('')
644
+ try {
645
+ const data = await callApi('/test', { method: 'POST' })
646
+ const list = Array.isArray(data.results) ? data.results : []
647
+ if (list.length === 0) {
648
+ // 用户刚「启用」了一个渠道却没填地址时最容易撞到这里,
649
+ // 所以要告诉他下一步做什么,而不是只说「没有」。
650
+ setTestMsg('没有可发送的渠道:上面至少勾选一个渠道并填好 Webhook / SendKey。')
651
+ } else {
652
+ const failed = list.filter(entry => !entry.ok)
653
+ setTestMsg(failed.length === 0
654
+ ? `${list.length} 个渠道均发送成功`
655
+ : failed.map(entry => `${entry.channel}:${entry.detail ?? '失败'}`).join(';'))
656
+ }
657
+ } catch (e) {
658
+ setTestMsg(`测试失败:${e.message}`)
659
+ } finally {
660
+ setTesting(false)
661
+ }
662
+ }, [])
663
+
664
+ /**
665
+ * 「闪一下试试」:把当前编辑中的次数 / 时长 / 颜色交给 Host 广播。
666
+ *
667
+ * 带上未保存的值是有意的——用户调完想先看一眼效果再决定要不要留,
668
+ * 逼他先保存会让这个按钮只对已经点过保存的人有用。
669
+ */
670
+ const runPreview = useCallback(async () => {
671
+ setPreviewing(true)
672
+ setPreviewMsg('')
673
+ try {
674
+ // 合并顺序:已保存的 → 正在编辑的草稿。预览必须反映输入框里现在
675
+ // 的值,否则「先调再预览」这件事根本不成立。
676
+ const data = await callApi('/flash', {
677
+ method: 'POST',
678
+ body: JSON.stringify({ inApp: { ...(settings?.inApp ?? {}), ...inAppDraft } }),
679
+ })
680
+ setPreviewMsg(data?.viewers > 0 ? '已发送,看屏幕' : '没有页面连着通知流(刷新页面后再试)')
681
+ } catch (e) {
682
+ setPreviewMsg(`预览失败:${e.message}`)
683
+ } finally {
684
+ setPreviewing(false)
685
+ }
686
+ }, [settings, inAppDraft])
687
+
688
+ if (error !== '') {
689
+ // 只给一行红字等于死局:用户唯一能做的是关掉面板再打开。
690
+ return h(
691
+ 'div',
692
+ { className: 'lg-card' },
693
+ h('p', { className: 'lg-title' }, '网关与通知'),
694
+ h('p', { className: 'lg-status lg-bad', role: 'alert' }, error),
695
+ h(
696
+ 'button',
697
+ { className: 'lg-btn-ghost', onClick: () => { setError(''); void load() } },
698
+ '重试',
699
+ ),
700
+ )
701
+ }
702
+
703
+ if (settings === null) {
704
+ return h(
705
+ 'div',
706
+ { className: 'lg-card' },
707
+ h('p', { className: 'lg-title' }, '网关与通知'),
708
+ h('p', { className: 'lg-sub' }, '读取配置中…'),
709
+ )
710
+ }
711
+
712
+ const channels = settings.channels ?? {}
713
+ const wecom = channels.wecom ?? {}
714
+ const feishu = channels.feishu ?? {}
715
+ const dingtalk = channels.dingtalk ?? {}
716
+ const wechat = channels.wechat ?? {}
717
+
718
+ const readyCount = [
719
+ wecom.enabled && wecom.webhook,
720
+ feishu.enabled && feishu.webhook,
721
+ dingtalk.enabled && dingtalk.webhook,
722
+ wechat.enabled && (wechat.serverchanSendKey || wechat.wxpusherAppToken),
723
+ ].filter(Boolean).length
724
+
725
+ const inApp = settings.inApp ?? {}
726
+ const inAppEnabled = inApp.enabled === true
727
+ const inAppFlashes = inApp.flashes ?? LIMITS.flashes.fallback
728
+ const inAppSeconds = inApp.durationSeconds ?? LIMITS.seconds.fallback
729
+ const inAppPeriod = Math.max(16, Math.round((inAppSeconds * 1000) / inAppFlashes))
730
+ const sources = settings.sources ?? {}
731
+ const settleSeconds = settings.gateway?.settleSeconds ?? LIMITS.settle.fallback
732
+ /**
733
+ * 总开关的状态必须贯穿整页。
734
+ *
735
+ * Host 侧在 `enabled === false` 时什么都不发(闪动也不闪),但页面
736
+ * 上仍会写着「2 / 2 已开」「已开启」——那是反方向的「开了却不响」,
737
+ * 比「关了还在响」更难查,因为所有开关看起来都对。
738
+ */
739
+ const globalOff = settings.enabled === false
740
+
741
+ /* 网关状态条:一行只读事实。绿=监听中,红=真的失败,灰=还没读到。 */
742
+ const listening = status !== null && status.listening !== false
743
+ const dotClass = status === null ? 'idle' : (listening ? 'on' : 'off')
744
+ const statusBar = h(
745
+ 'div',
746
+ { className: 'lg-statusbar', style: { marginBottom: 12 } },
747
+ h('span', { className: `lg-dot ${dotClass}` }),
748
+ h(
749
+ 'span',
750
+ null,
751
+ status === null
752
+ ? '网关状态未知'
753
+ : `${listening ? '监听中' : '未监听'} ${status.host}:${status.port}`
754
+ + ` · ${status.models ?? 0} 个模型`
755
+ + ` · ${status.auth ? '需 Bearer 认证' : '免认证(仅回环)'}`,
756
+ ),
757
+ )
758
+
759
+ /**
760
+ * 「本机会话会通知两次」的警示条。
761
+ *
762
+ * 这是整个改动里唯一必须让用户看懂的事实:dsh-task-notify 也在听
763
+ * turn/end,两个插件同时开着时,DSH 回合结束会各发一条消息、各闪一次
764
+ * (两层 overlay 同时播各自的节奏,比消息重复两倍还显眼)。
765
+ *
766
+ * 不能只写在勾选框下面那行 12px 灰字里——用户看到两条消息的第一反应
767
+ * 就是「这是 bug」,然后去提 issue。所以做成显式的警示条,关掉这个
768
+ * 勾选后整条消失,用户立刻知道自己解决了。
769
+ */
770
+ const duplicateWarning = sources.session !== false
771
+ ? h(
772
+ 'div',
773
+ { className: 'lg-warnbar' },
774
+ h('strong', null, '本机会话会通知两次。'),
775
+ h(
776
+ 'span',
777
+ null,
778
+ ' dsh-task-notify 也启用了,DSH 回合结束会各发一条消息、各闪一次。'
779
+ + '想只留一份:去「任务完成通知」页取消它的「启用通知」,或取消勾选下面这项。',
780
+ ),
781
+ )
782
+ : null
783
+
784
+ /**
785
+ * 触发源:网关请求 + DSH 会话。
786
+ *
787
+ * 两个勾选框必须有各自的说明,否则「为什么我关了通知还在响」会成为
788
+ * 最常见的问题——另一个来源还开着。
789
+ */
790
+ const sourcesBlock = h(
791
+ 'div',
792
+ { className: 'lg-block' },
793
+ h(
794
+ 'div',
795
+ { className: 'lg-head' },
796
+ h('span', { className: 'lg-name' }, '触发源'),
797
+ h(
798
+ 'span',
799
+ { className: `lg-badge${globalOff ? '' : ' on'}` },
800
+ globalOff
801
+ ? '总开关已关'
802
+ : `${(sources.gateway !== false) + (sources.session !== false)} / 2 已开`,
803
+ ),
804
+ ),
805
+ h('p', { className: 'lg-hint' }, '两条链路互相独立,共用下面的渠道配置。'),
806
+ duplicateWarning,
807
+ h(
808
+ 'div',
809
+ { className: 'lg-sources' },
810
+ h(
811
+ 'div',
812
+ { className: 'lg-source' },
813
+ h(Toggle, {
814
+ label: '网关请求结束',
815
+ checked: sources.gateway !== false,
816
+ disabled: saving,
817
+ onChange: value => setPath(['sources', 'gateway'], value),
818
+ }),
819
+ h(
820
+ 'p',
821
+ { className: 'lg-hint', style: { margin: '2px 0 0 22px' } },
822
+ '外部客户端(Codex / SDK / 脚本)打完任务时触发。',
823
+ ),
824
+ ),
825
+ h(
826
+ 'div',
827
+ { className: 'lg-source' },
828
+ h(Toggle, {
829
+ label: 'DSH 会话回合结束',
830
+ checked: sources.session !== false,
831
+ disabled: saving,
832
+ onChange: value => setPath(['sources', 'session'], value),
833
+ }),
834
+ h(
835
+ 'p',
836
+ { className: 'lg-hint', style: { margin: '2px 0 0 22px' } },
837
+ '本机 agent 的回合结束时触发(含界面闪动)。',
838
+ ),
839
+ ),
840
+ ),
841
+ /**
842
+ * 通知哪些结局(reasons)。
843
+ *
844
+ * Host 侧一直有这个字段、也一直按它过滤(默认只报 completed /
845
+ * error / blocked),但页面里一个勾选框都没有。于是「我明明开着,
846
+ * 被打断的那个任务却没收到通知」完全无从下手——用户不会想到去翻
847
+ * YAML 才知道 `aborted` 默认不在名单里。
848
+ */
849
+ h(
850
+ 'div',
851
+ { style: { marginTop: 12 } },
852
+ h('span', { className: 'lg-label', style: { display: 'block', marginBottom: 4, fontSize: 12, opacity: 0.72 } }, '通知这些结局'),
853
+ h(
854
+ 'div',
855
+ { style: { display: 'flex', flexWrap: 'wrap', gap: '4px 18px' } },
856
+ ...REASON_LABELS.map(([key, label]) =>
857
+ h(Toggle, {
858
+ key,
859
+ label,
860
+ checked: Array.isArray(settings.reasons) && settings.reasons.includes(key),
861
+ disabled: saving,
862
+ onChange: value => {
863
+ const current = Array.isArray(settings.reasons) ? settings.reasons : []
864
+ const next = value
865
+ ? [...current.filter(k => k !== key), key]
866
+ : current.filter(k => k !== key)
867
+ // 一个都不留会让插件永远不通知,又不报错——比报错更难查。
868
+ // Host 侧空数组会回落成默认值,这里也挡住,并给出提示。
869
+ if (next.length === 0) {
870
+ setSaveMsg({ kind: 'bad', text: '至少要保留一个结局,否则永远不会通知。' })
871
+ return
872
+ }
873
+ setPath(['reasons'], next)
874
+ },
875
+ }),
876
+ ),
877
+ ),
878
+ ),
879
+ // 静默窗口:只影响网关那条链路。
880
+ h(
881
+ 'div',
882
+ { className: 'lg-controls', style: { marginTop: 12 } },
883
+ h(NumberField, {
884
+ label: '网关静默窗口',
885
+ value: settleSeconds,
886
+ min: LIMITS.settle.min,
887
+ max: LIMITS.settle.max,
888
+ unitText: '秒',
889
+ disabled: saving || sources.gateway === false,
890
+ onCommit: value => setPath(['gateway', 'settleSeconds'], value),
891
+ }),
892
+ h(
893
+ 'span',
894
+ { className: 'lg-seg-text' },
895
+ settleSeconds === 0
896
+ ? '每个请求都通知'
897
+ : `网关安静 ${settleSeconds} 秒算任务结束,整段压成一条(不影响上面的会话通知)`,
898
+ ),
899
+ ),
900
+ )
901
+
902
+ /**
903
+ * DSH 内部通知那块卡片,压到最小高度:标题 + 一句说明 + 勾选/预览 +
904
+ * 三项并排 + 一行换算说明。换算说明只留最短的一句,不占额外段落。
905
+ */
906
+ const inAppBlock = h(
907
+ 'div',
908
+ { className: 'lg-block' },
909
+ h(
910
+ 'div',
911
+ { className: 'lg-head', style: { marginBottom: 0 } },
912
+ h('span', { className: 'lg-name' }, 'DSH 内部通知'),
913
+ h(
914
+ 'span',
915
+ { className: `lg-badge${inAppEnabled && !globalOff ? ' on' : ''}` },
916
+ inAppEnabled
917
+ ? (globalOff ? '已配置,但总开关关闭' : '已开启')
918
+ : '未开启',
919
+ ),
920
+ ),
921
+ h(
922
+ 'p',
923
+ { className: 'lg-hint', style: { margin: '2px 0 8px' } },
924
+ '网关请求或回合结束时整个程序背景闪动,与群机器人独立、无需 Webhook。'
925
+ + '两个触发源都开着时会各闪一次。',
926
+ ),
927
+ h(
928
+ 'div',
929
+ { className: 'lg-row-split', style: { marginBottom: 10 } },
930
+ h(Toggle, {
931
+ label: '启用 DSH 内部通知',
932
+ checked: inAppEnabled,
933
+ disabled: saving,
934
+ onChange: value => setPath(['inApp', 'enabled'], value),
935
+ }),
936
+ h(
937
+ 'button',
938
+ { className: 'lg-btn-ghost', onClick: runPreview, disabled: previewing },
939
+ previewing ? '闪动中…' : '闪一下试试',
940
+ ),
941
+ ),
942
+ h(
943
+ 'div',
944
+ { className: 'lg-controls' },
945
+ h(NumberField, {
946
+ label: '次数',
947
+ value: inAppFlashes,
948
+ min: LIMITS.flashes.min,
949
+ max: LIMITS.flashes.max,
950
+ unitText: '次',
951
+ disabled: saving,
952
+ onDraft: text => setInAppDraft(d => ({ ...d, flashes: Number(text) })),
953
+ onCommit: value => {
954
+ setInAppDraft(d => ({ ...d, flashes: value }))
955
+ setPath(['inApp', 'flashes'], value)
956
+ },
957
+ }),
958
+ h(NumberField, {
959
+ label: '时长',
960
+ value: inAppSeconds,
961
+ min: LIMITS.seconds.min,
962
+ max: LIMITS.seconds.max,
963
+ unitText: '秒',
964
+ disabled: saving,
965
+ onDraft: text => setInAppDraft(d => ({ ...d, durationSeconds: Number(text) })),
966
+ onCommit: value => {
967
+ setInAppDraft(d => ({ ...d, durationSeconds: value }))
968
+ setPath(['inApp', 'durationSeconds'], value)
969
+ },
970
+ }),
971
+ h(ColorField, {
972
+ value: normalizeColor(inApp.color),
973
+ disabled: saving,
974
+ onDraft: text => setInAppDraft(d => ({ ...d, color: normalizeColor(text) })),
975
+ onCommit: value => {
976
+ setInAppDraft(d => ({ ...d, color: value }))
977
+ setPath(['inApp', 'color'], value)
978
+ },
979
+ }),
980
+ ),
981
+ h(
982
+ 'p',
983
+ { className: 'lg-hint', style: { margin: '6px 0 0' } },
984
+ previewMsg !== ''
985
+ ? previewMsg
986
+ : `${inAppSeconds} 秒内 ${inAppFlashes} 次,每次约 ${inAppPeriod} 毫秒`,
987
+ ),
988
+ )
989
+
990
+ /**
991
+ * 渠道卡片。
992
+ *
993
+ * 徽标是三态而不是两态:`已勾选启用但没填 Webhook` 曾经显示成
994
+ * 「未启用」,而紧下方同一个勾选框明明是勾上的——自相矛盾。随后点
995
+ * 「发送测试」拿回空列表(Host 的 readyChannels 会过滤掉它),界面
996
+ * 说「没有已启用的渠道」,用户刚启用的东西凭空消失,这是首跑流程里
997
+ * 真正会让人放弃的地方。
998
+ */
999
+ const channelBlock = (name, kind, cfg, ready, hint, fields) => {
1000
+ const on = cfg.enabled === true
1001
+ const badge = ready
1002
+ ? { text: '已就绪', cls: ' on' }
1003
+ : on
1004
+ ? { text: '缺少 Webhook', cls: '' }
1005
+ : { text: '未启用', cls: '' }
1006
+ return h(
1007
+ 'div',
1008
+ { className: 'lg-block' },
1009
+ h(
1010
+ 'div',
1011
+ { className: 'lg-head' },
1012
+ h('span', { className: 'lg-name' }, name),
1013
+ h('span', { className: `lg-badge${badge.cls}` }, badge.text),
1014
+ ),
1015
+ h('p', { className: 'lg-hint' }, hint),
1016
+ h(Toggle, {
1017
+ label: `启用${name}`,
1018
+ checked: on,
1019
+ disabled: saving,
1020
+ onChange: value => setPath(['channels', kind, 'enabled'], value),
1021
+ }),
1022
+ // 勾了却没填地址:说清楚「勾选已生效,只差这一步」,
1023
+ // 而不是让用户对着一个矛盾的徽标猜。
1024
+ on && !ready && h(
1025
+ 'p',
1026
+ { className: 'lg-hint', style: { color: 'var(--dsw-alias-state-warn-primary, #c9821a)' } },
1027
+ kind === 'wechat'
1028
+ ? '还差凭据:Server酱 SendKey 或 WxPusher appToken 填一个才会发送。'
1029
+ : '还差 Webhook 地址:填好后才会发送。',
1030
+ ),
1031
+ ...fields.map(([key, label, placeholder]) =>
1032
+ h(Field, {
1033
+ key,
1034
+ label,
1035
+ value: cfg[key] ?? '',
1036
+ placeholder,
1037
+ disabled: saving,
1038
+ onCommit: value => setPath(['channels', kind, key], value),
1039
+ }),
1040
+ ),
1041
+ )
1042
+ }
1043
+
1044
+ return h(
1045
+ 'div',
1046
+ { className: globalOff ? 'lg-card off' : 'lg-card' },
1047
+ h(
1048
+ 'div',
1049
+ { className: 'lg-header' },
1050
+ h('p', { className: 'lg-title' }, '网关与通知'),
1051
+ h(
1052
+ 'p',
1053
+ { className: 'lg-sub' },
1054
+ '把 DSH 里已注册的模型用本机 OpenAI 兼容端点暴露给 Codex 等客户端。'
1055
+ + '下面配置任务结束后的通知:外部客户端通过网关跑完任务,以及本机 DSH 会话回合结束。',
1056
+ globalOff
1057
+ ? ' 总开关已关:以下设置暂不生效。'
1058
+ : (readyCount > 0 ? ` 当前 ${readyCount} 个渠道就绪。` : ' 当前没有可用渠道。'),
1059
+ ),
1060
+ ),
1061
+
1062
+ statusBar,
1063
+
1064
+ // ── 顶栏:总开关 + 子代理 + 发送测试 ──────────────────────
1065
+ h(
1066
+ 'div',
1067
+ { className: 'lg-toolbar' },
1068
+ h(Toggle, {
1069
+ label: '启用通知',
1070
+ checked: settings.enabled !== false,
1071
+ disabled: saving,
1072
+ onChange: value => setPath(['enabled'], value),
1073
+ }),
1074
+ h(Toggle, {
1075
+ label: '子代理会话也通知',
1076
+ // 长括号说明挪进 title:一行里放不下,也不该为它换行。
1077
+ title: '默认关,避免子代理会话刷屏',
1078
+ checked: settings.notifySubagents === true,
1079
+ disabled: saving,
1080
+ onChange: value => setPath(['notifySubagents'], value),
1081
+ }),
1082
+ h(
1083
+ 'button',
1084
+ { className: 'lg-btn', onClick: runTest, disabled: testing },
1085
+ testing ? '发送中…' : '测试通知',
1086
+ ),
1087
+ ),
1088
+
1089
+ sourcesBlock,
1090
+ inAppBlock,
1091
+
1092
+ // 顺序按实际使用频率排:飞书、钉钉在前,企业微信与微信在后。
1093
+ channelBlock(
1094
+ '飞书',
1095
+ 'feishu',
1096
+ feishu,
1097
+ Boolean(feishu.enabled && feishu.webhook),
1098
+ '群 → 设置 → 群机器人 → 添加 → 自定义机器人 → 复制 Webhook;开了签名校验就把密钥填上。',
1099
+ [
1100
+ ['webhook', 'Webhook 地址', 'https://open.feishu.cn/open-apis/bot/v2/hook/...'],
1101
+ ['secret', '签名密钥(可选)', '未开启签名校验则留空'],
1102
+ ],
1103
+ ),
1104
+ channelBlock(
1105
+ '钉钉',
1106
+ 'dingtalk',
1107
+ dingtalk,
1108
+ Boolean(dingtalk.enabled && dingtalk.webhook),
1109
+ '群 → 智能群助手 → 添加机器人 → 自定义 → 复制 Webhook。'
1110
+ + '若安全设置选了「加签」,把密钥一并填上;选了「自定义关键词」则不用。',
1111
+ [
1112
+ ['webhook', 'Webhook 地址', 'https://oapi.dingtalk.com/robot/send?access_token=...'],
1113
+ ['secret', '加签密钥(选了加签才填)', 'SEC...'],
1114
+ ],
1115
+ ),
1116
+ channelBlock(
1117
+ '企业微信',
1118
+ 'wecom',
1119
+ wecom,
1120
+ Boolean(wecom.enabled && wecom.webhook),
1121
+ '群 → 群机器人 → 添加机器人 → 创建 → 复制 Webhook 地址。',
1122
+ [['webhook', 'Webhook 地址', 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...']],
1123
+ ),
1124
+ channelBlock(
1125
+ '微信',
1126
+ 'wechat',
1127
+ wechat,
1128
+ Boolean(wechat.enabled && (wechat.serverchanSendKey || wechat.wxpusherAppToken)),
1129
+ '微信不开放第三方直接推送到个人号,需经服务号中转。个人主体无法自建服务号,所以用服务商通道:Server酱或 WxPusher。',
1130
+ [
1131
+ ['serverchanSendKey', 'Server酱 SendKey', 'SCT... 或 sctp...'],
1132
+ ['wxpusherAppToken', '或 WxPusher appToken', 'AT_...'],
1133
+ ],
1134
+ ),
1135
+
1136
+ saveMsg.text !== '' && h(
1137
+ 'div',
1138
+ {
1139
+ className: `lg-status lg-${saveMsg.kind}`,
1140
+ role: 'status',
1141
+ 'aria-live': saveMsg.kind === 'bad' ? 'assertive' : 'polite',
1142
+ },
1143
+ saveMsg.text,
1144
+ ),
1145
+ testMsg !== '' && h(
1146
+ 'div',
1147
+ {
1148
+ className: `lg-status ${testMsg.includes('成功') ? 'lg-ok' : 'lg-bad'}`,
1149
+ role: 'status',
1150
+ 'aria-live': 'polite',
1151
+ },
1152
+ testMsg,
1153
+ ),
1154
+ )
1155
+ }
1156
+
1157
+ /* ---------------------------- 插件体 ---------------------------- */
1158
+
1159
+ const inject = ['slots', 'locale']
1160
+
1161
+ /**
1162
+ * 闪动状态存在工厂作用域里,而不是某个组件的 state。
1163
+ *
1164
+ * 原因很直接:闪动必须能在用户**没打开设置页**的时候发生。订阅一旦绑在
1165
+ * 设置页组件上,关掉设置面板就等于关掉了通知——而「人不在看设置页」
1166
+ * 恰恰是这个功能最常见的使用场景。
1167
+ */
1168
+ const flashStore = createFlashStore()
1169
+
1170
+ function apply(ctx) {
1171
+ const t = ctx.locale.bind(NS)
1172
+ ctx.effect(() => ctx.locale.register(NS, { zh: DICT.zh, en: DICT.en }), 'llm-gateway: dictionaries')
1173
+
1174
+ // 事件流只开一条,跟着插件的生命周期开合。
1175
+ ctx.effect(() => subscribeFlashStream(flashStore), 'llm-gateway: flash stream')
1176
+
1177
+ // settings.section 是设置页里的一个分区;id 决定它的命名空间。
1178
+ // order 37 紧跟在 task-notify(36) 之后:两者都是「通知」类设置,
1179
+ // 排在一起用户不用来回翻。
1180
+ ctx.slots.inject('settings.section', () =>
1181
+ ctx.slots.register(
1182
+ { name: 'settings.section', id: 'llm-gateway', order: 37, label: () => t('nav'), locale: NS },
1183
+ () => h(SettingsPage),
1184
+ ),
1185
+ )
1186
+
1187
+ // shell.overlay 是框架级浮层:盖在所有列之上、在滚动容器之外,
1188
+ // 默认不吃鼠标事件。这正是「全屏闪一下但不挡操作」需要的座位。
1189
+ ctx.slots.inject('shell.overlay', () =>
1190
+ ctx.slots.register(
1191
+ { name: 'shell.overlay', id: 'llm-gateway.flash', order: 91 },
1192
+ () => h(FlashVeil, { store: flashStore }),
1193
+ ),
1194
+ )
1195
+ }
1196
+
1197
+ exports.inject = inject
1198
+ exports.apply = apply
1199
+ exports.name = 'llm-gateway'
1200
+ return module.exports
1201
+ },
1202
+ })