dsh-balance-sentinel 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,21 @@
3
3
  All notable changes to this project are documented here. Format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/); versions follow [SemVer](https://semver.org/).
5
5
 
6
+ ## [0.1.3] - 2026-11-18
7
+
8
+ ### Fixed
9
+
10
+ - **限流不再被当成测试失败**:测试请求返回 429(「操作太频繁」)时,面板只提示这句话,不再把没有结果对象的响应当成一次测试结论。此前这类被拒绝的请求会把徽章从「最近测试成功」改成红色失败,抹掉上一次真实结果。
11
+ - **旧轮询不再覆盖更新的状态**:先发出、后返回的 `/status` 在新测试失败或新 Webhook 保存之后落地时,整份过期响应直接丢弃——不会再把失败徽章改回旧的成功,也不会把面板退回旧地址;首次配置时也不会再因此重新弹出已关闭的配置表单。
12
+ - **单独点「发送测试推送」不再与徽章打架**:接口返回失败时,面板立即按响应更新当前通道的徽章与持久化提示,不再等下一次轮询(此前会同时显示「最近测试失败」和旧的「最近测试成功」)。属于其他通道或比当前更旧的结果不会被应用。
13
+ - **旧通道的未落盘结果不再清空新通道的有效记录**:合并改为先按当前通道过滤、再比较时间,避免「较新的旧通道结论先按时间胜出、随后因通道不匹配被丢弃」,连带把磁盘里那条可用记录一起丢掉;读取合并与常规保存两条路径都受影响。
14
+ - **浅色模式下文字太淡**:余额数字改为按皮肤取色(浅色 `#9c5c00` / `#c62828` / `#1f7a35`,白底约 5:1),徽章、错误块与失败原因改用向标签色混合的墨水,不再直接使用白底上约 2:1 的橙色。
15
+ - **「已配置,待测试」不再是一枚灰徽章**:四态各有自己的色 —— 未配置用次要灰、待测试用品牌蓝、最近测试成功用绿、最近测试失败用红;通道前的圆点与徽章同色,并带一圈淡光晕,不靠单一色相也能分辨。失败说明改用与错误块相同的混色墨水,避免宿主把 error 令牌调成粉色后 11.5px 处看不清。
16
+
17
+ ### Changed
18
+
19
+ - **面板跟随宿主深浅色**:读取 `body[data-ds-dark-theme]`(DSH 自身与 dsh-context 使用的同一约定),浅色皮肤换用白色卡片、细描边与宿主一级投影,深色皮肤保持原来的层级底色。卡片/徽章/浮层/错误块的底色改用 `color-mix()` 从 `--dsw-alias-*` 派生,不再使用只在深色下校准过的 `rgba()`;原生下拉菜单的 `colorScheme` 与告警红字也按皮肤切换,不再依赖 `prefers-color-scheme`。徽章文字改为把语义色向标签色混合,浅色卡片上不再发白。
20
+
6
21
  ## [0.1.2] - 2026-11-17
7
22
 
8
23
  ### Fixed
@@ -54,5 +69,6 @@ All notable changes to this project are documented here. Format follows
54
69
  - README 面板截图前置、补「先看三行」要点;适用范围与免 Key 边界并入安装节,不再单列小节。
55
70
  - GitHub About 描述收紧为一句:低余额推送 + 本机运行边界。
56
71
 
72
+ [0.1.3]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.3
57
73
  [0.1.2]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.2
58
74
  [0.1.0]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.0
package/README.en.md CHANGED
@@ -32,14 +32,14 @@ dsh plugin --profile web add github:liancheng2020/dsh-balance-sentinel
32
32
  # or npm (published to npm alongside each Release)
33
33
  dsh plugin --profile web add dsh-balance-sentinel
34
34
  # or the pinned Release tarball
35
- dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.2/dsh-balance-sentinel-0.1.2.tgz
35
+ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.3/dsh-balance-sentinel-0.1.3.tgz
36
36
  ```
37
37
 
38
38
  Any one of the three is enough; if the npm/Release line is not live yet, use the first. Desktop app: Settings → Plugins → add `dsh-balance-sentinel` or `github:liancheng2020/dsh-balance-sentinel`. Restart DSH once.
39
39
 
40
40
  **Where it runs**: local DSH desktop or local web host only — monitoring lives in the DSH process and **stops when DSH exits** (reopening resumes from the local state file); **no remote web panel** (the bridge binds `127.0.0.1:17430` and only accepts pages from this machine). **Key-free host accounts are supported**: the host must expose the account service with a signed-in account (key-free ≠ account-free); otherwise use `DEEPSEEK_API_KEY` or `balance.apiKey` — with neither, the panel states the exact reason.
41
41
 
42
- > Current version `0.1.2` (see [CHANGELOG](CHANGELOG.md)).
42
+ > Current version `0.1.3` (see [CHANGELOG](CHANGELOG.md)).
43
43
 
44
44
  ## First use (two steps)
45
45
 
@@ -57,6 +57,7 @@ If the balance is already below a threshold when you connect, one current-state
57
57
  - **Failures are traceable and retryable**: pending alerts persist; business failures back off 10 min and hold after 3 (manual retry in the panel); timeouts and dead response bodies are "delivery unconfirmed" — held immediately, never auto re-sent; a failed state save writes a fallback receipt, so restarts and multiple instances still do not re-send it (unconfirmed restores as held, never as sent). If neither the state nor the receipt can be written, the duplicate risk is logged explicitly.
58
58
  - **No wedge, no duplicate across instances**: host queries have a 15s deadline and the scheduler survives any exception; desktop + web sharing `DSH_HOME` push each transition exactly once (whole-cycle lock + disk merge).
59
59
  - **Channels**: WeCom / DingTalk / Feishu (card) / Bark / ServerChan / Telegram / generic webhook; auto-chunking; HTTP-200 business failures count as failures.
60
+ - **Follows the host skin**: the panel reads `data-ds-dark-theme`, so a light skin gets white cards, hairline borders and a soft shadow, with badges, toasts and native select menus switching with it.
60
61
  - Balance is the **official account number**; v1 ships no cost estimates.
61
62
 
62
63
  ## Config (optional, profile cordis.patch.yml)
package/README.md CHANGED
@@ -32,14 +32,14 @@ dsh plugin --profile web add github:liancheng2020/dsh-balance-sentinel
32
32
  # 或 npm(随 Release 一同发布到 npm)
33
33
  dsh plugin --profile web add dsh-balance-sentinel
34
34
  # 或 Release 固定版本 tarball
35
- dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.2/dsh-balance-sentinel-0.1.2.tgz
35
+ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.3/dsh-balance-sentinel-0.1.3.tgz
36
36
  ```
37
37
 
38
38
  三条任选一条即可;若 npm/Release 那条还没上线,用第一条。桌面端:设置 → 插件 → 添加插件,填 `dsh-balance-sentinel` 或 `github:liancheng2020/dsh-balance-sentinel`。装完重启一次 DSH。
39
39
 
40
40
  **适用环境**:仅本机 DSH Desktop/本机 Web,监控跑在 DSH 进程里、**退出即停**(重开从本机状态继续);**不支持远程 Web 面板**(桥接只绑 `127.0.0.1:17430`,只接受本机页面)。**支持宿主账号免填 Key**:宿主内置账号服务且已登录(免填 ≠ 无需账户),否则用 `DEEPSEEK_API_KEY` 或 `balance.apiKey`,都没有时面板给出明确原因。
41
41
 
42
- > 当前版本 `0.1.2`(见 [CHANGELOG](CHANGELOG.md))。
42
+ > 当前版本 `0.1.3`(见 [CHANGELOG](CHANGELOG.md))。
43
43
 
44
44
  ## 首次使用(两步接通)
45
45
 
@@ -57,6 +57,7 @@ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentin
57
57
  - **失败可追踪、可重试**:待发送告警持久化;业务失败 10 分钟退避、3 次后挂起可手动重试;超时等「送达不确定」立即挂起、不自动重发;状态保存失败时落盘备用回执,重启/多实例恢复后仍不重发(不确定的恢复为挂起,不标记成功)。状态与回执都无法落盘时会明确告警「去重无法保证」。
58
58
  - **不卡死、多实例不重推**:宿主查询 15s 兜底,任何异常后调度继续;desktop + web 共享 `DSH_HOME` 时整周期锁 + 磁盘合并,同一跃迁只推一次。
59
59
  - **通道**:企微 / 钉钉 / 飞书(消息卡片)/ Bark / Server酱 / Telegram / 通用 Webhook;超长自动分条;HTTP 200 但业务失败同样判失败。
60
+ - **跟随宿主深浅色**:面板读 `data-ds-dark-theme`,浅色皮肤用白卡片+细描边+轻投影,卡片、徽章、浮层与原生下拉菜单同步换色。
60
61
  - 余额来自**官方账户同源**,v1 不做成本估算。
61
62
 
62
63
  ## 配置(可选,profile 的 cordis.patch.yml)
package/client.js CHANGED
@@ -171,6 +171,25 @@ window.__ModuleLoader__.load({
171
171
  return lang
172
172
  }
173
173
 
174
+ // DSH marks the dark skin with <body data-ds-dark-theme> — the same contract
175
+ // the host's own UI reads. Follow that attribute instead of guessing from a
176
+ // colour probe: a light skin can still use a dark brand colour, and a probe
177
+ // would put the panel in the wrong mode on first paint.
178
+ function useDarkSkin() {
179
+ const [dark, setDark] = useState(true)
180
+ useEffect(() => {
181
+ const body = typeof document !== 'undefined' ? document.body : null
182
+ if (!body) return
183
+ const read = () => setDark(typeof body.hasAttribute === 'function' ? body.hasAttribute('data-ds-dark-theme') : true)
184
+ read()
185
+ if (typeof MutationObserver === 'undefined') return
186
+ const mo = new MutationObserver(read)
187
+ mo.observe(body, { attributes: true, attributeFilter: ['data-ds-dark-theme'] })
188
+ return () => mo.disconnect()
189
+ }, [])
190
+ return dark
191
+ }
192
+
174
193
  const T = {
175
194
  text: 'var(--dsw-alias-label-primary, #e8e8ea)',
176
195
  sub: 'var(--dsw-alias-label-secondary, #a0a0a8)',
@@ -187,36 +206,58 @@ window.__ModuleLoader__.load({
187
206
  success: 'var(--dsw-alias-state-success-primary, #34c759)',
188
207
  error: 'var(--dsw-alias-state-error-primary, #ff4d4f)',
189
208
  }
209
+ // Theme-following fills: color-mix() resolves against the host's --dsw-alias-*
210
+ // tokens, so one declaration is correct in both skins. The rgba() literals
211
+ // this replaces were tuned on the dark skin and turn into grey smudges on a
212
+ // white canvas.
213
+ const tint = (color, pct) => `color-mix(in srgb, ${color} ${pct}%, transparent)`
214
+ const mix = (color, pct, base) => `color-mix(in srgb, ${color} ${pct}%, ${base})`
215
+ // Ink for text painted in a state colour: pulled towards the label colour so
216
+ // it darkens on white and lightens on black. The raw warn orange is only
217
+ // ~2:1 on a white card, which is why badges and amounts use this instead.
218
+ const ink = (color) => mix(color, 58, T.text)
219
+ // Ink for a badge filled with a saturated state colour: it must contrast with
220
+ // that colour (not with the page), so it is a constant in both skins.
221
+ const INK_ON_SOLID = '#0e0e11'
190
222
  const css = {
191
- panel: { boxSizing: 'border-box', padding: '20px 22px', color: T.text, fontSize: 13, lineHeight: 1.6, overflowY: 'auto', height: '100%', background: T.base },
223
+ // The canvas comes from a custom property so the light skin can swap it for
224
+ // an opaque neutral (see the injected sheet); an inline bg would win over it.
225
+ panel: { boxSizing: 'border-box', padding: '20px 22px', color: T.text, fontSize: 13, lineHeight: 1.6, overflowY: 'auto', height: '100%', background: 'var(--sentinel-canvas, var(--dsw-alias-bg-base, #0e0e11))' },
192
226
  head: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 16 },
193
227
  titleWrap: { display: 'flex', alignItems: 'center', gap: 10 },
194
- iconBadge: { width: 38, height: 38, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'linear-gradient(135deg, rgba(91,140,255,0.18), rgba(245,166,35,0.14))', border: `1px solid ${T.border}`, color: T.brand, flex: 'none' },
228
+ iconBadge: { width: 38, height: 38, borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', background: `linear-gradient(135deg, ${tint(T.brand, 18)}, ${tint(T.warn, 14)})`, border: `1px solid ${T.border}`, color: T.brand, flex: 'none' },
195
229
  h1: { fontSize: 17, fontWeight: 650, margin: 0, letterSpacing: '0.2px', display: 'flex', alignItems: 'center', gap: 8 },
196
230
  live: { width: 7, height: 7, borderRadius: '50%', background: T.success },
197
231
  sub: { color: T.tertiary, fontSize: 12, margin: '3px 0 0' },
198
232
  btn: { fontSize: 12, padding: '6px 14px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.layer1, color: T.sub, cursor: 'pointer', transition: 'all .15s ease', display: 'inline-flex', alignItems: 'center', gap: 6, flex: 'none' },
199
233
  btnOutline: { fontSize: 12, padding: '6px 14px', borderRadius: 8, border: `1px solid ${T.border}`, background: 'transparent', color: T.sub, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, flex: 'none' },
200
- btnPrimary: { fontSize: 12, padding: '6px 14px', borderRadius: 8, border: '1px solid rgba(91,140,255,0.45)', background: 'rgba(91,140,255,0.16)', color: T.brand, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, flex: 'none' },
201
- hero: { background: `linear-gradient(135deg, rgba(91,140,255,0.10), ${T.layer1} 60%)`, border: `1px solid ${T.border}`, borderRadius: 12, padding: '16px 18px', marginBottom: 14 },
234
+ btnPrimary: { fontSize: 12, padding: '6px 14px', borderRadius: 8, border: `1px solid ${tint(T.brand, 45)}`, background: tint(T.brand, 16), color: T.brand, fontWeight: 600, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6, flex: 'none' },
235
+ hero: { background: `linear-gradient(135deg, ${tint(T.brand, 10)}, var(--sentinel-surface, #1a1a1f) 60%)`, border: 'var(--sentinel-line-w, 1px) solid var(--sentinel-line, #2e2e36)', boxShadow: 'var(--sentinel-shadow, none)', borderRadius: 12, padding: '16px 18px', marginBottom: 14 },
202
236
  heroVal: { fontSize: 30, fontWeight: 700, lineHeight: 1.2 },
203
237
  metaDim: { fontSize: 11.5, color: T.tertiary, margin: '2px 0' },
204
- banner: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap', padding: '9px 12px', marginBottom: 14, borderRadius: 10, border: `1px solid ${T.borderSoft}`, borderLeft: `3px solid ${T.brand}`, background: 'rgba(91,140,255,0.10)' },
238
+ banner: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap', padding: '9px 12px', marginBottom: 14, borderRadius: 10, border: 'var(--sentinel-line-w, 1px) solid var(--sentinel-line, #26262c)', borderLeft: `3px solid ${T.brand}`, background: tint(T.brand, 10) },
205
239
  bannerText: { fontSize: 12, color: T.sub },
206
- card: { background: T.layer1, border: `1px solid ${T.borderSoft}`, borderRadius: 10, padding: '12px 14px', marginBottom: 12 },
240
+ card: { background: 'var(--sentinel-surface, #1a1a1f)', border: 'var(--sentinel-line-w, 1px) solid var(--sentinel-line, #26262c)', boxShadow: 'var(--sentinel-shadow, none)', borderRadius: 10, padding: '12px 14px', marginBottom: 12 },
207
241
  row: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8, marginBottom: 6 },
208
242
  cardTitle: { fontWeight: 600, fontSize: 13, color: T.text, display: 'flex', alignItems: 'center', gap: 7 },
209
- badgeSoft: (c) => ({ fontSize: 10.5, fontWeight: 600, padding: '2px 9px', borderRadius: 20, color: c, border: `1px solid ${c}`, background: 'transparent', whiteSpace: 'nowrap', flex: 'none' }),
243
+ // A bare semantic colour at 10.5px is unreadable on a white card, so the ink
244
+ // is pulled towards the label colour (dark in the light skin, a touch
245
+ // lighter in the dark one) while the fill keeps the state's hue.
246
+ badgeSoft: (c) => ({ fontSize: 10.5, fontWeight: 600, padding: '2px 9px', borderRadius: 20, color: ink(c), border: `1px solid ${tint(c, 55)}`, background: tint(c, 12), whiteSpace: 'nowrap', flex: 'none' }),
210
247
  field: { marginBottom: 9 },
211
248
  fieldLabel: { display: 'block', fontSize: 11.5, color: T.tertiary, marginBottom: 4 },
212
- helpBox: { padding: '9px 11px', marginBottom: 9, borderRadius: 8, border: `1px dashed ${T.border}`, background: T.base },
249
+ helpBox: { padding: '9px 11px', marginBottom: 9, borderRadius: 8, border: 'var(--sentinel-line-w, 1px) dashed var(--sentinel-dash, #2e2e36)', background: 'var(--sentinel-canvas, var(--dsw-alias-bg-base, #0e0e11))' },
213
250
  input: { boxSizing: 'border-box', width: '100%', font: 'inherit', fontSize: 12, padding: '7px 10px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.base, color: T.text, outline: 'none' },
214
- select: { boxSizing: 'border-box', width: '100%', font: 'inherit', fontSize: 12, padding: '7px 10px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.base, color: T.text, outline: 'none', colorScheme: 'dark', cursor: 'pointer' },
251
+ // Native <select> popups ignore most styling: colorScheme is what makes
252
+ // Chromium render the list dark instead of grey-on-grey. It is applied at
253
+ // the call site from useDarkSkin() (see pushForm) rather than pinned here,
254
+ // or the light skin would still open a dark menu.
255
+ select: { boxSizing: 'border-box', width: '100%', font: 'inherit', fontSize: 12, padding: '7px 10px', borderRadius: 8, border: `1px solid ${T.border}`, background: T.base, color: T.text, outline: 'none', cursor: 'pointer' },
215
256
  option: { background: T.layer1, color: T.text },
216
257
  link: { color: T.brand, textDecoration: 'none', fontSize: 12, display: 'inline-flex', alignItems: 'center', gap: 3, transition: 'opacity .15s' },
217
- error: { color: T.error, fontSize: 12.5, padding: '12px 14px', background: 'rgba(255,77,79,0.08)', border: '1px solid rgba(255,77,79,0.3)', borderRadius: 10, marginBottom: 12 },
218
- warnBox: { color: T.warn, fontSize: 12, padding: '10px 12px', background: 'rgba(245,166,35,0.08)', border: '1px solid rgba(245,166,35,0.3)', borderRadius: 10, marginBottom: 12 },
219
- bridgeBox: { padding: '12px 14px', background: T.layer1, border: `1px dashed ${T.border}`, borderRadius: 10, marginBottom: 12 },
258
+ error: { color: ink(T.error), fontSize: 12.5, padding: '12px 14px', background: tint(T.error, 8), border: `1px solid ${tint(T.error, 30)}`, borderRadius: 10, marginBottom: 12 },
259
+ warnBox: { color: ink(T.warn), fontSize: 12, padding: '10px 12px', background: tint(T.warn, 8), border: `1px solid ${tint(T.warn, 30)}`, borderRadius: 10, marginBottom: 12 },
260
+ bridgeBox: { padding: '12px 14px', background: 'var(--sentinel-surface, #1a1a1f)', border: 'var(--sentinel-line-w, 1px) dashed var(--sentinel-dash, #2e2e36)', borderRadius: 10, marginBottom: 12 },
220
261
  pathLine: { fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 11.5, color: T.brand, marginTop: 6, wordBreak: 'break-all' },
221
262
  h2: { fontSize: 12, fontWeight: 600, margin: '0 0 10px', color: T.sub, textTransform: 'uppercase', letterSpacing: '0.6px' },
222
263
  foot: { marginTop: 8, paddingTop: 14, borderTop: `1px solid ${T.borderSoft}`, fontSize: 11.5, color: T.sub, display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' },
@@ -244,10 +285,16 @@ window.__ModuleLoader__.load({
244
285
  // Critical uses a fixed red: some skins tint --dsw-alias-state-error-primary
245
286
  // pink, which turned a real 告急 amount into a near-white number.
246
287
  const levelColor = (l) => l === 'critical' ? '#ff4d4f' : l === 'warn' ? T.warn : T.success
288
+ // The balance amount is the panel's headline. The raw warn orange measures
289
+ // about 2:1 on a white card, so the light skin gets a darkened value through
290
+ // a custom property while the dark skin keeps the vivid one.
291
+ const levelVal = (l) => l === 'critical' ? 'var(--sentinel-val-critical, #ff4d4f)'
292
+ : l === 'warn' ? 'var(--sentinel-val-warn, #f5a623)' : 'var(--sentinel-val-success, #34c759)'
247
293
  const fmtTime = (iso) => { if (!iso) return ''; try { return new Date(iso).toLocaleTimeString(LANG === 'en' ? 'en-US' : 'zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' }) } catch { return String(iso) } }
248
294
 
249
295
  function SentinelPanel() {
250
296
  LANG = useActiveLang()
297
+ const dark = useDarkSkin()
251
298
  const [nonce, setNonce] = useState(0)
252
299
  const [host, setHost] = useState(null)
253
300
  const [bridgeErr, setBridgeErr] = useState('')
@@ -264,6 +311,11 @@ window.__ModuleLoader__.load({
264
311
  const [warnDraft, setWarnDraft] = useState(null)
265
312
  const [critDraft, setCritDraft] = useState(null)
266
313
  const thTouched = useRef(false) // user typed in a threshold field
314
+ // Monotonic tokens for what the panel already knows locally. A /status
315
+ // request captures both when it leaves; anything that lands afterwards
316
+ // cannot be reflected in its response (see load()).
317
+ const verdictSeq = useRef(0) // a test verdict was folded into the badge
318
+ const configSeq = useRef(0) // a save/disable replaced the webhook itself
267
319
  const [toast, setToast] = useState(null)
268
320
 
269
321
  useEffect(() => {
@@ -286,21 +338,32 @@ window.__ModuleLoader__.load({
286
338
 
287
339
  useEffect(() => {
288
340
  const sheet = `
341
+ /* Surfaces follow the host skin the way dsh-context does: the dark skin
342
+ keeps the layer-1 fill and lets the wallpaper show through, while the
343
+ light skin gets an opaque neutral canvas, hairline borders and the
344
+ host's level-1 shadow so cards read as objects instead of grey mush. */
345
+ .sentinel-panel { --sentinel-surface: var(--dsw-alias-bg-layer-1, #1a1a1f); --sentinel-line: var(--dsw-alias-border-l1, #26262c); --sentinel-dash: var(--dsw-alias-border-l2, #2e2e36); --sentinel-line-w: 1px; --sentinel-shadow: none; --sentinel-canvas: var(--dsw-alias-bg-base, #0e0e11); --sentinel-val-warn: var(--dsw-alias-state-warn-primary, #f5a623); --sentinel-val-critical: #ff4d4f; --sentinel-val-success: var(--dsw-alias-state-success-primary, #34c759); }
346
+ /* Light skin: the vivid state colours land at ~2:1 on white, so the
347
+ headline amount uses a darkened ink. These values measure above 5:1
348
+ against #ffffff and #f4f6f8. */
349
+ body:not([data-ds-dark-theme]) .sentinel-panel { --sentinel-surface: var(--dsw-alias-bg-layer-1, #ffffff); --sentinel-line: var(--dsw-alias-border-l3, #e3e6ea); --sentinel-dash: var(--dsw-alias-border-l4, #d5d9de); --sentinel-line-w: 0.5px; --sentinel-shadow: var(--dsw-shadow-lv1, 0 1px 2px rgba(0,0,0,0.06)); --sentinel-canvas: var(--dsw-static-neutral-bluish-75, #f4f6f8); --sentinel-val-warn: #9c5c00; --sentinel-val-critical: #c62828; --sentinel-val-success: #1f7a35; }
289
350
  .sentinel-panel::-webkit-scrollbar { width: 8px; }
290
351
  .sentinel-panel::-webkit-scrollbar-thumb { background: ${T.border}; border-radius: 8px; }
291
352
  .sentinel-btn:hover { border-color: ${T.brand}; color: ${T.text}; background: ${T.hover}; }
292
353
  .sentinel-link:hover { opacity: 0.75; }
293
354
  .sentinel-toast { position: fixed; z-index: 999; pointer-events: none; display: flex; align-items: flex-start; gap: 8px; box-sizing: border-box; max-width: 80vw; padding: 10px 14px; border-radius: 10px; font-size: 12.5px; line-height: 1.45; transform: translateX(-50%); }
294
- .sentinel-toast-ok { background: rgba(52,199,89,0.16); border: 1px solid rgba(52,199,89,0.65); color: ${T.text}; }
295
- .sentinel-toast-err { background: rgba(255,77,79,0.14); border: 1px solid rgba(255,77,79,0.65); color: ${T.text}; }
296
- .sentinel-toast-icon { width: 18px; height: 18px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; color: #0e0e11; background: ${T.success}; }
355
+ .sentinel-toast-ok { background: ${tint(T.success, 16)}; border: 1px solid ${tint(T.success, 65)}; color: ${T.text}; }
356
+ .sentinel-toast-err { background: ${tint(T.error, 14)}; border: 1px solid ${tint(T.error, 65)}; color: ${T.text}; }
357
+ .sentinel-toast-icon { width: 18px; height: 18px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11px; font-weight: 700; color: ${INK_ON_SOLID}; background: ${T.success}; }
297
358
  .sentinel-toast-err .sentinel-toast-icon { background: ${T.error}; color: #fff; }
298
359
  .sentinel-toast-body { min-width: 0; }
299
360
  .sentinel-toast-title { font-weight: 650; }
300
361
  .sentinel-toast-sub { font-size: 12.5px; color: ${T.sub}; word-break: break-word; }
301
- /* fixed red: some skins tint --dsw-alias-state-error-primary pink */
362
+ /* fixed red: some skins tint --dsw-alias-state-error-primary pink.
363
+ Follow the host's skin attribute rather than the OS preference: the
364
+ two can disagree (dark app on a light desktop). */
302
365
  .sentinel-th-bad { color: #ff4d4f; }
303
- @media (prefers-color-scheme: light) { .sentinel-th-bad { color: #d93025; } }
366
+ body:not([data-ds-dark-theme]) .sentinel-th-bad { color: #d93025; }
304
367
  @media (prefers-reduced-motion: reduce) { .sentinel-toast { animation: none !important; } }
305
368
  `
306
369
  let el = document.getElementById('sentinel-style')
@@ -318,13 +381,35 @@ window.__ModuleLoader__.load({
318
381
  let attempt = 0
319
382
  let seeded = false
320
383
  const load = async () => {
384
+ // Ordering tokens taken when the request leaves, not when it returns.
385
+ const issued = verdictSeq.current
386
+ const issuedConfig = configSeq.current
321
387
  try {
322
388
  const res = await fetch(LOCAL_API + '/status', { headers: { Accept: 'application/json' } })
323
389
  if (!res.ok) throw new Error('http ' + res.status)
324
390
  const j = await res.json()
325
391
  if (cancelled) return
392
+ // One gate for the whole response. A save/disable that finished while
393
+ // this request was in flight owns the webhook section, so the snapshot
394
+ // predates it: drop it before touching state AND before the side
395
+ // effects below. `configured` drives the setup form, so letting an
396
+ // obsolete "not configured" snapshot through re-opened the form over
397
+ // a channel the user had just saved.
398
+ if (configSeq.current > issuedConfig) return
326
399
  attempt = 0
327
- setBridgeErr(''); setHost(j)
400
+ setBridgeErr('')
401
+ setHost((prev) => {
402
+ if (!prev) return j
403
+ // Checked again at apply time: a save can complete between the
404
+ // gate above and this updater being flushed.
405
+ if (configSeq.current > issuedConfig) return prev
406
+ // A /status issued before the newest test result cannot contain
407
+ // it. Taking the snapshot verbatim put the previous green verdict
408
+ // back over a failure the user had just watched happen; keep the
409
+ // verdict the panel already shows in that case.
410
+ if (verdictSeq.current > issued && j.channel === prev.channel) return { ...j, verify: prev.verify }
411
+ return j
412
+ })
328
413
  // Auto-open the setup form once, not on every poll: a later refresh
329
414
  // must not re-open it under a user who just closed it.
330
415
  if (!seeded && !j.configured) setEditing(true)
@@ -394,12 +479,36 @@ window.__ModuleLoader__.load({
394
479
  // Shared by the standalone test button and the save+test flow. It owns no
395
480
  // busy state on purpose: the caller keeps one busy window, so a failed save
396
481
  // or a failed test can never leave a button stuck on "Saving…".
482
+ // Fold a verdict into the panel state right away. Waiting for the next poll
483
+ // left the badge showing the previous "succeeded" next to a message saying
484
+ // the test just failed, for up to a full poll interval.
485
+ const applyVerify = (j) => {
486
+ // Only a response that carries a verdict is a test result. A refused
487
+ // request (429 "操作太频繁", a rejected body, a dead bridge) says
488
+ // nothing about delivery, so inventing a verdict from `ok:false` used to
489
+ // paint a red "failed" over the last known-good result.
490
+ const v = j && j.verify
491
+ if (!v || j.stale) return
492
+ // This verdict is newer than any snapshot still in flight.
493
+ verdictSeq.current += 1
494
+ setHost((prev) => {
495
+ if (!prev) return prev
496
+ // A verdict for another endpoint (saved from a second window) must not
497
+ // land on this channel's badge.
498
+ if (v.channel && prev.channel && v.channel !== prev.channel) return prev
499
+ // Never let an older verdict overwrite a newer one that is already shown.
500
+ if (prev.verify && Number(prev.verify.at || 0) > Number(v.at || 0)) return prev
501
+ return { ...prev, verify: v }
502
+ })
503
+ }
504
+
397
505
  const sendTest = async () => {
398
506
  const j = await post('/test-push')
399
507
  // The config was repointed while this request was in flight, so the
400
508
  // verdict belongs to a webhook that is no longer in use: say so instead
401
509
  // of letting the user read it as the state of the current channel.
402
510
  if (j.stale) { showResult({ ok: false, message: t('push.testStale') }); return j }
511
+ applyVerify(j)
403
512
  const warn = j.persisted === false ? t('push.notPersisted') : ''
404
513
  showResult(j.ok
405
514
  ? { ok: true, message: t('push.testOk', { c: j.channel || '', n: j.chunks || 1 }), hint: warn }
@@ -418,6 +527,9 @@ window.__ModuleLoader__.load({
418
527
  try {
419
528
  const j = await post('/webhook', form)
420
529
  if (!j.ok) { showResult({ ok: false, message: j.message || '' }); return }
530
+ // This response now owns the webhook section: a /status still in
531
+ // flight was built from the previous address and must not land.
532
+ configSeq.current += 1
421
533
  // The server decides what happens to the old test result: an unchanged
422
534
  // webhook keeps it, any edit drops it. Trust the response instead of
423
535
  // blanking locally and flashing "untested" on a no-op re-save.
@@ -445,6 +557,9 @@ window.__ModuleLoader__.load({
445
557
  try {
446
558
  const j = await post('/webhook', { channel: 'none' })
447
559
  if (!j.ok) { showResult({ ok: false, message: j.message || '' }); return }
560
+ // Same rule as a save: a poll issued before this point still says the
561
+ // channel was configured.
562
+ configSeq.current += 1
448
563
  setHost((prev) => ({ ...(prev || {}), channel: 'none', configured: false, urlHost: '', secretSet: false, verify: null }))
449
564
  setEditing(false)
450
565
  showResult({ ok: true, message: t('push.disabled') })
@@ -506,7 +621,7 @@ window.__ModuleLoader__.load({
506
621
  h('div', { style: css.row },
507
622
  h('span', { style: css.cardTitle }, h(BellIcon, { size: 16 }), t('meta.title')),
508
623
  h('span', { style: css.badgeSoft(levelColor(level)) }, t('level.' + level))),
509
- h('div', { style: { ...css.heroVal, color: levelColor(level) } }, `${sym(bal.currency)}${Number(bal.value).toFixed(2)}`),
624
+ h('div', { style: { ...css.heroVal, color: levelVal(level) } }, `${sym(bal.currency)}${Number(bal.value).toFixed(2)}`),
510
625
  h('div', { style: { display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap', marginTop: 8 } },
511
626
  h('a', { style: css.link, className: 'sentinel-link', href: TOP_UP, target: '_blank', rel: 'noreferrer' }, t('hero.topup'), h('span', null, '↗')),
512
627
  h('span', { style: css.metaDim }, t('hero.checkedAt', { t: fmtTime(bal.at) }))),
@@ -536,7 +651,7 @@ window.__ModuleLoader__.load({
536
651
  h('div', { style: css.field },
537
652
  h('label', { style: css.fieldLabel, htmlFor: 'sentinel-chan' }, t('push.field.channel')),
538
653
  h('select', {
539
- id: 'sentinel-chan', style: css.select, value: form.channel,
654
+ id: 'sentinel-chan', style: { ...css.select, colorScheme: dark ? 'dark' : 'light' }, value: form.channel,
540
655
  onChange: (e) => setForm({ channel: e.target.value, url: '', secret: '' }),
541
656
  }, CHANNELS.map((c) => h('option', { key: c, value: c, style: css.option }, t('chan.' + c))))),
542
657
  h('div', { style: css.field },
@@ -575,7 +690,13 @@ window.__ModuleLoader__.load({
575
690
  // an old success is dropped server-side the moment the webhook changes.
576
691
  const verifyInfo = host?.verify || null
577
692
  const connState = !host?.configured ? 'off' : !verifyInfo ? 'untested' : verifyInfo.ok ? 'verified' : 'failed'
578
- const connColor = connState === 'verified' ? T.success : connState === 'failed' ? T.error : connState === 'off' ? T.warn : T.sub
693
+ // One colour per state, so the dot and the badge agree and neither reads as
694
+ // "disabled": grey means nothing is set up, blue means set up but unproven,
695
+ // green and red mean the last test actually landed or failed.
696
+ const connColor = connState === 'verified' ? T.success
697
+ : connState === 'failed' ? T.error
698
+ : connState === 'untested' ? T.brand
699
+ : T.sub // off: a secondary grey, not the dimmed token (too faint on white)
579
700
  const connLine = connState === 'verified' ? t('push.verifiedAt', { t: fmtTime(verifyInfo.at) })
580
701
  + (verifyInfo.persisted === false ? ' · ' + t('push.notPersisted') : '')
581
702
  : connState === 'failed'
@@ -585,10 +706,21 @@ window.__ModuleLoader__.load({
585
706
 
586
707
  const pushSummary = () => h('div', { style: css.card },
587
708
  h('div', { style: css.row },
588
- h('span', { style: css.cardTitle }, h('span', { style: { width: 8, height: 8, borderRadius: '50%', background: connColor, flex: 'none' } }), t('push.channel', { c: t('chan.' + host.channel) })),
709
+ h('span', { style: css.cardTitle },
710
+ h('span', {
711
+ style: {
712
+ width: 8, height: 8, borderRadius: '50%', flex: 'none', background: connColor,
713
+ // A soft ring keeps the state readable by more than hue alone and
714
+ // stops the dot from looking like a stray speck on a wide card.
715
+ boxShadow: connState === 'off' ? 'none' : `0 0 0 3px ${tint(connColor, 20)}`,
716
+ },
717
+ }),
718
+ t('push.channel', { c: t('chan.' + host.channel) })),
589
719
  h('span', { style: css.badgeSoft(connColor) }, t('push.' + connState))),
590
720
  host.urlHost ? h('div', { style: css.metaDim }, t('push.current', { h: host.urlHost })) : null,
591
- connLine ? h('div', { style: { ...css.metaDim, color: connState === 'failed' ? T.error : undefined } }, connLine) : null,
721
+ // Failure text uses the same mixed ink as css.error: some skins tint the
722
+ // raw error token pink, which is unreadable at 11.5px on a light card.
723
+ connLine ? h('div', { style: { ...css.metaDim, color: connState === 'failed' ? ink(T.error) : undefined } }, connLine) : null,
592
724
  h('div', { style: css.metaDim }, host.configured ? t('push.hint') : t('push.empty')),
593
725
  h('div', { style: { display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' } },
594
726
  h('button', {
package/lib/state.js CHANGED
@@ -262,9 +262,13 @@ function pickVerify(mine, theirs) {
262
262
  // paths (read-from-disk and write-to-disk) go through here so neither can keep a
263
263
  // verdict alive across a config change.
264
264
  function reconcileVerify(mine, theirs, webhook) {
265
- const picked = pickVerify(mine, theirs)
266
- if (picked?.fp && picked.fp !== webhookFingerprint(webhook)) return null
267
- return picked
265
+ // Filter by channel first, then compare times. Picking by time first and
266
+ // discarding afterwards loses a valid record: a newer unpersisted verdict for
267
+ // the OLD webhook would win the race and then be thrown away, taking the
268
+ // file's perfectly good result for the CURRENT webhook with it.
269
+ const fp = webhookFingerprint(webhook)
270
+ const usable = (v) => (v && (!v.fp || v.fp === fp) ? v : null)
271
+ return pickVerify(usable(mine), usable(theirs))
268
272
  }
269
273
 
270
274
  // Re-read the shared state while holding the lock. The in-memory copy may be
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-balance-sentinel",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "DeepSeek 低余额主动推送到飞书/钉钉等 IM;仅限本机 DSH Desktop/本机 Web,DSH 运行期间监控;支持宿主账号免填 API Key(需已登录)。",
5
5
  "author": "liancheng2020",
6
6
  "type": "module",
@@ -97,8 +97,15 @@ const findById = (node, id) => [...walk(node)].find((n) => n.props && n.props.id
97
97
 
98
98
  const els = {}
99
99
  const docListeners = {}
100
+ // DSH marks the dark skin with this body attribute; the panel follows it.
101
+ const bodyAttrs = new Set(['data-ds-dark-theme'])
100
102
  global.document = {
101
103
  visibilityState: 'visible',
104
+ body: {
105
+ hasAttribute: (n) => bodyAttrs.has(n),
106
+ setAttribute: (n) => bodyAttrs.add(n),
107
+ removeAttribute: (n) => bodyAttrs.delete(n),
108
+ },
102
109
  getElementById: (id) => els[id] || null,
103
110
  createElement: (tag) => ({ tag, id: '', textContent: '', style: {} }),
104
111
  head: { appendChild: (el) => { if (el.id) els[el.id] = el } },
@@ -123,17 +130,37 @@ let webhookFails = 0
123
130
  let testPushFails = 0
124
131
  let testPushStale = 0
125
132
  let testPushUnpersisted = 0
133
+ let testPushThrottled = 0
134
+ // Hold the next /status response so a poll can be issued and answered out of
135
+ // order (the response is frozen at request time, like a real slow request).
136
+ let statusHold = 0
137
+ const heldStatus = []
138
+ // One-shot override for the next successful save, so a test can repoint the
139
+ // webhook to another channel/host (the mock otherwise echoes the old one).
140
+ let webhookReply = null
141
+ const releaseStatus = () => {
142
+ const h = heldStatus.shift()
143
+ if (!h) return false
144
+ h.resolve({ ok: true, status: 200, json: async () => h.snap })
145
+ return true
146
+ }
126
147
  const posts = []
127
148
  const fetchMock = async (url, init) => {
128
149
  const u = String(url)
129
150
  if (u.startsWith('http://127.0.0.1:17430/status')) {
130
151
  statusCalls++
131
152
  if (statusFails > 0) { statusFails--; throw new Error('ECONNREFUSED') }
153
+ if (statusHold > 0) {
154
+ statusHold--
155
+ const snap = JSON.parse(JSON.stringify(HOST))
156
+ return new Promise((resolve) => { heldStatus.push({ snap, resolve }) })
157
+ }
132
158
  return { ok: true, status: 200, json: async () => HOST }
133
159
  }
134
160
  if (u.startsWith('http://127.0.0.1:17430/webhook')) {
135
161
  const body = JSON.parse(init?.body || '{}')
136
162
  posts.push(['webhook', body])
163
+ if (webhookReply) { const r = webhookReply; webhookReply = null; return { ok: true, status: 200, json: async () => r } }
137
164
  const off = body.channel === 'none'
138
165
  if (webhookFails > 0) {
139
166
  webhookFails--
@@ -143,19 +170,28 @@ const fetchMock = async (url, init) => {
143
170
  }
144
171
  if (u.startsWith('http://127.0.0.1:17430/test-push')) {
145
172
  posts.push(['test-push'])
173
+ // The bridge answers 429 with no verdict at all: the request was refused, so
174
+ // nothing is known about delivery.
175
+ if (testPushThrottled > 0) {
176
+ testPushThrottled--
177
+ return { ok: true, status: 429, json: async () => ({ ok: false, code: 'too-frequent', message: '操作太频繁,请 3 秒后再试' }) }
178
+ }
179
+ const verdict = (ok, extra = {}) => ({
180
+ at: Date.now(), ok, channel: 'wecom', error: ok ? null : 'errcode 93000 invalid webhook', persisted: true, ...extra,
181
+ })
146
182
  if (testPushStale > 0) {
147
183
  testPushStale--
148
184
  return { ok: true, status: 200, json: async () => ({ ok: true, stale: true, chunks: 1, channel: 'wecom' }) }
149
185
  }
150
186
  if (testPushUnpersisted > 0) {
151
187
  testPushUnpersisted--
152
- return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, persisted: false }) }
188
+ return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, persisted: false, verify: verdict(false, { persisted: false }) }) }
153
189
  }
154
190
  if (testPushFails > 0) {
155
191
  testPushFails--
156
- return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, hint: 'Webhook 地址无效' }) }
192
+ return { ok: true, status: 200, json: async () => ({ ok: false, error: 'errcode 93000 invalid webhook', code: 93000, hint: 'Webhook 地址无效', verify: verdict(false) }) }
157
193
  }
158
- return { ok: true, status: 200, json: async () => ({ ok: true, chunks: 1, channel: 'wecom' }) }
194
+ return { ok: true, status: 200, json: async () => ({ ok: true, chunks: 1, channel: 'wecom', verify: verdict(true) }) }
159
195
  }
160
196
  if (u.startsWith('http://127.0.0.1:17430/prefs')) {
161
197
  const body = JSON.parse(init?.body || '{}')
@@ -401,7 +437,7 @@ await atest('P12 support boundary shown in zh/en; bridge-down names remote panel
401
437
 
402
438
  // Regression: a server-side rejection used to return before clearing `busy`, so
403
439
  // the save button stayed on "保存中…" and disabled forever.
404
- await atest('P14 save failure clears busy; edit then retry succeeds', async () => {
440
+ await atest('P13 save failure clears busy; edit then retry succeeds', async () => {
405
441
  resetHost(); HOST.configured = false; HOST.channel = 'none'
406
442
  webhookFails = 1
407
443
  const { render, dispose } = boot()
@@ -428,7 +464,7 @@ await atest('P14 save failure clears busy; edit then retry succeeds', async () =
428
464
  webhookFails = 0
429
465
  dispose()
430
466
  })
431
- await atest('P15 configured vs connected: untested / verified / failed', async () => {
467
+ await atest('P14 configured vs connected: untested / verified / failed', async () => {
432
468
  resetHost(); HOST.verify = null
433
469
  let b = boot(); b.render(); await sleep(30)
434
470
  let txt = textOf(b.render())
@@ -452,7 +488,7 @@ await atest('P15 configured vs connected: untested / verified / failed', async (
452
488
  // a red "must be positive" line, because the drafts were seeded only by a /status
453
489
  // that may land late (or not at all). An untouched draft must fall back to the
454
490
  // host value instead of rendering ''.
455
- await atest('P17 thresholds never render blank; fallback when host omits them', async () => {
491
+ await atest('P15 thresholds never render blank; fallback when host omits them', async () => {
456
492
  resetHost(); delete HOST.thresholds
457
493
  const { render, dispose } = boot()
458
494
  render()
@@ -485,7 +521,7 @@ await atest('P16 save&test failure still re-enables the button', async () => {
485
521
  })
486
522
  // A verdict can arrive after another page repointed the webhook; the panel must
487
523
  // say it was discarded instead of letting it read as the new channel's result.
488
- await atest('P19 stale verdict is explained, never shown as success', async () => {
524
+ await atest('P17 stale verdict is explained, never shown as success', async () => {
489
525
  resetHost()
490
526
  testPushStale = 1
491
527
  const { render, dispose } = boot()
@@ -498,7 +534,7 @@ await atest('P19 stale verdict is explained, never shown as success', async () =
498
534
  if (txt.includes('测试推送成功')) throw new Error('stale verdict must not read as success')
499
535
  dispose()
500
536
  })
501
- await atest('P20 unpersisted verdict is shown and labelled', async () => {
537
+ await atest('P18 unpersisted verdict is shown and labelled', async () => {
502
538
  resetHost()
503
539
  testPushUnpersisted = 1
504
540
  const { render, dispose } = boot()
@@ -511,8 +547,84 @@ await atest('P20 unpersisted verdict is shown and labelled', async () => {
511
547
  if (!txt.includes('重启后会丢失')) throw new Error('unpersisted result must say so')
512
548
  dispose()
513
549
  })
550
+ // The panel must follow the host skin attribute, not the OS preference: a dark
551
+ // app on a light desktop keeps the dark palette (and a dark <select> popup).
552
+ // Grey for "saved but untested" read as a disabled control; each state now owns
553
+ // a token so the dot and the badge cannot drift back to a neutral grey.
554
+ await atest('P19 each connection state gets its own colour', async () => {
555
+ const cases = [
556
+ [null, '已配置,待测试', 'brand-primary'],
557
+ [{ at: Date.now(), ok: true, channel: 'wecom', error: null }, '最近测试成功', 'state-success-primary'],
558
+ [{ at: Date.now(), ok: false, channel: 'wecom', error: 'errcode 93000' }, '最近测试失败', 'state-error-primary'],
559
+ ]
560
+ for (const [verify, label, token] of cases) {
561
+ resetHost(); HOST.verify = verify
562
+ const b = boot()
563
+ b.render()
564
+ await sleep(30)
565
+ const node = b.render()
566
+ const badge = [...walk(node)].find((n) => n.props && n.props.style && n.props.style.color
567
+ && String(n.props.style.color).includes(token) && textOf(n).includes(label))
568
+ if (!badge) throw new Error(`state "${label}" must use ${token}`)
569
+ b.dispose()
570
+ }
571
+ })
572
+ // A standalone test used to update only the inline result: the badge kept the
573
+ // previous green "succeeded" until the next poll landed.
574
+ await atest('P20 a failed test flips the badge without waiting for a poll', async () => {
575
+ resetHost()
576
+ HOST.verify = { at: Date.now() - 60000, ok: true, channel: 'wecom', error: null, persisted: true }
577
+ testPushFails = 1
578
+ const { render, dispose } = boot()
579
+ render()
580
+ await sleep(30)
581
+ if (!textOf(render()).includes('最近测试成功')) throw new Error('precondition: old success should be visible')
582
+ await findButton(render(), '发送测试推送').props.onClick()
583
+ await sleep(80)
584
+ const txt = textOf(render())
585
+ if (!txt.includes('最近测试失败')) throw new Error('badge must flip immediately: ' + txt.slice(0, 240))
586
+ if (txt.includes('最近测试成功')) throw new Error('the old success must not stay on screen')
587
+ testPushFails = 0
588
+ dispose()
589
+ })
590
+ // The light skin's vivid state colours land near 2:1 on white, so the headline
591
+ // amount switches to a darkened value through a custom property.
592
+ await atest('P21 light skin darkens the headline amount', async () => {
593
+ resetHost()
594
+ bodyAttrs.delete('data-ds-dark-theme')
595
+ const b = boot()
596
+ b.render()
597
+ await sleep(30)
598
+ const node = b.render()
599
+ const amount = [...walk(node)].find((n) => n.props && n.props.style && n.props.style.color
600
+ && String(n.props.style.color).includes('--sentinel-val-'))
601
+ if (!amount) throw new Error('amount must use a skin-aware colour variable')
602
+ const sheet = els['sentinel-style'] ? els['sentinel-style'].textContent : ''
603
+ if (!sheet.includes('--sentinel-val-warn: #9c5c00')) throw new Error('light warn ink missing from the sheet')
604
+ if (!sheet.includes('--sentinel-val-critical: #c62828')) throw new Error('light critical ink missing from the sheet')
605
+ bodyAttrs.add('data-ds-dark-theme')
606
+ b.dispose()
607
+ })
608
+ await atest('P22 host skin drives colorScheme and the light palette', async () => {
609
+ resetHost(); HOST.configured = false; HOST.channel = 'none'
610
+ bodyAttrs.add('data-ds-dark-theme')
611
+ let b = boot(); b.render(); await sleep(30)
612
+ let sel = findById(b.render(), 'sentinel-chan')
613
+ if (sel.props.style.colorScheme !== 'dark') throw new Error('dark skin must open a dark menu: ' + sel.props.style.colorScheme)
614
+ const sheet = els['sentinel-style'] ? els['sentinel-style'].textContent : ''
615
+ if (!sheet.includes('body:not([data-ds-dark-theme]) .sentinel-panel')) throw new Error('light palette override missing from the injected sheet')
616
+ if (!sheet.includes('--sentinel-surface')) throw new Error('surface variable missing from the injected sheet')
617
+ b.dispose()
514
618
 
515
- await atest('P13 zh/en catalogs have identical keys', async () => {
619
+ bodyAttrs.delete('data-ds-dark-theme')
620
+ b = boot(); b.render(); await sleep(30)
621
+ sel = findById(b.render(), 'sentinel-chan')
622
+ if (sel.props.style.colorScheme !== 'light') throw new Error('light skin must open a light menu: ' + sel.props.style.colorScheme)
623
+ b.dispose()
624
+ bodyAttrs.add('data-ds-dark-theme')
625
+ })
626
+
627
+ await atest('P23 zh/en catalogs have identical keys', async () => {
516
628
  const iZh = clientCode.indexOf(' zh: {')
517
629
  const iEn = clientCode.indexOf(' en: {')
518
630
  if (iZh < 0 || iEn < 0 || iEn < iZh) throw new Error('catalogs not found')
@@ -524,7 +636,7 @@ await atest('P13 zh/en catalogs have identical keys', async () => {
524
636
  if (missEn.length || missZh.length) throw new Error(`missing en: ${missEn.join(',') || '-'} | missing zh: ${missZh.join(',') || '-'}`)
525
637
  })
526
638
 
527
- await atest('P14 threshold save confirms via top toast, gone in 2s', async () => {
639
+ await atest('P24 threshold save confirms via top toast, gone in 2s', async () => {
528
640
  resetHost()
529
641
  const { render, dispose } = boot()
530
642
  render()
@@ -544,7 +656,7 @@ await atest('P14 threshold save confirms via top toast, gone in 2s', async () =>
544
656
  if (textOf(render()).includes('阈值已保存')) throw new Error('toast should fade after 2s and leave no inline copy')
545
657
  dispose()
546
658
  })
547
- await atest('P15 error notice is not auto-dismissed', async () => {
659
+ await atest('P25 error notice is not auto-dismissed', async () => {
548
660
  resetHost(); HOST.configured = false; HOST.channel = 'none'
549
661
  const { render, dispose } = boot()
550
662
  render()
@@ -562,7 +674,7 @@ await atest('P15 error notice is not auto-dismissed', async () => {
562
674
  dispose()
563
675
  })
564
676
 
565
- await atest('P16 poll clears a stale pending banner without any click', async () => {
677
+ await atest('P26 poll clears a stale pending banner without any click', async () => {
566
678
  resetHost(); HOST.pending = { kind: 'warn', cause: null, hold: false, ambiguous: false, attempts: 0, lastError: null }
567
679
  const b = boot()
568
680
  b.render()
@@ -575,8 +687,9 @@ await atest('P16 poll clears a stale pending banner without any click', async ()
575
687
  if (textOf(b.render()).includes('待发送')) throw new Error('poll did not clear the banner')
576
688
  b.dispose()
577
689
  })
578
- await atest('P17 polls pause while hidden and refresh on return', async () => {
690
+ await atest('P27 polls pause while hidden and refresh on return', async () => {
579
691
  resetHost()
692
+ const listenersBefore = (docListeners.visibilitychange || []).length
580
693
  const b = boot()
581
694
  b.render()
582
695
  await sleep(30)
@@ -587,10 +700,16 @@ await atest('P17 polls pause while hidden and refresh on return', async () => {
587
700
  global.document.visibilityState = 'visible'
588
701
  global.document.dispatch('visibilitychange'); await sleep(30)
589
702
  if (statusCalls !== base + 1) throw new Error('returning to the panel must refresh once')
703
+ // Unmount has to leave nothing behind: no live interval, no document listener.
590
704
  b.dispose()
705
+ if (!b.intervals.length || !b.intervals[0].cleared) throw new Error('unmount must clear the poll interval')
706
+ if ((docListeners.visibilitychange || []).length !== listenersBefore) throw new Error('unmount must drop the visibilitychange listener')
707
+ const afterDispose = statusCalls
708
+ global.document.dispatch('visibilitychange'); await sleep(30)
709
+ if (statusCalls !== afterDispose) throw new Error('a disposed panel must not poll')
591
710
  global.document.visibilityState = 'visible'
592
711
  })
593
- await atest('P18 background poll keeps in-progress threshold edits', async () => {
712
+ await atest('P28 background poll keeps in-progress threshold edits', async () => {
594
713
  resetHost()
595
714
  const b = boot()
596
715
  b.render()
@@ -605,6 +724,125 @@ await atest('P18 background poll keeps in-progress threshold edits', async () =>
605
724
  b.dispose()
606
725
  })
607
726
 
727
+ // Regression: a throttled test pushed the panel into "failed" for a request that
728
+ // never left the machine. A 429 carries no verdict, so it must only be reported.
729
+ await atest('P29 a 429 test keeps the last success and only warns', async () => {
730
+ resetHost()
731
+ HOST.verify = { at: Date.now() - 60000, ok: true, channel: 'wecom', error: null, persisted: true }
732
+ testPushThrottled = 1
733
+ const b = boot()
734
+ b.render()
735
+ await sleep(30)
736
+ if (!textOf(b.render()).includes('最近测试成功')) throw new Error('precondition: the last success must be visible')
737
+ await findButton(b.render(), '发送测试推送').props.onClick()
738
+ await sleep(80)
739
+ const txt = textOf(b.render())
740
+ if (!txt.includes('操作太频繁')) throw new Error('429 must be explained: ' + txt.slice(0, 240))
741
+ if (!txt.includes('最近测试成功')) throw new Error('a refused request must not rewrite the badge')
742
+ if (txt.includes('最近测试失败')) throw new Error('no verdict came back, so nothing may read as failed')
743
+ b.dispose()
744
+ })
745
+
746
+ // Regression: a /status that was already in flight when the test failed used to
747
+ // land afterwards and put the old green verdict back on the badge.
748
+ await atest('P30 a late /status cannot undo a newer failed test', async () => {
749
+ resetHost()
750
+ HOST.verify = { at: Date.now() - 60000, ok: true, channel: 'wecom', error: null, persisted: true }
751
+ const b = boot()
752
+ b.render()
753
+ await sleep(30)
754
+ if (!textOf(b.render()).includes('最近测试成功')) throw new Error('precondition: the old success must be visible')
755
+ statusHold = 1
756
+ b.tick() // poll leaves now, carrying the old success; its answer is held back
757
+ await sleep(20)
758
+ if (!heldStatus.length) throw new Error('the poll was not held')
759
+ testPushFails = 1
760
+ await findButton(b.render(), '发送测试推送').props.onClick()
761
+ await sleep(80)
762
+ if (!textOf(b.render()).includes('最近测试失败')) throw new Error('precondition: the test must fail first')
763
+ releaseStatus() // the slow poll finally answers
764
+ await sleep(40)
765
+ const txt = textOf(b.render())
766
+ if (!txt.includes('最近测试失败')) throw new Error('a stale poll resurrected the old success: ' + txt.slice(0, 240))
767
+ if (txt.includes('最近测试成功')) throw new Error('the old success must not come back')
768
+ testPushFails = 0
769
+ b.dispose()
770
+ })
771
+
772
+ // Regression: saving a new webhook used to be undone by a /status that was
773
+ // already in flight — the panel fell back to the previous address and to its
774
+ // "last test succeeded" badge, hiding that the new endpoint was never tested.
775
+ await atest('P31 a late /status cannot undo a saved webhook', async () => {
776
+ resetHost()
777
+ HOST.verify = { at: Date.now() - 60000, ok: true, channel: 'wecom', error: null, persisted: true }
778
+ const b = boot()
779
+ b.render()
780
+ await sleep(30)
781
+ let txt = textOf(b.render())
782
+ if (!txt.includes('qyapi.weixin.qq.com') || !txt.includes('最近测试成功')) throw new Error('precondition: old address + success must be visible')
783
+ statusHold = 1
784
+ b.tick() // poll leaves now, carrying the old webhook; its answer is held back
785
+ await sleep(20)
786
+ if (!heldStatus.length) throw new Error('the poll was not held')
787
+
788
+ await findButton(b.render(), '修改').props.onClick()
789
+ findById(b.render(), 'sentinel-chan').props.onChange({ target: { value: 'dingtalk' } })
790
+ findById(b.render(), 'sentinel-url').props.onChange({ target: { value: 'https://oapi.dingtalk.com/robot/send?access_token=t' } })
791
+ webhookReply = { ok: true, channel: 'dingtalk', configured: true, urlHost: 'oapi.dingtalk.com', secretSet: true }
792
+ await findButton(b.render(), '仅保存').props.onClick()
793
+ await sleep(80)
794
+ txt = textOf(b.render())
795
+ if (!txt.includes('oapi.dingtalk.com') || !txt.includes('已配置,待测试')) throw new Error('precondition: the saved webhook must be shown: ' + txt.slice(0, 240))
796
+ if (txt.includes('qyapi.weixin.qq.com')) throw new Error('precondition: the old address must be gone')
797
+
798
+ // Keep the mock host in step with the save, so only the held response can be stale.
799
+ HOST.channel = 'dingtalk'; HOST.urlHost = 'oapi.dingtalk.com'; HOST.verify = null
800
+ releaseStatus() // the slow poll finally answers with the old webhook
801
+ await sleep(40)
802
+ txt = textOf(b.render())
803
+ if (!txt.includes('oapi.dingtalk.com')) throw new Error('a stale poll restored the old address: ' + txt.slice(0, 240))
804
+ if (txt.includes('qyapi.weixin.qq.com')) throw new Error('the replaced address must not come back')
805
+ if (!txt.includes('已配置,待测试')) throw new Error('the new endpoint must stay untested: ' + txt.slice(0, 240))
806
+ if (txt.includes('最近测试成功')) throw new Error('the old verdict must not return for the new webhook')
807
+ b.dispose()
808
+ })
809
+
810
+ // Regression: the first-use auto-open ran on any early /status, including one
811
+ // that had been superseded by a save. The summary said "configured" while the
812
+ // setup form popped back open under it.
813
+ await atest('P32 a stale /status cannot reopen the form after saving', async () => {
814
+ resetHost()
815
+ Object.assign(HOST, { configured: false, channel: 'none', urlHost: '', secretSet: false, verify: null })
816
+ const b = boot()
817
+ b.render()
818
+ await sleep(30)
819
+ if (!findById(b.render(), 'sentinel-url')) throw new Error('precondition: first use must open the setup form')
820
+
821
+ statusHold = 1
822
+ await findButton(b.render(), '刷新').props.onClick()
823
+ b.render() // the refresh restarts the poll effect; that first /status is held
824
+ await sleep(20)
825
+ if (!heldStatus.length) throw new Error('the refresh poll was not held')
826
+
827
+ findById(b.render(), 'sentinel-url').props.onChange({ target: { value: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=k' } })
828
+ webhookReply = { ok: true, channel: 'wecom', configured: true, urlHost: 'qyapi.weixin.qq.com', secretSet: false }
829
+ await findButton(b.render(), '仅保存').props.onClick()
830
+ await sleep(80)
831
+ let node = b.render()
832
+ if (findById(node, 'sentinel-url')) throw new Error('precondition: a successful save must close the form')
833
+ if (!textOf(node).includes('已配置,待测试')) throw new Error('precondition: the saved channel must read untested')
834
+
835
+ // Keep the mock host in step with the save, so only the held response is stale.
836
+ Object.assign(HOST, { configured: true, channel: 'wecom', urlHost: 'qyapi.weixin.qq.com' })
837
+ releaseStatus() // the obsolete "not configured" snapshot finally answers
838
+ await sleep(40)
839
+ node = b.render()
840
+ if (findById(node, 'sentinel-url')) throw new Error('an obsolete /status reopened the setup form')
841
+ const txt = textOf(node)
842
+ if (!txt.includes('已配置,待测试')) throw new Error('the summary must still read untested: ' + txt.slice(0, 240))
843
+ b.dispose()
844
+ })
845
+
608
846
  console.log(`\n${passed} passed, ${failed} failed`)
609
847
  process.exitCode = failed ? 1 : 0
610
848
  setTimeout(() => process.exit(process.exitCode), 100).unref()
@@ -873,6 +873,29 @@ await atest('M14 a cycle does not carry a verdict onto a replaced webhook', asyn
873
873
  assert.equal(s.verify, null, 'a verdict for the old webhook must not follow the config')
874
874
  assert.equal(loadState().verify, null, 'and it must not be written back either')
875
875
  })
876
+ // A newer unwritten verdict for the OLD webhook must not win on time and then be
877
+ // thrown away, taking the file's valid record for the current webhook with it:
878
+ // filter by channel first, compare times second.
879
+ await atest('M15 a stale verdict for another webhook keeps the current record', async () => {
880
+ const s = fresh()
881
+ const A = { channel: 'wecom', url: 'http://127.0.0.1:1/a', secret: '' }
882
+ const B = { channel: 'wecom', url: 'http://127.0.0.1:1/b', secret: '' }
883
+ s.webhook = B
884
+ s.verify = { at: 1000, ok: true, channel: 'wecom', error: null, fp: webhookFingerprint(B), persisted: true }
885
+ assert.equal(saveState(s, undefined, { own: ['webhook', 'verify'] }), true)
886
+
887
+ const stale = { at: 2000, ok: false, channel: 'wecom', error: 'stale', fp: webhookFingerprint(A), persisted: false }
888
+ s.verify = { ...stale }
889
+ mergeStateFromDisk(s)
890
+ assert.equal(s.verify.ok, true, 'the valid record for the current webhook must win')
891
+ assert.equal(s.verify.fp, webhookFingerprint(B))
892
+
893
+ // The regular save path (a monitor cycle) must not change that verdict either.
894
+ s.verify = { ...stale }
895
+ assert.equal(saveState(s), true)
896
+ assert.equal(s.verify.ok, true, 'a monitor-cycle save must keep the current record')
897
+ assert.equal(loadState().verify.ok, true, 'and the file still holds it')
898
+ })
876
899
 
877
900
  console.log(`\n${passed} passed, ${failed} failed`)
878
901
  process.exitCode = failed ? 1 : 0