dsh-reminder-notify 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
 
12
12
  import { spawn } from 'node:child_process'
13
13
  import fs from 'node:fs'
14
+ import os from 'node:os'
14
15
  import path from 'node:path'
15
16
  import { fileURLToPath } from 'node:url'
16
17
 
@@ -74,6 +75,21 @@ export const Config = z === null ? undefined : z.object({
74
75
  balanceBaselineAt: z.number().default(0).description('内部状态:基线设定的时间(毫秒时间戳)').volatile(),
75
76
  balanceBaselineAccount: z.string().default('').description('内部状态:基线属于哪个账号(平台用户 id),换号自动重来').volatile(),
76
77
  balanceBaselineSource: z.string().default('').description('内部状态:基线来源(auto = 自动取余额,manual = 手动设定)').volatile(),
78
+ speakEnabled: z.boolean().default(false).description('弹卡时用系统语音把正文念出来(默认关,避免连环打扰)').volatile(),
79
+ buttonsEnabled: z.boolean().default(true).description('卡片上显示「知道了 / 稍后提醒」两个按钮').volatile(),
80
+ snoozeMinutes: z.number().min(1).max(240).step(1).default(10).description('点「稍后提醒」后多少分钟再弹(1–240)').volatile(),
81
+ queueEnabled: z.boolean().default(true).description('同一时刻只显示一张卡,其余排队,避免叠成一堆').volatile(),
82
+ queueMax: z.number().min(1).max(20).step(1).default(5).description('最多同时排几条(1–20),超出丢弃最旧的').volatile(),
83
+ mergeWindowMs: z.number().min(0).max(60000).step(500).default(3000).description('同档位提醒在这个窗口内合并成一条(毫秒,0 = 不合并)').volatile(),
84
+ quietEnabled: z.boolean().default(false).description('开启免打扰时段(decide 档位永远不吞)').volatile(),
85
+ quietStart: z.string().default('22:00').description('免打扰开始时间,HH:MM').volatile(),
86
+ quietEnd: z.string().default('08:00').description('免打扰结束时间,HH:MM(可跨零点)').volatile(),
87
+ quietMode: z.union(['hold', 'skip']).default('hold').description('免打扰期间:hold = 攒到时段结束再弹,skip = 直接丢弃').volatile(),
88
+ compactOnFullscreen: z.boolean().default(true).description('检测到全屏程序(游戏 / 视频)时自动缩成一条小卡片').volatile(),
89
+ historyEnabled: z.boolean().default(true).description('记录提醒历史(本地 JSON),供插件页看统计').volatile(),
90
+ historyLimit: z.number().min(20).max(2000).step(10).default(200).description('历史最多保留多少条(20–2000)').volatile(),
91
+ historyFile: z.string().default('').description('历史文件路径,留空 = <用户目录>\\.dsh\\dsh-reminder-notify\\history.json').volatile(),
92
+ dryRun: z.boolean().default(false).description('调试用:只试算参数、不真的弹窗(自检脚本会打开它)').volatile(),
77
93
  })
78
94
 
79
95
  const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)))
@@ -187,6 +203,21 @@ function settingsOf(config) {
187
203
  balanceBaselineAt: Math.max(0, num(c.balanceBaselineAt, 0)),
188
204
  balanceBaselineAccount: str(c.balanceBaselineAccount, ''),
189
205
  balanceBaselineSource: str(c.balanceBaselineSource, ''),
206
+ speakEnabled: c.speakEnabled === true,
207
+ buttonsEnabled: c.buttonsEnabled !== false,
208
+ snoozeMinutes: Math.round(clamp(num(c.snoozeMinutes, 10), 1, 240)),
209
+ queueEnabled: c.queueEnabled !== false,
210
+ queueMax: Math.round(clamp(num(c.queueMax, 5), 1, 20)),
211
+ mergeWindowMs: Math.max(0, Math.round(num(c.mergeWindowMs, 3000))),
212
+ quietEnabled: c.quietEnabled === true,
213
+ quietStart: str(c.quietStart, '22:00'),
214
+ quietEnd: str(c.quietEnd, '08:00'),
215
+ quietMode: str(c.quietMode, 'hold') === 'skip' ? 'skip' : 'hold',
216
+ compactOnFullscreen: c.compactOnFullscreen !== false,
217
+ historyEnabled: c.historyEnabled !== false,
218
+ historyLimit: Math.round(clamp(num(c.historyLimit, 200), 20, 2000)),
219
+ historyFile: str(c.historyFile, ''),
220
+ dryRun: c.dryRun === true,
190
221
  }
191
222
  }
192
223
 
@@ -275,7 +306,8 @@ function launch(file, argv, cwd) {
275
306
  })
276
307
  }
277
308
 
278
- function argvOfScriptHost(title, message, seconds, position, accent, audioPath, sound, extras) {
309
+ function argvOfScriptHost(o) {
310
+ // 参数用数组逐项传,不拼字符串:中文、空格、括号都不需要转义。
279
311
  const argv = [
280
312
  '-NoProfile',
281
313
  '-NonInteractive',
@@ -284,25 +316,230 @@ function argvOfScriptHost(title, message, seconds, position, accent, audioPath,
284
316
  '-WindowStyle',
285
317
  'Hidden',
286
318
  '-File',
287
- null, // 由调用方填入脚本路径
319
+ o.scriptPath,
288
320
  '-Title',
289
- psSafe(title),
321
+ psSafe(o.title),
290
322
  '-Msg',
291
- psSafe(message),
323
+ psSafe(o.message),
292
324
  '-Seconds',
293
- String(seconds),
325
+ String(o.seconds),
294
326
  '-Pos',
295
- position,
327
+ o.position,
296
328
  '-Accent',
297
- accent,
329
+ o.accent,
298
330
  ]
299
- if (sound && audioPath !== '') argv.push('-Audio', audioPath)
331
+ if (o.sound && o.audioPath !== '') argv.push('-Audio', o.audioPath)
300
332
  else argv.push('-NoSound')
301
- if (extras && extras.background) argv.push('-Background', extras.background)
302
- if (extras && extras.icon) argv.push('-Icon', extras.icon)
333
+ if (o.background) argv.push('-Background', o.background)
334
+ if (o.icon) argv.push('-Icon', o.icon)
335
+ if (o.speak) argv.push('-Speak', psSafe(o.speak))
336
+ if (o.resultPath) argv.push('-ResultPath', o.resultPath)
337
+ if (o.buttonsEnabled === false) argv.push('-NoButtons')
338
+ else argv.push('-SnoozeMinutes', String(o.snoozeMinutes))
339
+ if (o.compact) argv.push('-Compact')
340
+ if (o.autoCompact) argv.push('-AutoCompact')
341
+ if (o.queueLeft > 0) argv.push('-QueueLeft', String(o.queueLeft))
303
342
  return argv
304
343
  }
305
344
 
345
+ // ——— 提醒队列 ————————————————————————————————————————————————————
346
+ //
347
+ // 一次只放一张卡。模型有时会在一轮里连发两三条提醒,直接 spawn 会在屏幕角上叠一摞,
348
+ // 谁也看不清;所以这里排一个先进先出的队列:
349
+ // · 同一档位在 mergeWindowMs 内到的第二条,直接并进排队中的那一条(正文换行追加);
350
+ // · 卡片关掉之后再放下一张,卡上会写「还有 N 条」;
351
+ // · 用户点「稍后提醒」,这条隔 snoozeMinutes 再回到队尾。
352
+ const queue = []
353
+ let active = null
354
+
355
+ function historyPathOf(settings) {
356
+ if (settings.historyFile !== '') return path.resolve(settings.historyFile)
357
+ return path.join(os.homedir(), '.dsh', 'dsh-reminder-notify', 'history.json')
358
+ }
359
+
360
+ function readHistory(settings) {
361
+ try {
362
+ const parsed = JSON.parse(fs.readFileSync(historyPathOf(settings), 'utf8'))
363
+ return Array.isArray(parsed) ? parsed : []
364
+ } catch {
365
+ return []
366
+ }
367
+ }
368
+
369
+ function writeHistory(settings, list) {
370
+ const file = historyPathOf(settings)
371
+ fs.mkdirSync(path.dirname(file), { recursive: true })
372
+ fs.writeFileSync(file, JSON.stringify(list), 'utf8')
373
+ }
374
+
375
+ function appendHistory(settings, entry) {
376
+ if (!settings.historyEnabled) return
377
+ try {
378
+ const list = readHistory(settings)
379
+ list.push(entry)
380
+ const limit = settings.historyLimit
381
+ writeHistory(settings, list.length > limit ? list.slice(list.length - limit) : list)
382
+ } catch {
383
+ // 历史写不进去不影响弹卡本身
384
+ }
385
+ }
386
+
387
+ // "22:00" → 1320(当天第几分钟);解析不出来返回 null。
388
+ export function parseClock(text) {
389
+ const found = /^(\d{1,2}):(\d{2})$/.exec(String(text ?? '').trim())
390
+ if (found === null) return null
391
+ const hours = Number(found[1])
392
+ const minutes = Number(found[2])
393
+ if (hours > 23 || minutes > 59) return null
394
+ return hours * 60 + minutes
395
+ }
396
+
397
+ export function inQuietHours(settings, now = new Date()) {
398
+ if (!settings.quietEnabled) return false
399
+ const start = parseClock(settings.quietStart)
400
+ const end = parseClock(settings.quietEnd)
401
+ if (start === null || end === null || start === end) return false
402
+ const clock = now.getHours() * 60 + now.getMinutes()
403
+ // 跨零点的时段(22:00 → 08:00)用 or 判断
404
+ return start < end ? clock >= start && clock < end : clock >= start || clock < end
405
+ }
406
+
407
+ export function quietEndAt(settings, now = new Date()) {
408
+ const end = parseClock(settings.quietEnd)
409
+ if (end === null) return 0
410
+ const at = new Date(now.getTime())
411
+ at.setHours(Math.floor(end / 60), end % 60, 0, 0)
412
+ if (at.getTime() <= now.getTime()) at.setDate(at.getDate() + 1)
413
+ return at.getTime()
414
+ }
415
+
416
+ function enqueue(item) {
417
+ const settings = item.settings
418
+ if (!settings.queueEnabled) {
419
+ // 关掉排队:立刻弹,仍然记一条历史
420
+ active = item
421
+ showItem(item).catch(() => {}).finally(() => {
422
+ active = null
423
+ pump()
424
+ })
425
+ return { queued: false, position: 0 }
426
+ }
427
+ const now = Date.now()
428
+ if (settings.mergeWindowMs > 0) {
429
+ const pending = queue.find(
430
+ (other) =>
431
+ other.kind === item.kind &&
432
+ (other.holdUntil ?? 0) === 0 &&
433
+ now - other.createdAt <= settings.mergeWindowMs,
434
+ )
435
+ if (pending !== undefined) {
436
+ pending.count += 1
437
+ const merged = `${pending.message}\n${item.message}`.slice(0, 600)
438
+ pending.message = merged
439
+ return { queued: true, merged: true, position: queue.indexOf(pending) + 1, count: pending.count }
440
+ }
441
+ }
442
+ queue.push(item)
443
+ while (queue.length > settings.queueMax) queue.shift()
444
+ pump()
445
+ // pump() 可能已经把它直接放上屏(队列原本是空的),那种情况不算"排队"。
446
+ const showing = active === item
447
+ return { queued: !showing, position: queue.indexOf(item) + 1 }
448
+ }
449
+
450
+ function pump() {
451
+ if (active !== null) return
452
+ const now = Date.now()
453
+ const index = queue.findIndex((item) => (item.holdUntil ?? 0) <= now)
454
+ if (index < 0) {
455
+ // 全都在免打扰时段里攒着:睡到最早那一条的放行时间再看
456
+ const next = queue.reduce((min, item) => Math.min(min, item.holdUntil ?? Infinity), Infinity)
457
+ if (Number.isFinite(next)) {
458
+ const timer = setTimeout(() => pump(), Math.max(1000, Math.min(next - now, 60 * 60 * 1000)))
459
+ if (typeof timer.unref === 'function') timer.unref()
460
+ }
461
+ return
462
+ }
463
+ const [item] = queue.splice(index, 1)
464
+ active = item
465
+ showItem(item)
466
+ .catch(() => {})
467
+ .finally(() => {
468
+ active = null
469
+ pump()
470
+ })
471
+ }
472
+
473
+ async function showItem(item) {
474
+ const settings = item.settings
475
+ const scriptPath = path.resolve(settings.scriptPath)
476
+ if (!fs.existsSync(scriptPath)) return
477
+ const extras = appearanceOf(item.kind, settings)
478
+ const queueLeft = queue.filter((other) => (other.holdUntil ?? 0) <= Date.now()).length
479
+ const resultFile = path.join(
480
+ os.tmpdir(),
481
+ `dsh-reminder-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.json`,
482
+ )
483
+ const argv = argvOfScriptHost({
484
+ scriptPath,
485
+ title: item.title,
486
+ message: item.message,
487
+ seconds: item.seconds,
488
+ position: settings.position,
489
+ accent: accentOf(item.kind, settings),
490
+ audioPath: item.audioPath,
491
+ sound: item.sound,
492
+ background: extras.background,
493
+ icon: extras.icon,
494
+ speak: item.speak,
495
+ resultPath: resultFile,
496
+ buttonsEnabled: settings.buttonsEnabled,
497
+ snoozeMinutes: settings.snoozeMinutes,
498
+ autoCompact: settings.compactOnFullscreen,
499
+ queueLeft,
500
+ })
501
+ let action = 'unknown'
502
+ try {
503
+ const { exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
504
+ await exited
505
+ } catch {
506
+ // spawn 失败就当作没弹出来,记录一条便于排查
507
+ }
508
+ try {
509
+ const parsed = JSON.parse(fs.readFileSync(resultFile, 'utf8'))
510
+ if (parsed !== null && typeof parsed === 'object' && typeof parsed.action === 'string') {
511
+ action = parsed.action
512
+ if (action === 'snooze') {
513
+ const minutes = Math.round(clamp(num(parsed.snooze, settings.snoozeMinutes), 1, 240))
514
+ const timer = setTimeout(() => {
515
+ queue.unshift({ ...item, createdAt: Date.now(), snoozed: true, count: 1, holdUntil: 0 })
516
+ pump()
517
+ }, minutes * 60 * 1000)
518
+ if (typeof timer.unref === 'function') timer.unref()
519
+ }
520
+ }
521
+ } catch {
522
+ // 没有结果文件(比如宿主被杀)时按 unknown 记
523
+ }
524
+ try {
525
+ fs.unlinkSync(resultFile)
526
+ } catch {
527
+ // 清不掉就算了,文件名带 pid + 时间戳不会互相覆盖
528
+ }
529
+ item.action = action
530
+ appendHistory(settings, {
531
+ at: Date.now(),
532
+ kind: item.kind,
533
+ title: item.title,
534
+ message: item.message,
535
+ action,
536
+ count: item.count ?? 1,
537
+ snoozed: item.snoozed === true,
538
+ quiet: item.quiet === true,
539
+ })
540
+ return action
541
+ }
542
+
306
543
  async function notify(kind, args, settings) {
307
544
  if (process.platform !== 'win32') {
308
545
  return { ok: false, error: 'only-windows', detail: '桌面提醒只能在本机 Windows 上弹出' }
@@ -319,6 +556,7 @@ async function notify(kind, args, settings) {
319
556
  const seconds = Math.round(clamp(num(args.seconds, settings.seconds), 2, 600))
320
557
  const sound = args.sound === false ? false : settings.sound
321
558
  const audio = audioNameOf(kind, settings)
559
+ const speak = str(args.speak, settings.speakEnabled ? message : '')
322
560
 
323
561
  if (settings.hostMode === 'exe') {
324
562
  const dir = clientDirOf(settings)
@@ -365,27 +603,24 @@ async function notify(kind, args, settings) {
365
603
  }
366
604
  }
367
605
  const audioDir = path.resolve(settings.audioDir)
368
- const audioPath = sound && audio !== '' ? path.join(audioDir, audio) : ''
369
- const speak = str(args.speak, '')
606
+ let audioPath = sound && audio !== '' ? path.join(audioDir, audio) : ''
607
+ let audioMissing
370
608
  if (audioPath !== '' && !fs.existsSync(audioPath)) {
371
609
  // 音频缺失不该让提醒消失:退回静音,正文照常弹。
372
- return await fireScript(settings, title, message, seconds, kind, '', false, scriptPath, audioPath, speak)
610
+ audioMissing = audioPath
611
+ audioPath = ''
373
612
  }
374
- return await fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, '', speak)
375
- }
376
613
 
377
- async function fireScript(settings, title, message, seconds, kind, audioPath, sound, scriptPath, missingAudio, speak) {
614
+ // 免打扰:decide 是「要人来拍板」的,任何时段都不能吞;其余档位按 quietMode 处理。
615
+ const quiet = kind !== 'decide' && inQuietHours(settings)
378
616
  const extras = appearanceOf(kind, settings)
379
- const argv = argvOfScriptHost(title, message, seconds, settings.position, accentOf(kind, settings), audioPath, sound, extras)
380
- argv[argv.indexOf(null)] = scriptPath
381
- if (typeof speak === 'string' && speak !== '') argv.push('-Speak', psSafe(speak))
382
- try {
383
- const { pid, exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
384
- // Add-Type 编译 C# 需要几百毫秒,所以等 900ms 才能发现「参数错、起不来」的情况。
385
- const early = await Promise.race([exited, new Promise((r) => setTimeout(() => r('running'), 900))])
617
+
618
+ // 自检 / 调参用:只把将要传给宿主的参数算出来,不落任何进程、不写历史。
619
+ if (settings.dryRun) {
386
620
  return {
387
621
  ok: true,
388
622
  hostMode: 'script',
623
+ dryRun: true,
389
624
  kind,
390
625
  title,
391
626
  message,
@@ -393,15 +628,74 @@ async function fireScript(settings, title, message, seconds, kind, audioPath, so
393
628
  position: settings.position,
394
629
  sound: sound && audioPath !== '',
395
630
  audio: sound && audioPath !== '' ? audioPath : null,
396
- audioMissing: missingAudio !== '' ? missingAudio : undefined,
631
+ audioMissing: audioMissing !== '' && audioMissing !== undefined ? audioMissing : undefined,
632
+ speak: speak !== '' ? speak : null,
397
633
  background: extras.background !== '' ? extras.background : null,
398
634
  icon: extras.icon !== '' ? extras.icon : null,
399
- pid,
400
- host: scriptPath,
401
- earlyExit: early === 'running' ? null : early,
635
+ quiet,
402
636
  }
403
- } catch (error) {
404
- return { ok: false, error: 'spawn-failed', detail: String(error && error.message ? error.message : error) }
637
+ }
638
+
639
+ if (quiet && settings.quietMode === 'skip') {
640
+ appendHistory(settings, {
641
+ at: Date.now(),
642
+ kind,
643
+ title,
644
+ message,
645
+ action: 'quiet-skip',
646
+ count: 1,
647
+ snoozed: false,
648
+ quiet: true,
649
+ })
650
+ return {
651
+ ok: true,
652
+ hostMode: 'script',
653
+ kind,
654
+ title,
655
+ message,
656
+ skipped: 'quiet',
657
+ quietRange: `${settings.quietStart}-${settings.quietEnd}`,
658
+ }
659
+ }
660
+ const holdUntil = quiet ? quietEndAt(settings) : 0
661
+
662
+ const item = {
663
+ kind,
664
+ title,
665
+ message,
666
+ seconds,
667
+ sound: sound && audioPath !== '',
668
+ audioPath,
669
+ audioMissing,
670
+ speak,
671
+ settings,
672
+ createdAt: Date.now(),
673
+ count: 1,
674
+ snoozed: false,
675
+ quiet,
676
+ holdUntil,
677
+ }
678
+ const placement = enqueue(item)
679
+ return {
680
+ ok: true,
681
+ hostMode: 'script',
682
+ kind,
683
+ title,
684
+ message,
685
+ seconds,
686
+ position: settings.position,
687
+ sound: sound && audioPath !== '',
688
+ audio: sound && audioPath !== '' ? audioPath : null,
689
+ audioMissing: audioMissing !== '' && audioMissing !== undefined ? audioMissing : undefined,
690
+ speak: speak !== '' ? speak : null,
691
+ background: extras.background !== '' ? extras.background : null,
692
+ icon: extras.icon !== '' ? extras.icon : null,
693
+ queued: placement.queued === true || placement.merged === true,
694
+ merged: placement.merged === true ? true : undefined,
695
+ position_in_queue: placement.position,
696
+ count: placement.count,
697
+ quiet: quiet || undefined,
698
+ holdUntil: holdUntil > 0 ? new Date(holdUntil).toISOString() : undefined,
405
699
  }
406
700
  }
407
701
 
@@ -418,6 +712,11 @@ const parameters = {
418
712
  title: { type: 'string', description: '弹窗标题。不传时按档位使用默认标题。' },
419
713
  seconds: { type: 'number', description: '弹窗停留秒数,2–600。不传用插件 Config 的 seconds(默认 60)。' },
420
714
  sound: { type: 'boolean', description: '本次是否播放提示音。不传用插件 Config 的 sound(默认开)。' },
715
+ speak: {
716
+ type: 'string',
717
+ description:
718
+ '用系统语音念出来的句子(不弹窗也能念)。不传时:插件里开了「语音朗读」就念正文,否则不念。',
719
+ },
421
720
  },
422
721
  }
423
722
 
@@ -428,6 +727,7 @@ function toolDefinition(getSettings) {
428
727
  "Pop a native desktop reminder (voice + toast, bottom-right, auto-dismiss, never steals focus) on the user's Windows screen, then return immediately. " +
429
728
  'It renders the card with the system PowerShell + WinForms host shipped in this plugin, so nothing is downloaded and no unsigned exe is involved. ' +
430
729
  'Use kind="done" when a piece of work is finished and handed off, and kind="decide" before asking the user to approve or choose something. ' +
730
+ 'Cards carry 「知道了 / 稍后提醒」 buttons; extra cards queue instead of stacking, and every reminder lands in the local history. ' +
431
731
  'This replaces running 发送提醒.ps1 -Voice 完成/决定 by hand: do not spawn a reminder host yourself, and do not call this in a loop.',
432
732
  parameters,
433
733
  output: {
@@ -457,6 +757,7 @@ const AUDIO_ROUTE = '/dsh-reminder-notify/audio'
457
757
  const CONFIG_ROUTE = '/dsh-reminder-notify/config'
458
758
  const PREVIEW_ROUTE = '/dsh-reminder-notify/preview'
459
759
  const BALANCE_ROUTE = '/dsh-reminder-notify/balance'
760
+ const HISTORY_ROUTE = '/dsh-reminder-notify/history'
460
761
 
461
762
  // 面板要「把音频目录里的文件列成下拉」,但 Client 侧没有任何读文件能力,
462
763
  // 所以由 Host 注册一条只读的 GET 路由,页面用同源 fetch 取这个 JSON。
@@ -943,11 +1244,97 @@ function registerBalanceRoute(ctx, getSettings, config) {
943
1244
  void config
944
1245
  }
945
1246
 
1247
+ // ——— 提醒历史 ————————————————————————————————————————————————————
1248
+ //
1249
+ // 存在本地 JSON(默认 <用户目录>/.dsh/dsh-reminder-notify/history.json),
1250
+ // 面板只读这条路由,不直接读文件 —— Client 侧没有任何文件访问能力。
1251
+ export function historyStats(entries) {
1252
+ const byKind = { done: 0, decide: 0, raw: 0 }
1253
+ const byAction = {}
1254
+ const dayKey = (ms) => {
1255
+ const d = new Date(ms)
1256
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
1257
+ }
1258
+ const buckets = new Map()
1259
+ for (let i = 6; i >= 0; i -= 1) {
1260
+ const d = new Date()
1261
+ d.setDate(d.getDate() - i)
1262
+ buckets.set(dayKey(d.getTime()), 0)
1263
+ }
1264
+ const today = dayKey(Date.now())
1265
+ let todayCount = 0
1266
+ for (const entry of entries) {
1267
+ if (entry === null || typeof entry !== 'object') continue
1268
+ const kind = String(entry.kind ?? '')
1269
+ if (byKind[kind] !== undefined) byKind[kind] += 1
1270
+ const action = String(entry.action ?? 'unknown')
1271
+ byAction[action] = (byAction[action] ?? 0) + 1
1272
+ const key = dayKey(num(entry.at, 0))
1273
+ if (key === today) todayCount += 1
1274
+ if (buckets.has(key)) buckets.set(key, buckets.get(key) + 1)
1275
+ }
1276
+ return {
1277
+ total: entries.length,
1278
+ today: todayCount,
1279
+ byKind,
1280
+ byAction,
1281
+ last7: [...buckets.entries()].map(([date, count]) => ({ date, count })),
1282
+ }
1283
+ }
1284
+
1285
+ function registerHistoryRoute(ctx, getSettings) {
1286
+ const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
1287
+ if (web === undefined || web === null || typeof web.register !== 'function') {
1288
+ ctx.logger?.warn?.('dsh-reminder-notify: webServer is unavailable, the history panel stays hidden')
1289
+ return
1290
+ }
1291
+ const reply = (res, status, payload) => {
1292
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1293
+ res.end(JSON.stringify(payload))
1294
+ }
1295
+ const route = {
1296
+ kind: 'exact',
1297
+ path: HISTORY_ROUTE,
1298
+ handler: async (req, res) => {
1299
+ try {
1300
+ const settings = getSettings()
1301
+ const method = (req.method ?? 'GET').toUpperCase()
1302
+ if (method === 'GET') {
1303
+ const entries = readHistory(settings)
1304
+ return reply(res, 200, {
1305
+ ok: true,
1306
+ enabled: settings.historyEnabled,
1307
+ file: historyPathOf(settings),
1308
+ stats: historyStats(entries),
1309
+ entries: entries.slice(-50).reverse(),
1310
+ })
1311
+ }
1312
+ if (method !== 'POST') return reply(res, 405, { ok: false, error: 'use GET or POST' })
1313
+ const body = await readJsonBody(req)
1314
+ if (body !== null && typeof body === 'object' && body.mode === 'clear') {
1315
+ writeHistory(settings, [])
1316
+ return reply(res, 200, { ok: true, cleared: true, file: historyPathOf(settings) })
1317
+ }
1318
+ return reply(res, 400, { ok: false, error: 'unknown mode' })
1319
+ } catch (error) {
1320
+ return reply(res, 500, { ok: false, error: String(error?.message ?? error) })
1321
+ }
1322
+ },
1323
+ }
1324
+ ctx.effect(() => {
1325
+ const dispose = web.register(route)
1326
+ return () => {
1327
+ if (typeof dispose === 'function') dispose()
1328
+ }
1329
+ }, 'dsh-reminder-notify: history route')
1330
+ }
1331
+
946
1332
  export function apply(ctx, config) {
947
1333
  registerAudioRoute(ctx, () => settingsOf(config))
948
1334
  registerConfigRoute(ctx, () => settingsOf(config))
949
1335
  registerPreviewRoute(ctx, () => settingsOf(config))
950
1336
  registerBalanceRoute(ctx, () => settingsOf(config), config)
1337
+ registerHistoryRoute(ctx, () => settingsOf(config))
951
1338
  const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools
952
1339
  if (tools === undefined || tools === null || typeof tools.register !== 'function') {
953
1340
  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.10.2",
3
+ "version": "0.11.0",
4
4
  "description": "DSH 桌面提醒插件:把「完成/需要决定」提醒变成 notify_user 工具(浮动卡片 + 提示音,不抢焦点,纯 PowerShell 源码宿主,仓库零 exe)",
5
5
  "author": "Jiangshuaiye1203",
6
6
  "type": "module",
@@ -63,4 +63,4 @@
63
63
  "registry": "https://registry.npmjs.org/"
64
64
  },
65
65
  "license": "MIT"
66
- }
66
+ }