@andy.ian/dsh-homing 2.1.4 → 2.1.6
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 +42 -0
- package/SECURITY.md +90 -0
- package/bin/backup.mjs +3 -2
- package/bin/bootstrap-server.mjs +2 -1
- package/bin/inbox.mjs +46 -0
- package/bin/renew-cert.mjs +2 -1
- package/bin/window-agent-daemon.mjs +268 -0
- package/index.js +686 -87
- package/lib/compress.mjs +29 -5
- package/lib/exec-path.mjs +85 -0
- package/lib/files-page.mjs +27 -2
- package/lib/files.mjs +3 -2
- package/lib/git.mjs +5 -2
- package/lib/guard.mjs +43 -0
- package/lib/local-socket.mjs +50 -0
- package/lib/log-file.mjs +50 -0
- package/lib/node-runtime.mjs +44 -0
- package/lib/office.mjs +133 -0
- package/lib/orientation.mjs +158 -0
- package/lib/pty.mjs +6 -3
- package/lib/secret.mjs +46 -0
- package/lib/shells.mjs +2 -1
- package/lib/term-page.mjs +2 -0
- package/lib/vendor/des-vnc.mjs +266 -0
- package/lib/vendor/novnc/LICENSE.txt +62 -0
- package/lib/vendor/novnc/core/base64.js +104 -0
- package/lib/vendor/novnc/core/crypto/aes.js +178 -0
- package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
- package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
- package/lib/vendor/novnc/core/crypto/des.js +330 -0
- package/lib/vendor/novnc/core/crypto/dh.js +55 -0
- package/lib/vendor/novnc/core/crypto/md5.js +82 -0
- package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
- package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
- package/lib/vendor/novnc/core/decoders/h264.js +321 -0
- package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
- package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
- package/lib/vendor/novnc/core/decoders/raw.js +59 -0
- package/lib/vendor/novnc/core/decoders/rre.js +44 -0
- package/lib/vendor/novnc/core/decoders/tight.js +393 -0
- package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
- package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
- package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
- package/lib/vendor/novnc/core/deflator.js +84 -0
- package/lib/vendor/novnc/core/display.js +578 -0
- package/lib/vendor/novnc/core/encodings.js +54 -0
- package/lib/vendor/novnc/core/inflator.js +65 -0
- package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
- package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
- package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
- package/lib/vendor/novnc/core/input/keyboard.js +294 -0
- package/lib/vendor/novnc/core/input/keysym.js +616 -0
- package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
- package/lib/vendor/novnc/core/input/util.js +191 -0
- package/lib/vendor/novnc/core/input/vkeys.js +116 -0
- package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
- package/lib/vendor/novnc/core/ra2.js +312 -0
- package/lib/vendor/novnc/core/rfb.js +3420 -0
- package/lib/vendor/novnc/core/util/browser.js +233 -0
- package/lib/vendor/novnc/core/util/cursor.js +249 -0
- package/lib/vendor/novnc/core/util/element.js +32 -0
- package/lib/vendor/novnc/core/util/events.js +138 -0
- package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
- package/lib/vendor/novnc/core/util/int.js +15 -0
- package/lib/vendor/novnc/core/util/logging.js +56 -0
- package/lib/vendor/novnc/core/util/strings.js +28 -0
- package/lib/vendor/novnc/core/websock.js +369 -0
- package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
- package/lib/vendor/novnc/vendor/pako/README.md +6 -0
- package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
- package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
- package/lib/vendor/vnc.bundle.js +14592 -0
- package/lib/vendor/ws/LICENSE +20 -0
- package/lib/vendor/ws/index.js +22 -0
- package/lib/vendor/ws/lib/buffer-util.js +142 -0
- package/lib/vendor/ws/lib/constants.js +19 -0
- package/lib/vendor/ws/lib/event-target.js +292 -0
- package/lib/vendor/ws/lib/extension.js +203 -0
- package/lib/vendor/ws/lib/limiter.js +55 -0
- package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
- package/lib/vendor/ws/lib/receiver.js +743 -0
- package/lib/vendor/ws/lib/sender.js +610 -0
- package/lib/vendor/ws/lib/stream.js +161 -0
- package/lib/vendor/ws/lib/subprotocol.js +62 -0
- package/lib/vendor/ws/lib/validation.js +152 -0
- package/lib/vendor/ws/lib/websocket-server.js +562 -0
- package/lib/vendor/ws/lib/websocket.js +1426 -0
- package/lib/vendor/ws/package.json +74 -0
- package/lib/vendor/ws/wrapper.mjs +21 -0
- package/lib/vnc-app.js +567 -0
- package/lib/vnc-auth-proxy.mjs +179 -0
- package/lib/vnc-boot.js +45 -0
- package/lib/vnc-page.mjs +77 -0
- package/lib/vnc-pointer.mjs +17 -0
- package/lib/vnc.mjs +75 -0
- package/lib/window-app.js +155 -0
- package/lib/window-page.mjs +111 -0
- package/lib/window-remote.mjs +227 -0
- package/lib/ws-bridge.mjs +130 -0
- package/package.json +6 -2
- package/permissions.json +91 -0
- package/restart/client.mjs +85 -19
- package/restart/daemon/cli.mjs +55 -13
- package/restart/daemon/lib/detach.mjs +3 -2
- package/restart/daemon/lib/process-tree.mjs +17 -3
- package/restart/daemon/lib/restart-flow.mjs +36 -0
- package/restart/daemon/main.mjs +299 -80
- package/restart/engine.mjs +24 -8
- package/restart/port.mjs +88 -0
- package/restart/runner.mjs +4 -3
- package/restart/service.mjs +8 -5
- package/restart/watchdog.mjs +134 -0
package/restart/daemon/main.mjs
CHANGED
|
@@ -36,10 +36,14 @@ import os from 'node:os'
|
|
|
36
36
|
import path from 'node:path'
|
|
37
37
|
import http from 'node:http'
|
|
38
38
|
import { spawn, spawnSync } from 'node:child_process'
|
|
39
|
-
import {
|
|
39
|
+
import { fileURLToPath } from 'node:url'
|
|
40
|
+
import { rootOf, authorizeRestart, isInManagedTree } from './lib/process-tree.mjs'
|
|
40
41
|
import { decideUpgrade } from './lib/update-state.mjs'
|
|
41
|
-
import { startHidden, ancestorMatches, chainNames } from './lib/detach.mjs'
|
|
42
|
-
import {
|
|
42
|
+
import { startHidden, startViaCim, ancestorMatches, chainNames } from './lib/detach.mjs'
|
|
43
|
+
import { systemExe, powershellExe } from '../../lib/exec-path.mjs'
|
|
44
|
+
import { createLogWriter } from '../../lib/log-file.mjs'
|
|
45
|
+
import { createRestartFlow, computeBackoff, planAfterExit, planMonitorTick, shouldResetRestarts } from './lib/restart-flow.mjs'
|
|
46
|
+
import { isValidRestartPort, resolveRestartPort } from '../port.mjs'
|
|
43
47
|
|
|
44
48
|
// ---------- 参数 ----------
|
|
45
49
|
function arg(name, fallback = '') {
|
|
@@ -52,23 +56,90 @@ const has = (name) => process.argv.includes('--' + name)
|
|
|
52
56
|
|
|
53
57
|
const dshHome = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
|
|
54
58
|
const stateDir = arg('state', path.join(dshHome, 'restart-daemon'))
|
|
55
|
-
|
|
59
|
+
// 端口可配置:--control > 环境变量 > settings.json restartDaemon.port > 8790
|
|
60
|
+
const controlPort = (() => {
|
|
61
|
+
const explicit = Number(arg('control', ''))
|
|
62
|
+
if (isValidRestartPort(explicit)) return explicit
|
|
63
|
+
return resolveRestartPort()
|
|
64
|
+
})()
|
|
56
65
|
const bridgePort = Number(arg('bridge', '8787'))
|
|
57
66
|
const pollMs = Number(arg('poll', '2000'))
|
|
58
67
|
const logFile = path.join(stateDir, 'restart-daemon.log')
|
|
59
68
|
const stateFile = path.join(stateDir, 'restart-daemon.json')
|
|
60
69
|
const pidFile = path.join(stateDir, 'restart-daemon.pid')
|
|
61
70
|
const MAX_PAUSE_MINUTES = 24 * 60
|
|
71
|
+
// 守护进程身份(/health 用,供端口归属校验与看门狗识别,不含敏感路径)
|
|
72
|
+
const SERVICE_ID = 'dsh-homing-restart-daemon'
|
|
73
|
+
const VERSION = (() => {
|
|
74
|
+
try {
|
|
75
|
+
return JSON.parse(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json'), 'utf8')).version
|
|
76
|
+
} catch {
|
|
77
|
+
return 'unknown'
|
|
78
|
+
}
|
|
79
|
+
})()
|
|
80
|
+
const daemonStartedAt = new Date()
|
|
81
|
+
const heartbeatFile = path.join(stateDir, 'heartbeat.json')
|
|
82
|
+
const stoppedMarker = path.join(stateDir, 'stopped.json')
|
|
83
|
+
const portConflictMarker = path.join(stateDir, 'port-conflict.json')
|
|
84
|
+
|
|
85
|
+
// 写心跳:看门狗/外部监控可据此判断守护进程是否活着
|
|
86
|
+
function writeHeartbeat() {
|
|
87
|
+
try {
|
|
88
|
+
fs.mkdirSync(stateDir, { recursive: true })
|
|
89
|
+
fs.writeFileSync(heartbeatFile, JSON.stringify({
|
|
90
|
+
service: SERVICE_ID,
|
|
91
|
+
version: VERSION,
|
|
92
|
+
pid: process.pid,
|
|
93
|
+
startedAt: daemonStartedAt.toISOString(),
|
|
94
|
+
ts: new Date().toISOString(),
|
|
95
|
+
restarts: totalRestarts,
|
|
96
|
+
childPid: managedPid ?? child?.pid ?? null,
|
|
97
|
+
port: controlPort,
|
|
98
|
+
}))
|
|
99
|
+
} catch { /* 心跳失败不影响主流程 */ }
|
|
100
|
+
}
|
|
62
101
|
|
|
63
102
|
// 根据"客户端本地端口"反查发起连接的进程 PID。
|
|
64
103
|
// 用于确认重启指令确实来自 DSH 进程内部(我们的策略模块),
|
|
65
104
|
// 而不是同机其他进程——令牌文件同用户可读,PID 校验才是硬约束。
|
|
66
105
|
// 监听某端口的进程 PID(用于识别"插件宿主")
|
|
106
|
+
// 端口可配置后,单实例不再只靠"同一端口 bind 失败"。
|
|
107
|
+
// 用最新心跳判断是否已有同类守护进程在别的端口运行;交接中的旧实例(ppid)跳过。
|
|
108
|
+
function runningDaemonElsewhere() {
|
|
109
|
+
try {
|
|
110
|
+
const heartbeat = JSON.parse(fs.readFileSync(heartbeatFile, 'utf8'))
|
|
111
|
+
if (!heartbeat || !heartbeat.pid || heartbeat.pid === process.pid) return null
|
|
112
|
+
const age = Date.now() - Date.parse(heartbeat.ts ?? 0)
|
|
113
|
+
if (!(age >= 0 && age < 30_000)) return null
|
|
114
|
+
if (heartbeat.pid === process.ppid) return null
|
|
115
|
+
process.kill(Number(heartbeat.pid), 0)
|
|
116
|
+
return heartbeat
|
|
117
|
+
} catch {
|
|
118
|
+
return null
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// 探测 127.0.0.1:<port> 上是否是我们自己的守护进程(带服务标识)
|
|
123
|
+
function probeControlHealth(port, timeoutMs = 1500) {
|
|
124
|
+
return new Promise((resolve) => {
|
|
125
|
+
const request = http.request({ host: '127.0.0.1', port, path: '/health', method: 'GET', timeout: timeoutMs, agent: false }, (up) => {
|
|
126
|
+
const chunks = []
|
|
127
|
+
up.on('data', (chunk) => chunks.push(chunk))
|
|
128
|
+
up.on('end', () => {
|
|
129
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))) } catch { resolve(null) }
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
request.on('timeout', () => { request.destroy(); resolve(null) })
|
|
133
|
+
request.on('error', () => resolve(null))
|
|
134
|
+
request.end()
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
67
138
|
function listeningPid(port) {
|
|
68
139
|
const target = String(port);
|
|
69
140
|
try {
|
|
70
141
|
if (process.platform === 'win32') {
|
|
71
|
-
const out = spawnSync(
|
|
142
|
+
const out = spawnSync(NETSTAT, ['-ano', '-p', 'tcp'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
|
|
72
143
|
if (out.status !== 0 || !out.stdout) return null;
|
|
73
144
|
for (const line of out.stdout.split('\n')) {
|
|
74
145
|
const cols = line.trim().split(/\s+/u);
|
|
@@ -80,7 +151,7 @@ function listeningPid(port) {
|
|
|
80
151
|
}
|
|
81
152
|
return null;
|
|
82
153
|
}
|
|
83
|
-
const out = spawnSync(
|
|
154
|
+
const out = spawnSync(SS, ['-tlnp'], { encoding: 'utf8', timeout: 5000 });
|
|
84
155
|
if (out.status === 0 && out.stdout) {
|
|
85
156
|
for (const line of out.stdout.split('\n')) {
|
|
86
157
|
if (!line.includes(':' + target)) continue;
|
|
@@ -94,14 +165,71 @@ function listeningPid(port) {
|
|
|
94
165
|
}
|
|
95
166
|
}
|
|
96
167
|
|
|
168
|
+
// 抓一次父子关系快照:Windows 用 CIM,POSIX 用 ps。
|
|
169
|
+
// 仅重启请求时调用(低频),换取"来源必须在我管理的进程树内"的强校验。
|
|
170
|
+
const POWERSHELL = powershellExe()
|
|
171
|
+
const NETSTAT = systemExe('netstat')
|
|
172
|
+
const SS = systemExe('ss')
|
|
173
|
+
const PS = systemExe('ps')
|
|
174
|
+
const TASKLIST = systemExe('tasklist')
|
|
175
|
+
const REG = systemExe('reg')
|
|
176
|
+
const TASKKILL = systemExe('taskkill')
|
|
177
|
+
|
|
178
|
+
function processParentMap() {
|
|
179
|
+
try {
|
|
180
|
+
if (process.platform === 'win32') {
|
|
181
|
+
const script = 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }'
|
|
182
|
+
const out = spawnSync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script], {
|
|
183
|
+
encoding: 'utf8', windowsHide: true, timeout: 8000,
|
|
184
|
+
})
|
|
185
|
+
if (out.status !== 0 || !out.stdout) return null
|
|
186
|
+
const map = new Map()
|
|
187
|
+
for (const line of String(out.stdout).split(/\r?\n/u)) {
|
|
188
|
+
const parts = line.trim().split(/\s+/u).map(Number)
|
|
189
|
+
if (parts.length >= 2 && Number.isFinite(parts[0]) && parts[0] > 0 && Number.isFinite(parts[1])) {
|
|
190
|
+
map.set(parts[0], parts[1])
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return map.size > 0 ? map : null
|
|
194
|
+
}
|
|
195
|
+
const out = spawnSync(PS, ['-eo', 'pid=,ppid='], { encoding: 'utf8', timeout: 5000 })
|
|
196
|
+
if (out.status !== 0 || !out.stdout) return null
|
|
197
|
+
const map = new Map()
|
|
198
|
+
for (const line of String(out.stdout).split(/\n/u)) {
|
|
199
|
+
const parts = line.trim().split(/\s+/u).map(Number)
|
|
200
|
+
if (parts.length >= 2 && parts[0] > 0 && Number.isFinite(parts[1])) map.set(parts[0], parts[1])
|
|
201
|
+
}
|
|
202
|
+
return map.size > 0 ? map : null
|
|
203
|
+
} catch {
|
|
204
|
+
return null
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// 有有效子进程句柄时,来源必须在该句柄进程的子树内;否则拒绝。
|
|
209
|
+
function verifyManagedTree(srcPid) {
|
|
210
|
+
const candidate = child?.pid ?? managedPid ?? null
|
|
211
|
+
let rootPid = null
|
|
212
|
+
try {
|
|
213
|
+
rootPid = candidate && listDshPids().includes(Number(candidate)) ? Number(candidate) : null
|
|
214
|
+
} catch {
|
|
215
|
+
rootPid = null
|
|
216
|
+
}
|
|
217
|
+
const parentMap = rootPid ? processParentMap() : null
|
|
218
|
+
if (rootPid && parentMap === null) {
|
|
219
|
+
log('进程树快照失败,跳过树内校验(保留 PID/宿主校验)')
|
|
220
|
+
return { enforced: false, ok: true, reason: 'tree-snapshot-unavailable' }
|
|
221
|
+
}
|
|
222
|
+
return isInManagedTree({ srcPid, rootPid, parentOf: (pid) => parentMap?.get(pid) ?? null })
|
|
223
|
+
}
|
|
224
|
+
|
|
97
225
|
// 列出所有进程名(tasklist,无需 wmic)
|
|
98
226
|
function listProcessNames() {
|
|
99
227
|
try {
|
|
100
228
|
if (process.platform !== 'win32') {
|
|
101
|
-
const out = spawnSync(
|
|
229
|
+
const out = spawnSync(PS, ['-eo', 'comm='], { encoding: 'utf8', timeout: 5000 })
|
|
102
230
|
return String(out.stdout ?? '').split(/\n/u).map((x) => x.trim()).filter(Boolean)
|
|
103
231
|
}
|
|
104
|
-
const out = spawnSync(
|
|
232
|
+
const out = spawnSync(TASKLIST, ['/FO', 'CSV', '/NH'], { encoding: 'utf8', windowsHide: true, timeout: 8000 })
|
|
105
233
|
return String(out.stdout ?? '')
|
|
106
234
|
.split(/\r?\n/u)
|
|
107
235
|
.map((line) => line.match(/^"([^"]+)"/u)?.[1])
|
|
@@ -116,7 +244,7 @@ function peerPidForPort(remotePort, controlPortNumber) {
|
|
|
116
244
|
const cport = String(controlPortNumber);
|
|
117
245
|
try {
|
|
118
246
|
if (process.platform === 'win32') {
|
|
119
|
-
const out = spawnSync(
|
|
247
|
+
const out = spawnSync(NETSTAT, ['-ano', '-p', 'tcp'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
|
|
120
248
|
if (out.status !== 0 || !out.stdout) return null;
|
|
121
249
|
for (const line of out.stdout.split('\n')) {
|
|
122
250
|
const cols = line.trim().split(/\s+/u);
|
|
@@ -130,7 +258,7 @@ function peerPidForPort(remotePort, controlPortNumber) {
|
|
|
130
258
|
}
|
|
131
259
|
return null;
|
|
132
260
|
}
|
|
133
|
-
const out = spawnSync(
|
|
261
|
+
const out = spawnSync(SS, ['-tnp'], { encoding: 'utf8', timeout: 5000 });
|
|
134
262
|
if (out.status === 0 && out.stdout) {
|
|
135
263
|
for (const line of out.stdout.split('\n')) {
|
|
136
264
|
if (!line.includes(':' + rport)) continue;
|
|
@@ -168,9 +296,11 @@ function localIso(date = new Date()) {
|
|
|
168
296
|
+ sign + pad(Math.floor(abs / 60)) + ':' + pad(abs % 60)
|
|
169
297
|
}
|
|
170
298
|
|
|
299
|
+
const writeLogLine = createLogWriter(logFile)
|
|
300
|
+
|
|
171
301
|
function log(message) {
|
|
172
302
|
const line = `${new Date().toISOString()} ${message}\n`
|
|
173
|
-
|
|
303
|
+
writeLogLine(line)
|
|
174
304
|
if (!has('detach')) process.stdout.write(line)
|
|
175
305
|
}
|
|
176
306
|
|
|
@@ -201,7 +331,7 @@ const procName = path.basename(exeName, path.extname(exeName))
|
|
|
201
331
|
function listDshPids() {
|
|
202
332
|
try {
|
|
203
333
|
if (process.platform === 'win32') {
|
|
204
|
-
const out = spawnSync(
|
|
334
|
+
const out = spawnSync(TASKLIST, ['/FI', `IMAGENAME eq ${exeName}`, '/FO', 'CSV', '/NH'], {
|
|
205
335
|
encoding: 'utf8', windowsHide: true, timeout: 5000,
|
|
206
336
|
})
|
|
207
337
|
return String(out.stdout ?? '')
|
|
@@ -210,7 +340,7 @@ function listDshPids() {
|
|
|
210
340
|
.filter(Boolean)
|
|
211
341
|
.map((match) => Number(match[2]))
|
|
212
342
|
}
|
|
213
|
-
const out = spawnSync(
|
|
343
|
+
const out = spawnSync(PS, ['-eo', 'pid=,comm='], { encoding: 'utf8', timeout: 5000 })
|
|
214
344
|
return String(out.stdout ?? '')
|
|
215
345
|
.split(/\n/u)
|
|
216
346
|
.map((line) => line.trim().split(/\s+/u))
|
|
@@ -249,8 +379,9 @@ async function refreshProbe() {
|
|
|
249
379
|
}
|
|
250
380
|
|
|
251
381
|
let child = null
|
|
252
|
-
let
|
|
253
|
-
let restarts = 0
|
|
382
|
+
let managedPid = null
|
|
383
|
+
let restarts = 0 // 退避计数(稳定 60 秒后归零)
|
|
384
|
+
let totalRestarts = 0 // 累计重启次数(守护进程生命周期内,不归零;用于展示)
|
|
254
385
|
let stoppingForRestart = false
|
|
255
386
|
let restarting = false
|
|
256
387
|
let launchFailed = false
|
|
@@ -263,8 +394,8 @@ function persist(extra = {}) {
|
|
|
263
394
|
exe: exePath,
|
|
264
395
|
controlPort,
|
|
265
396
|
bridgePort,
|
|
266
|
-
restarts,
|
|
267
|
-
childPid: child?.pid ?? null,
|
|
397
|
+
restarts: totalRestarts,
|
|
398
|
+
childPid: managedPid ?? child?.pid ?? null,
|
|
268
399
|
platform: process.platform,
|
|
269
400
|
startedAt: startedAt.toISOString(),
|
|
270
401
|
updatedAt: new Date().toISOString(),
|
|
@@ -343,7 +474,7 @@ function installedVersion() {
|
|
|
343
474
|
// 兜底:注册表里的 DisplayVersion(reg.exe,不是 PowerShell)
|
|
344
475
|
if (!installedVersionCache) {
|
|
345
476
|
try {
|
|
346
|
-
const out = spawnSync(
|
|
477
|
+
const out = spawnSync(REG, ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'DeepSeek Harness', '/v', 'DisplayVersion'], { encoding: 'utf8', timeout: 5000, windowsHide: true })
|
|
347
478
|
installedVersionCache = (/DisplayVersion\s+REG_SZ\s+(\S+)/u.exec(out.stdout ?? '')?.[1] ?? '').trim() || null
|
|
348
479
|
} catch {
|
|
349
480
|
installedVersionCache = null
|
|
@@ -387,45 +518,90 @@ function launch() {
|
|
|
387
518
|
return null
|
|
388
519
|
}
|
|
389
520
|
launchFailed = false
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
log(
|
|
521
|
+
// 关键:用 WMI 创建进程,让 DSH 的父进程变成 WmiPrvSE,而不是本守护进程。
|
|
522
|
+
// 否则"重启/停止守护进程"时会把作为子进程的 DSH 一起带走(实测两者一起退出)。
|
|
523
|
+
try {
|
|
524
|
+
const result = startViaCim({ command: exePath, args: [] })
|
|
525
|
+
if (result.ok && result.pid > 0) {
|
|
526
|
+
managedPid = result.pid
|
|
527
|
+
launchedAt = Date.now()
|
|
528
|
+
log('启动 DSH:' + exePath + '(PID ' + result.pid + ',WMI 脱离进程树)')
|
|
529
|
+
return { pid: result.pid, viaCim: true }
|
|
530
|
+
}
|
|
531
|
+
log('WMI 启动失败:' + (result.error ?? '未知原因') + ',回退到 spawn')
|
|
532
|
+
} catch (error) {
|
|
533
|
+
log('WMI 启动异常:' + (error?.message ?? String(error)) + ',回退到 spawn')
|
|
534
|
+
}
|
|
535
|
+
try {
|
|
536
|
+
const spawned = spawn(exePath, [], { stdio: 'ignore', windowsHide: false, detached: process.platform !== 'win32' })
|
|
537
|
+
spawned.on('error', (error) => { log('启动失败:' + (error.code ?? error.message)); launchFailed = true })
|
|
538
|
+
managedPid = spawned.pid ?? null
|
|
539
|
+
launchedAt = Date.now()
|
|
540
|
+
log('启动 DSH:' + exePath + '(PID ' + (spawned.pid ?? '未知') + ',spawn 回退)')
|
|
541
|
+
return { pid: spawned.pid, viaCim: false }
|
|
542
|
+
} catch (error) {
|
|
543
|
+
log('启动失败:' + (error?.message ?? String(error)))
|
|
401
544
|
launchFailed = true
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
545
|
+
return null
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ---------- 监视循环 ----------
|
|
550
|
+
// 不依赖子进程句柄(WMI 启动拿不到句柄),统一用轮询判断存活、退避与崩溃拉起。
|
|
551
|
+
let monitorTimer = null
|
|
552
|
+
// 本轮连续运行的起点(DSH 消失时清零),用于稳定 60 秒后归零重启次数
|
|
553
|
+
let runningSince = 0
|
|
554
|
+
let launchPending = false
|
|
555
|
+
let launchedAt = 0
|
|
556
|
+
|
|
557
|
+
function startMonitor() {
|
|
558
|
+
if (monitorTimer) return
|
|
559
|
+
monitorTimer = setInterval(async () => {
|
|
560
|
+
try { await refreshProbe() } catch { /* 忽略 */ }
|
|
561
|
+
let info = { running: false, pids: [] }
|
|
562
|
+
try { info = await probe() } catch { /* 忽略 */ }
|
|
563
|
+
const now = Date.now()
|
|
564
|
+
if (info.running) {
|
|
565
|
+
// runningSince 只在连续运行的起点设置;
|
|
566
|
+
// 之后每轮都用它判断是否稳定满 60 秒,不能拿旧起点瞬间归零。
|
|
567
|
+
if (!runningSince) runningSince = now
|
|
568
|
+
if (shouldResetRestarts({ restarts, runningSince, now })) {
|
|
569
|
+
restarts = 0
|
|
570
|
+
log('DSH 稳定运行 60 秒,重启次数归零')
|
|
571
|
+
}
|
|
412
572
|
return
|
|
413
573
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
574
|
+
runningSince = 0
|
|
575
|
+
const decision = planMonitorTick({
|
|
576
|
+
running: false,
|
|
577
|
+
stopping: stoppingForRestart,
|
|
578
|
+
restarting,
|
|
579
|
+
launchPending,
|
|
580
|
+
launchFailed,
|
|
581
|
+
paused: pausedUntil > now,
|
|
582
|
+
launchedAt,
|
|
583
|
+
now,
|
|
584
|
+
})
|
|
585
|
+
if (decision.action !== 'relaunch') return
|
|
586
|
+
const plan = planAfterExit({ stopping: false, pausedUntil, restarts: Math.max(1, restarts), now })
|
|
587
|
+
if (plan.action === 'skip') { log('暂停中,不拉起 DSH'); return }
|
|
588
|
+
restarts += 1
|
|
589
|
+
totalRestarts += 1
|
|
590
|
+
persist()
|
|
591
|
+
launchPending = true
|
|
592
|
+
try {
|
|
418
593
|
await waitForUpgrade()
|
|
419
594
|
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
|
|
420
|
-
if (
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
595
|
+
if (plan.delayMs) await new Promise((resolve) => setTimeout(resolve, plan.delayMs))
|
|
596
|
+
const current = await probe()
|
|
597
|
+
if (current.running) return
|
|
598
|
+
child = launch()
|
|
599
|
+
persist()
|
|
600
|
+
} finally {
|
|
601
|
+
launchPending = false
|
|
602
|
+
}
|
|
603
|
+
}, pollMs)
|
|
604
|
+
monitorTimer.unref?.()
|
|
429
605
|
}
|
|
430
606
|
|
|
431
607
|
async function killDsh() {
|
|
@@ -442,7 +618,7 @@ async function killDsh() {
|
|
|
442
618
|
}
|
|
443
619
|
for (const pid of listDshPids()) {
|
|
444
620
|
try {
|
|
445
|
-
if (process.platform === 'win32') spawnSync(
|
|
621
|
+
if (process.platform === 'win32') spawnSync(TASKKILL, ['/F', '/PID', String(pid)], { windowsHide: true })
|
|
446
622
|
else process.kill(pid, 'SIGKILL')
|
|
447
623
|
} catch { /* 已退出 */ }
|
|
448
624
|
}
|
|
@@ -469,16 +645,16 @@ function schedulePauseExpiry(minutes) {
|
|
|
469
645
|
const info = await probe()
|
|
470
646
|
if (info.running) { log('暂停到期,DSH 仍在运行'); return }
|
|
471
647
|
log('暂停到期,拉起 DSH')
|
|
472
|
-
|
|
648
|
+
child = launch()
|
|
649
|
+
persist()
|
|
473
650
|
}, minutes * 60_000)
|
|
474
651
|
timer.unref?.()
|
|
475
652
|
}
|
|
476
653
|
|
|
477
654
|
function cors(res) {
|
|
478
|
-
//
|
|
479
|
-
|
|
480
|
-
res
|
|
481
|
-
res.setHeader('access-control-allow-headers', 'content-type')
|
|
655
|
+
// 调用方是插件服务端(同机进程),不需要浏览器 CORS。
|
|
656
|
+
// 不发送 access-control-allow-origin,避免任意网页读取 /status(路径/PID)。
|
|
657
|
+
void res
|
|
482
658
|
}
|
|
483
659
|
|
|
484
660
|
// 重启流程(顺序/超时/并发/异常复位都在 lib/restart-flow.mjs,可单测)
|
|
@@ -497,6 +673,8 @@ const restart = () => {
|
|
|
497
673
|
// 并发请求交给流程层返回 busy,不重复累加计数
|
|
498
674
|
if (restartFlow.inFlight) return restartFlow.restart();
|
|
499
675
|
restarts += 1;
|
|
676
|
+
totalRestarts += 1;
|
|
677
|
+
persist();
|
|
500
678
|
return restartFlow.restart();
|
|
501
679
|
};
|
|
502
680
|
|
|
@@ -504,6 +682,12 @@ function startControl() {
|
|
|
504
682
|
const server = http.createServer(async (req, res) => {
|
|
505
683
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
506
684
|
cors(res)
|
|
685
|
+
// 正常调用方是插件服务端/CLI(无 Origin);浏览器跨站请求会带 Origin → 直接拒绝
|
|
686
|
+
if (req.headers.origin) {
|
|
687
|
+
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
688
|
+
res.end(JSON.stringify({ error: 'cross-origin request rejected' }))
|
|
689
|
+
return
|
|
690
|
+
}
|
|
507
691
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return }
|
|
508
692
|
const paused = pausedUntil > Date.now()
|
|
509
693
|
// 授权模型:调用者必须是插件宿主进程本身;并断言目标进程树包含该宿主
|
|
@@ -518,21 +702,35 @@ function startControl() {
|
|
|
518
702
|
res.end(JSON.stringify({ error: '拒绝:' + verdict.reason }))
|
|
519
703
|
return
|
|
520
704
|
}
|
|
521
|
-
|
|
705
|
+
const treeVerdict = verifyManagedTree(srcPid)
|
|
706
|
+
if (!treeVerdict.ok) {
|
|
707
|
+
log('拒绝变更操作:来源不在受管进程树内 来源PID=' + srcPid + ' 受管根=' + (child?.pid ?? '无') + ' 原因=' + treeVerdict.reason)
|
|
708
|
+
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8' })
|
|
709
|
+
res.end(JSON.stringify({ error: '拒绝:' + treeVerdict.reason }))
|
|
710
|
+
return
|
|
711
|
+
}
|
|
712
|
+
log('授权通过:来源PID=' + srcPid + ' 插件宿主=' + hostPid + ' 目标根=' + verdict.rootPid + ' 树内进程数=' + verdict.treeSize + ' 受管树=' + (treeVerdict.enforced ? treeVerdict.reason : '未启用'))
|
|
522
713
|
}
|
|
523
714
|
if (url.pathname === '/health') {
|
|
524
715
|
// 轻量探活:不 spawn 任何进程、不读文件
|
|
525
716
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
526
|
-
res.end(JSON.stringify({
|
|
717
|
+
res.end(JSON.stringify({
|
|
718
|
+
ok: true,
|
|
719
|
+
service: SERVICE_ID,
|
|
720
|
+
version: VERSION,
|
|
721
|
+
pid: process.pid,
|
|
722
|
+
uptimeSeconds: Math.round(process.uptime()),
|
|
723
|
+
startedAt: daemonStartedAt.toISOString(),
|
|
724
|
+
}))
|
|
527
725
|
return
|
|
528
726
|
}
|
|
529
727
|
if (url.pathname === '/status') {
|
|
530
728
|
// 读缓存快照(轮询每 2 秒刷新);首次请求若还没有快照,补一次实时探测
|
|
531
729
|
if (!lastProbe.value) await refreshProbe()
|
|
532
730
|
const age = lastProbe.at ? Math.round((Date.now() - lastProbe.at) / 1000) : null
|
|
533
|
-
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
731
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' })
|
|
534
732
|
res.end(JSON.stringify({
|
|
535
|
-
daemon: { pid: process.pid, restarts, restarting, exe: exePath },
|
|
733
|
+
daemon: { pid: process.pid, restarts: totalRestarts, restarting, exe: exePath ? path.basename(exePath) : null },
|
|
536
734
|
...(lastProbe.value ?? { pids: [], bridge: false, running: false }),
|
|
537
735
|
probeAgeSeconds: age,
|
|
538
736
|
lastProbeAt: lastProbe.at ? localIso(new Date(lastProbe.at)) : null,
|
|
@@ -564,6 +762,11 @@ function startControl() {
|
|
|
564
762
|
return
|
|
565
763
|
}
|
|
566
764
|
if (url.pathname === '/stop') {
|
|
765
|
+
// 记录"用户主动停止",避免看门狗把停止误判为崩溃并重新拉起
|
|
766
|
+
try {
|
|
767
|
+
fs.mkdirSync(stateDir, { recursive: true })
|
|
768
|
+
fs.writeFileSync(stoppedMarker, JSON.stringify({ at: new Date().toISOString(), pid: process.pid }))
|
|
769
|
+
} catch { /* 忽略 */ }
|
|
567
770
|
log('收到停止指令:守护进程退出,不再拉起 DSH')
|
|
568
771
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
|
|
569
772
|
res.end(JSON.stringify({ stopped: true }))
|
|
@@ -582,13 +785,34 @@ function startControl() {
|
|
|
582
785
|
})
|
|
583
786
|
server.on('error', (error) => {
|
|
584
787
|
if (error.code === 'EADDRINUSE') {
|
|
585
|
-
|
|
586
|
-
|
|
788
|
+
void (async () => {
|
|
789
|
+
// 先确认占用者是不是同类守护进程,而不是"任何程序"都当成已有实例
|
|
790
|
+
const info = await probeControlHealth(controlPort)
|
|
791
|
+
if (info && info.service === SERVICE_ID) {
|
|
792
|
+
log('控制端口已被另一个守护进程占用(version=' + (info.version ?? '?') + ' pid=' + (info.pid ?? '?') + ');本实例退出(单实例保护)')
|
|
793
|
+
process.exit(0)
|
|
794
|
+
}
|
|
795
|
+
const occupant = listeningPid(controlPort)
|
|
796
|
+
try {
|
|
797
|
+
fs.mkdirSync(stateDir, { recursive: true })
|
|
798
|
+
fs.writeFileSync(portConflictMarker, JSON.stringify({
|
|
799
|
+
port: controlPort,
|
|
800
|
+
occupantPid: occupant ?? null,
|
|
801
|
+
at: new Date().toISOString(),
|
|
802
|
+
}))
|
|
803
|
+
} catch { /* 忽略 */ }
|
|
804
|
+
log('控制端口被非本程序占用:占用者PID=' + (occupant ?? '未知') + ';本实例退出,DSH 将失去守护(exit=2)')
|
|
805
|
+
process.exit(2)
|
|
806
|
+
})()
|
|
807
|
+
return
|
|
587
808
|
}
|
|
588
809
|
log(`控制端口错误:${error.code}`)
|
|
589
810
|
process.exit(1)
|
|
590
811
|
})
|
|
591
|
-
server.listen(controlPort, '127.0.0.1', () =>
|
|
812
|
+
server.listen(controlPort, '127.0.0.1', () => {
|
|
813
|
+
try { fs.rmSync(portConflictMarker, { force: true }) } catch { /* 忽略 */ }
|
|
814
|
+
log(`控制接口:http://127.0.0.1:${controlPort}/status`)
|
|
815
|
+
})
|
|
592
816
|
return server
|
|
593
817
|
}
|
|
594
818
|
|
|
@@ -605,12 +829,12 @@ process.on('unhandledRejection', (reason) => {
|
|
|
605
829
|
function processNameOf(pid) {
|
|
606
830
|
try {
|
|
607
831
|
if (process.platform === 'win32') {
|
|
608
|
-
const out = spawnSync(
|
|
832
|
+
const out = spawnSync(TASKLIST, ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'], {
|
|
609
833
|
encoding: 'utf8', windowsHide: true, timeout: 5000,
|
|
610
834
|
})
|
|
611
835
|
return String(out.stdout ?? '').match(/^"([^"]+)"/u)?.[1] ?? null
|
|
612
836
|
}
|
|
613
|
-
const out = spawnSync(
|
|
837
|
+
const out = spawnSync(PS, ['-p', String(pid), '-o', 'comm='], { encoding: 'utf8', timeout: 5000 })
|
|
614
838
|
return String(out.stdout ?? '').trim() || null
|
|
615
839
|
} catch {
|
|
616
840
|
return null
|
|
@@ -661,7 +885,11 @@ if (has('restart')) {
|
|
|
661
885
|
}
|
|
662
886
|
else {
|
|
663
887
|
fs.writeFileSync(pidFile, String(process.pid))
|
|
664
|
-
|
|
888
|
+
try { fs.rmSync(stoppedMarker, { force: true }) } catch { /* 忽略 */ }
|
|
889
|
+
writeHeartbeat()
|
|
890
|
+
const heartbeatTimer = setInterval(writeHeartbeat, 10_000)
|
|
891
|
+
heartbeatTimer.unref?.()
|
|
892
|
+
log('守护进程启动:pid=' + process.pid + ' 平台=' + process.platform + ' exe=' + (exePath ?? '未找到') + ' version=' + VERSION)
|
|
665
893
|
const cleanup = () => { try { fs.rmSync(pidFile, { force: true }) } catch { /* 忽略 */ } }
|
|
666
894
|
process.on('SIGINT', () => { log('收到 SIGINT,退出'); cleanup(); process.exit(0) })
|
|
667
895
|
process.on('SIGTERM', () => { log('收到 SIGTERM,退出'); cleanup(); process.exit(0) })
|
|
@@ -671,21 +899,12 @@ else {
|
|
|
671
899
|
const info = await probe()
|
|
672
900
|
if (info.running) {
|
|
673
901
|
log('DSH 已在运行(PID ' + info.pids.join(',') + '),接管监视(' + pollMs / 1000 + ' 秒轮询)')
|
|
674
|
-
|
|
675
|
-
await refreshProbe()
|
|
676
|
-
if (stoppingForRestart || restarting || launchFailed) return
|
|
677
|
-
const current = await probe()
|
|
678
|
-
if (!current.running) {
|
|
679
|
-
restarts += 1
|
|
680
|
-
log('检测到 DSH 已退出(外部拉起),准备拉起')
|
|
681
|
-
await waitForUpgrade()
|
|
682
|
-
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH'); return }
|
|
683
|
-
if (!child) { child = launch(); persist() }
|
|
684
|
-
}
|
|
685
|
-
}, pollMs)
|
|
902
|
+
runningSince = Date.now()
|
|
686
903
|
} else {
|
|
687
904
|
log('未发现运行中的 DSH,等待(可能是升级中)后拉起')
|
|
688
905
|
await waitForUpgrade()
|
|
689
906
|
if (pausedUntil > Date.now()) { log('暂停中,不拉起 DSH') } else { child = launch(); persist() }
|
|
690
907
|
}
|
|
908
|
+
startMonitor()
|
|
909
|
+
|
|
691
910
|
}
|
package/restart/engine.mjs
CHANGED
|
@@ -41,6 +41,7 @@ export function idleState(reason = '未排队') {
|
|
|
41
41
|
*/
|
|
42
42
|
export function decide(state, spec, input) {
|
|
43
43
|
const { now, busyNow, busyTitles = [] } = input;
|
|
44
|
+
const activityAt = Number(input.lastActivityAt) || 0;
|
|
44
45
|
const next = { ...state, round: state.round + 1 };
|
|
45
46
|
const quietMs = spec.idle.quietMs;
|
|
46
47
|
|
|
@@ -50,31 +51,43 @@ export function decide(state, spec, input) {
|
|
|
50
51
|
|
|
51
52
|
const notBefore = next.startedAt + next.afterSeconds * 1000;
|
|
52
53
|
if (now < notBefore) {
|
|
53
|
-
next.reason =
|
|
54
|
+
next.reason = `等待最早时间(还差 ${Math.ceil((notBefore - now) / 1000)} 秒)`;
|
|
54
55
|
return { state: next, action: ACTION.WAIT_EARLIEST, reason: next.reason };
|
|
55
56
|
}
|
|
56
57
|
|
|
57
58
|
if (busyNow) {
|
|
58
59
|
next.quietSince = null;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
// 注意:这里只表示"有会话在运行",不代表用户输入。
|
|
61
|
+
// 用户输入由活动信标单独处理(见下面的 activityAt)。
|
|
62
|
+
const shortTitles = busyTitles.slice(0, 2).map((title) => {
|
|
63
|
+
const text = String(title ?? '');
|
|
64
|
+
return text.length > 10 ? text.slice(0, 10) + '…' : text;
|
|
65
|
+
});
|
|
66
|
+
next.reason = shortTitles.length ? '会话运行中:' + shortTitles.join('、') : '会话运行中';
|
|
62
67
|
return { state: next, action: ACTION.BUSY, reason: next.reason };
|
|
63
68
|
}
|
|
64
69
|
|
|
65
70
|
if (next.quietSince === null) {
|
|
66
71
|
next.quietSince = now;
|
|
67
|
-
next.reason =
|
|
72
|
+
next.reason = `开始安静窗口(${Math.round(quietMs / 1000)} 秒)`;
|
|
68
73
|
return { state: next, action: ACTION.START_QUIET, reason: next.reason };
|
|
69
74
|
}
|
|
70
75
|
|
|
76
|
+
// 安静窗口期间出现新的用户活动 → 以活动时间重新计时
|
|
77
|
+
if (activityAt > next.quietSince) {
|
|
78
|
+
next.quietSince = activityAt;
|
|
79
|
+
const left = Math.max(0, quietMs - (now - activityAt));
|
|
80
|
+
next.reason = '用户活动,重新计时(还差 ' + Math.ceil(left / 1000) + ' 秒)';
|
|
81
|
+
return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason };
|
|
82
|
+
}
|
|
83
|
+
|
|
71
84
|
const waited = now - next.quietSince;
|
|
72
85
|
if (waited >= quietMs) {
|
|
73
|
-
next.reason = '
|
|
86
|
+
next.reason = '准备触发';
|
|
74
87
|
return { state: next, action: ACTION.TRIGGER, reason: next.reason };
|
|
75
88
|
}
|
|
76
89
|
|
|
77
|
-
next.reason =
|
|
90
|
+
next.reason = `安静窗口(还差 ${Math.ceil((quietMs - waited) / 1000)} 秒)`;
|
|
78
91
|
return { state: next, action: ACTION.WAIT_QUIET, reason: next.reason };
|
|
79
92
|
}
|
|
80
93
|
|
|
@@ -84,7 +97,10 @@ export function decide(state, spec, input) {
|
|
|
84
97
|
*/
|
|
85
98
|
export function recheckBeforeTrigger(state, spec, input, guardKey = 'recheckBeforeTrigger') {
|
|
86
99
|
if (!spec.guard[guardKey]) return { state, cancelled: false, reason: 'skipped' };
|
|
87
|
-
|
|
100
|
+
const now = Number(input.now) || Date.now();
|
|
101
|
+
const activityAt = Number(input.lastActivityAt) || 0;
|
|
102
|
+
const recentActivity = activityAt > 0 && now - activityAt < spec.idle.quietMs;
|
|
103
|
+
if (!input.busyNow && !recentActivity) return { state, cancelled: false, reason: 'idle' };
|
|
88
104
|
return {
|
|
89
105
|
state: { ...state, quietSince: null, reason: '刚要重启时检测到新活动,已取消并重新计时' },
|
|
90
106
|
cancelled: true,
|