dsh-reminder-notify 0.15.0 → 0.16.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/README.md CHANGED
@@ -100,3 +100,26 @@ reminder.config() // 当前生效配置的只读副
100
100
 
101
101
  `notify()` 的 `kind` 与 `notify_user` 一致(`done` / `decide` / `raw`),其余参数同工具参数;调用同样受冷却、排队、合并、免打扰、历史记录约束。
102
102
 
103
+ ## 出问题先自检(0.16 起)
104
+
105
+ 面板「高级:历史、余额与宿主」里的「工程与可靠性:自检」有三个按钮:**运行自检**(逐项打勾)、**弹样卡**、**测 GitHub**。
106
+ 其中「GitHub 连通性」一项会在 hosts 里发现「把 github.com 指到 127.0.0.1」的本机重定向时标红——那是 Steam++(Watt Toolkit)
107
+ 加速 GitHub 的做法:加速器在跑时正常,它没接管(只开了进程没点「一键加速」/被强杀)时浏览器和 git 都会连不上。
108
+
109
+ 推送时如果遇到这种情况,直接跑:
110
+
111
+ ```powershell
112
+ powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx
113
+ ```
114
+
115
+ 它会先测通不通;不通且发现本机重定向就临时注释 + 刷 DNS 再测,通了才 push,结束再按原样还原 hosts(`-KeepChanges` 保留改动、`-DryRun` 只探测不推送)。
116
+
117
+
118
+ 设置面板最下面的「工程与可靠性:自检」里有两个按钮:
119
+
120
+ - **运行自检**:逐条检查系统 / PowerShell / 宿主脚本 / 提示音目录与文件 / 历史文件可写 / 面板路由 / `notify_user` / 配置可写 / 余额接口 / 宿主服务 API / 最近一次宿主退出码,✗ 会带上具体路径或原因。
121
+ - **弹样卡**:真的弹一张 12 秒的卡,能看到就说明宿主链路正常(比读日志快)。
122
+
123
+ 宿主兜底:卡片该写结果文件却没写(被杀、被策略拦下、非零退出)时,会记一条 `host-failed` 到历史,并在 0.8 秒后**静音重试一次**(`retryHostOnce`,默认开);最近 5 次失败原因显示在自检块里。
124
+
125
+ CI 在 `.github/workflows/ci.yml`:Ubuntu 与 Windows 各跑 node 20/22,做语法检查 + 两套无窗口自检(真弹卡的自检只在本机跑,CI 没有交互桌面)。
package/client.js CHANGED
@@ -22,6 +22,7 @@ window.__ModuleLoader__.load({
22
22
  const BALANCE_ROUTE = '/dsh-reminder-notify/balance'
23
23
  // 0.11 新增:提醒历史(GET 拿统计+最近记录,POST { mode: 'clear' } 清空)。
24
24
  const HISTORY_ROUTE = '/dsh-reminder-notify/history'
25
+ const DOCTOR_ROUTE = '/dsh-reminder-notify/doctor'
25
26
  const DIGEST_ROUTE = '/dsh-reminder-notify/digest'
26
27
  // 下拉按扩展名分组:wav 一组、mp3 一组……组内按文件名排序,一眼能看出格式。
27
28
  function groupAudioFiles(files) {
@@ -263,6 +264,36 @@ window.__ModuleLoader__.load({
263
264
  tryShown: '已经弹出一张样卡,20 秒后自动关闭。',
264
265
  tryQuiet: '现在在免打扰时段,样卡被拦住了(正常行为)。',
265
266
  tryFailed: '没能弹出示意卡:',
267
+ retryHostOnce: '宿主失败时重试一次',
268
+ retryHostOnceHint: '第一次没画出卡片(比如被系统策略拦下)时,静音再弹一次。',
269
+ groupDoctor: '工程与可靠性:自检',
270
+ doctorHint: '「运行自检」逐条检查宿主路径、提示音、历史可写与各项服务;「弹样卡」会真的弹一张,验证宿主能不能画。',
271
+ doctorNotRun: '还没运行过自检。',
272
+ doctorRun: '运行自检',
273
+ doctorRunning: '检查中…',
274
+ doctorAllOk: '全部通过。',
275
+ doctorHasFailures: '有项目没通过,见下面的 ✗。',
276
+ doctorProbe: '弹样卡',
277
+ doctorProbeOk: '样卡已弹出,能看到就说明宿主正常。',
278
+ doctorProbeFailed: '自检失败:',
279
+ doctorGithub: '测 GitHub',
280
+ doctorGithubOk: 'GitHub 能连上:HTTP ',
281
+ doctorGithubFailed: 'GitHub 连不上:',
282
+ check_github: 'GitHub 连通性',
283
+ doctorLastExit: '最近退出码',
284
+ doctorFailures: '最近失败次数',
285
+ check_platform: '系统',
286
+ check_powershell: 'PowerShell',
287
+ check_host_script: '宿主脚本',
288
+ check_audio_dir: '提示音目录',
289
+ check_audio_files: '提示音文件',
290
+ check_history_writable: '历史文件可写',
291
+ check_routes: '面板路由',
292
+ check_tools: 'notify_user',
293
+ check_config_editor: '配置可写',
294
+ check_account: '余额接口',
295
+ check_service_api: '宿主服务',
296
+ check_host_exit: '宿主退出码',
266
297
  speakEnabled: '朗读提醒内容',
267
298
  buttonsEnabled: '卡片显示按钮',
268
299
  snoozeMinutes: '「稍后提醒」延后分钟',
@@ -373,6 +404,36 @@ window.__ModuleLoader__.load({
373
404
  tryShown: 'A sample card is on screen; it closes itself in 20 seconds.',
374
405
  tryQuiet: 'Quiet hours are active, so the sample was held back (expected).',
375
406
  tryFailed: 'Could not show the sample: ',
407
+ retryHostOnce: 'Retry once when the host fails',
408
+ retryHostOnceHint: 'If the first card never drew (blocked by policy, for example), try once more with sound off.',
409
+ groupDoctor: 'Reliability: self-check',
410
+ doctorHint: 'Run the self-check to verify the host path, audio files, writable history and every service; "probe" pops a real card to prove the host can draw.',
411
+ doctorNotRun: 'The self-check has not run yet.',
412
+ doctorRun: 'Run self-check',
413
+ doctorRunning: 'Checking…',
414
+ doctorAllOk: 'Everything passed.',
415
+ doctorHasFailures: 'Some checks failed — see the ✗ lines below.',
416
+ doctorProbe: 'Probe a card',
417
+ doctorProbeOk: 'A probe card is on screen; if you can see it, the host is fine.',
418
+ doctorProbeFailed: 'Self-check failed: ',
419
+ doctorGithub: 'Test GitHub',
420
+ doctorGithubOk: 'GitHub reachable: HTTP ',
421
+ doctorGithubFailed: 'GitHub unreachable: ',
422
+ check_github: 'GitHub reachability',
423
+ doctorLastExit: 'last exit code',
424
+ doctorFailures: 'recent failures',
425
+ check_platform: 'platform',
426
+ check_powershell: 'PowerShell',
427
+ check_host_script: 'host script',
428
+ check_audio_dir: 'audio directory',
429
+ check_audio_files: 'audio files',
430
+ check_history_writable: 'history file writable',
431
+ check_routes: 'panel routes',
432
+ check_tools: 'notify_user',
433
+ check_config_editor: 'config writable',
434
+ check_account: 'balance API',
435
+ check_service_api: 'host service API',
436
+ check_host_exit: 'host exit code',
376
437
  speakEnabled: 'Speak the reminder',
377
438
  buttonsEnabled: 'Show card buttons',
378
439
  snoozeMinutes: 'Snooze minutes',
@@ -513,6 +574,7 @@ window.__ModuleLoader__.load({
513
574
  { key: 'position', group: 'basic', kind: 'select', options: ['br', 'center', 'tr'], optionLabels: ['positionBr', 'positionCenter', 'positionTr'] },
514
575
  { key: 'sound', group: 'basic', kind: 'boolean' },
515
576
  { key: 'cooldownMs', group: 'host', kind: 'number' },
577
+ { key: 'retryHostOnce', group: 'host', kind: 'boolean' },
516
578
  { key: 'doneAudio', group: 'audio', kind: 'text' },
517
579
  { key: 'decideAudio', group: 'audio', kind: 'text' },
518
580
  { key: 'rawAudio', group: 'audio', kind: 'text' },
@@ -575,6 +637,7 @@ window.__ModuleLoader__.load({
575
637
  seconds: 'secondsHint',
576
638
  sound: 'soundHint',
577
639
  cooldownMs: 'cooldownHint',
640
+ retryHostOnce: 'retryHostOnceHint',
578
641
  doneAudio: 'audioHint',
579
642
  audioDir: 'audioDirHint',
580
643
  cardBackground: 'cardBackgroundHint',
@@ -635,6 +698,7 @@ window.__ModuleLoader__.load({
635
698
  { id: 'queue', label: 'groupQueue', groups: ['queue'] },
636
699
  { id: 'misc', label: 'groupAdvanced', groups: ['digest', 'history', 'balance', 'host'] },
637
700
  { id: 'help', label: 'groupHelp', groups: [] },
701
+ { id: 'doctor', label: 'groupDoctor', groups: [] },
638
702
  ]
639
703
 
640
704
  // 0.14:说明收进面板里,按条目折叠。
@@ -676,6 +740,8 @@ window.__ModuleLoader__.load({
676
740
  const [openBlocks, setOpenBlocks] = React.useState({})
677
741
  const [tryBusy, setTryBusy] = React.useState(null)
678
742
  const [helpOpen, setHelpOpen] = React.useState({})
743
+ const [doctor, setDoctor] = React.useState(null)
744
+ const [doctorBusy, setDoctorBusy] = React.useState(false)
679
745
 
680
746
  React.useEffect(() => {
681
747
  if (typeof fetch !== 'function') {
@@ -878,6 +944,61 @@ window.__ModuleLoader__.load({
878
944
  })
879
945
  }
880
946
 
947
+ // 0.16 自检:把宿主路径、提示音、历史可写、各项服务逐条查一遍;顺带能弹一张样卡验证宿主。
948
+ function runDoctor(mode) {
949
+ if (doctorBusy) return
950
+ setDoctorBusy(true)
951
+ setMessage(null)
952
+ Promise.resolve()
953
+ .then(() => {
954
+ const init = mode === 'probe' || mode === 'github'
955
+ ? {
956
+ method: 'POST',
957
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
958
+ body: JSON.stringify({ mode }),
959
+ }
960
+ : { headers: { accept: 'application/json' } }
961
+ return fetch(DOCTOR_ROUTE, init)
962
+ })
963
+ .then((response) => {
964
+ const status = response ? response.status : 0
965
+ const body = response && typeof response.json === 'function' ? response.json() : Promise.resolve(null)
966
+ return Promise.resolve(body)
967
+ .catch(() => null)
968
+ .then((data) => {
969
+ if (response && response.ok && data && data.ok !== false) return data
970
+ const detail = data && data.error ? data.error : 'HTTP ' + status
971
+ throw new Error(detail)
972
+ })
973
+ })
974
+ .then((data) => {
975
+ setDoctorBusy(false)
976
+ if (data && data.report) setDoctor(data.report)
977
+ const label = typeof t === 'function' ? t : (key) => key
978
+ if (mode === 'github') {
979
+ const probe = data && data.github ? data.github : {}
980
+ if (probe.ok === true) {
981
+ setMessage({ ok: true, text: label('doctorGithubOk') + String(probe.statusCode || '') + ' · ' + String(probe.ms || 0) + 'ms' })
982
+ } else {
983
+ setMessage({ ok: false, text: label('doctorGithubFailed') + String(probe.error || ('HTTP ' + (probe.statusCode || 0))) })
984
+ }
985
+ return
986
+ }
987
+ if (mode === 'probe') {
988
+ const card = data && data.card ? data.card : {}
989
+ if (card.ok === false) {
990
+ setMessage({ ok: false, text: label('doctorProbeFailed') + String(card.detail || card.error || '') })
991
+ return
992
+ }
993
+ setMessage({ ok: true, text: label('doctorProbeOk') })
994
+ }
995
+ })
996
+ .catch((error) => {
997
+ setDoctorBusy(false)
998
+ const prefix = typeof t === 'function' ? t('doctorProbeFailed') : 'self-check failed: '
999
+ setMessage({ ok: false, text: prefix + String((error && error.message) || error) })
1000
+ })
1001
+ }
881
1002
  // 0.13「试试看」:让宿主真的弹一张样卡(POST /preview,mode=card),
882
1003
  // 比读说明书更快知道每一档长什么样。样卡只停 20 秒,不改任何配置。
883
1004
  function tryCard(kind) {
@@ -1367,7 +1488,49 @@ window.__ModuleLoader__.load({
1367
1488
 
1368
1489
  const advanced = ADV_BLOCKS.map((block) => {
1369
1490
  const open = openBlocks[block.id] === true
1370
- const children = block.id === 'help'
1491
+ const children = block.id === 'doctor'
1492
+ ? [
1493
+ h(
1494
+ 'div',
1495
+ { className: 'drn-help', key: 'doctor-panel' },
1496
+ h('div', { className: 'drn-head-intro' }, label('doctorHint')),
1497
+ doctor === null
1498
+ ? h('div', { className: 'drn-hint' }, label('doctorNotRun'))
1499
+ : h(
1500
+ 'div',
1501
+ { className: 'drn-help' },
1502
+ h('div', { className: 'drn-hint' }, doctor.ok === true ? label('doctorAllOk') : label('doctorHasFailures')),
1503
+ (doctor.checks || []).map((check, index) =>
1504
+ h(
1505
+ 'div',
1506
+ { className: 'drn-hint', key: 'check-' + index },
1507
+ (check.ok ? '✓ ' : '✗ ') + label('check_' + String(check.id || '').replace(/-/g, '_')) + ' · ' + String(check.detail || ''),
1508
+ ),
1509
+ ),
1510
+ h('div', { className: 'drn-hint' }, label('doctorLastExit') + ' ' + String(doctor.host && doctor.host.lastExit === null ? '—' : doctor.host && doctor.host.lastExit) + ' · ' + label('doctorFailures') + ' ' + String(doctor.host ? doctor.host.failureCount : 0)),
1511
+ ),
1512
+ h(
1513
+ 'div',
1514
+ { className: 'drn-pick' },
1515
+ h(
1516
+ 'button',
1517
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: doctorBusy, onClick: () => runDoctor('check') },
1518
+ label(doctorBusy ? 'doctorRunning' : 'doctorRun'),
1519
+ ),
1520
+ h(
1521
+ 'button',
1522
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: doctorBusy, onClick: () => runDoctor('probe') },
1523
+ label('doctorProbe'),
1524
+ ),
1525
+ h(
1526
+ 'button',
1527
+ { type: 'button', className: 'drn-btn drn-digest-btn', disabled: doctorBusy, onClick: () => runDoctor('github') },
1528
+ label(doctorBusy ? 'doctorRunning' : 'doctorGithub'),
1529
+ ),
1530
+ ),
1531
+ ),
1532
+ ]
1533
+ : block.id === 'help'
1371
1534
  ? [
1372
1535
  h(
1373
1536
  'div',
package/cordis.patch.yml CHANGED
@@ -94,3 +94,4 @@
94
94
  pushDecide: true
95
95
  # 日报同时推到手机
96
96
  pushDigest: true
97
+ retryHostOnce: true
package/docs/PUBLISH.md CHANGED
@@ -12,7 +12,7 @@ DSH 的「插件市场 → 发现」页读的是**索引 URL**:一份 JSON(
12
12
  | 索引地址(他人添加这个) | `https://jiangshuaiye1203.github.io/dsh-reminder-notify/publish/index.json` |
13
13
  | 站点首页 | https://jiangshuaiye1203.github.io/dsh-reminder-notify/ |
14
14
  | npm 包 | https://www.npmjs.com/package/dsh-reminder-notify |
15
- | 当前版本 | **0.14.0**,装源为 **npm**(`dsh-reminder-notify@0.14.0`),不再是 git 固定提交 |
15
+ | 当前版本 | **0.16.0**,装源为 **npm**(`dsh-reminder-notify@0.16.0`),不再是 git 固定提交 |
16
16
  | Pages | Deploy from a branch,`main` / `(root)` |
17
17
 
18
18
  发新版(npm 源):改代码 → 升 `package.json` 版本 → `scripts\publish-npm.cmd` 发布到 npm →
package/docs/detail.en.md CHANGED
@@ -11,3 +11,4 @@ Cards are drawn by the bundled `host/ReminderHost.ps1` with the built-in PowerSh
11
11
  - **Want it on your phone**: open push under "Digest & push", pick the format, paste your own webhook URL (WeCom bot or Server Chan), then press "Send one now".
12
12
  - **Everything else**: folded into "How it works (expand to read)" inside the settings panel below, one topic at a time.
13
13
  - **For other plugins**: this plugin exposes a `reminder` service (`notify` / `digest` / `stats` / `config`); see the README.
14
+ - The self-check now has a **GitHub reachability** item (it flags hosts entries pointing github.com at 127.0.0.1, i.e. the Steam++ acceleration table) plus a **Test GitHub** button; `scripts/github-push.ps1` repairs that state around a push and restores hosts afterwards.
package/docs/detail.zh.md CHANGED
@@ -11,3 +11,4 @@
11
11
  - **想推到手机**:在「日报与推送」里打开推送、选格式、填自己的 webhook 地址(企业微信机器人或 Server 酱),点「现在发一条」验证。
12
12
  - **其余说明**:全部收在下面设置面板的「使用说明(点开才看)」里,一次只展开一条。
13
13
  - **给别的插件用**:本插件对外提供 `reminder` 服务(`notify` / `digest` / `stats` / `config`),写法见 README。
14
+ - 自检里新增「GitHub 连通性」:hosts 里有指向 127.0.0.1 的 github 行(Steam++ 加速表)时标红,另有「测 GitHub」按钮现测一次;推送用 `scripts/github-push.ps1` 可自动处理并还原。
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 https from 'node:https'
14
15
  import os from 'node:os'
15
16
  import path from 'node:path'
16
17
  import { fileURLToPath } from 'node:url'
@@ -101,6 +102,7 @@ export const Config = z === null ? undefined : z.object({
101
102
  pushFormat: z.union(['wecom', 'serverchan', 'json', 'text']).default('wecom').description('推送格式:wecom 企业微信机器人、serverchan Server酱、json 通用 JSON、text 纯文本').volatile(),
102
103
  pushDecide: z.boolean().default(true).description('「需要你来决定」档位也推到手机').volatile(),
103
104
  pushDigest: z.boolean().default(true).description('日报同时推到手机').volatile(),
105
+ retryHostOnce: z.boolean().default(true).description('宿主第一次没画出卡片时,自动静音重试一次').volatile(),
104
106
  dryRun: z.boolean().default(false).description('调试用:只试算参数、不真的弹窗(自检脚本会打开它)').volatile(),
105
107
  })
106
108
 
@@ -241,6 +243,7 @@ function settingsOf(config) {
241
243
  pushFormat: ['wecom', 'serverchan', 'json', 'text'].includes(c.pushFormat) ? c.pushFormat : 'wecom',
242
244
  pushDecide: c.pushDecide !== false,
243
245
  pushDigest: c.pushDigest !== false,
246
+ retryHostOnce: c.retryHostOnce !== false,
244
247
  dryRun: c.dryRun === true,
245
248
  }
246
249
  }
@@ -523,11 +526,14 @@ async function showItem(item) {
523
526
  queueLeft,
524
527
  })
525
528
  let action = 'unknown'
529
+ let exitCode = null
530
+ let hostError
526
531
  try {
527
532
  const { exited } = await launch(settings.powershellPath, argv, PACKAGE_ROOT)
528
- await exited
529
- } catch {
533
+ exitCode = await exited
534
+ } catch (error) {
530
535
  // spawn 失败就当作没弹出来,记录一条便于排查
536
+ hostError = String(error?.message ?? error)
531
537
  }
532
538
  try {
533
539
  const parsed = JSON.parse(fs.readFileSync(resultFile, 'utf8'))
@@ -545,12 +551,30 @@ async function showItem(item) {
545
551
  } catch {
546
552
  // 没有结果文件(比如宿主被杀)时按 unknown 记
547
553
  }
554
+ // 0.16:宿主明明该写结果却没写(或非零退出)就记一次 host-failed,并在下面自动重试一次。
555
+ if (hostError !== undefined) {
556
+ action = 'host-failed'
557
+ noteHostRun(exitCode, action, hostError)
558
+ } else if (action === 'unknown' && exitCode !== null && exitCode !== 0) {
559
+ action = 'host-failed'
560
+ noteHostRun(exitCode, action, 'host exited before writing a result')
561
+ } else {
562
+ noteHostRun(exitCode, action)
563
+ }
548
564
  try {
549
565
  fs.unlinkSync(resultFile)
550
566
  } catch {
551
567
  // 清不掉就算了,文件名带 pid + 时间戳不会互相覆盖
552
568
  }
553
569
  item.action = action
570
+ if (action === 'host-failed' && settings.retryHostOnce && item.retried !== true) {
571
+ // 兜底:静音重试一次(宿主偶发被系统策略拦下时,第二次通常能画出来)。
572
+ const retry = setTimeout(() => {
573
+ queue.unshift({ ...item, retried: true, count: item.count ?? 1, holdUntil: 0, createdAt: Date.now() })
574
+ pump()
575
+ }, 800)
576
+ if (typeof retry.unref === 'function') retry.unref()
577
+ }
554
578
  appendHistory(settings, {
555
579
  at: Date.now(),
556
580
  kind: item.kind,
@@ -1532,6 +1556,230 @@ function registerDigestRoute(ctx, getSettings) {
1532
1556
  }, 'dsh-reminder-notify: digest route')
1533
1557
  }
1534
1558
 
1559
+ /** 宿主健康:最近一次退出码 / 结果 / 失败原因,供自诊断面板与 doctor 路由读取。 */
1560
+ const hostHealth = { lastExit: null, lastAction: null, lastAt: 0, lastError: '', failures: [] }
1561
+
1562
+ function noteHostRun(exitCode, action, error) {
1563
+ hostHealth.lastExit = exitCode
1564
+ hostHealth.lastAction = action
1565
+ hostHealth.lastAt = Date.now()
1566
+ hostHealth.lastError = error === undefined ? '' : String(error)
1567
+ if (error !== undefined || action === 'host-failed') {
1568
+ hostHealth.failures.push({
1569
+ at: hostHealth.lastAt,
1570
+ exit: exitCode,
1571
+ action,
1572
+ error: hostHealth.lastError,
1573
+ })
1574
+ if (hostHealth.failures.length > 10) hostHealth.failures.shift()
1575
+ }
1576
+ }
1577
+
1578
+ /** 在 PATH 里找一个可执行文件(Windows 上补 .exe),找不到返回 null。 */
1579
+ function resolveOnPath(name) {
1580
+ if (typeof name !== 'string' || name.trim() === '') return null
1581
+ const exts = process.platform === 'win32' ? ['', '.exe', '.cmd', '.bat'] : ['']
1582
+ const dirs = String(process.env.PATH ?? '').split(path.delimiter).filter((dir) => dir !== '')
1583
+ for (const dir of dirs) {
1584
+ for (const ext of exts) {
1585
+ const candidate = path.join(dir, name + ext)
1586
+ try {
1587
+ if (fs.existsSync(candidate)) return candidate
1588
+ } catch {
1589
+ // 无权访问的目录跳过
1590
+ }
1591
+ }
1592
+ }
1593
+ return null
1594
+ }
1595
+
1596
+ /**
1597
+ * 0.16 自诊断:把「要什么、在哪、通不通」逐条列出来。
1598
+ * 只读,不弹卡、不改配置;面板的「运行自检」和 doctor 路由都用它。
1599
+ */
1600
+ export function doctorReport(ctx, getSettings) {
1601
+ const settings = getSettings()
1602
+ const checks = []
1603
+ const add = (id, ok, detail) => checks.push({ id, ok: ok === true, detail: String(detail ?? '') })
1604
+
1605
+ add('platform', process.platform === 'win32', process.platform)
1606
+
1607
+ const psName = str(settings.powershellPath, 'powershell.exe')
1608
+ const looksLikePath = psName.includes('/') || psName.includes('\\')
1609
+ const psPath = looksLikePath ? path.resolve(psName) : resolveOnPath(psName)
1610
+ add('powershell', psPath !== null && psPath !== undefined && fs.existsSync(psPath), psPath ?? `找不到 ${psName}`)
1611
+
1612
+ const scriptPath = path.resolve(str(settings.scriptPath, BUNDLED_HOST_SCRIPT))
1613
+ add('host-script', fs.existsSync(scriptPath), scriptPath)
1614
+
1615
+ const audioDir = path.resolve(str(settings.audioDir, BUNDLED_AUDIO_DIR))
1616
+ const doneAudio = str(settings.doneAudio, '')
1617
+ const decideAudio = str(settings.decideAudio, '')
1618
+ const audioOk = fs.existsSync(audioDir)
1619
+ add('audio-dir', audioOk, audioDir)
1620
+ if (audioOk) {
1621
+ const missing = [doneAudio, decideAudio]
1622
+ .filter((file) => file !== '')
1623
+ .filter((file) => !fs.existsSync(path.join(audioDir, file)))
1624
+ add('audio-files', missing.length === 0, missing.length === 0 ? '两个提示音都在' : '缺少 ' + missing.join('、'))
1625
+ }
1626
+
1627
+ // 调用方可能只给半份 settings(自检、别的插件),这里兜一层,别让诊断自己崩。
1628
+ let histFile = ''
1629
+ try {
1630
+ histFile = historyPathOf(settings)
1631
+ } catch {
1632
+ histFile = path.join(os.homedir(), '.dsh', 'dsh-reminder-notify', 'history.json')
1633
+ }
1634
+ let writable = false
1635
+ try {
1636
+ fs.mkdirSync(path.dirname(histFile), { recursive: true })
1637
+ fs.accessSync(path.dirname(histFile), fs.constants.W_OK)
1638
+ writable = true
1639
+ } catch {
1640
+ writable = false
1641
+ }
1642
+ add('history-writable', writable, histFile)
1643
+
1644
+ const service = (name) => (typeof ctx.get === 'function' ? ctx.get(name) : undefined)
1645
+ const web = service('webServer')
1646
+ add('routes', web !== undefined && web !== null && typeof web.register === 'function', web === undefined ? 'webServer 不可用' : 'webServer 可用')
1647
+ const tools = service('tools')
1648
+ add('tools', tools !== undefined && tools !== null && typeof tools.register === 'function', tools === undefined ? 'tools 不可用' : 'notify_user 可注册')
1649
+ add('config-editor', service('configEditor') !== undefined, service('configEditor') === undefined ? '面板只能读(旧宿主)' : '可写')
1650
+ add('account', service('deepseekAccount') !== undefined, service('deepseekAccount') === undefined ? '读不到余额(不影响卡片)' : '可读余额')
1651
+ add('service-api', typeof ctx.provide === 'function', typeof ctx.provide === 'function' ? "可 provide('reminder')" : '旧宿主没有 ctx.provide')
1652
+
1653
+ // 0.16.1:GitHub 连通性。Steam++(Watt Toolkit)加速 GitHub 靠改 hosts 把 github.com
1654
+ // 指到 127.0.0.1,由它的本地代理接住;它没接管(只开了进程没点「一键加速」/被强杀)时,
1655
+ // 浏览器和 git 都会连不上。这里做静态判断:hosts 里有没有本机重定向。
1656
+ // 真正「能不能连」用 POST /doctor {mode:'github'} 现测。
1657
+ const hostsFile = process.platform === 'win32'
1658
+ ? path.join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'drivers', 'etc', 'hosts')
1659
+ : '/etc/hosts'
1660
+ let githubLines = []
1661
+ try {
1662
+ githubLines = fs.readFileSync(hostsFile, 'utf8')
1663
+ .split(/\r?\n/)
1664
+ .map((line) => line.trim())
1665
+ .filter((line) => line !== '' && !line.startsWith('#'))
1666
+ .filter((line) => /^\d{1,3}(\.\d{1,3}){3}\s/.test(line))
1667
+ .filter((line) => /github\.com|githubusercontent\.com/i.test(line))
1668
+ } catch {
1669
+ githubLines = []
1670
+ }
1671
+ const loopback = githubLines.filter((line) => /^127\.0\.0\.1\s/.test(line))
1672
+ if (githubLines.length === 0) {
1673
+ add('github', true, 'hosts 里没有 github 重定向(裸连)')
1674
+ } else if (loopback.length === 0) {
1675
+ add('github', true, 'hosts 指向 ' + githubLines[0].split(/\s+/)[0])
1676
+ } else {
1677
+ add('github', false, 'hosts 把 github 指到 127.0.0.1(Steam++ 加速表);加速器没接管就连不上,跑 scripts/github-push.ps1 会自动处理')
1678
+ }
1679
+
1680
+ const lastExit = hostHealth.lastExit
1681
+ const hostOk = lastExit === null || lastExit === 0
1682
+ add('host-exit', hostOk, lastExit === null ? '还没有弹过卡片' : `最近一次退出码 ${lastExit}`)
1683
+
1684
+ return {
1685
+ ok: checks.every((check) => check.ok),
1686
+ version: packageVersion(),
1687
+ platform: process.platform,
1688
+ node: process.version,
1689
+ paths: { powershell: psPath ?? null, hostScript: scriptPath, audioDir, history: histFile },
1690
+ host: {
1691
+ lastExit: hostHealth.lastExit,
1692
+ lastAction: hostHealth.lastAction,
1693
+ lastAt: hostHealth.lastAt,
1694
+ lastError: hostHealth.lastError,
1695
+ failureCount: hostHealth.failures.length,
1696
+ failures: hostHealth.failures.slice(-5),
1697
+ },
1698
+ checks,
1699
+ }
1700
+ }
1701
+
1702
+ const DOCTOR_ROUTE = '/dsh-reminder-notify/doctor'
1703
+
1704
+ /** 现测一次 https://github.com(HEAD,8 秒超时)。 */
1705
+ export function probeGithub(timeoutMs = 8000) {
1706
+ const started = Date.now()
1707
+ return new Promise((resolve) => {
1708
+ let settled = false
1709
+ const done = (payload) => {
1710
+ if (settled) return
1711
+ settled = true
1712
+ resolve({ ...payload, ms: Date.now() - started })
1713
+ }
1714
+ try {
1715
+ const req = https.request(
1716
+ { method: 'HEAD', host: 'github.com', path: '/', timeout: timeoutMs, headers: { 'user-agent': 'dsh-reminder-notify-doctor' } },
1717
+ (res) => {
1718
+ res.resume()
1719
+ const code = res.statusCode ?? 0
1720
+ done({ ok: code >= 200 && code < 500, statusCode: code })
1721
+ },
1722
+ )
1723
+ req.on('timeout', () => {
1724
+ req.destroy()
1725
+ done({ ok: false, error: `timeout ${timeoutMs}ms` })
1726
+ })
1727
+ req.on('error', (error) => done({ ok: false, error: String(error?.message ?? error) }))
1728
+ req.end()
1729
+ } catch (error) {
1730
+ done({ ok: false, error: String(error?.message ?? error) })
1731
+ }
1732
+ })
1733
+ }
1734
+
1735
+ function registerDoctorRoute(ctx, getSettings) {
1736
+ const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
1737
+ if (web === undefined || web === null || typeof web.register !== 'function') {
1738
+ ctx.logger?.warn?.('dsh-reminder-notify: webServer is unavailable, the doctor panel stays hidden')
1739
+ return
1740
+ }
1741
+ const reply = (res, status, payload) => {
1742
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1743
+ res.end(JSON.stringify(payload))
1744
+ }
1745
+ const route = {
1746
+ kind: 'exact',
1747
+ path: DOCTOR_ROUTE,
1748
+ handler: async (req, res) => {
1749
+ try {
1750
+ const settings = getSettings()
1751
+ const method = (req.method ?? 'GET').toUpperCase()
1752
+ if (method === 'GET') return reply(res, 200, { ok: true, report: doctorReport(ctx, getSettings) })
1753
+ if (method !== 'POST') return reply(res, 405, { ok: false, error: 'use GET or POST' })
1754
+ const body = await readJsonBody(req)
1755
+ const mode = body !== null && typeof body === 'object' ? str(body.mode, 'check') : 'check'
1756
+ if (mode === 'check') return reply(res, 200, { ok: true, report: doctorReport(ctx, getSettings) })
1757
+ if (mode === 'github') {
1758
+ const probe = await probeGithub()
1759
+ return reply(res, 200, { ok: true, mode: 'github', github: probe })
1760
+ }
1761
+ if (mode === 'probe') {
1762
+ const card = await notify(
1763
+ 'raw',
1764
+ { title: '自检样卡', message: '这张卡由「运行自检」弹出,能看到就说明宿主正常。', seconds: 12 },
1765
+ { ...settings, quietEnabled: false },
1766
+ )
1767
+ return reply(res, 200, { ok: true, mode: 'probe', card })
1768
+ }
1769
+ return reply(res, 400, { ok: false, error: 'unknown mode' })
1770
+ } catch (error) {
1771
+ return reply(res, 500, { ok: false, error: String(error?.message ?? error) })
1772
+ }
1773
+ },
1774
+ }
1775
+ ctx.effect(() => {
1776
+ const dispose = web.register(route)
1777
+ return () => {
1778
+ if (typeof dispose === 'function') dispose()
1779
+ }
1780
+ }, 'dsh-reminder-notify: doctor route')
1781
+ }
1782
+
1535
1783
  function registerHistoryRoute(ctx, getSettings) {
1536
1784
  const web = typeof ctx.get === 'function' ? ctx.get('webServer') : undefined
1537
1785
  if (web === undefined || web === null || typeof web.register !== 'function') {
@@ -1628,6 +1876,7 @@ export function apply(ctx, config) {
1628
1876
  registerHistoryRoute(ctx, () => settingsOf(config))
1629
1877
  registerDigestRoute(ctx, () => settingsOf(config))
1630
1878
  registerDigestLoop(ctx, () => settingsOf(config))
1879
+ registerDoctorRoute(ctx, () => settingsOf(config))
1631
1880
  const tools = typeof ctx.get === 'function' ? ctx.get('tools') : ctx.tools
1632
1881
  if (tools === undefined || tools === null || typeof tools.register !== 'function') {
1633
1882
  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.15.0",
3
+ "version": "0.16.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.14.0",
52
- "publishTimestamp": 1795191602,
51
+ "version": "0.16.0",
52
+ "publishTimestamp": 1795223256,
53
53
  "source": {
54
54
  "type": "npm"
55
55
  },
@@ -0,0 +1,170 @@
1
+ # github-push.ps1 —— 推送前自动处理「Steam++ 加速表把 github.com 指到 127.0.0.1」的情况。
2
+ #
3
+ # 背景:Steam++(Watt Toolkit)加速 GitHub 的原理是改 hosts,把 github.com 指到
4
+ # 127.0.0.1,由它自己的本地代理接住。加速器在跑时一切正常;它没接管(进程开了但
5
+ # 没点「一键加速」、被强杀、崩了)时,浏览器和 git 都会连不上,报
6
+ # ERR_CONNECTION_REFUSED / Empty reply from server。
7
+ #
8
+ # 这个脚本做的事:
9
+ # 1. 先测 https://github.com 通不通;
10
+ # 2. 不通且 hosts 里有 127.0.0.1 的 github 行 → 临时注释它们(加 [dsh-temp] 标记)+ 刷 DNS,再测一次;
11
+ # 3. 通了就 git push(用 -Token,或环境变量 GITHUB_TOKEN,走 extraHeader,不落盘);
12
+ # 4. 无论成功失败,默认结束后把临时注释还原(-KeepChanges 则保留改动,方便继续用裸连)。
13
+ #
14
+ # 用法:
15
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -DryRun
16
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx
17
+ # powershell -NoProfile -ExecutionPolicy Bypass -File scripts/github-push.ps1 -Token ghp_xxx -KeepChanges
18
+
19
+ param(
20
+ [string]$Remote = 'origin',
21
+ [string]$Branch = 'main',
22
+ [string]$Token = $env:GITHUB_TOKEN,
23
+ [string]$RepoRoot = (Split-Path -Parent $PSScriptRoot),
24
+ [switch]$DryRun,
25
+ [switch]$KeepChanges
26
+ )
27
+
28
+ $ErrorActionPreference = 'Stop'
29
+ $HostsPath = Join-Path $env:SystemRoot 'System32\drivers\etc\hosts'
30
+ $Marker = '# [dsh-temp] '
31
+ $script:changed = $false
32
+ $script:restored = $false
33
+ $script:original = @()
34
+
35
+ function Test-GitHub {
36
+ # 用独立进程的 curl.exe 探测:不受 PowerShell 进程内 DNS / 连接池缓存影响,
37
+ # 注释 hosts 后重测能立刻反映真实结果。没有 curl 时退回 HttpWebRequest。
38
+ $curl = Join-Path $env:SystemRoot 'System32\curl.exe'
39
+ if (Test-Path $curl) {
40
+ try {
41
+ $raw = (& $curl -s -o NUL -w '%{http_code}' --max-time 8 --ssl-no-revoke -I https://github.com/ 2>$null | Out-String).Trim()
42
+ $code = 0
43
+ [void][int]::TryParse($raw, [ref]$code)
44
+ if ($code -gt 0) { return @{ ok = ($code -ge 200 -and $code -lt 500); code = $code; error = '' } }
45
+ return @{ ok = $false; code = 0; error = 'curl 无响应(连接超时)' }
46
+ } catch {
47
+ return @{ ok = $false; code = 0; error = $_.Exception.Message }
48
+ }
49
+ }
50
+ try {
51
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
52
+ $req = [System.Net.HttpWebRequest]::Create('https://github.com/')
53
+ $req.Method = 'HEAD'
54
+ $req.Timeout = 8000
55
+ $req.UserAgent = 'dsh-github-push'
56
+ $res = $req.GetResponse()
57
+ $code = [int]$res.StatusCode
58
+ $res.Close()
59
+ return @{ ok = ($code -ge 200 -and $code -lt 500); code = $code; error = '' }
60
+ } catch {
61
+ return @{ ok = $false; code = 0; error = $_.Exception.Message }
62
+ }
63
+ }
64
+
65
+ function Clear-Dns {
66
+ try { & "$env:SystemRoot\System32\ipconfig.exe" /flushdns 2>$null | Out-Null } catch { }
67
+ }
68
+
69
+ function Get-HostsBlockers {
70
+ if (-not (Test-Path $HostsPath)) { return @() }
71
+ $lines = [System.IO.File]::ReadAllLines($HostsPath)
72
+ $hits = New-Object System.Collections.ArrayList
73
+ for ($i = 0; $i -lt $lines.Length; $i++) {
74
+ $trim = $lines[$i].Trim()
75
+ if ($trim -eq '' -or $trim.StartsWith('#')) { continue }
76
+ if ($trim -match '^127\.0\.0\.1\s' -and $trim -match 'github') { [void]$hits.Add($i) }
77
+ }
78
+ return @($hits)
79
+ }
80
+
81
+ function Set-HostsLines([string[]]$Lines) {
82
+ [System.IO.File]::WriteAllLines($HostsPath, $Lines, (New-Object System.Text.UTF8Encoding($false)))
83
+ }
84
+
85
+ function Restore-Hosts {
86
+ if (-not $script:changed) { return }
87
+ if ($KeepChanges) {
88
+ Write-Host ' hosts 保持改动(Steam++ 的屏蔽行仍被注释,GitHub 走裸连)。'
89
+ } else {
90
+ try {
91
+ Set-HostsLines $script:original
92
+ Clear-Dns
93
+ Write-Host ' hosts 已还原成原样。'
94
+ $script:restored = $true
95
+ } catch {
96
+ Write-Host (" hosts 还原失败,请手动检查:{0}" -f $_.Exception.Message)
97
+ }
98
+ }
99
+ $script:changed = $false
100
+ }
101
+
102
+ try {
103
+ Write-Host '[1/4] 测试 https://github.com ...'
104
+ $probe = Test-GitHub
105
+ if ($probe.ok) {
106
+ Write-Host (" OK(HTTP {0})" -f $probe.code)
107
+ } else {
108
+ Write-Host (" 连不上:{0}" -f $probe.error)
109
+ $blockers = Get-HostsBlockers
110
+ if ($blockers.Count -eq 0) {
111
+ Write-Host ' hosts 里没有 127.0.0.1 的 github 行,问题不在 hosts(可能是代理 / 网络)。'
112
+ Write-Host ' 建议:打开 Steam++ → 网络加速 → 勾 GitHub → 一键加速,并保持它运行。'
113
+ if (-not $DryRun) { exit 2 }
114
+ } else {
115
+ Write-Host (" 发现 {0} 行本机重定向(Steam++ 加速表),临时注释后重试 ..." -f $blockers.Count)
116
+ $script:original = @([System.IO.File]::ReadAllLines($HostsPath))
117
+ $lines = @($script:original)
118
+ foreach ($i in $blockers) { $lines[$i] = $Marker + $lines[$i] }
119
+ Set-HostsLines $lines
120
+ $script:changed = $true
121
+ Clear-Dns
122
+ $probe = Test-GitHub
123
+ if ($probe.ok) {
124
+ Write-Host (" OK(HTTP {0})" -f $probe.code)
125
+ } else {
126
+ Write-Host (" 仍然连不上:{0}" -f $probe.error)
127
+ Write-Host ' 建议:打开 Steam++ → 网络加速 → 勾 GitHub → 一键加速,保持运行后重试。'
128
+ Restore-Hosts
129
+ if (-not $DryRun) { exit 2 }
130
+ }
131
+ }
132
+ }
133
+
134
+ Write-Host '[2/4] 检查仓库状态 ...'
135
+ Push-Location $RepoRoot
136
+ try {
137
+ $status = git status --porcelain
138
+ if ($status) {
139
+ Write-Host ' 工作树有未提交的改动(脚本不会替你提交):'
140
+ $status | ForEach-Object { Write-Host " $_" }
141
+ }
142
+ $ahead = (git rev-list --count "origin/$Branch..HEAD" 2>$null | Out-String).Trim()
143
+ Write-Host (" 待推送提交:{0} 个" -f $ahead)
144
+
145
+ Write-Host '[3/4] 推送 ...'
146
+ if ($DryRun) {
147
+ Write-Host ' -DryRun:跳过实际推送。'
148
+ } elseif ($ahead -eq '0') {
149
+ Write-Host ' 没有需要推送的提交。'
150
+ } elseif (-not $Token) {
151
+ Write-Host ' 没给令牌:请加 -Token ghp_xxx,或先设置环境变量 GITHUB_TOKEN。'
152
+ Write-Host ' 令牌在 https://github.com/settings/tokens/new 生成(勾 repo;要改 .github/workflows 还要勾 workflow)。'
153
+ } else {
154
+ $basic = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("x-access-token:$Token"))
155
+ & git -c credential.helper= -c "http.https://github.com/.extraHeader=Authorization: Basic $basic" push $Remote $Branch
156
+ if ($LASTEXITCODE -ne 0) { throw "git push 失败(退出码 $LASTEXITCODE)" }
157
+ Write-Host ' 推送完成。记得去 https://github.com/settings/tokens 删掉这个临时令牌。'
158
+ }
159
+ } finally {
160
+ Pop-Location
161
+ }
162
+ } catch {
163
+ Write-Host ("出错:{0}" -f $_.Exception.Message)
164
+ exit 1
165
+ } finally {
166
+ Write-Host '[4/4] 收尾 ...'
167
+ $wasChanged = $script:changed
168
+ Restore-Hosts
169
+ if (-not $wasChanged) { Write-Host ' hosts 未改动。' }
170
+ }