@leiyi-works/dsh-auto-restart 0.1.8 → 0.2.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 +11 -3
- package/client.js +8 -0
- package/index.js +162 -0
- package/lib/install-watchdog.cmd +13 -0
- package/lib/install-watchdog.ps1 +105 -0
- package/lib/watchdog.ps1 +181 -0
- package/lib/watchdog.vbs +13 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -21,10 +21,18 @@
|
|
|
21
21
|
1. 等所有会话空闲(`api-session/status` + `agent/status`),**一直等、没有上限**;
|
|
22
22
|
2. 最后一次会话活动(发消息、回合开始/结束)之后再安静 10 秒,避免刚发出、回合还没起来的消息被重启吞掉、文字回到输入框;
|
|
23
23
|
3. 等插件管理器安静 3 秒(不打断进行中的安装/更新);
|
|
24
|
-
4.
|
|
25
|
-
5.
|
|
24
|
+
4. **优先交给常驻后台看门狗**:看门狗只在登录 Windows 时由「启动文件夹」里的引线自动启动,插件把请求写进 `~/.dsh/dsh-auto-restart/watchdog-request.json`,由它先杀 Electron 主进程、清残留、拉起应用并最大化——**不碰 WMI,也不会触发安全软件的 WMI 提示**;
|
|
25
|
+
5. 看门狗没在跑时(未安装/被关掉)才退回 WMI 守护进程:写一个隐藏窗口的快捷方式,交给 explorer.exe 启动守护进程(脱离 DSH 的 job object),由它完成同样的「先杀主进程 → 清残留 → 拉起 → 最大化」。
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
### 后台看门狗(零弹窗模式)
|
|
28
|
+
|
|
29
|
+
首次启动时插件会检测:没装就自动弹一个**中文控制台窗口**,说明用途并等你按回车安装。安装做三件事:把脚本拷到 `~/.dsh/dsh-auto-restart/`、在启动文件夹写一个隐藏引线、立刻启动看门狗。之后每次登录 Windows 它自动起来,所有自动重启都不再经过 WMI。
|
|
30
|
+
|
|
31
|
+
- 面板里只显示看门狗状态(运行中/未安装/已安装无心跳),**没有安装/卸载按钮**;
|
|
32
|
+
- 卸载:在 `~/.dsh/dsh-auto-restart/` 里执行 `powershell -File install-watchdog.ps1 -Uninstall`;
|
|
33
|
+
- 看门狗日志:`~/.dsh/dsh-auto-restart/watchdog.log`。
|
|
34
|
+
|
|
35
|
+
> 少数安全软件(如 360)对「PowerShell 操作 WMI」有行为规则:装了看门狗后重启不走 WMI,就不会再因此弹窗;安装看门狗那一次仍可能被提示一次,允许即可。
|
|
28
36
|
|
|
29
37
|
会话记录在磁盘上,重启后回到同一个会话。**没有每小时次数上限**,只有 60 秒冷却防止连环重启。
|
|
30
38
|
|
package/client.js
CHANGED
|
@@ -285,6 +285,14 @@ window.__ModuleLoader__.load({
|
|
|
285
285
|
h('span', { style: styles.val }, (status.busySessions ?? []).length === 0 ? '空闲' : `${status.busySessions.length} 个在跑`),
|
|
286
286
|
h('span', { style: styles.key }, '插件基线'),
|
|
287
287
|
h('span', { style: styles.val }, `${status.baseline ?? '—'} / 当前 ${status.current ?? '—'}`),
|
|
288
|
+
h('span', { style: styles.key }, '后台看门狗'),
|
|
289
|
+
h('span', { style: styles.val }, status.watchdog === undefined
|
|
290
|
+
? '—'
|
|
291
|
+
: status.watchdog.alive === true
|
|
292
|
+
? `运行中(pid=${status.watchdog.heartbeat?.pid ?? '?'})`
|
|
293
|
+
: status.watchdog.installed === true
|
|
294
|
+
? '已安装但当前没有心跳(重启会用 WMI 兜底)'
|
|
295
|
+
: '未安装(DSH 启动时会弹安装窗口;未安装时重启走 WMI,可能触发安全软件提示)'),
|
|
288
296
|
h('span', { style: styles.key }, '日志'),
|
|
289
297
|
h('span', { style: styles.val }, status.logPath ?? '—'),
|
|
290
298
|
status.disabled
|
package/index.js
CHANGED
|
@@ -26,6 +26,7 @@ import { createHash } from 'node:crypto'
|
|
|
26
26
|
import { spawn } from 'node:child_process'
|
|
27
27
|
import {
|
|
28
28
|
appendFileSync,
|
|
29
|
+
copyFileSync,
|
|
29
30
|
existsSync,
|
|
30
31
|
mkdirSync,
|
|
31
32
|
readFileSync,
|
|
@@ -138,6 +139,137 @@ function disabledPath() {
|
|
|
138
139
|
return join(dataDir(), 'disabled')
|
|
139
140
|
}
|
|
140
141
|
|
|
142
|
+
/** Resident watchdog files (installed into the data dir so updates keep them). */
|
|
143
|
+
function watchdogHeartbeatPath() {
|
|
144
|
+
return join(dataDir(), 'watchdog-heartbeat.json')
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function watchdogRequestPath() {
|
|
148
|
+
return join(dataDir(), 'watchdog-request.json')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function watchdogVbsPath() {
|
|
152
|
+
return join(dataDir(), 'watchdog.vbs')
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function watchdogInstallerPath() {
|
|
156
|
+
return join(dataDir(), 'install-watchdog.cmd')
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function watchdogLogPath() {
|
|
160
|
+
return join(dataDir(), 'watchdog.log')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function startupEntryPath() {
|
|
164
|
+
const appData = process.env.APPDATA
|
|
165
|
+
if (typeof appData !== 'string' || appData.trim() === '') return ''
|
|
166
|
+
return join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'dsh-auto-restart-watchdog.vbs')
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Copy the watchdog helper files next to the runtime state (idempotent). */
|
|
170
|
+
function ensureWatchdogFiles() {
|
|
171
|
+
const names = ['watchdog.ps1', 'watchdog.vbs', 'install-watchdog.cmd', 'install-watchdog.ps1']
|
|
172
|
+
try {
|
|
173
|
+
mkdirSync(dataDir(), { recursive: true })
|
|
174
|
+
} catch {
|
|
175
|
+
return
|
|
176
|
+
}
|
|
177
|
+
for (const file of names) {
|
|
178
|
+
const source = join(PKG_DIR, 'lib', file)
|
|
179
|
+
const target = join(dataDir(), file)
|
|
180
|
+
try {
|
|
181
|
+
if (!existsSync(source)) continue
|
|
182
|
+
copyFileSync(source, target)
|
|
183
|
+
} catch (error) {
|
|
184
|
+
logLine('warn', `同步看门狗文件失败 ${file}: ${String(error?.message ?? error)}`)
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** The watchdog's heartbeat, when it is fresh enough to be trusted. */
|
|
190
|
+
function readWatchdogHeartbeat() {
|
|
191
|
+
const parsed = readJsonFile(watchdogHeartbeatPath())
|
|
192
|
+
if (parsed === null || typeof parsed !== 'object') return null
|
|
193
|
+
const at = typeof parsed.at === 'string' ? Date.parse(parsed.at) : Number.NaN
|
|
194
|
+
if (!Number.isFinite(at)) return null
|
|
195
|
+
const ageMs = Date.now() - at
|
|
196
|
+
if (ageMs < 0 || ageMs > 20000) return null
|
|
197
|
+
return { pid: Number(parsed.pid) || 0, at: new Date(at).toISOString(), ageMs }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function watchdogAlive() {
|
|
201
|
+
return readWatchdogHeartbeat() !== null
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function watchdogInstalled() {
|
|
205
|
+
const entry = startupEntryPath()
|
|
206
|
+
return entry !== '' && existsSync(entry)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* True only for the real user home. Tests and throwaway harnesses point DSH_HOME
|
|
211
|
+
* at a temp directory; opening a real console installer from there would be a
|
|
212
|
+
* surprise, so the offer is limited to the actual desktop user.
|
|
213
|
+
*/
|
|
214
|
+
function isRealUserHome() {
|
|
215
|
+
try {
|
|
216
|
+
return resolve(dshHome()) === resolve(join(homedir(), '.dsh'))
|
|
217
|
+
} catch {
|
|
218
|
+
return false
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Ask the resident watchdog to perform the restart; it survives our death. */
|
|
223
|
+
function dispatchToWatchdog(state, cfg, reason) {
|
|
224
|
+
const exe = resolveExe(cfg)
|
|
225
|
+
const request = {
|
|
226
|
+
id: `${Date.now()}-${process.pid}`,
|
|
227
|
+
exe,
|
|
228
|
+
rootPid: process.ppid,
|
|
229
|
+
hostPid: process.pid,
|
|
230
|
+
delayMs: Math.max(0, Number(cfg.restartDelayMs) || 0),
|
|
231
|
+
maximize: cfg.maximizeOnRestart !== false,
|
|
232
|
+
launchArgs: Array.isArray(cfg.launchArgs) ? cfg.launchArgs : [],
|
|
233
|
+
reason,
|
|
234
|
+
requestedAt: new Date().toISOString(),
|
|
235
|
+
}
|
|
236
|
+
try {
|
|
237
|
+
writeJsonAtomic(watchdogRequestPath(), request)
|
|
238
|
+
} catch (error) {
|
|
239
|
+
logLine('error', `写入看门狗请求失败:${String(error?.message ?? error)}`)
|
|
240
|
+
return { ok: false, error: '写入看门狗请求失败' }
|
|
241
|
+
}
|
|
242
|
+
const now = Date.now()
|
|
243
|
+
state.lastRestartAt = now
|
|
244
|
+
state.dispatchedAt = now
|
|
245
|
+
state.dispatchedDelay = request.delayMs
|
|
246
|
+
state.restarts = [...state.restarts.filter((t) => now - t < 3600000), now]
|
|
247
|
+
state.lastReason = reason
|
|
248
|
+
saveState(state)
|
|
249
|
+
settled(state)
|
|
250
|
+
logLine('warn', `已交给后台看门狗重启:${reason};exe=${exe} delay=${request.delayMs}ms maximize=${request.maximize}`)
|
|
251
|
+
return { ok: true, dryRun: false, via: 'watchdog', delayMs: request.delayMs }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Open the one-time console installer through explorer (outside DSH's process tree). */
|
|
255
|
+
function offerWatchdogInstall() {
|
|
256
|
+
const installer = watchdogInstallerPath()
|
|
257
|
+
if (!existsSync(installer)) {
|
|
258
|
+
logLine('warn', `安装脚本不存在:${installer}`)
|
|
259
|
+
return false
|
|
260
|
+
}
|
|
261
|
+
try {
|
|
262
|
+
const child = spawn('explorer.exe', [installer], { windowsHide: true, stdio: 'ignore' })
|
|
263
|
+
child.on('error', (error) => logLine('warn', `打开看门狗安装窗口失败:${String(error?.message ?? error)}`))
|
|
264
|
+
child.unref?.()
|
|
265
|
+
logLine('info', '未检测到后台看门狗:已打开安装窗口(在窗口里按回车安装)')
|
|
266
|
+
return true
|
|
267
|
+
} catch (error) {
|
|
268
|
+
logLine('warn', `打开看门狗安装窗口失败:${String(error?.message ?? error)}`)
|
|
269
|
+
return false
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
141
273
|
/** Expand a leading `~` so a portable config can store the home shorthand. */
|
|
142
274
|
function expandHome(value) {
|
|
143
275
|
if (typeof value !== 'string' || value === '') return value
|
|
@@ -435,6 +567,12 @@ function dispatchRestart(state, cfg, reason, options = {}) {
|
|
|
435
567
|
abortPending(state, `应用可执行文件不存在:${exe}`)
|
|
436
568
|
return { ok: false, error: `应用可执行文件不存在:${exe}` }
|
|
437
569
|
}
|
|
570
|
+
|
|
571
|
+
// Preferred path: a resident watchdog started outside DSH's process tree; it
|
|
572
|
+
// performs the restart without any WMI call. Falls back to the WMI launcher
|
|
573
|
+
// when the watchdog is not running.
|
|
574
|
+
if (watchdogAlive()) return dispatchToWatchdog(state, cfg, reason)
|
|
575
|
+
|
|
438
576
|
const delay = Math.max(0, Number(cfg.restartDelayMs) || 0)
|
|
439
577
|
const supervisor = expandHome(cfg.supervisorScript) || join(PKG_DIR, 'lib', 'restart-supervisor.ps1')
|
|
440
578
|
const launcher = join(PKG_DIR, 'lib', 'launch-supervisor.ps1')
|
|
@@ -537,6 +675,7 @@ function createState(profileDir) {
|
|
|
537
675
|
busy: new Set(),
|
|
538
676
|
lastReason: '',
|
|
539
677
|
lastSkipLog: 0,
|
|
678
|
+
installerOffered: false,
|
|
540
679
|
}
|
|
541
680
|
}
|
|
542
681
|
|
|
@@ -699,6 +838,13 @@ function installRoutes(ctx, baseConfig) {
|
|
|
699
838
|
enabled: cfg.enabled,
|
|
700
839
|
dryRun: cfg.dryRun,
|
|
701
840
|
maximizeOnRestart: cfg.maximizeOnRestart,
|
|
841
|
+
watchdog: {
|
|
842
|
+
alive: watchdogAlive(),
|
|
843
|
+
heartbeat: readWatchdogHeartbeat(),
|
|
844
|
+
installed: watchdogInstalled(),
|
|
845
|
+
startupEntry: startupEntryPath(),
|
|
846
|
+
logPath: watchdogLogPath(),
|
|
847
|
+
},
|
|
702
848
|
waitForIdle: cfg.waitForIdle,
|
|
703
849
|
busySessions: state ? [...state.busy] : [],
|
|
704
850
|
pending: state ? state.pendingSince > 0 : false,
|
|
@@ -800,6 +946,22 @@ export function apply(ctx, config) {
|
|
|
800
946
|
|
|
801
947
|
logLine('info', `${MARK} ${VERSION} 已加载:profile=${profileDir} dryRun=${cfg.dryRun} cooldown=${cfg.cooldownMs}ms cap=${cfg.maxPerHour === 0 ? '无' : cfg.maxPerHour + '/h'} maximize=${cfg.maximizeOnRestart} desktop=${isDesktopHost()}`)
|
|
802
948
|
|
|
949
|
+
// Resident watchdog: keep its files current; when it is missing, offer the
|
|
950
|
+
// one-time console installer (at most once per boot, and only when the
|
|
951
|
+
// Startup entry is absent).
|
|
952
|
+
ensureWatchdogFiles()
|
|
953
|
+
const heartbeat = readWatchdogHeartbeat()
|
|
954
|
+
if (heartbeat !== null) {
|
|
955
|
+
logLine('info', `后台看门狗运行中:pid=${heartbeat.pid} 心跳=${heartbeat.at}`)
|
|
956
|
+
} else if (!watchdogInstalled()) {
|
|
957
|
+
if (state.installerOffered === false && isRealUserHome() && isDesktopHost()) {
|
|
958
|
+
state.installerOffered = true
|
|
959
|
+
offerWatchdogInstall()
|
|
960
|
+
}
|
|
961
|
+
} else {
|
|
962
|
+
logLine('warn', '后台看门狗已安装但当前没有心跳(可能刚登录还没起来),本次重启会用 WMI 兜底')
|
|
963
|
+
}
|
|
964
|
+
|
|
803
965
|
// Track busy sessions so a restart never cuts an answer.
|
|
804
966
|
ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
|
|
805
967
|
const id = String(sessionId)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
@echo off
|
|
2
|
+
rem Opens the dsh-auto-restart watchdog installer in a visible console window.
|
|
3
|
+
rem ASCII only; the PowerShell script it calls holds the Chinese explanation.
|
|
4
|
+
setlocal
|
|
5
|
+
set "PS1=%~dp0install-watchdog.ps1"
|
|
6
|
+
if not exist "%PS1%" (
|
|
7
|
+
echo installer script missing: %PS1%
|
|
8
|
+
pause
|
|
9
|
+
exit /b 2
|
|
10
|
+
)
|
|
11
|
+
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%PS1%" %*
|
|
12
|
+
echo.
|
|
13
|
+
pause
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[switch]$Uninstall
|
|
3
|
+
)
|
|
4
|
+
|
|
5
|
+
# Console installer for the dsh-auto-restart watchdog. Run by the user (the plugin
|
|
6
|
+
# opens this window through explorer, so the watchdog it starts is created outside
|
|
7
|
+
# DSH's process tree and survives the restart it performs).
|
|
8
|
+
# This file is written as UTF-8 with BOM so Windows PowerShell 5.1 shows the
|
|
9
|
+
# Chinese text correctly.
|
|
10
|
+
|
|
11
|
+
$ErrorActionPreference = 'Stop'
|
|
12
|
+
$DataDir = Join-Path $env:USERPROFILE '.dsh\dsh-auto-restart'
|
|
13
|
+
$StartupDir = Join-Path $env:APPDATA 'Microsoft\Windows\Start Menu\Programs\Startup'
|
|
14
|
+
$StartupFile = Join-Path $StartupDir 'dsh-auto-restart-watchdog.vbs'
|
|
15
|
+
$WatchdogVbs = Join-Path $DataDir 'watchdog.vbs'
|
|
16
|
+
$Heartbeat = Join-Path $DataDir 'watchdog-heartbeat.json'
|
|
17
|
+
$StopFile = Join-Path $DataDir 'watchdog.stop'
|
|
18
|
+
|
|
19
|
+
function Write-Utf8NoBom([string]$Path, [string]$Text) {
|
|
20
|
+
[System.IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.UTF8Encoding($false)))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function Test-Heartbeat([int]$Seconds) {
|
|
24
|
+
$deadline = (Get-Date).AddSeconds($Seconds)
|
|
25
|
+
while ((Get-Date) -lt $deadline) {
|
|
26
|
+
if (Test-Path -LiteralPath $Heartbeat) {
|
|
27
|
+
try {
|
|
28
|
+
$beat = Get-Content -LiteralPath $Heartbeat -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
29
|
+
$at = [datetime]::Parse([string]$beat.at)
|
|
30
|
+
if (((Get-Date) - $at).TotalSeconds -lt 15) { return $true }
|
|
31
|
+
} catch {}
|
|
32
|
+
}
|
|
33
|
+
Start-Sleep -Milliseconds 500
|
|
34
|
+
}
|
|
35
|
+
return $false
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if ($Uninstall) {
|
|
39
|
+
if (Test-Path -LiteralPath $StartupFile) { Remove-Item -LiteralPath $StartupFile -Force -ErrorAction SilentlyContinue }
|
|
40
|
+
Write-Utf8NoBom $StopFile 'stop'
|
|
41
|
+
Write-Host ''
|
|
42
|
+
Write-Host ' dsh-auto-restart:后台看门狗已卸载。' -ForegroundColor Yellow
|
|
43
|
+
Write-Host ' 以后自动重启会退回 WMI 方式(安全软件可能偶尔提示)。' -ForegroundColor Yellow
|
|
44
|
+
Write-Host ''
|
|
45
|
+
exit 0
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
Write-Host ''
|
|
49
|
+
Write-Host ' ================================================================' -ForegroundColor Cyan
|
|
50
|
+
Write-Host ' dsh-auto-restart:安装后台看门狗(一次性)' -ForegroundColor Cyan
|
|
51
|
+
Write-Host ' ================================================================' -ForegroundColor Cyan
|
|
52
|
+
Write-Host ''
|
|
53
|
+
Write-Host ' 为什么需要它:' -ForegroundColor White
|
|
54
|
+
Write-Host ' 自动重启要让 DSH 先退出再打开。现在的方式是每次用 PowerShell 去调' -ForegroundColor Gray
|
|
55
|
+
Write-Host ' WMI 启动一个临时进程,安全软件(360)会把它当成可疑行为,偶尔弹窗、' -ForegroundColor Gray
|
|
56
|
+
Write-Host ' 甚至在没人看着时直接拦掉。' -ForegroundColor Gray
|
|
57
|
+
Write-Host ''
|
|
58
|
+
Write-Host ' 装了这个看门狗之后:' -ForegroundColor White
|
|
59
|
+
Write-Host ' · 一个隐藏的小进程常驻后台,等 DSH 发出的“请重启”请求;' -ForegroundColor Gray
|
|
60
|
+
Write-Host ' · 每次自动重启都不再碰 WMI,360 不会再因为重启弹窗;' -ForegroundColor Gray
|
|
61
|
+
Write-Host ' · 它会在每次登录 Windows 时自动启动(写在启动文件夹里)。' -ForegroundColor Gray
|
|
62
|
+
Write-Host ''
|
|
63
|
+
Write-Host ' 本次操作会:' -ForegroundColor White
|
|
64
|
+
Write-Host ' 1) 把启动引线写入:' -ForegroundColor Gray
|
|
65
|
+
Write-Host (' ' + $StartupFile) -ForegroundColor DarkGray
|
|
66
|
+
Write-Host ' 2) 立即启动看门狗(隐藏窗口,不占屏幕)。' -ForegroundColor Gray
|
|
67
|
+
Write-Host ''
|
|
68
|
+
Write-Host ' 想卸载:以后在同一个窗口里跑一次本脚本加 -Uninstall 即可。' -ForegroundColor DarkGray
|
|
69
|
+
Write-Host ''
|
|
70
|
+
|
|
71
|
+
[void](Read-Host ' 按回车安装(直接关窗口 = 取消)')
|
|
72
|
+
|
|
73
|
+
$installed = $false
|
|
74
|
+
$errorText = ''
|
|
75
|
+
try {
|
|
76
|
+
if (-not (Test-Path -LiteralPath $WatchdogVbs)) { throw ('看门狗脚本不存在:' + $WatchdogVbs + '(先启动一次 DSH,让插件把文件放好)') }
|
|
77
|
+
if (-not (Test-Path -LiteralPath $StartupDir)) { New-Item -ItemType Directory -Force -Path $StartupDir | Out-Null }
|
|
78
|
+
$vbs = @(
|
|
79
|
+
''' dsh-auto-restart watchdog autostart (created by the plugin installer)',
|
|
80
|
+
'Option Explicit',
|
|
81
|
+
'Dim shell',
|
|
82
|
+
'Set shell = CreateObject("WScript.Shell")',
|
|
83
|
+
('shell.Run "wscript.exe //B ""' + $WatchdogVbs + '""", 0, False')
|
|
84
|
+
) -join "`r`n"
|
|
85
|
+
Write-Utf8NoBom $StartupFile $vbs
|
|
86
|
+
if (Test-Path -LiteralPath $StopFile) { Remove-Item -LiteralPath $StopFile -Force -ErrorAction SilentlyContinue }
|
|
87
|
+
Start-Process -FilePath 'wscript.exe' -ArgumentList ('//B "' + $WatchdogVbs + '"') | Out-Null
|
|
88
|
+
$installed = Test-Heartbeat 15
|
|
89
|
+
if (-not $installed) { throw '看门狗已启动但 15 秒内没有心跳,请把窗口内容发给助手。' }
|
|
90
|
+
} catch {
|
|
91
|
+
$errorText = $_.Exception.Message
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
Write-Host ''
|
|
95
|
+
if ($installed) {
|
|
96
|
+
Write-Host ' 安装完成:后台看门狗已在运行,并已加入登录自启。' -ForegroundColor Green
|
|
97
|
+
Write-Host ' 以后自动重启不会再触发安全软件的 WMI 提示。' -ForegroundColor Green
|
|
98
|
+
Write-Host ''
|
|
99
|
+
Write-Host ' 这个窗口可以直接关掉了。' -ForegroundColor Gray
|
|
100
|
+
} else {
|
|
101
|
+
Write-Host (' 安装失败:' + $errorText) -ForegroundColor Red
|
|
102
|
+
Write-Host ' 可以把这个窗口截图发给助手排查。' -ForegroundColor Red
|
|
103
|
+
}
|
|
104
|
+
Write-Host ''
|
|
105
|
+
[void](Read-Host ' 按回车关闭窗口')
|
package/lib/watchdog.ps1
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[string]$DataDir = ''
|
|
3
|
+
)
|
|
4
|
+
|
|
5
|
+
# dsh-auto-restart watchdog: a resident helper that performs restarts without
|
|
6
|
+
# WMI: it polls request.json, kills the desktop app, relaunches it and maximizes
|
|
7
|
+
# the window. Started at Windows logon from the Startup folder (see
|
|
8
|
+
# install-watchdog.ps1), so it lives outside DSH's process tree and survives the
|
|
9
|
+
# restart it performs. ASCII only: PowerShell 5.1 misreads BOM-less non-ASCII.
|
|
10
|
+
|
|
11
|
+
$ErrorActionPreference = 'Stop'
|
|
12
|
+
if ([string]::IsNullOrWhiteSpace($DataDir)) {
|
|
13
|
+
$DataDir = Join-Path $env:USERPROFILE '.dsh\dsh-auto-restart'
|
|
14
|
+
}
|
|
15
|
+
$LogPath = Join-Path $DataDir 'watchdog.log'
|
|
16
|
+
$HeartbeatPath = Join-Path $DataDir 'watchdog-heartbeat.json'
|
|
17
|
+
$RequestPath = Join-Path $DataDir 'watchdog-request.json'
|
|
18
|
+
$ResultPath = Join-Path $DataDir 'restart-result.json'
|
|
19
|
+
$StopPath = Join-Path $DataDir 'watchdog.stop'
|
|
20
|
+
|
|
21
|
+
function Write-Log([string]$Message) {
|
|
22
|
+
try {
|
|
23
|
+
$line = (Get-Date).ToString('o') + ' [watchdog] ' + $Message + [Environment]::NewLine
|
|
24
|
+
[System.IO.File]::AppendAllText($LogPath, $line, (New-Object System.Text.UTF8Encoding($false)))
|
|
25
|
+
} catch {}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function Wait-ProcessGone([int]$ProcessId, [int]$TimeoutMs) {
|
|
29
|
+
$deadline = (Get-Date).AddMilliseconds($TimeoutMs)
|
|
30
|
+
while ((Get-Date) -lt $deadline) {
|
|
31
|
+
if (-not (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue)) { return $true }
|
|
32
|
+
Start-Sleep -Milliseconds 200
|
|
33
|
+
}
|
|
34
|
+
return $false
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function Get-ProcessById([int]$ProcessId) {
|
|
38
|
+
try { return Get-CimInstance Win32_Process -Filter ('ProcessId=' + $ProcessId) -ErrorAction Stop } catch { return $null }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function Find-RootProcess([string]$Exe, [int]$RootPid) {
|
|
42
|
+
$exeName = [System.IO.Path]::GetFileNameWithoutExtension($Exe)
|
|
43
|
+
$candidate = Get-ProcessById $RootPid
|
|
44
|
+
if ($candidate -ne $null) {
|
|
45
|
+
$image = [string]$candidate.ExecutablePath
|
|
46
|
+
if ($image -ne '') {
|
|
47
|
+
try {
|
|
48
|
+
if ([System.IO.Path]::GetFullPath($image).ToLowerInvariant() -eq [System.IO.Path]::GetFullPath($Exe).ToLowerInvariant()) { return $candidate }
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
$all = @(Get-CimInstance Win32_Process -Filter ('Name="' + $exeName + '.exe"') -ErrorAction SilentlyContinue)
|
|
53
|
+
if ($all.Count -eq 0) { return $null }
|
|
54
|
+
$oldest = $all[0]
|
|
55
|
+
foreach ($item in $all) {
|
|
56
|
+
try { if ($item.CreationDate -lt $oldest.CreationDate) { $oldest = $item } } catch {}
|
|
57
|
+
}
|
|
58
|
+
return $oldest
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function Set-WindowMaximized([IntPtr]$Handle) {
|
|
62
|
+
if ($Handle -eq [IntPtr]::Zero) { return $false }
|
|
63
|
+
try {
|
|
64
|
+
if (-not ('DshWatchdogWin32' -as [type])) {
|
|
65
|
+
Add-Type -TypeDefinition @"
|
|
66
|
+
using System;
|
|
67
|
+
using System.Runtime.InteropServices;
|
|
68
|
+
public static class DshWatchdogWin32 {
|
|
69
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
70
|
+
}
|
|
71
|
+
"@ -ErrorAction Stop
|
|
72
|
+
}
|
|
73
|
+
[void][DshWatchdogWin32]::ShowWindow($Handle, 3)
|
|
74
|
+
return $true
|
|
75
|
+
} catch {
|
|
76
|
+
Write-Log ('maximize failed: ' + $_.Exception.Message)
|
|
77
|
+
return $false
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function Invoke-Restart([string]$RequestFile) {
|
|
82
|
+
$spec = $null
|
|
83
|
+
try { $spec = Get-Content -LiteralPath $RequestFile -Raw -Encoding UTF8 | ConvertFrom-Json } catch { Write-Log ('request unreadable: ' + $_.Exception.Message); return }
|
|
84
|
+
$exe = [string]$spec.exe
|
|
85
|
+
if (-not (Test-Path -LiteralPath $exe)) { Write-Log 'aborting: exe missing'; return }
|
|
86
|
+
$delay = 0
|
|
87
|
+
try { $delay = [int]$spec.delayMs } catch {}
|
|
88
|
+
if ($delay -lt 0) { $delay = 0 }
|
|
89
|
+
Write-Log ('request ' + [string]$spec.id + ': exe=' + $exe + ' root=' + [string]$spec.rootPid + ' delay=' + $delay + 'ms')
|
|
90
|
+
Start-Sleep -Milliseconds $delay
|
|
91
|
+
|
|
92
|
+
$root = Find-RootProcess $exe ([int]$spec.rootPid)
|
|
93
|
+
if ($root -eq $null) { Write-Log 'aborting: app not running'; Write-Result 'aborted' 'app not running'; return }
|
|
94
|
+
Write-Log ('killing root pid=' + $root.ProcessId)
|
|
95
|
+
Stop-Process -Id ([int]$root.ProcessId) -Force -ErrorAction SilentlyContinue
|
|
96
|
+
[void](Wait-ProcessGone ([int]$root.ProcessId) 15000)
|
|
97
|
+
$exeName = [System.IO.Path]::GetFileNameWithoutExtension($exe)
|
|
98
|
+
$left = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
99
|
+
foreach ($proc in $left) { Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue }
|
|
100
|
+
$deadline = (Get-Date).AddSeconds(15)
|
|
101
|
+
while ((Get-Date) -lt $deadline) {
|
|
102
|
+
if (@(Get-Process -Name $exeName -ErrorAction SilentlyContinue).Count -eq 0) { break }
|
|
103
|
+
Start-Sleep -Milliseconds 250
|
|
104
|
+
}
|
|
105
|
+
$remaining = @(Get-Process -Name $exeName -ErrorAction SilentlyContinue)
|
|
106
|
+
if ($remaining.Count -gt 0) {
|
|
107
|
+
& taskkill.exe /F /IM ($exeName + '.exe') 2>$null | Out-Null
|
|
108
|
+
Start-Sleep -Milliseconds 800
|
|
109
|
+
}
|
|
110
|
+
Write-Log 'app stopped; relaunching'
|
|
111
|
+
$startArgs = @{ FilePath = $exe; WorkingDirectory = (Split-Path -Parent $exe); PassThru = $true }
|
|
112
|
+
$launchArgs = @($spec.launchArgs)
|
|
113
|
+
if ($launchArgs.Count -gt 0) { $startArgs['ArgumentList'] = $launchArgs }
|
|
114
|
+
$started = Start-Process @startArgs
|
|
115
|
+
$newPid = [int]$started.Id
|
|
116
|
+
Write-Log ('relaunched pid=' + $newPid)
|
|
117
|
+
$windowUp = $false
|
|
118
|
+
$deadline = (Get-Date).AddSeconds(60)
|
|
119
|
+
while ((Get-Date) -lt $deadline) {
|
|
120
|
+
$alive = Get-Process -Id $newPid -ErrorAction SilentlyContinue
|
|
121
|
+
if ($alive -eq $null) { break }
|
|
122
|
+
if ($alive.MainWindowHandle -ne 0) { $windowUp = $true; break }
|
|
123
|
+
Start-Sleep -Milliseconds 500
|
|
124
|
+
}
|
|
125
|
+
$maximized = $false
|
|
126
|
+
if ($windowUp) {
|
|
127
|
+
if ([string]$spec.maximize -ne 'False') {
|
|
128
|
+
$current = Get-Process -Id $newPid -ErrorAction SilentlyContinue
|
|
129
|
+
if ($current -ne $null) { $maximized = Set-WindowMaximized $current.MainWindowHandle }
|
|
130
|
+
if ($maximized) {
|
|
131
|
+
Start-Sleep -Milliseconds 700
|
|
132
|
+
$again = Get-Process -Id $newPid -ErrorAction SilentlyContinue
|
|
133
|
+
if ($again -ne $null) { [void](Set-WindowMaximized $again.MainWindowHandle) }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
Write-Result 'relaunched' ('window up, pid=' + $newPid + $(if ($maximized) { ', maximized' } else { '' }))
|
|
137
|
+
Write-Log 'restart complete'
|
|
138
|
+
} else {
|
|
139
|
+
Write-Result 'relaunched-no-window' ('pid=' + $newPid)
|
|
140
|
+
Write-Log 'relaunched without a window'
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function Write-Result([string]$Phase, [string]$Detail) {
|
|
145
|
+
try {
|
|
146
|
+
$payload = '{"phase":"' + $Phase + '","detail":"' + ($Detail -replace '\\','\\\\' -replace '"','\"') + '","pid":' + $PID + ',"at":"' + (Get-Date).ToString('o') + '"}'
|
|
147
|
+
[System.IO.File]::WriteAllText($ResultPath, $payload, (New-Object System.Text.UTF8Encoding($false)))
|
|
148
|
+
} catch {}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
Write-Log ('watchdog started pid=' + $PID)
|
|
152
|
+
$handledId = ''
|
|
153
|
+
$lastHeartbeat = [datetime]::MinValue
|
|
154
|
+
while ($true) {
|
|
155
|
+
if (Test-Path -LiteralPath $StopPath) { Write-Log 'stop file found; exiting'; break }
|
|
156
|
+
$now = Get-Date
|
|
157
|
+
if (($now - $lastHeartbeat).TotalSeconds -ge 5) {
|
|
158
|
+
try {
|
|
159
|
+
$beat = '{"pid":' + $PID + ',"at":"' + $now.ToString('o') + '"}'
|
|
160
|
+
[System.IO.File]::WriteAllText($HeartbeatPath, $beat, (New-Object System.Text.UTF8Encoding($false)))
|
|
161
|
+
} catch {}
|
|
162
|
+
$lastHeartbeat = $now
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
if (Test-Path -LiteralPath $RequestPath) {
|
|
166
|
+
$raw = Get-Content -LiteralPath $RequestPath -Raw -Encoding UTF8
|
|
167
|
+
$req = $null
|
|
168
|
+
try { $req = $raw | ConvertFrom-Json } catch { $req = $null }
|
|
169
|
+
$id = if ($req -ne $null) { [string]$req.id } else { $raw.GetHashCode().ToString() }
|
|
170
|
+
if ($id -ne '' -and $id -ne $handledId) {
|
|
171
|
+
$handledId = $id
|
|
172
|
+
# Consume the request: keep a private copy so a reboot cannot replay it.
|
|
173
|
+
$current = Join-Path $DataDir 'watchdog-request.current.json'
|
|
174
|
+
try { [System.IO.File]::WriteAllText($current, $raw, (New-Object System.Text.UTF8Encoding($false))) } catch {}
|
|
175
|
+
try { Remove-Item -LiteralPath $RequestPath -Force -ErrorAction SilentlyContinue } catch {}
|
|
176
|
+
Invoke-Restart $current
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
} catch { Write-Log ('loop error: ' + $_.Exception.Message) }
|
|
180
|
+
Start-Sleep -Milliseconds 400
|
|
181
|
+
}
|
package/lib/watchdog.vbs
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
' Hidden launcher for the dsh-auto-restart watchdog: wscript is a GUI-subsystem
|
|
2
|
+
' process, so no console window is created and the watchdog never steals focus.
|
|
3
|
+
' ASCII only.
|
|
4
|
+
Option Explicit
|
|
5
|
+
Dim shell, fso, scriptDir, ps1
|
|
6
|
+
Set shell = CreateObject("WScript.Shell")
|
|
7
|
+
Set fso = CreateObject("Scripting.FileSystemObject")
|
|
8
|
+
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
|
|
9
|
+
ps1 = scriptDir & "\watchdog.ps1"
|
|
10
|
+
If Not fso.FileExists(ps1) Then
|
|
11
|
+
WScript.Quit 2
|
|
12
|
+
End If
|
|
13
|
+
shell.Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File """ & ps1 & """", 0, False
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-auto-restart",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"title": "自动重启",
|
|
6
|
-
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile
|
|
6
|
+
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",
|
|
7
7
|
"main": "index.js",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.js",
|
|
@@ -18,6 +18,8 @@
|
|
|
18
18
|
"client.js",
|
|
19
19
|
"cordis.patch.yml",
|
|
20
20
|
"lib/*.ps1",
|
|
21
|
+
"lib/*.vbs",
|
|
22
|
+
"lib/*.cmd",
|
|
21
23
|
"locale/*.json",
|
|
22
24
|
"icon.svg",
|
|
23
25
|
"README.md"
|