dsh-balance-sentinel 0.1.3 → 0.1.5

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,38 @@
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.5] - 2026-11-20
7
+
8
+ ### Changed
9
+
10
+ - **首次进入不再自动展开配置表单**:未配置推送通道时由顶部横幅(「监控中,通知未接通」+「现在配置」)说明并引导,表单只在点击后出现。此前进入面板即摊开一个空表单,与横幅说的是同一件事,且点「刷新」会把用户已经关掉的表单再次弹出;表单内重复的空态说明一并去掉,未配置时该卡片的入口按钮从「仅保存」改为「配置推送」(它本来也只是打开表单,并未保存任何东西;文案与同作者的 dsh-aihot-radar 对齐,横幅 CTA 仍为「现在配置」);同时未配置的表单也有了「取消」,点开看一眼或误点都能退出,不提交任何内容。
11
+ - **署名与安装尾注改为默认关闭**:低余额告警、恢复通知和测试推送在未显式开启时不再附带任何推广尾注,推送内容只讲余额。`notify.signature` 现在保留「未设置 / `true` / `false`」三态——不设默认值,避免宿主配置库把未填写补成 `false`、连带丢弃只配了 `signatureText` 的老用户的自定义尾注;只写 `signatureText` 视为开启,`signature: false` 优先于它。面板推送卡片新增「附上插件安装链接」勾选框(默认关闭,写入状态文件,不用改 YAML),`/status` 与发送端都按合并后的实际状态执行。README 中英示例配置同步为 `signature: false` 并说明三态。
12
+ - **推送卡片收紧为「一行一件事」**:地址与测试时间合并成 `open.feishu.cn · 11:31:49`(成功/失败已由标题右侧徽章表达,不再重复写「最近测试成功:」),失败原因单独一行,「低余额/恢复通知将推送到这里,保存即生效,无需重启」移到配置表单底部(那里才在解释保存行为)。安装链接开关保留自己一行并带完整说明「附上安装链接(默认关闭,开启后告警尾部会多一行署名)」,动作按钮仍在其下方左对齐,且「修改」与「发送测试推送」改用同一按钮样式(不再一实一描边);配置表单里开关与按钮之间补了 10px 间距。摘要态由 6 行减到 4 行。
13
+ - **告警标题带上插件名**:`余额哨兵 · DeepSeek 余额告急/预警/告警已解除/已恢复`。尾注默认关闭后,被转发到群里的卡片仍需能自解释来源,前缀足够短,不会被 IM 标题截断。
14
+
15
+ ### Fixed
16
+
17
+ - **尾注开关不再被旧实例改回**:`notify` 之前不在状态合并与写入保护里,面板关掉尾注后,另一个仍持有旧内存的实例只要保存一次常规状态(如余额),磁盘就会被写回「跟随配置」,等于把开关重新打开。现在读取合并(`mergeStateFromDisk`)会采纳磁盘值,写入(`SECTIONS`)把 `notify` 当作面板独占字段——不拥有它的保存方一律沿用文件内容,开启与关闭两个方向都成立。
18
+ - **取消编辑后「修改」按钮不再留一圈亮边**:表单里的「关闭推送」与摘要态的「修改」在按钮行中同处一个位置,React 复用同一个 DOM 节点;「关闭推送」额外用 `borderColor` 覆盖描边颜色,回到摘要态时该覆盖被清除,复用的按钮失去自己的内联描边色、退回 `currentColor`(再叠加品牌色 hover 规则就是一圈亮蓝描边),看起来像还停在选中态。该按钮改用 `border` 简写声明描边;面板内按钮的 hover 不再改描边色,焦点环只留给键盘(`:focus-visible`),鼠标点击不残留。
19
+ - **迟到的 `/status` 不再改回开关**:面板保存尾注开关成功后递增配置版本,保存之前发出的轮询响应整体丢弃(与保存 Webhook 同一规则),复选框不会在用户眼前跳回旧值。
20
+ - **旧查询不再覆盖新余额**:两个实例(或 poke 与在途轮询)的查询可能反序返回。轮询结果现在以「查询发起时刻」为序落地:拿到锁并合并磁盘状态后,若已记录的结论发起得不早于本轮(含同一毫秒的平局),整轮结果直接丢弃——不回写余额、不改告警等级、不触发推送,也不写盘。时间戳只有毫秒精度,两个实例可能在同一毫秒发起查询,此时谁先落盘谁就代表面板已展示的事实,宁可少落一次也不回滚。
21
+ - **丢弃旧响应后仍会自动轮询**:上一版的早退 `return` 跳过了周期末尾的 `setTimeout`,被丢弃的那台实例会就此停摆,只能靠手动刷新唤醒。定时器改为在 `finally` 里重排,任何提前返回(旧响应、停止时竞态)都不会让实例静默停转。
22
+ - **损坏的锁不再永久阻塞**:锁文件不可读(创建后未写完、写入被截断)此前一律无法接管,等于此后所有实例都不再写入和推送。锁龄现在优先取心跳时间戳、读不到时退回文件 mtime,只有「不可读且超过 TTL」才接管;刚创建尚未写完的锁与仍有效的锁都不会被抢,一直被占的写方靠 token 校验自动放弃。接管守卫文件损坏时同样按 mtime 自愈。
23
+ - **停止监控后不再发送**:`stop()` 发生在查询在途时,返回的余额此前仍会走完判定并推送。现在查询返回后先校验停止标志,已停止则本轮既不落盘也不推送。
24
+ - **失败轮询不再把旧余额当当前余额发送**:本轮查询失败时 `balance.ok` 为 false,此前待发告警仍会带着上一次的数字发出去。现在告警保留在待发槽里,等下一次查询成功、按新余额重新判定后再发。
25
+ - **宿主未登录时 API Key 回退恢复**:`signed-out` 此前会短路返回,即使配置了 Key 也走不到备用接口,与 README「否则用 `DEEPSEEK_API_KEY` 或 `balance.apiKey`」相违。现在只有「没有 Key」才报未登录;两者都不可用时面板文案改为「未登录且无可用 Key」,并写明登录与配置 Key 两条路径。
26
+ - **通知来源更正**:Bark 的 `group` 与通用 Webhook 的 `source` 从 `aihot-radar` 改为 `balance-sentinel`。
27
+
28
+ ### Tests
29
+
30
+ - `node scripts/selftest.mjs`:79 passed / 0 failed。本轮新增 12 条:C1-C4 覆盖锁恢复(过期且不可读可接管、刚创建的空锁与心跳新鲜的锁不得被抢、可读但超 TTL 仍可接管);R1 让两个实例反序返回(先发后答 vs 后发先答)断言旧结果不推送、不回写余额、不改等级;R1b 用 1s 轮询下限(测试专用环境变量 `SENTINEL_POLL_FLOOR_SEC`,生产仍是 60s)验证被丢弃的一轮之后仍会自动跑下一轮;R1c 冻结 `Date.now` 制造同毫秒平局,断言已接受的 ¥30 不会回滚成 ¥3、不告警,且该轮标记为 stale;R2 在查询在途时停止监控,断言返回后不推送不落盘;R3 断言查询失败时待发告警保留、下一次成功查询后才发出;S10/S11 覆盖宿主未登录时走 REST Key、Key 被拒时如实报 `unauthorized`;F6 断言 Bark `group` 与通用 Webhook `source` 均为 `balance-sentinel`。另外仍覆盖三种署名情况——默认关闭(默认测试消息、`critical`/`warn` 告警、`recovered` 恢复通知正文均无 `安装:`、安装 spec 与仓库地址)、显式开启(`signature: true` 正常附上尾注,Feishu 走 `lark_md` note,纯文本通道只留标签)、显式关闭(`signature: false` 即使带 `signatureText` 也不附带)。F1b 断言四类标题都以「余额哨兵 · 」开头且保留告急/预警/恢复/解除字样;F4 先用源码断言 `notify.signature` 不带任何默认值,再在装有宿主 Schema 包时用真实配置解析验证 `{ notify: { signatureText } }` 解析后 `signature` 仍为 `undefined`、未配置解析为空即关闭、显式 `false`/`true` 各自生效(未安装该包时打印 SKIP,只跑源码断言);F5 覆盖面板覆盖值与 `null`(跟随配置)的合并;B6b/B6c 起本地 hook 抓桥接真实 POST 的 `/test-push` 正文,默认无尾注、`signature: true` 有尾注,并验证 `POST /notify` 后 `/status` 与发送内容同步翻转、关回去也生效。
31
+ - `node scripts/selftest-client.mjs`:39 passed / 0 failed(P35:面板开关默认未勾选、勾选后发出 `signature: true`、再由服务端回填为勾选态、取消勾选可回到关闭;P37:旧 `/status` 返回后复选框不得跳回旧值;P38:「关闭推送」不得引入 `borderColor` 覆盖、取消后「修改」仍自带描边、hover 规则不得把描边刷成品牌色、键盘焦点仍有焦点环)。
32
+ - 针对上述两个合并点的有效性验证:M15 使用真实临时状态文件,分别以 `false`/`true` 让面板实例写一次、再让「仍持有跟随配置值」的实例只保存 `alert`,断言磁盘值不变;再断言 `mergeStateFromDisk` 会采纳磁盘值。单独移除写入保护时 M15 报 `a routine save must not overwrite false`,单独移除读取合并时报 `mergeStateFromDisk must adopt false`。P37 移除配置版本递增后报 `a stale /status turned the footer switch back off`。
33
+ - 本轮六项修复的有效性验证(逐项回退修复后跑同一套回归):去掉「已记录结论更晚」的比较后 R1 报 `a superseded reading must not push`;去掉停止标志检查后 R2 报 `a stopped monitor must not push what an old query returned`;去掉 `balance.ok` 守卫后 R3 报 `the old number must not be sent as the current balance`;把 `signed-out` 重新放回短路条件后 S10/S11 同时失败;锁接管条件改回「读不到就放弃」后 C1 报 `an expired unreadable lock must not block forever`,改成「见锁就抢」后 C3 报 `a live lock with a fresh heartbeat is never taken over`;比较改回严格大于后 R1c 报 `a tie must not push`(余额从 ¥30 回落到 ¥3 并告急);定时器移回 `finally` 之外后 R1b 报 `the dropped cycle must still re-arm the poll (calls: 1)`。
34
+ - 打包产物检查(本轮):`npm pack` 解包后从 tarball 内 import 并执行 6 项检查,6/6 通过 —— 未登录 + Key 走 REST、`balance.ok=false` 时 `deliverPending` 返回 null 且保留 pending、Bark `group` 与通用 `source` 正确、过期且不可读的锁可恢复而新锁不被抢、`client.js` 与 `locale/*.json` 已随包、打包副本可正常读写状态。
35
+ - 打包产物检查(署名改动):对 `npm pack` 的 tarball 解包后直接 import 包内 `lib/notify.js` 与 `lib/balance.js`(不读工作区源码),14/14 通过 —— `index.js` 里 `notify.signature` 无默认值、`signatureLine({})` 为空、`signatureEnabled({ signatureText })` 为真、面板覆盖优先于配置、默认测试消息与 `critical`/`warn`/`recovered` 正文均不含尾注、三类告警标题均以「余额哨兵 · 」开头、显式开启时正常附上。
36
+ - LPM 的报告针对 0.1.2,本次改动未经重新扫描,不能据此认为相关拦截已解除。
37
+
6
38
  ## [0.1.3] - 2026-11-18
7
39
 
8
40
  ### Fixed
@@ -69,6 +101,7 @@ All notable changes to this project are documented here. Format follows
69
101
  - README 面板截图前置、补「先看三行」要点;适用范围与免 Key 边界并入安装节,不再单列小节。
70
102
  - GitHub About 描述收紧为一句:低余额推送 + 本机运行边界。
71
103
 
104
+ [0.1.5]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.5
72
105
  [0.1.3]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.3
73
106
  [0.1.2]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.2
74
107
  [0.1.0]: https://github.com/liancheng2020/dsh-balance-sentinel/releases/tag/v0.1.0
package/README.en.md CHANGED
@@ -32,19 +32,19 @@ 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.3/dsh-balance-sentinel-0.1.3.tgz
35
+ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.5/dsh-balance-sentinel-0.1.5.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.3` (see [CHANGELOG](CHANGELOG.md)).
42
+ > Current version `0.1.5` (see [CHANGELOG](CHANGELOG.md)).
43
43
 
44
44
  ## First use (two steps)
45
45
 
46
46
  1. Open the **Balance Sentinel** panel: your real balance immediately, or a clear reason (signed out / no account service / network…).
47
- 2. Pick a channel, paste the webhook (auto-detected) → **Save and send test**. The Feishu/DingTalk form includes "How to get a bot webhook": official doc + three-step path + the security settings that channel supports. **Until a channel is saved it watches without pushing**.
47
+ 2. Click **Set it up**, pick a channel, paste the webhook (auto-detected) → **Save and send test**. The Feishu/DingTalk form includes "How to get a bot webhook": official doc + three-step path + the security settings that channel supports. **Until a channel is saved it watches without pushing**.
48
48
 
49
49
  Saving only gets you to "configured, not tested"; the badge turns into "last test succeeded" once a test push actually lands, and into "last test failed" (with the reason and time) when it does not. Editing the channel or credentials clears the old result, so a stale "verified" can never pass for a working endpoint.
50
50
 
@@ -75,8 +75,8 @@ If the balance is already below a threshold when you connect, one current-state
75
75
  quiet: { start: "", end: "" } # e.g. "23:00"–"08:00"
76
76
  apiKey: "" # fallback for older hosts only
77
77
  notify:
78
- signature: true # "via …" footer line whose install spec is tappable, opt-out
79
- signatureText: ""
78
+ signature: false # off by default (same switch in the panel, no config edit needed); true appends the "via …" install line
79
+ signatureText: "" # custom text; setting only this also turns the footer on
80
80
  localApi:
81
81
  enabled: true # panel bridge on 127.0.0.1:17430
82
82
  ```
package/README.md CHANGED
@@ -32,19 +32,19 @@ 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.3/dsh-balance-sentinel-0.1.3.tgz
35
+ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentinel/releases/download/v0.1.5/dsh-balance-sentinel-0.1.5.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.3`(见 [CHANGELOG](CHANGELOG.md))。
42
+ > 当前版本 `0.1.5`(见 [CHANGELOG](CHANGELOG.md))。
43
43
 
44
44
  ## 首次使用(两步接通)
45
45
 
46
46
  1. 打开 **余额哨兵** 面板:立刻看到真实余额,或明确原因(未登录 / 无账号服务 / 网络…)。
47
- 2. 「推送配置」选通道 → 粘 webhook(自动识别)→ **保存并发送测试**。飞书/钉钉框内有「如何获取机器人 Webhook」:官方链接 + 三步路径 + 该通道适用的安全设置。**没配通道前只监控不推送**。
47
+ 2. 点「现在配置」→「推送配置」选通道 → 粘 webhook(自动识别)→ **保存并发送测试**。飞书/钉钉框内有「如何获取机器人 Webhook」:官方链接 + 三步路径 + 该通道适用的安全设置。**没配通道前只监控不推送**。
48
48
 
49
49
  保存成功只说明通道「已配置,待测试」,测试推送真的送达才会变成「最近测试成功」;失败则显示「最近测试失败」并附原因与时间。改通道或凭据后旧结果立即清除,不会有残留的「已验证」冒充接通。
50
50
 
@@ -75,8 +75,8 @@ dsh plugin --profile web add https://github.com/liancheng2020/dsh-balance-sentin
75
75
  quiet: { start: "", end: "" } # 免打扰,如 "23:00"–"08:00"
76
76
  apiKey: "" # 仅老宿主回落用;优先宿主账号/环境变量
77
77
  notify:
78
- signature: true # 推送尾部署名(安装标识可点击),可关
79
- signatureText: ""
78
+ signature: false # 默认关闭(面板同一开关,不用改配置);改 true 才在推送尾部附署名与安装链接
79
+ signatureText: "" # 自定义署名文案;只填这里也视为开启
80
80
  localApi:
81
81
  enabled: true # 面板桥接 127.0.0.1:17430,可关
82
82
  ```
package/client.js CHANGED
@@ -54,7 +54,7 @@ window.__ModuleLoader__.load({
54
54
  'level.normal': '余额正常', 'level.warn': '余额预警', 'level.critical': '余额告急',
55
55
  'reason.title': '余额暂不可用', 'reason.retry': '重试',
56
56
  'reason.no-source': '宿主没有账号服务,也未提供 API Key。带官方「设置→账号与余额」的宿主支持免填 Key;否则在配置 balance.apiKey 或环境变量 DEEPSEEK_API_KEY 提供 Key。',
57
- 'reason.signed-out': '宿主未登录 DeepSeek 账户:请在官方「设置→账号与余额」登录后重试。',
57
+ 'reason.signed-out': '宿主未登录 DeepSeek 账户,也没有可用的 API Key:请在官方「设置→账号与余额」登录,或配置 balance.apiKey / 环境变量 DEEPSEEK_API_KEY 后重试。',
58
58
  'reason.unauthorized': 'API Key 无效或过期:请更新 Key,或改用宿主账号登录(免填 Key)。',
59
59
  'reason.account-failed': '宿主账号服务查询失败,稍后自动重试。',
60
60
  'reason.account-error': '宿主账号服务调用异常,稍后自动重试。',
@@ -74,19 +74,19 @@ window.__ModuleLoader__.load({
74
74
  'sec.push': '推送配置', 'push.channel': '推送通道:{c}', 'push.on': '已配置', 'push.off': '未配置',
75
75
  'push.untested': '已配置,待测试', 'push.verified': '最近测试成功', 'push.failed': '最近测试失败',
76
76
  'push.untestedHint': '通道已保存,但还没有测试过发送:点「发送测试推送」确认能收到,别等真告警时才发现地址不通。',
77
- 'push.verifiedAt': '最近测试成功:{t}',
78
- 'push.failedAt': '最近测试失败:{t}{e}',
77
+ 'push.failedWhy': '失败原因:{e}',
79
78
  'push.testStale': '测试期间推送配置已变更,本次结果未计入当前通道。',
80
79
  'push.notPersisted': '结果未写入状态文件,重启后会丢失。',
81
80
  'chan.none': '未配置', 'chan.wecom': '企业微信', 'chan.dingtalk': '钉钉', 'chan.feishu': '飞书',
82
81
  'chan.bark': 'Bark', 'chan.serverchan': 'Server酱', 'chan.telegram': 'Telegram', 'chan.generic': '通用 Webhook',
83
82
  'push.hint': '低余额/恢复通知将推送到这里,保存即生效,无需重启。',
84
83
  'push.empty': '还没有配置推送通道。填好地址保存,余额不足时自动提醒到 IM。',
85
- 'push.current': '当前地址:{h}',
86
84
  'push.field.channel': '推送通道', 'push.field.url': 'Webhook 地址', 'push.field.token': 'Bot Token',
87
85
  'push.field.secret': '加签密钥(可选)', 'push.field.chat': 'chat_id',
88
86
  'push.saveTest': '保存并发送测试', 'push.save': '仅保存', 'push.saving': '保存中…',
89
- 'push.edit': '修改', 'push.cancel': '取消', 'push.saved': '已保存,立即生效。',
87
+ 'push.edit': '修改', 'push.setup': '配置推送', 'push.cancel': '取消', 'push.saved': '已保存,立即生效。',
88
+ 'push.signature': '附上安装链接', 'push.signatureHint': '(默认关闭,开启后告警尾部会多一行署名)',
89
+ 'push.signatureTitle': '默认关闭;开启后告警尾部会多一行署名与安装链接',
90
90
  'push.disable': '关闭推送', 'push.disableConfirm': '确认关闭?', 'push.disabled': '已关闭推送,可随时重新配置。',
91
91
  'push.test': '发送测试推送', 'push.testing': '发送中…',
92
92
  'push.testOk': '测试推送成功:{c} 通道正常,发出 {n} 条。',
@@ -105,7 +105,7 @@ window.__ModuleLoader__.load({
105
105
  'level.normal': 'Balance OK', 'level.warn': 'Low balance', 'level.critical': 'Critical balance',
106
106
  'reason.title': 'Balance unavailable', 'reason.retry': 'Retry',
107
107
  'reason.no-source': 'No host account service and no API key. Hosts with the official "Account & Balance" page support key-free accounts; otherwise set balance.apiKey in config or the DEEPSEEK_API_KEY env var.',
108
- 'reason.signed-out': 'The host is not signed in to a DeepSeek account: sign in via the official "Account & Balance" page, then retry.',
108
+ 'reason.signed-out': 'The host is not signed in to a DeepSeek account and no API key is available: sign in via the official "Account & Balance" page, or set balance.apiKey / the DEEPSEEK_API_KEY env var, then retry.',
109
109
  'reason.unauthorized': 'API key invalid or expired: update the key, or sign in with the host account (no key needed).',
110
110
  'reason.account-failed': 'Host account service query failed; retrying automatically.',
111
111
  'reason.account-error': 'Host account service call errored; retrying automatically.',
@@ -125,19 +125,20 @@ window.__ModuleLoader__.load({
125
125
  'sec.push': 'Push settings', 'push.channel': 'Push channel: {c}', 'push.on': 'Configured', 'push.off': 'Not set',
126
126
  'push.untested': 'Configured, not tested', 'push.verified': 'Last test succeeded', 'push.failed': 'Last test failed',
127
127
  'push.untestedHint': 'The webhook is saved but has never been tested: hit "Send test push" now, so a dead endpoint cannot stay hidden until a real alert needs it.',
128
- 'push.verifiedAt': 'Last test succeeded: {t}',
129
- 'push.failedAt': 'Last test failed: {t}{e}',
128
+ 'push.failedWhy': 'Failure: {e}',
130
129
  'push.testStale': 'The push config changed while the test was running; this result was discarded.',
131
130
  'push.notPersisted': 'Result not written to the state file; it will be lost on restart.',
132
131
  'chan.none': 'Not set', 'chan.wecom': 'WeCom', 'chan.dingtalk': 'DingTalk', 'chan.feishu': 'Feishu',
133
132
  'chan.bark': 'Bark', 'chan.serverchan': 'ServerChan', 'chan.telegram': 'Telegram', 'chan.generic': 'Generic webhook',
134
133
  'push.hint': 'Low-balance / recovery notices push here. Saving applies immediately, no restart.',
135
134
  'push.empty': 'No push channel yet. Save a URL and get IM alerts when the balance runs low.',
136
- 'push.current': 'Endpoint: {h}',
135
+
137
136
  'push.field.channel': 'Channel', 'push.field.url': 'Webhook URL', 'push.field.token': 'Bot Token',
138
137
  'push.field.secret': 'Sign secret (optional)', 'push.field.chat': 'chat_id',
139
138
  'push.saveTest': 'Save and send test', 'push.save': 'Save only', 'push.saving': 'Saving…',
140
- 'push.edit': 'Edit', 'push.cancel': 'Cancel', 'push.saved': 'Saved; effective immediately.',
139
+ 'push.edit': 'Edit', 'push.setup': 'Set up push', 'push.cancel': 'Cancel', 'push.saved': 'Saved; effective immediately.',
140
+ 'push.signature': 'Append the install link', 'push.signatureHint': '(off by default, adds a signature line on alerts)',
141
+ 'push.signatureTitle': 'Off by default; when on, alerts end with a signature line and install link',
141
142
  'push.disable': 'Turn off', 'push.disableConfirm': 'Confirm?', 'push.disabled': 'Push turned off; configure it again anytime.',
142
143
  'push.test': 'Send test push', 'push.testing': 'Sending…',
143
144
  'push.testOk': 'Test push via {c} succeeded, {n} message(s) sent.',
@@ -230,7 +231,6 @@ window.__ModuleLoader__.load({
230
231
  live: { width: 7, height: 7, borderRadius: '50%', background: T.success },
231
232
  sub: { color: T.tertiary, fontSize: 12, margin: '3px 0 0' },
232
233
  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' },
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' },
234
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
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 },
236
236
  heroVal: { fontSize: 30, fontWeight: 700, lineHeight: 1.2 },
@@ -349,7 +349,19 @@ window.__ModuleLoader__.load({
349
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; }
350
350
  .sentinel-panel::-webkit-scrollbar { width: 8px; }
351
351
  .sentinel-panel::-webkit-scrollbar-thumb { background: ${T.border}; border-radius: 8px; }
352
- .sentinel-btn:hover { border-color: ${T.brand}; color: ${T.text}; background: ${T.hover}; }
352
+ /* Quiet interaction states for every button in the panel. The border is
353
+ never recoloured on hover: a recycled button node can end up without
354
+ its own inline border colour (see the "turn off" button in the form),
355
+ and a brand-coloured hover rule then draws a bright ring around a
356
+ plain action like "修改" — which reads as "still selected" and, once
357
+ the pointer leaves, can survive the whole render. Focus is the same
358
+ deal: we draw the ring ourselves, and only for keyboard focus, so a
359
+ mouse click never leaves one behind. */
360
+ .sentinel-panel button { outline: none; -webkit-tap-highlight-color: transparent; }
361
+ .sentinel-panel button:hover:not(:disabled) { border-color: ${T.border}; color: ${T.text}; background: ${T.hover}; box-shadow: none; }
362
+ .sentinel-panel button:active:not(:disabled) { transform: scale(0.98); }
363
+ .sentinel-panel button:focus { outline: none; box-shadow: none; }
364
+ .sentinel-panel button:focus-visible { outline: 1px solid ${tint(T.brand, 55)}; outline-offset: 1px; }
353
365
  .sentinel-link:hover { opacity: 0.75; }
354
366
  .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%); }
355
367
  .sentinel-toast-ok { background: ${tint(T.success, 16)}; border: 1px solid ${tint(T.success, 65)}; color: ${T.text}; }
@@ -379,7 +391,6 @@ window.__ModuleLoader__.load({
379
391
  let cancelled = false
380
392
  let timer = null
381
393
  let attempt = 0
382
- let seeded = false
383
394
  const load = async () => {
384
395
  // Ordering tokens taken when the request leaves, not when it returns.
385
396
  const issued = verdictSeq.current
@@ -410,10 +421,11 @@ window.__ModuleLoader__.load({
410
421
  if (verdictSeq.current > issued && j.channel === prev.channel) return { ...j, verify: prev.verify }
411
422
  return j
412
423
  })
413
- // Auto-open the setup form once, not on every poll: a later refresh
414
- // must not re-open it under a user who just closed it.
415
- if (!seeded && !j.configured) setEditing(true)
416
- seeded = true
424
+ // The setup form never opens by itself. An unconfigured channel is
425
+ // announced by the banner (with its own CTA), so first use reads as
426
+ // the monitor it is instead of a form to fill in; opening it stays a
427
+ // deliberate click, and no refresh can pop it open again.
428
+ //
417
429
  // Refresh the draft only while the user has not typed in the field.
418
430
  // This must be a synchronous ref read, not a functional setState that
419
431
  // compares against a closure variable: React runs that updater later,
@@ -646,8 +658,41 @@ window.__ModuleLoader__.load({
646
658
  h('div', { style: { ...css.metaDim, marginTop: 6, whiteSpace: 'pre-line' } }, t('help.' + ch + '.steps')))
647
659
  }
648
660
 
661
+ // Footer opt-in lives in the panel: send the whole switch, never a delta, so
662
+ // the checkbox and the state file cannot disagree after a failed write.
663
+ const toggleSignature = async (on) => {
664
+ setBusy('sig'); showResult(null)
665
+ try {
666
+ const j = await post('/notify', { signature: !!on })
667
+ if (!j.ok) { showResult({ ok: false, message: j.message || '' }); return }
668
+ // Same rule as a webhook save: a /status issued before this write still
669
+ // reports the old switch, and letting it land would flip the checkbox
670
+ // back under the user.
671
+ configSeq.current += 1
672
+ setHost((prev) => ({ ...(prev || {}), signature: !!j.signature }))
673
+ } catch (e) { showResult({ ok: false, message: String(e?.message || e) }) }
674
+ finally { setBusy('') }
675
+ }
676
+
677
+ const signatureToggle = (extra) => h('label', {
678
+ htmlFor: 'sentinel-sig',
679
+ // The full sentence lives in the tooltip: on the card it was the longest
680
+ // line for the least important control.
681
+ title: t('push.signatureTitle'),
682
+ style: { display: 'flex', alignItems: 'flex-start', gap: 6, marginTop: 10, cursor: busy ? 'default' : 'pointer', fontSize: 12, ...extra },
683
+ },
684
+ h('input', {
685
+ type: 'checkbox', id: 'sentinel-sig', checked: !!host?.signature, disabled: !!busy,
686
+ style: { margin: '2px 0 0', accentColor: T.brand },
687
+ onChange: (e) => toggleSignature(e.target.checked),
688
+ }),
689
+ h('span', { style: { color: T.sub, lineHeight: 1.5 } },
690
+ h('span', { style: { color: T.text } }, t('push.signature')),
691
+ // Chinese full-width brackets sit flush against the label; the Latin
692
+ // parenthesis needs a small gap to stay legible.
693
+ h('span', { style: { ...css.metaDim, marginLeft: LANG === 'en' ? 4 : 0 } }, t('push.signatureHint'))))
694
+
649
695
  const pushForm = () => h('div', { style: css.card },
650
- host?.configured ? null : h('div', { style: { ...css.metaDim, marginBottom: 10 } }, t('push.empty')),
651
696
  h('div', { style: css.field },
652
697
  h('label', { style: css.fieldLabel, htmlFor: 'sentinel-chan' }, t('push.field.channel')),
653
698
  h('select', {
@@ -671,11 +716,23 @@ window.__ModuleLoader__.load({
671
716
  onChange: (e) => setForm({ ...form, secret: e.target.value }),
672
717
  })) : null,
673
718
  webhookHelp(),
674
- h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
675
- host?.configured ? h('button', { type: 'button', style: css.btn, disabled: !!busy, onClick: () => { setEditing(false); setOffConfirm(false); showResult(null) } }, t('push.cancel')) : null,
719
+ signatureToggle(),
720
+ // Breathing room between the switch and the actions: without it the two
721
+ // rows read as one block and the buttons crowd the checkbox label.
722
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' } },
723
+ // Also offered before the first save: the form no longer opens by
724
+ // itself, so whoever opened it (by mistake or just to look) needs a way
725
+ // back to the summary without saving anything.
726
+ h('button', { type: 'button', style: css.btn, disabled: !!busy, onClick: () => { setEditing(false); setOffConfirm(false); showResult(null) } }, t('push.cancel')),
676
727
  host?.configured ? h('button', {
677
728
  type: 'button', disabled: !!busy,
678
- style: { ...css.btn, color: offConfirm ? T.error : T.sub, borderColor: offConfirm ? T.error : T.border },
729
+ // The red border is a shorthand, not a borderColor override: this
730
+ // button sits at the same position in the row as the "修改" button of
731
+ // the summary, so React recycles one DOM node for both. When the
732
+ // extra borderColor key disappears on the way back, React clears that
733
+ // inline colour and the recycled node falls back to currentColor —
734
+ // a hard grey ring around "修改" that no longer matches its siblings.
735
+ style: { ...css.btn, color: offConfirm ? T.error : T.sub, border: `1px solid ${offConfirm ? T.error : T.border}` },
679
736
  onClick: disablePush,
680
737
  }, offConfirm ? t('push.disableConfirm') : t('push.disable')) : null,
681
738
  h('button', { type: 'button', style: css.btn, disabled: !!busy, onClick: () => saveWebhook(false) }, t('push.save')),
@@ -683,7 +740,10 @@ window.__ModuleLoader__.load({
683
740
  type: 'button', disabled: !!busy,
684
741
  style: busy ? { ...css.btnPrimary, opacity: 0.6, cursor: 'not-allowed' } : css.btnPrimary,
685
742
  onClick: () => saveWebhook(true),
686
- }, busy === 'test' ? t('push.testing') : busy === 'save' ? t('push.saving') : t('push.saveTest'))))
743
+ }, busy === 'test' ? t('push.testing') : busy === 'save' ? t('push.saving') : t('push.saveTest'))),
744
+ // Where this sentence is actually useful: it explains what saving does,
745
+ // so it belongs next to the save buttons, not in the summary card.
746
+ h('div', { style: { ...css.metaDim, marginTop: 8 } }, t('push.hint')))
687
747
 
688
748
  // "Configured" is not "connected": a stored webhook proves nothing until a
689
749
  // test push comes back. Four states, and only a tested-good one is green —
@@ -697,12 +757,17 @@ window.__ModuleLoader__.load({
697
757
  : connState === 'failed' ? T.error
698
758
  : connState === 'untested' ? T.brand
699
759
  : T.sub // off: a secondary grey, not the dimmed token (too faint on white)
700
- const connLine = connState === 'verified' ? t('push.verifiedAt', { t: fmtTime(verifyInfo.at) })
701
- + (verifyInfo.persisted === false ? ' · ' + t('push.notPersisted') : '')
702
- : connState === 'failed'
703
- ? t('push.failedAt', { t: fmtTime(verifyInfo.at), e: verifyInfo.error ? (LANG === 'en' ? ': ' : ':') + verifyInfo.error : '' })
704
- + (verifyInfo.persisted === false ? ' · ' + t('push.notPersisted') : '')
705
- : connState === 'untested' ? t('push.untestedHint') : ''
760
+ // Address and test time share one line: the pill on the title row already
761
+ // says whether that test passed, so spelling out "最近测试成功" here only
762
+ // added words. The failure reason stays on its own line — it is the one
763
+ // thing worth reading twice.
764
+ const testTime = verifyInfo && verifyInfo.at ? fmtTime(verifyInfo.at) : ''
765
+ const persistedNote = verifyInfo && verifyInfo.persisted === false ? t('push.notPersisted') : ''
766
+ const metaLine = [host?.urlHost, (connState === 'verified' || connState === 'failed') ? testTime : '', persistedNote]
767
+ .filter(Boolean).join(' · ')
768
+ const detailLine = connState === 'failed' ? t('push.failedWhy', { e: verifyInfo.error || '' })
769
+ : connState === 'untested' ? t('push.untestedHint')
770
+ : ''
706
771
 
707
772
  const pushSummary = () => h('div', { style: css.card },
708
773
  h('div', { style: css.row },
@@ -717,18 +782,28 @@ window.__ModuleLoader__.load({
717
782
  }),
718
783
  t('push.channel', { c: t('chan.' + host.channel) })),
719
784
  h('span', { style: css.badgeSoft(connColor) }, t('push.' + connState))),
720
- host.urlHost ? h('div', { style: css.metaDim }, t('push.current', { h: host.urlHost })) : null,
785
+ metaLine ? h('div', { style: css.metaDim }, metaLine) : null,
721
786
  // Failure text uses the same mixed ink as css.error: some skins tint the
722
787
  // 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,
724
- h('div', { style: css.metaDim }, host.configured ? t('push.hint') : t('push.empty')),
788
+ detailLine ? h('div', { style: { ...css.metaDim, color: connState === 'failed' ? ink(T.error) : undefined } }, detailLine) : null,
789
+ host.configured ? null : h('div', { style: css.metaDim }, t('push.empty')),
790
+ // The switch keeps its own line and the explanation stays with it: this is
791
+ // the only place a user learns what the toggle does. Actions sit below it,
792
+ // left-aligned like the rest of the panel.
793
+ signatureToggle(),
725
794
  h('div', { style: { display: 'flex', gap: 8, marginTop: 10, flexWrap: 'wrap' } },
726
795
  h('button', {
727
796
  type: 'button', disabled: !!busy || !host.configured, className: 'sentinel-btn',
728
797
  style: busy || !host.configured ? { ...css.btn, opacity: 0.5, cursor: 'not-allowed' } : css.btn,
729
798
  onClick: testPush,
730
799
  }, busy === 'test' ? t('push.testing') : t('push.test')),
731
- h('button', { type: 'button', disabled: !!busy, className: 'sentinel-btn', style: host.configured ? css.btnOutline : css.btn, onClick: openForm }, host.configured ? t('push.edit') : t('push.save'))))
800
+ // With no auto-open this button is the section's only way in, so it has
801
+ // to say what it does ("configure") rather than "save" — there is
802
+ // nothing saved at this point, it just opens the form. Same wording as
803
+ // dsh-aihot-radar's push card (push.setup), so the two panels read alike.
804
+ // Same weight as the test button next to it: two equal actions, not a
805
+ // primary/secondary pair.
806
+ h('button', { type: 'button', disabled: !!busy, className: 'sentinel-btn', style: css.btn, onClick: openForm }, host.configured ? t('push.edit') : t('push.setup'))))
732
807
 
733
808
  const resultBlock = (r, extra) => h('div', { style: { marginTop: 8, ...extra } },
734
809
  h('div', { style: { color: r.ok ? T.success : T.error, fontSize: 12 } }, r.message),
package/index.js CHANGED
@@ -30,7 +30,12 @@ export const Config = z.object({
30
30
  apiKey: z.string().default(''),
31
31
  }).default({}),
32
32
  notify: z.object({
33
- signature: z.boolean().default(true),
33
+ // Deliberately NO default: the config store materialises defaults into the
34
+ // saved object, and a default of `false` would make "unset" indistinguishable
35
+ // from an explicit opt-out — erasing a custom signatureText set by an older
36
+ // user. Leaving it optional keeps three states: unset (footer follows
37
+ // signatureText), true (append), false (never append).
38
+ signature: z.boolean(),
34
39
  signatureText: z.string().default(''),
35
40
  }).default({}),
36
41
  localApi: z.object({
package/lib/balance.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // single pending slot merges undelivered alerts so quiet hours / failures never
5
5
  // burst-spam, and classified retries make sure none disappears silently.
6
6
 
7
- import { isWebhookConfigured, withSignature } from './notify.js'
7
+ import { isWebhookConfigured, withSignature, effectiveNotify } from './notify.js'
8
8
  import { acquireStateLock, mergeStateFromDisk, touchStateLock, dataDir } from './state.js'
9
9
  import * as T from './time.js'
10
10
  import { mkdirSync, readFileSync, writeFileSync, unlinkSync } from 'node:fs'
@@ -94,7 +94,11 @@ export function createBalanceSource(opts = {}) {
94
94
  if (opts.remoteGet || opts.accountGet) {
95
95
  try {
96
96
  const r = await withTimeout(() => viaAccount())
97
- if (r.ok || r.reason === 'signed-out' || !opts.apiKey) return r
97
+ // A signed-out host is precisely the case the key fallback exists for:
98
+ // README promises "host account when signed in, otherwise the key", so
99
+ // only short-circuit when no key can answer. Reporting signed-out while
100
+ // a key is configured would leave the monitor with no usable source.
101
+ if (r.ok || !opts.apiKey) return r
98
102
  } catch (err) {
99
103
  if (!opts.apiKey) return { ok: false, reason: 'account-error', error: String(err?.message || err) }
100
104
  }
@@ -116,13 +120,16 @@ export function formatAlert(kind, state, th, notify, cause) {
116
120
  const v = fmt(b.value ?? 0)
117
121
  const level = kind === 'current' ? state.alert.level : kind === 'recovered' ? 'normal' : kind
118
122
  const resolved = kind === 'recovered' && cause === 'threshold'
123
+ // Keep the plugin name on every title, not just on the test push: with the
124
+ // install footer now opt-in, a forwarded alert has no other way to say where
125
+ // it came from. The prefix is short enough to survive IM title truncation.
119
126
  const head = level === 'critical'
120
- ? `DeepSeek 余额告急:${s}${v},低于 ${s}${fmt(th.critical)}`
127
+ ? `余额哨兵 · DeepSeek 余额告急:${s}${v},低于 ${s}${fmt(th.critical)}`
121
128
  : level === 'warn'
122
- ? `DeepSeek 余额预警:${s}${v},低于 ${s}${fmt(th.warn)}`
129
+ ? `余额哨兵 · DeepSeek 余额预警:${s}${v},低于 ${s}${fmt(th.warn)}`
123
130
  : resolved
124
- ? `DeepSeek 余额告警已解除:${s}${v}`
125
- : `DeepSeek 余额已恢复:${s}${v}`
131
+ ? `余额哨兵 · DeepSeek 余额告警已解除:${s}${v}`
132
+ : `余额哨兵 · DeepSeek 余额已恢复:${s}${v}`
126
133
  const title = kind === 'current' ? `${head}(当前状态)` : head
127
134
  const lines = [`### ${title}`, '']
128
135
  if (level !== 'normal') {
@@ -186,6 +193,11 @@ export async function deliverPending(state, notifier, notify, nowMs, quiet, conf
186
193
  const p = state.pending
187
194
  if (!p || p.hold || quiet || nowMs < (p.nextAt || 0)) return null
188
195
  if (!isWebhookConfigured(state.webhook)) return null
196
+ // A failed poll keeps the last known number in state.balance but flags it
197
+ // ok:false. Sending now would print that old figure as the current one, so the
198
+ // alert stays pending and is re-classified by the next successful reading —
199
+ // it is neither dropped nor delivered against a stale balance.
200
+ if (!state.balance?.ok) return null
189
201
  const th = effectiveThresholds(state, config)
190
202
  const { title, text } = formatAlert(p.kind, state, th, notify, p.cause)
191
203
  let r
@@ -292,7 +304,11 @@ function applyReceipt(state, r) {
292
304
  export function startMonitor({ fetchBalance, state, notifier, config, save, logger, onCycle }) {
293
305
  const bal = config.balance || {}
294
306
  if (bal.enabled === false) return { stop: () => {}, poke: () => {} }
295
- const intervalMs = Math.max(60, bal.pollSeconds ?? 60) * 1000
307
+ // One poll per minute is the production floor. Overridable the way the lock TTL
308
+ // is (see SENTINEL_LOCK_TTL_MS), so a test can watch several cycles in seconds;
309
+ // production never sets it.
310
+ const floorSec = Number(process.env.SENTINEL_POLL_FLOOR_SEC) || 60
311
+ const intervalMs = Math.max(floorSec, bal.pollSeconds ?? 60) * 1000
296
312
  const tz = T.resolveTz(bal.timezone, logger)
297
313
  let stopped = false
298
314
  let running = false
@@ -305,12 +321,32 @@ export function startMonitor({ fetchBalance, state, notifier, config, save, logg
305
321
  const now = Date.now()
306
322
  // Network outside the lock: both instances may read, only one may decide.
307
323
  const fr = await fetchBalance()
324
+ // Stopping wins over a query that was already in flight: a monitor that was
325
+ // switched off must not push, record or persist whatever comes back after
326
+ // shutdown. (The request itself cannot be cancelled here.)
327
+ if (stopped) return
308
328
  const release = acquireStateLock(logger)
309
329
  if (!release) {
310
330
  onCycle?.({ fetch: fr, skipped: true })
311
331
  } else {
312
332
  try {
313
333
  mergeStateFromDisk(state)
334
+ // A reading is only as new as the cycle that started the query. Another
335
+ // instance (or a poke that ran while this fetch was in flight) may have
336
+ // recorded one that was issued later and answered first; applying this
337
+ // response would roll the balance back and could re-fire a transition or
338
+ // push from a number the user has already left behind. Drop it entirely:
339
+ // no write, no state change, no delivery.
340
+ // The comparison is `>=` on purpose: the stamp has millisecond
341
+ // resolution, so two instances can issue their queries inside the same
342
+ // millisecond and neither is "older". Whoever recorded first is what
343
+ // the panel already shows, so a tie is treated as superseded too — the
344
+ // alternative is a same-millisecond reply rolling ¥30 back to ¥3.
345
+ const recorded = Date.parse(String(state.lastResult?.at || ''))
346
+ if (Number.isFinite(recorded) && recorded >= now) {
347
+ onCycle?.({ fetch: fr, skipped: true, stale: true })
348
+ return
349
+ }
314
350
  // A save failure leaves the disk behind the last webhook call. The
315
351
  // note restores either the delivered transition or the uncertain hold
316
352
  // (disk still behind, possibly another instance or a restart).
@@ -319,7 +355,9 @@ export function startMonitor({ fetchBalance, state, notifier, config, save, logg
319
355
  const th = effectiveThresholds(state, config)
320
356
  const quiet = T.isQuietNow(bal.quiet, new Date(now), tz)
321
357
  const transition = applyBalance(state, fr, th, now)
322
- const delivery = await deliverPending(state, notifier, config.notify || {}, now, quiet, config)
358
+ // Merge the panel toggle over the YAML config in one place, so a flip
359
+ // applies to every alert and recovery sent afterwards.
360
+ const delivery = await deliverPending(state, notifier, effectiveNotify(config.notify, state), now, quiet, config)
323
361
  let saved = false
324
362
  if (touchStateLock()) {
325
363
  try { saved = save?.(state) !== false } catch (err) { logger?.warn?.(`状态保存异常:${err?.message || err}`) }
@@ -353,8 +391,12 @@ export function startMonitor({ fetchBalance, state, notifier, config, save, logg
353
391
  onCycle?.({ error: String(err?.message || err) })
354
392
  } finally {
355
393
  running = false
394
+ // Re-arm from the finally, never from the happy path: a cycle can return
395
+ // early (a superseded reading, a stop that raced the query) and that must
396
+ // not leave the monitor with no next poll. A silently frozen instance looks
397
+ // exactly like a healthy one until the balance moves.
398
+ if (!stopped) timer = setTimeout(cycle, intervalMs)
356
399
  }
357
- if (!stopped) timer = setTimeout(cycle, intervalMs)
358
400
  }
359
401
 
360
402
  // Panel saves (thresholds / webhook) re-evaluate now, not up to a minute later.
package/lib/localapi.js CHANGED
@@ -6,7 +6,7 @@
6
6
  // panel shows the reason and a manual state.json path.
7
7
 
8
8
  import http from 'node:http'
9
- import { withSignature, isWebhookConfigured as configured } from './notify.js'
9
+ import { withSignature, signatureEnabled, effectiveNotify, isWebhookConfigured as configured } from './notify.js'
10
10
  import { effectiveThresholds } from './balance.js'
11
11
  import { mergeStateFromDisk, stateLockHeld, webhookFingerprint } from './state.js'
12
12
 
@@ -154,7 +154,10 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
154
154
  thresholds: effectiveThresholds(state, config),
155
155
  quiet: config.balance?.quiet || { start: '', end: '' },
156
156
  enabled: config.balance?.enabled !== false,
157
- signature: config.notify?.signature !== false,
157
+ // Report what the sender will actually do: config plus the panel
158
+ // toggle. The footer is opt-in, so an unset config reads as "off" here
159
+ // instead of claiming a line that never gets appended.
160
+ signature: signatureEnabled(effectiveNotify(config.notify, state)),
158
161
  // Most recent "send test" outcome. `configured` only says a webhook is
159
162
  // stored; this is the only field that can say the channel ever worked.
160
163
  verify: publicVerify(state.verify),
@@ -234,6 +237,28 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
234
237
  return json(res, 200, { ok: true, thresholds: effectiveThresholds(state, config) })
235
238
  }
236
239
 
240
+ // Push footer toggle. Panel-owned and stored in state rather than the
241
+ // profile YAML, so opting in needs no config edit; null hands control back
242
+ // to notify.signature (unset there means "follow signatureText").
243
+ if (req.method === 'POST' && path === '/notify') {
244
+ if (!needJson()) return json(res, 415, fail('bad-content-type', '请求格式不正确'))
245
+ const body = await readJson(req)
246
+ if (!body) return json(res, 400, fail('bad-json', '请求体不是合法 JSON'))
247
+ const sig = body?.signature
248
+ if (sig !== true && sig !== false && sig !== null) {
249
+ return json(res, 400, fail('bad-signature', '开关值需为 true / false / null'))
250
+ }
251
+ const tx = { ...state }
252
+ mergeStateFromDisk(tx)
253
+ tx.notify = { ...(tx.notify || {}), signature: sig }
254
+ if (save && save(tx, ['notify']) === false) {
255
+ return json(res, 503, fail('busy', '状态文件被占用,请稍后重试'))
256
+ }
257
+ state.notify = tx.notify
258
+ logger?.info?.(`推送尾注${sig === null ? '恢复为跟随配置' : sig ? '已开启' : '已关闭'}`)
259
+ return json(res, 200, { ok: true, signature: signatureEnabled(effectiveNotify(config.notify, state)) })
260
+ }
261
+
237
262
  // Manual retry for a held / unconfirmed pending alert. Refused while a
238
263
  // monitor cycle is in flight: resetting the shared pending mid-send would
239
264
  // corrupt the delivery transaction.
@@ -264,7 +289,7 @@ export function startLocalApi({ port = LOCAL_API_PORT, state, notifier, config,
264
289
  const targetFp = webhookFingerprint(target)
265
290
  const channel = target.channel
266
291
  const r = await notifier.send(target, '余额哨兵 · 测试推送',
267
- withSignature('这是一条测试消息:webhook 通道工作正常。', config.notify))
292
+ withSignature('这是一条测试消息:webhook 通道工作正常。', effectiveNotify(config.notify, state)))
268
293
  const hint = r.ok ? '' : hintFor(channel, r.code, r.error, r.status || 0)
269
294
 
270
295
  // The saved config is the source of truth. If it moved while the request