@leiyi-works/dsh-auto-restart 0.1.8 → 0.2.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/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. 写一个隐藏窗口的快捷方式,交给 **explorer.exe** 启动守护进程(它是 Explorer 的子进程,能脱离 DSH 的 job object 活下来;**全程不用 WMI**,避免安全软件弹「操作 WMI」);
25
- 5. 守护进程等 `restartDelayMs`(默认 2 秒)→ **先杀 Electron 主进程**(否则 Host 先退出会让主进程弹「DeepSeek Harness 无法使用」并响一声)→ 清掉残留应用进程 → `Start-Process` 拉起应用 → 等主窗口出现 → 按 `maximizeOnRestart` 把窗口最大化 → 写回执。
24
+ 4. **优先交给常驻后台看门狗**:看门狗只在登录 Windows 时由「启动文件夹」里的引线自动启动,插件把请求写进 `~/.dsh/dsh-auto-restart/watchdog-request.json`,由它先杀 Electron 主进程、清残留、拉起应用并最大化——**不碰 WMI,也不会触发安全软件的 WMI 提示**;
25
+ 5. 看门狗没在跑时(未安装/被关掉)才退回 WMI 守护进程:写一个隐藏窗口的快捷方式,交给 explorer.exe 启动守护进程(脱离 DSH 的 job object),由它完成同样的「先杀主进程 → 清残留 → 拉起 → 最大化」。
26
26
 
27
- > 少数安全软件(如 360 的「文件防护」)仍可能按进程树把重启瞬间其它会话写图片/文档的行为提示出来;把 DSH 安装目录和 `~/.dsh` 加入信任区即可。
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,124 @@ 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
+ /** Ask the resident watchdog to perform the restart; it survives our death. */
210
+ function dispatchToWatchdog(state, cfg, reason) {
211
+ const exe = resolveExe(cfg)
212
+ const request = {
213
+ id: `${Date.now()}-${process.pid}`,
214
+ exe,
215
+ rootPid: process.ppid,
216
+ hostPid: process.pid,
217
+ delayMs: Math.max(0, Number(cfg.restartDelayMs) || 0),
218
+ maximize: cfg.maximizeOnRestart !== false,
219
+ launchArgs: Array.isArray(cfg.launchArgs) ? cfg.launchArgs : [],
220
+ reason,
221
+ requestedAt: new Date().toISOString(),
222
+ }
223
+ try {
224
+ writeJsonAtomic(watchdogRequestPath(), request)
225
+ } catch (error) {
226
+ logLine('error', `写入看门狗请求失败:${String(error?.message ?? error)}`)
227
+ return { ok: false, error: '写入看门狗请求失败' }
228
+ }
229
+ const now = Date.now()
230
+ state.lastRestartAt = now
231
+ state.dispatchedAt = now
232
+ state.dispatchedDelay = request.delayMs
233
+ state.restarts = [...state.restarts.filter((t) => now - t < 3600000), now]
234
+ state.lastReason = reason
235
+ saveState(state)
236
+ settled(state)
237
+ logLine('warn', `已交给后台看门狗重启:${reason};exe=${exe} delay=${request.delayMs}ms maximize=${request.maximize}`)
238
+ return { ok: true, dryRun: false, via: 'watchdog', delayMs: request.delayMs }
239
+ }
240
+
241
+ /** Open the one-time console installer through explorer (outside DSH's process tree). */
242
+ function offerWatchdogInstall() {
243
+ const installer = watchdogInstallerPath()
244
+ if (!existsSync(installer)) {
245
+ logLine('warn', `安装脚本不存在:${installer}`)
246
+ return false
247
+ }
248
+ try {
249
+ const child = spawn('explorer.exe', [installer], { windowsHide: true, stdio: 'ignore' })
250
+ child.on('error', (error) => logLine('warn', `打开看门狗安装窗口失败:${String(error?.message ?? error)}`))
251
+ child.unref?.()
252
+ logLine('info', '未检测到后台看门狗:已打开安装窗口(在窗口里按回车安装)')
253
+ return true
254
+ } catch (error) {
255
+ logLine('warn', `打开看门狗安装窗口失败:${String(error?.message ?? error)}`)
256
+ return false
257
+ }
258
+ }
259
+
141
260
  /** Expand a leading `~` so a portable config can store the home shorthand. */
142
261
  function expandHome(value) {
143
262
  if (typeof value !== 'string' || value === '') return value
@@ -435,6 +554,12 @@ function dispatchRestart(state, cfg, reason, options = {}) {
435
554
  abortPending(state, `应用可执行文件不存在:${exe}`)
436
555
  return { ok: false, error: `应用可执行文件不存在:${exe}` }
437
556
  }
557
+
558
+ // Preferred path: a resident watchdog started outside DSH's process tree; it
559
+ // performs the restart without any WMI call. Falls back to the WMI launcher
560
+ // when the watchdog is not running.
561
+ if (watchdogAlive()) return dispatchToWatchdog(state, cfg, reason)
562
+
438
563
  const delay = Math.max(0, Number(cfg.restartDelayMs) || 0)
439
564
  const supervisor = expandHome(cfg.supervisorScript) || join(PKG_DIR, 'lib', 'restart-supervisor.ps1')
440
565
  const launcher = join(PKG_DIR, 'lib', 'launch-supervisor.ps1')
@@ -537,6 +662,7 @@ function createState(profileDir) {
537
662
  busy: new Set(),
538
663
  lastReason: '',
539
664
  lastSkipLog: 0,
665
+ installerOffered: false,
540
666
  }
541
667
  }
542
668
 
@@ -699,6 +825,13 @@ function installRoutes(ctx, baseConfig) {
699
825
  enabled: cfg.enabled,
700
826
  dryRun: cfg.dryRun,
701
827
  maximizeOnRestart: cfg.maximizeOnRestart,
828
+ watchdog: {
829
+ alive: watchdogAlive(),
830
+ heartbeat: readWatchdogHeartbeat(),
831
+ installed: watchdogInstalled(),
832
+ startupEntry: startupEntryPath(),
833
+ logPath: watchdogLogPath(),
834
+ },
702
835
  waitForIdle: cfg.waitForIdle,
703
836
  busySessions: state ? [...state.busy] : [],
704
837
  pending: state ? state.pendingSince > 0 : false,
@@ -800,6 +933,22 @@ export function apply(ctx, config) {
800
933
 
801
934
  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
935
 
936
+ // Resident watchdog: keep its files current; when it is missing, offer the
937
+ // one-time console installer (at most once per boot, and only when the
938
+ // Startup entry is absent).
939
+ ensureWatchdogFiles()
940
+ const heartbeat = readWatchdogHeartbeat()
941
+ if (heartbeat !== null) {
942
+ logLine('info', `后台看门狗运行中:pid=${heartbeat.pid} 心跳=${heartbeat.at}`)
943
+ } else if (!watchdogInstalled()) {
944
+ if (state.installerOffered === false) {
945
+ state.installerOffered = true
946
+ offerWatchdogInstall()
947
+ }
948
+ } else {
949
+ logLine('warn', '后台看门狗已安装但当前没有心跳(可能刚登录还没起来),本次重启会用 WMI 兜底')
950
+ }
951
+
803
952
  // Track busy sessions so a restart never cuts an answer.
804
953
  ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
805
954
  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 ' 按回车关闭窗口')
@@ -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
+ }
@@ -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.8",
3
+ "version": "0.2.0",
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"