dsh-reminder-notify 0.8.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -18,6 +18,21 @@ window.__ModuleLoader__.load({
18
18
  const AUDIO_ROUTE = '/dsh-reminder-notify/audio'
19
19
  const CONFIG_ROUTE = '/dsh-reminder-notify/config'
20
20
  const AUDIO_KEYS = ['doneAudio', 'decideAudio', 'rawAudio']
21
+ const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
22
+ const BALANCE_ROUTE = '/dsh-reminder-notify/balance'
23
+ // 下拉按扩展名分组:wav 一组、mp3 一组……组内按文件名排序,一眼能看出格式。
24
+ function groupAudioFiles(files) {
25
+ const byExt = new Map()
26
+ for (const name of files) {
27
+ const dot = name.lastIndexOf('.')
28
+ const ext = dot >= 0 ? name.slice(dot + 1).toLowerCase() : 'other'
29
+ if (!byExt.has(ext)) byExt.set(ext, [])
30
+ byExt.get(ext).push(name)
31
+ }
32
+ return [...byExt.entries()]
33
+ .sort((a, b) => a[0].localeCompare(b[0]))
34
+ .map(([ext, names]) => ({ ext, names: names.sort((a, b) => a.localeCompare(b, 'zh-Hans-CN')) }))
35
+ }
21
36
 
22
37
  const zh = {
23
38
  title: '桌面提醒设置',
@@ -30,6 +45,7 @@ window.__ModuleLoader__.load({
30
45
  groupBasic: '基本',
31
46
  groupAudio: '提示音',
32
47
  groupLook: '外观',
48
+ groupBalance: 'DeepSeek 余额',
33
49
  groupHost: '宿主与路径',
34
50
  seconds: '停留秒数',
35
51
  secondsHint: '2–600 秒,到点自动关闭。',
@@ -75,11 +91,37 @@ window.__ModuleLoader__.load({
75
91
  audioScanning: '正在读取音频目录…',
76
92
  audioEmpty: '音频目录里没有可用的音频文件',
77
93
  audioFailed: '读取音频目录失败:',
94
+ preview: '试听',
95
+ previewing: '播放中…',
96
+ previewOk: '已播放:',
97
+ previewFailed: '试听失败:',
78
98
  hostMode: '宿主模式',
79
99
  hostModeScript: '包内脚本(推荐)',
80
100
  hostModeExe: '外部 exe 客户端',
81
101
  scriptPath: '脚本宿主路径',
82
102
  scriptPathHint: '留空 = 插件自带的 host/ReminderHost.ps1。',
103
+ balanceEnabled: '启用余额提醒',
104
+ balanceHint: '定期查 DeepSeek 账户余额,跌破阈值时弹卡片并语音播报(用本机已登录的 DSH 账号,不需要 API key)。',
105
+ balanceThresholds: '余额阈值(百分比,逗号分隔)',
106
+ balanceThresholdsHint: '相对于「基线」的百分比,例如 20,10,5:剩 20%、10%、5% 各提醒一次,不重复报。',
107
+ balanceCheckMinutes: '检查间隔(分钟)',
108
+ balanceCheckHint: '5–1440 分钟;余额检查不会很频繁,避免打扰账号服务。',
109
+ balanceSpeak: '语音播报余额',
110
+ balanceSpeakHint: '勾上后除了弹卡还会念出来;关闭则只弹卡片。',
111
+ balanceStatus: '当前余额',
112
+ balanceQuery: '立即查询',
113
+ balanceQuerying: '查询中…',
114
+ balanceReset: '把当前余额设为基线',
115
+ balanceUnknown: '还没查过余额',
116
+ balanceBaseline: '基线',
117
+ balanceBonus: '赠送金',
118
+ balanceBaselineAuto: '自动',
119
+ balanceBaselineManual: '手动',
120
+ balanceBaselineHint: '基线只认「充值余额」,赠送金不算;换账号会自动重来,刚充值后的 30 分钟内不播报,连续两次查到低于阈值才响。',
121
+ balanceAccountUnavailable: '这台机器的宿主没提供账号服务,查不到余额。',
122
+ balanceSignedOut: 'DSH 还没登录 DeepSeek 账号,查不到余额。',
123
+ balanceUnavailable: '账号服务暂时拿不到余额。',
124
+ balanceNoWallet: '账号里没有人民币(CNY)钱包。',
83
125
  powershellPath: 'PowerShell 可执行文件',
84
126
  clientDir: '客户端目录(仅 exe 模式)',
85
127
  empty: '(留空用默认)',
@@ -108,6 +150,7 @@ window.__ModuleLoader__.load({
108
150
  groupBasic: 'Basics',
109
151
  groupAudio: 'Sounds',
110
152
  groupLook: 'Appearance',
153
+ groupBalance: 'DeepSeek balance',
111
154
  groupHost: 'Host and paths',
112
155
  seconds: 'Duration (seconds)',
113
156
  secondsHint: '2–600 seconds, then it closes itself.',
@@ -153,11 +196,37 @@ window.__ModuleLoader__.load({
153
196
  audioScanning: 'Reading the sound directory…',
154
197
  audioEmpty: 'No audio files in the sound directory',
155
198
  audioFailed: 'Could not read the sound directory: ',
199
+ preview: 'Play',
200
+ previewing: 'Playing…',
201
+ previewOk: 'Played: ',
202
+ previewFailed: 'Preview failed: ',
156
203
  hostMode: 'Host mode',
157
204
  hostModeScript: 'Bundled script (recommended)',
158
205
  hostModeExe: 'External exe client',
159
206
  scriptPath: 'Script host path',
160
207
  scriptPathHint: 'Empty uses the bundled host/ReminderHost.ps1.',
208
+ balanceEnabled: 'Balance alerts',
209
+ balanceHint: 'Polls your DeepSeek balance and alerts when it drops below a share of the baseline. Uses the signed-in DSH account, no API key needed.',
210
+ balanceThresholds: 'Thresholds (% of baseline, comma separated)',
211
+ balanceThresholdsHint: 'Relative to the baseline, e.g. 20,10,5 alerts at 20%, 10% and 5% once each.',
212
+ balanceCheckMinutes: 'Check interval (minutes)',
213
+ balanceCheckHint: '5–1440 minutes; keep it polite to the account service.',
214
+ balanceSpeak: 'Speak the balance',
215
+ balanceSpeakHint: 'Reads the number aloud in addition to the card.',
216
+ balanceStatus: 'Current balance',
217
+ balanceQuery: 'Check now',
218
+ balanceQuerying: 'Checking…',
219
+ balanceReset: 'Set current balance as baseline',
220
+ balanceUnknown: 'Not checked yet',
221
+ balanceBaseline: 'baseline',
222
+ balanceBonus: 'bonus',
223
+ balanceBaselineAuto: 'auto',
224
+ balanceBaselineManual: 'manual',
225
+ balanceBaselineHint: 'The baseline counts the recharge wallet only (bonus credit excluded). It resets when the account changes, stays quiet for 30 minutes after a top-up, and needs two consecutive readings below a threshold.',
226
+ balanceAccountUnavailable: 'The account service is unavailable on this host.',
227
+ balanceSignedOut: 'DSH is not signed in to a DeepSeek account.',
228
+ balanceUnavailable: 'The balance is temporarily unavailable.',
229
+ balanceNoWallet: 'No CNY wallet on this account.',
161
230
  powershellPath: 'PowerShell executable',
162
231
  clientDir: 'Client directory (exe mode)',
163
232
  empty: '(empty uses the default)',
@@ -232,6 +301,10 @@ window.__ModuleLoader__.load({
232
301
  { key: 'decideMessageTemplate', group: 'look', kind: 'text' },
233
302
  { key: 'rawTitleTemplate', group: 'look', kind: 'text' },
234
303
  { key: 'rawMessageTemplate', group: 'look', kind: 'text' },
304
+ { key: 'balanceEnabled', group: 'balance', kind: 'boolean' },
305
+ { key: 'balanceThresholds', group: 'balance', kind: 'text' },
306
+ { key: 'balanceCheckMinutes', group: 'balance', kind: 'number' },
307
+ { key: 'balanceSpeak', group: 'balance', kind: 'boolean' },
235
308
  { key: 'hostMode', group: 'host', kind: 'select', options: ['script', 'exe'], optionLabels: ['hostModeScript', 'hostModeExe'] },
236
309
  { key: 'scriptPath', group: 'host', kind: 'text' },
237
310
  { key: 'powershellPath', group: 'host', kind: 'text' },
@@ -261,10 +334,14 @@ window.__ModuleLoader__.load({
261
334
  rawTitleTemplate: 'perKindTemplateHint',
262
335
  rawMessageTemplate: 'perKindTemplateHint',
263
336
  scriptPath: 'scriptPathHint',
337
+ balanceEnabled: 'balanceHint',
338
+ balanceThresholds: 'balanceThresholdsHint',
339
+ balanceCheckMinutes: 'balanceCheckHint',
340
+ balanceSpeak: 'balanceSpeakHint',
264
341
  }
265
342
 
266
- const GROUPS = ['basic', 'audio', 'look', 'host']
267
- const GROUP_LABELS = { basic: 'groupBasic', audio: 'groupAudio', look: 'groupLook', host: 'groupHost' }
343
+ const GROUPS = ['basic', 'audio', 'look', 'balance', 'host']
344
+ const GROUP_LABELS = { basic: 'groupBasic', audio: 'groupAudio', look: 'groupLook', balance: 'groupBalance', host: 'groupHost' }
268
345
 
269
346
  function sameValue(a, b) {
270
347
  return JSON.stringify(a) === JSON.stringify(b)
@@ -281,8 +358,11 @@ window.__ModuleLoader__.load({
281
358
  const [draft, setDraft] = React.useState(null)
282
359
  const [busy, setBusy] = React.useState(false)
283
360
  const [picking, setPicking] = React.useState(false)
361
+ const [previewing, setPreviewing] = React.useState(null)
284
362
  const [message, setMessage] = React.useState(null)
285
363
  const [audio, setAudio] = React.useState({ dir: '', files: [], error: null })
364
+ const [balance, setBalance] = React.useState(null)
365
+ const [balanceBusy, setBalanceBusy] = React.useState(false)
286
366
 
287
367
  React.useEffect(() => {
288
368
  if (typeof fetch !== 'function') {
@@ -339,6 +419,11 @@ window.__ModuleLoader__.load({
339
419
  }
340
420
  }, [scanDir])
341
421
 
422
+ // 打开面板时读一次余额快照(不触发提醒,只是显示)。
423
+ React.useEffect(() => {
424
+ refreshBalance()
425
+ }, [])
426
+
342
427
  if (props.view === 'summary') {
343
428
  const tr = typeof t === 'function' ? t : (key) => key
344
429
  const posKey = values.position === 'center' ? 'positionCenter' : values.position === 'tr' ? 'positionTr' : 'positionBr'
@@ -440,6 +525,119 @@ window.__ModuleLoader__.load({
440
525
  })
441
526
  }
442
527
 
528
+ // 试听:面板没有本地文件访问能力,交给宿主按档位代播(POST /preview)。
529
+ // 先保存再用当前编辑值试听会更准,但这里刻意不落盘 —— 试听不该改动配置。
530
+ function previewAudio(key) {
531
+ if (previewing !== null) return
532
+ const kind = key === 'decideAudio' ? 'decide' : key === 'rawAudio' ? 'raw' : 'done'
533
+ setPreviewing(key)
534
+ setMessage(null)
535
+ Promise.resolve()
536
+ .then(() =>
537
+ fetch(PREVIEW_ROUTE, {
538
+ method: 'POST',
539
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
540
+ body: JSON.stringify({ kind }),
541
+ }),
542
+ )
543
+ .then((response) => {
544
+ const status = response ? response.status : 0
545
+ const body = response && typeof response.json === 'function' ? response.json() : Promise.resolve(null)
546
+ return Promise.resolve(body)
547
+ .catch(() => null)
548
+ .then((data) => {
549
+ if (response && response.ok && data && data.ok !== false) return data
550
+ const detail = data && (data.detail || data.error) ? (data.detail || data.error) : 'HTTP ' + status
551
+ throw new Error(detail)
552
+ })
553
+ })
554
+ .then((data) => {
555
+ setPreviewing(null)
556
+ const label = typeof t === 'function' ? t('previewOk') : 'Playing: '
557
+ setMessage({ ok: true, text: label + String((data && data.audio) || '') })
558
+ })
559
+ .catch((error) => {
560
+ setPreviewing(null)
561
+ const prefix = typeof t === 'function' ? t('previewFailed') : 'preview failed: '
562
+ setMessage({ ok: false, text: prefix + String((error && error.message) || error) })
563
+ })
564
+ }
565
+
566
+ // 余额:数字与「立即查询 / 重置基线」都走同一个路由(宿主侧问账号服务)。
567
+ function shortTime(ms) {
568
+ const n = Number(ms)
569
+ if (!Number.isFinite(n) || n <= 0) return ''
570
+ const d = new Date(n)
571
+ const pad = (v) => (v < 10 ? '0' + v : String(v))
572
+ return pad(d.getMonth() + 1) + '-' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes())
573
+ }
574
+
575
+ function balanceText() {
576
+ const label = typeof t === 'function' ? t : (key) => key
577
+ if (balance === null) return label('balanceUnknown')
578
+ if (balance.ok === false) {
579
+ const reasons = {
580
+ 'account-unavailable': label('balanceAccountUnavailable'),
581
+ 'signed-out': label('balanceSignedOut'),
582
+ 'balance-unavailable': label('balanceUnavailable'),
583
+ 'no-cny-wallet': label('balanceNoWallet'),
584
+ }
585
+ return (reasons[balance.error] || String(balance.error || ''))
586
+ }
587
+ if (balance.balance === null || balance.balance === undefined) return label('balanceUnknown')
588
+ const parts = ['¥' + Number(balance.balance).toFixed(2)]
589
+ if (balance.pct !== null && balance.pct !== undefined) parts.push('(' + balance.pct + '%)')
590
+ if (balance.baseline) {
591
+ const source =
592
+ balance.baselineSource === 'manual'
593
+ ? label('balanceBaselineManual')
594
+ : balance.baselineSource === 'auto'
595
+ ? label('balanceBaselineAuto')
596
+ : ''
597
+ const at = shortTime(balance.baselineAt)
598
+ const tail = [source, at].filter(Boolean).join(' · ')
599
+ parts.push(' · ' + label('balanceBaseline') + ' ¥' + Number(balance.baseline).toFixed(2) + (tail ? '(' + tail + ')' : ''))
600
+ }
601
+ if (Number(balance.bonus) > 0) {
602
+ parts.push(' · ' + label('balanceBonus') + ' ¥' + Number(balance.bonus).toFixed(2))
603
+ }
604
+ return parts.join('')
605
+ }
606
+
607
+ function applyBalance(payload) {
608
+ if (payload && typeof payload === 'object') setBalance(payload)
609
+ }
610
+
611
+ function balanceFetch(options) {
612
+ setBalanceBusy(true)
613
+ Promise.resolve()
614
+ .then(() => fetch(BALANCE_ROUTE, options))
615
+ .then((response) => {
616
+ const body = response && typeof response.json === 'function' ? response.json() : Promise.resolve(null)
617
+ return Promise.resolve(body).catch(() => null)
618
+ })
619
+ .then((data) => {
620
+ setBalanceBusy(false)
621
+ if (data && typeof data === 'object') applyBalance(data)
622
+ })
623
+ .catch((error) => {
624
+ setBalanceBusy(false)
625
+ setBalance({ ok: false, error: String((error && error.message) || error) })
626
+ })
627
+ }
628
+
629
+ function refreshBalance() {
630
+ balanceFetch({ headers: { accept: 'application/json' } })
631
+ }
632
+
633
+ function queryBalance() {
634
+ balanceFetch({ method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: '{}' })
635
+ }
636
+
637
+ function resetBalance() {
638
+ balanceFetch({ method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ mode: 'reset' }) })
639
+ }
640
+
443
641
  function control(field) {
444
642
  const value = effective[field.key]
445
643
  const disabled = !writable || busy
@@ -478,6 +676,12 @@ window.__ModuleLoader__.load({
478
676
  onChange: (e) => edit(field.key, e.target.value, field.kind),
479
677
  })
480
678
  if (AUDIO_KEYS.includes(field.key) && audio.files.length > 0) {
679
+ const groups = groupAudioFiles(audio.files)
680
+ const options = [h('option', { value: '', key: '__pick' }, typeof t === 'function' ? t('audioPick') : 'pick')]
681
+ for (const group of groups) {
682
+ const children = group.names.map((name) => h('option', { key: name, value: name }, name))
683
+ options.push(h('optgroup', { key: 'grp-' + group.ext, label: group.ext }, children))
684
+ }
481
685
  return h(
482
686
  'div',
483
687
  { className: 'drn-pick' },
@@ -493,9 +697,19 @@ window.__ModuleLoader__.load({
493
697
  if (picked !== '') edit(field.key, picked, 'text')
494
698
  },
495
699
  },
496
- [h('option', { value: '' }, typeof t === 'function' ? t('audioPick') : 'pick')].concat(
497
- audio.files.map((name) => h('option', { value: name }, name)),
498
- ),
700
+ options,
701
+ ),
702
+ h(
703
+ 'button',
704
+ {
705
+ type: 'button',
706
+ className: 'drn-btn small drn-preview',
707
+ disabled: disabled || previewing !== null,
708
+ onClick: () => previewAudio(field.key),
709
+ },
710
+ previewing === field.key
711
+ ? (typeof t === 'function' ? t('previewing') : 'Playing…')
712
+ : (typeof t === 'function' ? t('preview') : 'Play'),
499
713
  ),
500
714
  )
501
715
  }
@@ -514,28 +728,60 @@ window.__ModuleLoader__.load({
514
728
  return input
515
729
  }
516
730
 
517
- const groups = GROUPS.map((group) =>
518
- h(
519
- 'div',
520
- { className: 'drn-group', key: group },
521
- h('div', { className: 'drn-group-title' }, typeof t === 'function' ? t(GROUP_LABELS[group]) : group),
522
- FIELDS.filter((field) => field.group === group).map((field) =>
731
+ const groups = GROUPS.map((group) => {
732
+ const rows = FIELDS.filter((field) => field.group === group).map((field) =>
733
+ h(
734
+ 'div',
735
+ { className: 'drn-row', key: field.key },
736
+ h(
737
+ 'div',
738
+ { className: 'drn-row-main' },
739
+ h('div', { className: 'drn-label' }, typeof t === 'function' ? t(field.key) : field.key),
740
+ HINTS[field.key] && typeof t === 'function'
741
+ ? h('div', { className: 'drn-hint' }, t(HINTS[field.key]))
742
+ : null,
743
+ ),
744
+ h('div', { className: 'drn-control' }, control(field)),
745
+ ),
746
+ )
747
+ if (group === 'balance') {
748
+ rows.push(
523
749
  h(
524
750
  'div',
525
- { className: 'drn-row', key: field.key },
751
+ { className: 'drn-row', key: 'balance-status' },
526
752
  h(
527
753
  'div',
528
754
  { className: 'drn-row-main' },
529
- h('div', { className: 'drn-label' }, typeof t === 'function' ? t(field.key) : field.key),
530
- HINTS[field.key] && typeof t === 'function'
531
- ? h('div', { className: 'drn-hint' }, t(HINTS[field.key]))
755
+ h('div', { className: 'drn-label' }, typeof t === 'function' ? t('balanceStatus') : 'DeepSeek balance'),
756
+ h('div', { className: 'drn-hint' }, balanceText()),
757
+ typeof t === 'function'
758
+ ? h('div', { className: 'drn-hint drn-balance-rule' }, t('balanceBaselineHint'))
532
759
  : null,
533
760
  ),
534
- h('div', { className: 'drn-control' }, control(field)),
761
+ h(
762
+ 'div',
763
+ { className: 'drn-pick' },
764
+ h(
765
+ 'button',
766
+ { type: 'button', className: 'drn-btn small', disabled: balanceBusy, onClick: queryBalance },
767
+ typeof t === 'function' ? t(balanceBusy ? 'balanceQuerying' : 'balanceQuery') : 'Check now',
768
+ ),
769
+ h(
770
+ 'button',
771
+ { type: 'button', className: 'drn-btn small', disabled: balanceBusy, onClick: resetBalance },
772
+ typeof t === 'function' ? t('balanceReset') : 'Reset baseline',
773
+ ),
774
+ ),
535
775
  ),
536
- ),
537
- ),
538
- )
776
+ )
777
+ }
778
+ return h(
779
+ 'div',
780
+ { className: 'drn-group', key: group },
781
+ h('div', { className: 'drn-group-title' }, typeof t === 'function' ? t(GROUP_LABELS[group]) : group),
782
+ rows,
783
+ )
784
+ })
539
785
 
540
786
  return h(
541
787
  'div',
package/docs/detail.en.md CHANGED
@@ -6,7 +6,7 @@ The card host is the bundled `host/ReminderHost.ps1`, drawn with the system Powe
6
6
 
7
7
  ## Settings
8
8
 
9
- Open "Desktop reminder" in the Plugins page; the panel sits right under the description and has four groups:
9
+ Open "Desktop reminder" in the Plugins page; the panel sits right under the description and has five groups:
10
10
 
11
11
  - **Basics**: duration, position, sound on/off
12
12
  - **Sounds**: audio directory ("Browse…" picks a directory), the three per-kind file names (wav / mp3). Once a directory is picked the dropdown lists the audio files in it.
@@ -15,6 +15,21 @@ Open "Desktop reminder" in the Plugins page; the panel sits right under the desc
15
15
 
16
16
  Changes apply on "Save" — no restart needed.
17
17
 
18
+ - **DeepSeek balance**: enable, thresholds (20/10/5 % by default), check interval, spoken alerts; the panel can check now and set the current balance as the baseline
19
+
20
+ ## DeepSeek balance alerts
21
+
22
+ The balance comes from the signed-in DSH account on this machine (host `deepseekAccount` service); no API key is needed.
23
+
24
+ "20% left" needs a denominator, and the plugin uses a **baseline**: the balance right after the last top-up. The first check records the current balance as the baseline; if the balance later rises above it (a top-up), the baseline is raised automatically. When the balance falls below baseline × threshold%, the card pops (and optionally speaks), once per threshold.
25
+
26
+ Baseline rules (0.10.1):
27
+
28
+ - **Recharge wallet only** — bonus credit is shown separately and never counted, so bonus expiry cannot fake a plunge;
29
+ - the baseline stores the **account id and set time**: switching DeepSeek accounts resets it, and the panel shows `baseline ¥x (auto/manual · time)`;
30
+ - no alert for **30 minutes after a top-up**, and an alert needs **two consecutive readings** below the threshold, which filters out top-up reversals and similar jitter;
31
+ - when the balance cannot be read (signed out, service error) the last snapshot is kept and marked stale instead of being treated as ¥0.
32
+
18
33
  ## Known limits
19
34
 
20
35
  - Windows only (`os: ["win32"]`): the card host is WinForms.
package/docs/detail.zh.md CHANGED
@@ -6,15 +6,29 @@
6
6
 
7
7
  ## 设置
8
8
 
9
- 在「插件」页打开「桌面提醒」,描述下方就是设置面板,分四组:
9
+ 在「插件」页打开「桌面提醒」,描述下方就是设置面板,分五组:
10
10
 
11
11
  - **基本**:停留秒数、弹窗位置、是否播放提示音
12
12
  - **提示音**:提示音目录(可点「浏览…」选目录)、三档提示音文件名(wav / mp3),选了目录后下拉框会列出目录里的音频
13
13
  - **外观**:背景图、标题图标、强调色、标题/正文模板(`{title}` `{message}` `{kind}` `{time}`),以及每档位单独覆盖的背景 / 图标 / 模板
14
+ - **DeepSeek 余额**:开关、阈值(默认 20,10,5 %)、检查间隔、是否语音播报;面板里能「立即查询」,也能把当前余额设为基线
14
15
  - **宿主**:脚本模式或 exe 模式、脚本路径、PowerShell 路径
15
16
 
16
17
  改完点「保存」,立刻生效,不用重启。
17
18
 
19
+ ## DeepSeek 余额提醒
20
+
21
+ 余额数据来自本机已登录的 DSH 账号(宿主 `deepseekAccount` 服务),不需要 API key。
22
+
23
+ 「剩 20%」得有个分母,插件用的是**基线**:最近一次充值后的余额。第一次检查时把当前余额记为基线;之后余额比基线还高(说明刚充过值)就自动把基线抬上去并重新待命。余额跌到 基线 × 阈值% 以下就弹卡 +(可选)语音播报,同一档只报一次。
24
+
25
+ 基线口径(0.10.1 起):
26
+
27
+ - **只认「充值余额」**,赠送金单独显示、不计入百分比(否则赠送金到期清零会误报);
28
+ - 基线绑定**账号身份与设定时间**,换 DeepSeek 账号会自动重来,面板上能看到「基线 ¥x(自动/手动 · 时间)」;
29
+ - 刚充值/刚抬升基线的 **30 分钟内不播报**,并且要**连续两次查到低于阈值**才响,避免充值入账被冲正之类的抖动误报;
30
+ - 查不到余额(未登录、接口失败)时保留上次结果,只显示过期提示,不会当成 0 元去喊。
31
+
18
32
  ## 已知限制
19
33
 
20
34
  - 仅 Windows(`os: ["win32"]`):卡片宿主是 WinForms。
@@ -24,7 +24,9 @@ param(
24
24
  [string]$Accent = '#2ECC71',
25
25
  [string]$Background = '',
26
26
  [string]$Icon = '',
27
+ [string]$Speak = '',
27
28
  [switch]$NoSound,
29
+ [switch]$Preview,
28
30
  [string]$Log = ''
29
31
  )
30
32
 
@@ -316,6 +318,49 @@ if (-not $NoSound -and -not [string]::IsNullOrEmpty($Audio) -and (Test-Path -Lit
316
318
  }
317
319
  }
318
320
 
321
+ # ---- 语音朗读(System.Speech,优先中文音色) ---------------------------------
322
+ # 和 -Audio 互不冲突:有提示音就放提示音,同时朗读 -Speak 的文本。
323
+ # 朗读是异步的(SpeakAsync),不拖慢卡片弹出;读不完就随进程退出被掐断。
324
+ $script:synth = $null
325
+ if (-not [string]::IsNullOrEmpty($Speak)) {
326
+ try {
327
+ Add-Type -AssemblyName System.Speech
328
+ $script:synth = New-Object System.Speech.Synthesis.SpeechSynthesizer
329
+ try {
330
+ $zh = $script:synth.GetInstalledVoices() |
331
+ Where-Object { $_.VoiceInfo.Culture.Name -like 'zh-*' } |
332
+ Select-Object -First 1
333
+ if ($zh -ne $null) { $script:synth.SelectVoice($zh.VoiceInfo.Name) }
334
+ } catch { }
335
+ $script:synth.Rate = 0
336
+ $script:synth.Volume = 100
337
+ $script:synth.SpeakAsync($Speak) | Out-Null
338
+ Write-Log ('speak ' + $Speak)
339
+ } catch {
340
+ Write-Log ('speak-failed ' + $_.Exception.Message)
341
+ $script:synth = $null
342
+ }
343
+ }
344
+
345
+ # ---- 试听:只放声音,不弹卡 ----------------------------------------------------
346
+ # 面板里的「试听」按钮走这条分支:播完(或最多 8 秒)就退出,不留窗口。
347
+ if ($Preview) {
348
+ if ($script:player -ne $null) {
349
+ $deadline = (Get-Date).AddSeconds(8)
350
+ while ((Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 200 }
351
+ try { $script:player.Stop() } catch { }
352
+ $script:player.Dispose()
353
+ }
354
+ if ($script:wmp -ne $null) {
355
+ $deadline = (Get-Date).AddSeconds(8)
356
+ while ((Get-Date) -lt $deadline -and $script:wmp.playState -ne 1) { Start-Sleep -Milliseconds 200 }
357
+ try { $script:wmp.controls.stop(); $script:wmp.close() } catch { }
358
+ try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:wmp) } catch { }
359
+ }
360
+ Write-Log 'preview exit'
361
+ exit 0
362
+ }
363
+
319
364
  # ---- 显示并进入消息循环 -----------------------------------------------------
320
365
  $form.Show()
321
366
  $form.RaiseWithoutActivating()
@@ -324,6 +369,7 @@ $timer.Start()
324
369
  [System.Windows.Forms.Application]::Run()
325
370
 
326
371
  if ($script:player -ne $null) { $script:player.Dispose() }
372
+ if ($script:synth -ne $null) { try { $script:synth.Dispose() } catch { } }
327
373
  if ($script:wmp -ne $null) {
328
374
  try { $script:wmp.controls.stop(); $script:wmp.close() } catch { }
329
375
  try { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($script:wmp) } catch { }
package/index.js CHANGED
@@ -65,6 +65,15 @@ export const Config = z === null ? undefined : z.object({
65
65
  decideMessageTemplate: z.string().default('').description('decide 档位单独的正文模板,留空 = 用通用模板').volatile(),
66
66
  rawTitleTemplate: z.string().default('').description('raw 档位单独的标题模板,留空 = 用通用模板').volatile(),
67
67
  rawMessageTemplate: z.string().default('').description('raw 档位单独的正文模板,留空 = 用通用模板').volatile(),
68
+ balanceEnabled: z.boolean().default(false).description('DeepSeek 余额不足时弹卡提醒(用本机已登录的 DSH 账号查余额)').volatile(),
69
+ balanceBaseline: z.number().default(0).description('余额基线(充值后的余额);0 = 自动记录见过的最高余额').volatile(),
70
+ balanceThresholds: z.string().default('20,10,5').description('触发阈值,按基线的百分比,逗号分隔(例如 20,10,5)').volatile(),
71
+ balanceSpeak: z.boolean().default(true).description('提醒时用系统语音读出余额').volatile(),
72
+ balanceCheckMinutes: z.number().min(5).max(1440).step(5).default(30).description('自动查余额的间隔(分钟)').volatile(),
73
+ balanceFired: z.number().default(0).description('内部状态:已经报过的最小阈值,余额回升后自动清零').volatile(),
74
+ balanceBaselineAt: z.number().default(0).description('内部状态:基线设定的时间(毫秒时间戳)').volatile(),
75
+ balanceBaselineAccount: z.string().default('').description('内部状态:基线属于哪个账号(平台用户 id),换号自动重来').volatile(),
76
+ balanceBaselineSource: z.string().default('').description('内部状态:基线来源(auto = 自动取余额,manual = 手动设定)').volatile(),
68
77
  })
69
78
 
70
79
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)))
@@ -169,6 +178,15 @@ function settingsOf(config) {
169
178
  decideMessageTemplate: typeof c.decideMessageTemplate === 'string' ? c.decideMessageTemplate : '',
170
179
  rawTitleTemplate: typeof c.rawTitleTemplate === 'string' ? c.rawTitleTemplate : '',
171
180
  rawMessageTemplate: typeof c.rawMessageTemplate === 'string' ? c.rawMessageTemplate : '',
181
+ balanceEnabled: c.balanceEnabled === true,
182
+ balanceBaseline: Math.max(0, num(c.balanceBaseline, 0)),
183
+ balanceThresholds: typeof c.balanceThresholds === 'string' ? c.balanceThresholds : '20,10,5',
184
+ balanceSpeak: c.balanceSpeak !== false,
185
+ balanceCheckMinutes: Math.round(clamp(num(c.balanceCheckMinutes, 30), 5, 1440)),
186
+ balanceFired: Math.max(0, num(c.balanceFired, 0)),
187
+ balanceBaselineAt: Math.max(0, num(c.balanceBaselineAt, 0)),
188
+ balanceBaselineAccount: str(c.balanceBaselineAccount, ''),
189
+ balanceBaselineSource: str(c.balanceBaselineSource, ''),
172
190
  }
173
191
  }
174
192
 
@@ -348,17 +366,19 @@ async function notify(kind, args, settings) {
348
366
  }
349
367
  const audioDir = path.resolve(settings.audioDir)
350
368
  const audioPath = sound && audio !== '' ? path.join(audioDir, audio) : ''
369
+ const speak = str(args.speak, '')
351
370
  if (audioPath !== '' && !fs.existsSync(audioPath)) {
352
371
  // 音频缺失不该让提醒消失:退回静音,正文照常弹。
353
- return await fireScript(settings, title, message, seconds, kind, '', false, scriptPath, audioPath)
372
+ return await fireScript(settings, title, message, seconds, kind, '', false, scriptPath, audioPath, speak)
354
373
  }
355
- return await fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, '')
374
+ return await fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, '', speak)
356
375
  }
357
376
 
358
- async function fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, missingAudio) {
377
+ async function fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, missingAudio, speak) {
359
378
  const extras = appearanceOf(kind, settings)
360
379
  const argv = argvOfScriptHost(title, message, seconds, settings.position, accentOf(kind, settings), audioPath, sound, extras)
361
380
  argv[argv.indexOf(null)] = scriptPath
381
+ if (typeof speak === 'string' && speak !== '') argv.push('-Speak', psSafe(speak))
362
382
  try {
363
383
  const { pid, exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
364
384
  // Add-Type 编译 C# 需要几百毫秒,所以等 900ms 才能发现「参数错、起不来」的情况。
@@ -435,6 +455,8 @@ function toolDefinition(getSettings) {
435
455
  const AUDIO_EXTENSIONS = ['.wav', '.mp3', '.ogg', '.m4a', '.flac', '.aac', '.wma']
436
456
  const AUDIO_ROUTE = '/dsh-reminder-notify/audio'
437
457
  const CONFIG_ROUTE = '/dsh-reminder-notify/config'
458
+ const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
459
+ const BALANCE_ROUTE = '/dsh-reminder-notify/balance'
438
460
 
439
461
  // 面板要「把音频目录里的文件列成下拉」,但 Client 侧没有任何读文件能力,
440
462
  // 所以由 Host 注册一条只读的 GET 路由,页面用同源 fetch 取这个 JSON。
@@ -488,6 +510,45 @@ function registerAudioRoute(ctx, getSettings) {
488
510
  }, 'dsh-reminder-notify: audio list route')
489
511
  }
490
512
 
513
+ // 试听:只按档位放一遍提示音,不弹卡。面板拿不到本地音频文件,所以由宿主代播。
514
+ export async function previewAudio(kind, settings) {
515
+ if (process.platform !== 'win32') {
516
+ return { ok: false, error: 'only-windows', detail: '试听只能在 Windows 上播放' }
517
+ }
518
+ const audio = audioNameOf(kind, settings)
519
+ if (audio === '') {
520
+ return { ok: false, error: 'no-audio', detail: '这个档位没有配置提示音(留空 = 静音)' }
521
+ }
522
+ const audioPath = path.join(path.resolve(settings.audioDir), audio)
523
+ if (!fs.existsSync(audioPath)) {
524
+ return { ok: false, error: 'audio-not-found', detail: `找不到音频文件:${audioPath}` }
525
+ }
526
+ const scriptPath = path.resolve(settings.scriptPath)
527
+ if (!fs.existsSync(scriptPath)) {
528
+ return { ok: false, error: 'host-script-not-found', detail: `找不到提醒脚本宿主:${scriptPath}` }
529
+ }
530
+ const argv = [
531
+ '-NoProfile',
532
+ '-NonInteractive',
533
+ '-ExecutionPolicy',
534
+ 'Bypass',
535
+ '-WindowStyle',
536
+ 'Hidden',
537
+ '-File',
538
+ scriptPath,
539
+ '-Preview',
540
+ '-Audio',
541
+ audioPath,
542
+ ]
543
+ try {
544
+ const { pid, exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
545
+ const early = await Promise.race([exited, new Promise((r) => setTimeout(() => r('running'), 900))])
546
+ return { ok: true, kind, audio: audioPath, pid, earlyExit: early === 'running' ? null : early }
547
+ } catch (error) {
548
+ return { ok: false, error: 'spawn-failed', detail: String((error && error.message) || error) }
549
+ }
550
+ }
551
+
491
552
  function readJsonBody(req, limit = 256 * 1024) {
492
553
  return new Promise((resolve, reject) => {
493
554
  let size = 0
@@ -564,9 +625,329 @@ function registerConfigRoute(ctx, getSettings) {
564
625
  }, 'dsh-reminder-notify: settings route')
565
626
  }
566
627
 
628
+ function registerPreviewRoute(ctx, getSettings) {
629
+ const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
630
+ if (web === undefined || web === null || typeof web.register !== 'function') {
631
+ ctx.logger?.warn?.('dsh-reminder-notify: webServer is unavailable, the preview buttons stay hidden')
632
+ return
633
+ }
634
+ const reply = (res, status, payload) => {
635
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
636
+ res.end(JSON.stringify(payload))
637
+ }
638
+ const route = {
639
+ kind: 'exact',
640
+ path: PREVIEW_ROUTE,
641
+ handler: async (req, res) => {
642
+ try {
643
+ if ((req.method ?? 'GET').toUpperCase() !== 'POST') {
644
+ return reply(res, 405, { ok: false, error: 'use POST' })
645
+ }
646
+ const body = await readJsonBody(req)
647
+ const kind = str(body?.kind, 'done')
648
+ if (!['done', 'decide', 'raw'].includes(kind)) {
649
+ return reply(res, 400, { ok: false, error: `unknown kind: ${kind}` })
650
+ }
651
+ const result = await previewAudio(kind, getSettings())
652
+ if (result.ok) return reply(res, 200, result)
653
+ const status = result.error === 'no-audio' || result.error === 'audio-not-found' ? 400 : 500
654
+ return reply(res, status, result)
655
+ } catch (error) {
656
+ return reply(res, 500, { ok: false, error: String(error?.message ?? error) })
657
+ }
658
+ },
659
+ }
660
+ ctx.effect(() => {
661
+ const dispose = web.register(route)
662
+ return () => {
663
+ if (typeof dispose === 'function') dispose()
664
+ }
665
+ }, 'dsh-reminder-notify: preview route')
666
+ }
667
+
668
+ // ——— DeepSeek 余额提醒 ——————————————————————————————————————————————
669
+ //
670
+ // 数据来自宿主账号服务 deepseekAccount.getBalance():返回的是钱包余额
671
+ // (AccountWallet = { currency, balance: string }),走本机已登录的 DSH 账号,
672
+ // 不需要用户另外填 API key。
673
+ //
674
+ // 「剩 20%」得有个分母:分母就是「基线」——最近一次充值后的余额。插件自己维护它:
675
+ // 余额比基线还高(说明刚充过值)就把基线抬到当前余额,并清空已报阈值;
676
+ // 余额跌到 基线×阈值% 以下就报一次,报过的阈值不再重复报。
677
+ //
678
+ // 基线口径(0.10.1 起):
679
+ // - 只算「充值钱包」(AccountWallet.value),赠送金(bonusWallets)不参与,
680
+ // 否则赠送金到期清零会让总余额断崖式下跌,触发假警报;
681
+ // - 基线连带记录账号 id 与设定时间:换账号自动重来,刚抬升的 30 分钟内不播报,
682
+ // 避免「充值入账 → 服务端冲正」这类抖动误报;
683
+ // - 播报前会立刻再读一次余额做确认(连续两次采样都在阈值以下才响)。
684
+ const balanceState = { balance: null, bonus: null, currency: 'CNY', at: 0, pct: null, error: null }
685
+ const BALANCE_COOLDOWN_MS = 30 * 60 * 1000
686
+
687
+ export function parseThresholds(text) {
688
+ const list = String(text ?? '')
689
+ .split(/[,,\s]+/)
690
+ .map((part) => Number(part))
691
+ .filter((n) => Number.isFinite(n) && n > 0 && n <= 100)
692
+ const unique = [...new Set(list)].sort((a, b) => b - a)
693
+ return unique.length > 0 ? unique : [20, 10, 5]
694
+ }
695
+
696
+ // 从账号服务读余额;返回 { balance, bonus, currency, accountId } 或 { error }。
697
+ // balance 只算充值钱包;bonus 是赠送钱包(只展示,不参与百分比)。
698
+ async function readAccountBalance(ctx) {
699
+ const account = typeof ctx.get === 'function' ? ctx.get('deepseekAccount') : undefined
700
+ if (account === undefined || account === null || typeof account.getBalance !== 'function') {
701
+ return { error: 'account-unavailable' }
702
+ }
703
+ const meta = {
704
+ version: '0.10.1',
705
+ locale: 'zh-CN',
706
+ timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
707
+ }
708
+ const result = await account.getBalance(meta)
709
+ if (result === null || result === undefined) return { error: 'signed-out' }
710
+ if (result.status !== 'ready') return { error: 'balance-unavailable' }
711
+ const sumOf = (wallets) =>
712
+ Math.round(
713
+ (wallets ?? [])
714
+ .filter((wallet) => wallet && wallet.currency === 'CNY')
715
+ .reduce((sum, wallet) => sum + num(wallet.balance, 0), 0) * 100,
716
+ ) / 100
717
+ const rechargeWallets = (result.value ?? []).filter((wallet) => wallet && wallet.currency === 'CNY')
718
+ if (rechargeWallets.length === 0) return { error: 'no-cny-wallet' }
719
+ const balance = sumOf(result.value)
720
+ const bonus = sumOf(result.bonusWallets)
721
+ // 账号身份:用来判断「是不是换号了」,读不到就留空(不影响余额判断)。
722
+ let accountId = ''
723
+ if (typeof account.getProfile === 'function') {
724
+ try {
725
+ const profile = await account.getProfile(meta)
726
+ if (profile !== null && profile !== undefined && profile.status === 'ready' && profile.value) {
727
+ accountId = String(profile.value.id ?? '')
728
+ }
729
+ } catch {
730
+ accountId = ''
731
+ }
732
+ }
733
+ return { balance, bonus, currency: 'CNY', accountId }
734
+ }
735
+
736
+ // 写回状态(基线和已报阈值):都是 volatile 字段,写完立刻生效,不会重启插件。
737
+ async function saveBalanceState(ctx, patch) {
738
+ const entry = ctx.fiber?.entry
739
+ const editor = typeof ctx.get === 'function' ? ctx.get('configEditor') : undefined
740
+ if (entry === undefined || editor === undefined || typeof editor.edit !== 'function') return false
741
+ try {
742
+ await editor.edit(entry, (current) => ({ ...current, ...patch }))
743
+ return true
744
+ } catch {
745
+ return false
746
+ }
747
+ }
748
+
749
+ // 查一次余额,必要时弹卡;force=true 时忽略冷却也会回报状态(供面板显示)。
750
+ export async function checkBalance(ctx, getSettings, { force = false } = {}) {
751
+ const settings = getSettings()
752
+ const read = await readAccountBalance(ctx)
753
+ if (read.error !== undefined) {
754
+ // 读不到(没登录 / 接口失败)时保留上次快照,绝不当成 0,避免「余额只剩 0 元」的误报。
755
+ balanceState.error = read.error
756
+ balanceState.at = Date.now()
757
+ return { ok: false, error: read.error, enabled: settings.balanceEnabled }
758
+ }
759
+ const balance = read.balance
760
+ const thresholds = parseThresholds(settings.balanceThresholds)
761
+ const now = Date.now()
762
+ const patch = {}
763
+ let baseline = settings.balanceBaseline
764
+ let fired = settings.balanceFired
765
+ let baselineAt = settings.balanceBaselineAt
766
+ let baselineAccount = settings.balanceBaselineAccount
767
+ let baselineSource = settings.balanceBaselineSource
768
+
769
+ // 换账号 → 旧基线作废(A 账号的 100 元基线套到 B 账号的 5 元上会立刻误报)。
770
+ if (read.accountId !== '' && baselineAccount !== '' && read.accountId !== baselineAccount) {
771
+ baseline = 0
772
+ baselineAt = 0
773
+ patch.balanceBaselineAt = 0
774
+ if (fired !== 0) {
775
+ fired = 0
776
+ patch.balanceFired = 0
777
+ }
778
+ }
779
+
780
+ // 充值(余额高于基线)或首次运行 → 基线抬到当前余额,并清空已报阈值。
781
+ if (baseline <= 0 || balance > baseline) {
782
+ baseline = balance
783
+ baselineAt = now
784
+ baselineSource = 'auto'
785
+ baselineAccount = read.accountId || baselineAccount
786
+ patch.balanceBaseline = baseline
787
+ patch.balanceBaselineAt = baselineAt
788
+ patch.balanceBaselineAccount = baselineAccount
789
+ patch.balanceBaselineSource = baselineSource
790
+ if (fired !== 0) {
791
+ fired = 0
792
+ patch.balanceFired = 0
793
+ }
794
+ }
795
+
796
+ const pct = baseline > 0 ? (balance / baseline) * 100 : 100
797
+ balanceState.balance = balance
798
+ balanceState.bonus = read.bonus
799
+ balanceState.currency = read.currency
800
+ balanceState.pct = Math.round(pct * 10) / 10
801
+ balanceState.at = now
802
+ balanceState.error = null
803
+
804
+ // 余额回到最高阈值以上 → 重新待命(下次跌破可以再报)。
805
+ const highest = thresholds[0]
806
+ if (pct > highest && fired !== 0) {
807
+ fired = 0
808
+ patch.balanceFired = 0
809
+ }
810
+
811
+ let firedNow = 0
812
+ const cooling = baselineAt > 0 && now - baselineAt < BALANCE_COOLDOWN_MS
813
+ if (settings.balanceEnabled && (!cooling || force)) {
814
+ // 只报「新跨过的最深一档」:20 → 10 → 5 各报一次,不会一次堆三张卡。
815
+ const crossed = thresholds.find((t) => pct <= t && t < fired) ?? thresholds.find((t) => pct <= t && fired === 0)
816
+ if (crossed !== undefined && crossed > 0) {
817
+ // 连续两次采样确认:立刻再读一次,两次都在阈值以下才播报。
818
+ const confirm = await readAccountBalance(ctx)
819
+ const confirmPct =
820
+ confirm.error === undefined && baseline > 0 ? (confirm.balance / baseline) * 100 : null
821
+ const confirmed = confirmPct !== null && confirmPct <= crossed
822
+ if (confirmed) {
823
+ firedNow = crossed
824
+ fired = crossed
825
+ patch.balanceFired = crossed
826
+ const message = `DeepSeek 余额只剩 ¥${balance.toFixed(2)}(约基线的 ${Math.round(pct)}%,已低于 ${crossed}%)`
827
+ const speak = settings.balanceSpeak ? `余额还剩 ${balance.toFixed(2)} 元,已经不足百分之 ${crossed}` : ''
828
+ try {
829
+ await notify('raw', { title: 'DeepSeek 余额不足', message, seconds: 20, speak }, settings)
830
+ } catch {
831
+ // 提醒失败不影响余额检查本身
832
+ }
833
+ }
834
+ }
835
+ }
836
+ if (Object.keys(patch).length > 0) await saveBalanceState(ctx, patch)
837
+ return {
838
+ ok: true,
839
+ enabled: settings.balanceEnabled,
840
+ balance,
841
+ bonus: read.bonus,
842
+ currency: read.currency,
843
+ baseline,
844
+ baselineAt,
845
+ baselineSource,
846
+ cooling,
847
+ pct: balanceState.pct,
848
+ thresholds,
849
+ fired,
850
+ firedNow: firedNow > 0 ? firedNow : null,
851
+ forced: force,
852
+ }
853
+ }
854
+
855
+ function registerBalanceRoute(ctx, getSettings, config) {
856
+ const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
857
+ const replyOf = (res) => (status, payload) => {
858
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
859
+ res.end(JSON.stringify(payload))
860
+ }
861
+ const settingsNow = () => getSettings()
862
+ const snapshot = () => ({
863
+ ok: balanceState.error === null,
864
+ enabled: settingsNow().balanceEnabled,
865
+ balance: balanceState.balance,
866
+ bonus: balanceState.bonus,
867
+ currency: balanceState.currency,
868
+ baseline: settingsNow().balanceBaseline,
869
+ baselineAt: settingsNow().balanceBaselineAt,
870
+ baselineSource: settingsNow().balanceBaselineSource,
871
+ pct: balanceState.pct,
872
+ at: balanceState.at,
873
+ error: balanceState.error,
874
+ })
875
+ if (web !== undefined && web !== null && typeof web.register === 'function') {
876
+ const route = {
877
+ kind: 'exact',
878
+ path: BALANCE_ROUTE,
879
+ handler: async (req, res) => {
880
+ const reply = replyOf(res)
881
+ try {
882
+ const method = (req.method ?? 'GET').toUpperCase()
883
+ if (method === 'GET') return reply(200, snapshot())
884
+ if (method !== 'POST') return reply(405, { ok: false, error: 'use GET or POST' })
885
+ const body = await readJsonBody(req)
886
+ if (body !== null && typeof body === 'object' && body.mode === 'reset') {
887
+ // 「把当前余额设为基线」:读一次当前余额,直接写成人设定的基线。
888
+ const entry = ctx.fiber?.entry
889
+ const editor = typeof ctx.get === 'function' ? ctx.get('configEditor') : undefined
890
+ const read = await readAccountBalance(ctx)
891
+ if (entry === undefined || editor?.edit === undefined) {
892
+ return reply(409, { ok: false, error: 'configuration cannot be saved in this profile' })
893
+ }
894
+ if (read.error !== undefined) return reply(400, { ok: false, error: read.error })
895
+ const now = Date.now()
896
+ await editor.edit(entry, (current) => ({
897
+ ...current,
898
+ balanceBaseline: read.balance,
899
+ balanceBaselineAt: now,
900
+ balanceBaselineAccount: read.accountId || '',
901
+ balanceBaselineSource: 'manual',
902
+ balanceFired: 0,
903
+ }))
904
+ balanceState.balance = read.balance
905
+ balanceState.bonus = read.bonus
906
+ balanceState.pct = 100
907
+ balanceState.error = null
908
+ balanceState.at = now
909
+ return reply(200, { ...snapshot(), reset: true, baseline: read.balance })
910
+ }
911
+ const result = await checkBalance(ctx, getSettings, { force: true })
912
+ return reply(200, result)
913
+ } catch (error) {
914
+ return reply(500, { ok: false, error: String(error?.message ?? error) })
915
+ }
916
+ },
917
+ }
918
+ ctx.effect(() => {
919
+ const dispose = web.register(route)
920
+ return () => {
921
+ if (typeof dispose === 'function') dispose()
922
+ }
923
+ }, 'dsh-reminder-notify: balance route')
924
+ } else {
925
+ ctx.logger?.warn?.('dsh-reminder-notify: webServer is unavailable, the balance card stays read-only')
926
+ }
927
+
928
+ // 自动检查:每 60 秒醒一次,按 balanceCheckMinutes 的间隔真正查一次。
929
+ // config 是 volatile,改完立刻生效,所以这里每次都用 getSettings() 现读。
930
+ // 这里用全局定时器而不是 ctx.setInterval —— 后者要求插件 inject 'timer',
931
+ // 而本插件故意保持「只 inject tools」的低依赖,卸载时靠 ctx.effect 收尾。
932
+ let lastCheck = 0
933
+ const timer = setInterval(() => {
934
+ const settings = getSettings()
935
+ if (!settings.balanceEnabled) return
936
+ const gap = Math.max(1, settings.balanceCheckMinutes) * 60 * 1000
937
+ if (Date.now() - lastCheck < gap) return
938
+ lastCheck = Date.now()
939
+ checkBalance(ctx, getSettings).catch(() => {})
940
+ }, 60 * 1000)
941
+ if (typeof timer?.unref === 'function') timer.unref()
942
+ ctx.effect(() => () => clearInterval(timer), 'dsh-reminder-notify: balance watcher')
943
+ void config
944
+ }
945
+
567
946
  export function apply(ctx, config) {
568
947
  registerAudioRoute(ctx, () => settingsOf(config))
569
948
  registerConfigRoute(ctx, () => settingsOf(config))
949
+ registerPreviewRoute(ctx, () => settingsOf(config))
950
+ registerBalanceRoute(ctx, () => settingsOf(config), config)
570
951
  const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools
571
952
  if (tools === undefined || tools === null || typeof tools.register !== 'function') {
572
953
  ctx.logger?.warn?.('dsh-reminder-notify: tools service is unavailable, notify_user was not registered')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-reminder-notify",
3
- "version": "0.8.2",
3
+ "version": "0.10.1",
4
4
  "description": "DSH 桌面提醒插件:把「完成/需要决定」提醒变成 notify_user 工具(浮动卡片 + 提示音,不抢焦点,纯 PowerShell 源码宿主,仓库零 exe)",
5
5
  "author": "Jiangshuaiye1203",
6
6
  "type": "module",
@@ -48,8 +48,8 @@
48
48
  },
49
49
  "versions": [
50
50
  {
51
- "version": "0.8.1",
52
- "publishTimestamp": 1795094364,
51
+ "version": "0.9.0",
52
+ "publishTimestamp": 1795097054,
53
53
  "source": {
54
54
  "type": "npm"
55
55
  },