@andy.ian/dsh-homing 2.0.1 → 2.0.3

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/lib/shell.mjs DELETED
@@ -1,274 +0,0 @@
1
- /**
2
- * shell 执行:给 /shell 页面用(手机端的 "Git Bash")。
3
- *
4
- * 这是**故意**执行任意命令的能力,所以边界写清楚:
5
- * - 只有已登录会话能进(路由层校验);
6
- * - 每条命令写审计(含工作目录与命令行);
7
- * - 30 秒超时 + 64KB 输出上限;超时杀整棵进程树;
8
- * - 优先用 Git Bash(不能用 WSL 的 bash:它把 D:\ 当成 /mnt/d,路径语义不同),没有就退回 cmd.exe;
9
- * - 支持 `cd <目录>` 这类"改变当前目录"的指令(页面维持一个 cwd 字段)。
10
- */
11
- import fs from 'node:fs'
12
- import path from 'node:path'
13
- import { spawn, spawnSync } from 'node:child_process'
14
-
15
- const MAX_OUTPUT = 64 * 1024
16
- const DEFAULT_TIMEOUT = 30_000
17
-
18
- let bashPath = null
19
- let bashChecked = false
20
-
21
- /** 找一个可用的 bash;找不到返回 null(用 cmd 兜底) */
22
- export function findBash() {
23
- if (bashChecked) return bashPath
24
- bashChecked = true
25
- // Windows 上裸 bash 通常是 WSL 启动器(C:\Windows\System32\bash.exe),
26
- // 它把 D:\\ 当成 /mnt/d,路径语义完全不同 —— 所以只认 Git Bash 的显式路径。
27
- const candidates = process.platform === 'win32'
28
- ? [
29
- 'C:/Program Files/Git/bin/bash.exe',
30
- 'C:/Program Files/Git/usr/bin/bash.exe',
31
- 'C:/Program Files (x86)/Git/bin/bash.exe',
32
- ]
33
- : ['bash', '/bin/bash'];
34
- for (const candidate of candidates) {
35
- try {
36
- const result = spawnSync(candidate, ['-lc', 'echo ok'], { encoding: 'utf8', timeout: 5000, windowsHide: true })
37
- if (result.status === 0 && String(result.stdout).includes('ok')) {
38
- bashPath = candidate
39
- return bashPath
40
- }
41
- } catch {
42
- // 换下一个
43
- }
44
- }
45
- return null
46
- }
47
-
48
- /** 把 `cd xxx` 解析成新目录;不是 cd 就返回 null */
49
- export function parseCd(command, cwd) {
50
- const match = /^\s*cd(?:\s+(.+))?\s*$/u.exec(String(command ?? ''))
51
- if (match === null) return null
52
- const raw = (match[1] ?? '').trim().replace(/^["']|["']$/gu, '')
53
- if (raw === '') return path.resolve(cwd)
54
- const expanded = raw.startsWith('~') ? path.join(process.env.USERPROFILE ?? process.env.HOME ?? '', raw.slice(1)) : raw
55
- return path.resolve(cwd, expanded)
56
- }
57
-
58
- /** 执行一条命令 */
59
- export function runShell(cwd, command) {
60
- const text = String(command ?? '').trim()
61
- if (text === '') return Promise.resolve({ ok: false, error: '命令为空' })
62
-
63
- let workdir = cwd
64
- try {
65
- if (!fs.statSync(workdir).isDirectory()) workdir = process.cwd()
66
- } catch {
67
- workdir = process.cwd()
68
- }
69
-
70
- const gitBash = findBash()
71
- const spawnArgs = gitBash === null
72
- ? { command: 'cmd.exe', argv: ['/d', '/s', '/c', text], verbatim: true }
73
- : { command: gitBash, argv: ['-lc', text], verbatim: false }
74
-
75
- return new Promise((resolve) => {
76
- let child
77
- try {
78
- child = spawn(spawnArgs.command, spawnArgs.argv, {
79
- cwd: workdir,
80
- windowsHide: true,
81
- windowsVerbatimArguments: spawnArgs.verbatim,
82
- env: {
83
- ...process.env,
84
- // 避免交互式程序卡住
85
- GIT_TERMINAL_PROMPT: '0',
86
- GIT_ASKPASS: 'echo',
87
- GIT_PAGER: 'cat',
88
- GIT_EDITOR: 'true',
89
- PAGER: 'cat',
90
- TERM: 'dumb',
91
- LANG: 'C.UTF-8',
92
- },
93
- stdio: ['ignore', 'pipe', 'pipe'],
94
- })
95
- } catch (error) {
96
- resolve({ ok: false, error: `启动失败:${error.message}`, cwd: workdir })
97
- return
98
- }
99
-
100
- let settled = false
101
- const finish = (value) => {
102
- if (settled) return
103
- settled = true
104
- resolve(value)
105
- }
106
-
107
- const chunks = []
108
- let total = 0
109
- const collect = (chunk) => {
110
- if (total >= MAX_OUTPUT) return
111
- chunks.push(chunk)
112
- total += chunk.length
113
- }
114
- child.stdout.on('data', collect)
115
- child.stderr.on('data', collect)
116
-
117
- const decode = () => {
118
- const buffer = Buffer.concat(chunks).subarray(0, MAX_OUTPUT)
119
- const utf8 = buffer.toString('utf8')
120
- if (!utf8.includes('\uFFFD')) return utf8
121
- try {
122
- return new TextDecoder('gbk').decode(buffer)
123
- } catch {
124
- return utf8
125
- }
126
- }
127
-
128
- const timer = setTimeout(() => {
129
- try {
130
- if (process.platform === 'win32' && child.pid) {
131
- spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
132
- } else {
133
- child.kill('SIGKILL')
134
- }
135
- } catch { /* 已退出 */ }
136
- finish({ ok: false, code: null, output: decode() + '\n(超时,已终止)', cwd: workdir, timeout: true })
137
- }, DEFAULT_TIMEOUT)
138
-
139
- child.on('error', (error) => {
140
- clearTimeout(timer)
141
- finish({ ok: false, error: `启动失败:${error.message}`, cwd: workdir })
142
- })
143
- child.on('close', (code) => {
144
- clearTimeout(timer)
145
- const output = decode()
146
- finish({ ok: code === 0, code, output: output === '' ? '(无输出)' : output, cwd: workdir })
147
- })
148
- })
149
- }
150
-
151
- /** 常见命令(补全第一段用) */
152
- const COMMON_CMDS = [
153
- 'git', 'ls', 'cd', 'pwd', 'cat', 'head', 'tail', 'grep', 'find', 'rg',
154
- 'node', 'npm', 'pnpm', 'python', 'pip', 'code', 'curl', 'ssh', 'scp',
155
- 'mkdir', 'rm', 'cp', 'mv', 'echo', 'touch', 'tar', 'unzip', 'git-bash',
156
- ];
157
-
158
- /**
159
- * 补全候选:
160
- * - 光标所在段没有空格(在打命令)→ 常见命令 + 当前目录下的可执行文件
161
- * - 段里有路径成分(/ 或 \ 或 . 开头)→ 该目录下的匹配项(目录带结尾 /)
162
- * 返回 [{ value, label, kind }],页面点一下就把最后一段替换掉。
163
- */
164
- /** git 子命令(补全 git <Tab> 与 git stat<Tab> 用) */
165
- const GIT_SUBCOMMANDS = [
166
- 'add', 'am', 'apply', 'archive', 'bisect', 'blame', 'branch', 'bundle', 'checkout',
167
- 'cherry-pick', 'clean', 'clone', 'commit', 'config', 'describe', 'diff', 'fetch',
168
- 'format-patch', 'fsck', 'gc', 'grep', 'help', 'init', 'log', 'ls-files',
169
- 'ls-remote', 'merge', 'mv', 'notes', 'pull', 'push', 'rebase', 'reflog', 'remote',
170
- 'reset', 'restore', 'revert', 'rm', 'shortlog', 'show', 'stash', 'status',
171
- 'submodule', 'switch', 'tag', 'worktree',
172
- ];
173
- const GIT_BRANCH_SUBS = new Set(['checkout', 'switch', 'branch', 'merge', 'rebase', 'reset', 'diff', 'log', 'show', 'cherry-pick']);
174
- const NPM_SUBCOMMANDS = ['install', 'run', 'test', 'add', 'remove', 'update', 'exec', 'init', 'publish', 'pack', 'audit', 'list', 'version'];
175
- const PNPM_SUBCOMMANDS = ['install', 'run', 'test', 'add', 'remove', 'update', 'exec', 'init', 'publish', 'pack', 'list', 'why', 'dlx'];
176
-
177
- /** git 官方子命令清单(git --list-cmds,比手写列表全;实测约 30ms) */
178
- function gitSubcommands(cwd) {
179
- try {
180
- const result = spawnSync('git', ['--list-cmds=main,others,alias'], {
181
- cwd, encoding: 'utf8', timeout: 4000, windowsHide: true,
182
- });
183
- if (result.status !== 0) return [];
184
- return String(result.stdout).split('\n').map((line) => line.trim()).filter((line) => line !== '');
185
- } catch {
186
- return [];
187
- }
188
- }
189
-
190
- /** 仓库里的分支(同步取,用于 git checkout 的补全) */
191
- function gitBranches(cwd) {
192
- try {
193
- const result = spawnSync('git', ['branch', '-a', '--format=%(refname:short)'], {
194
- cwd, encoding: 'utf8', timeout: 4000, windowsHide: true,
195
- });
196
- if (result.status !== 0) return [];
197
- return String(result.stdout).split('\n').map((line) => line.trim()).filter((line) => line !== '' && !line.includes('HEAD'));
198
- } catch {
199
- return [];
200
- }
201
- }
202
-
203
- export function completeCandidates(cwd, line) {
204
- const text = String(line ?? '');
205
- // 最后一段(按空白切)
206
- const parts = text.split(/(\s+)/u);
207
- const last = parts.length === 0 ? '' : parts[parts.length - 1];
208
- const prefixOf = (value, prefix) => value.toLowerCase().startsWith(prefix.toLowerCase());
209
-
210
- // 命令专属补全:git 子命令/分支、npm/pnpm 子命令(真 bash 靠这些补全脚本)
211
- const beforeLast = text.slice(0, Math.max(0, text.length - last.length)).trim();
212
- if (beforeLast !== '') {
213
- const head = beforeLast.split(/\s+/u);
214
- const tool = head[0];
215
- const sub = head[1] ?? '';
216
- const push = (items) => items
217
- .filter((item) => item.toLowerCase().startsWith(last.toLowerCase()))
218
- .map((item) => ({ value: item, label: item, kind: 'cmd' }));
219
- if ((tool === 'git' || tool === 'git.exe') && head.length === 1) {
220
- const full = push(gitSubcommands(cwd));
221
- return (full.length > 0 ? full : push(GIT_SUBCOMMANDS)).slice(0, 30);
222
- }
223
- if ((tool === 'git' || tool === 'git.exe') && head.length === 2 && GIT_BRANCH_SUBS.has(sub)) {
224
- const hits = push(gitBranches(cwd));
225
- if (hits.length > 0) return hits.slice(0, 20);
226
- return push(GIT_SUBCOMMANDS).slice(0, 10);
227
- }
228
- if ((tool === 'npm' || tool === 'npm.cmd') && head.length === 1) return push(NPM_SUBCOMMANDS).slice(0, 15);
229
- if (tool === 'pnpm' && head.length === 1) return push(PNPM_SUBCOMMANDS).slice(0, 15);
230
- }
231
-
232
- // 已打了命令时,最后一段按文件名补全(cat cand<Tab> → candidate.txt);含 / \ . ~ 也算路径
233
- const isArgument = text.slice(0, text.length - last.length).trim() !== '';
234
- const pathLike = isArgument || last.includes('/') || last.includes('\\') || last.startsWith('.') || last.startsWith('~');
235
- if (pathLike) {
236
- // 没有分隔符时,目录部分是当前目录,前缀就是整段(cat cand → 当前目录的 cand*)
237
- const hasSep = /[\\/]/u.test(last);
238
- const dirPart = hasSep ? last.replace(/[\\/][^\\/]*$/u, '') : '';
239
- const basePart = hasSep ? last.slice(dirPart.length).replace(/^[\\/]/u, '') : last;
240
- const dirAbs = parseCd('cd ' + (dirPart === '' ? '.' : dirPart), cwd) ?? cwd;
241
- let names = [];
242
- try {
243
- names = fs.readdirSync(dirAbs);
244
- } catch {
245
- return [];
246
- }
247
- const out = [];
248
- for (const name of names) {
249
- if (!prefixOf(name, basePart)) continue;
250
- const full = path.join(dirAbs, name);
251
- let isDir = false;
252
- try {
253
- isDir = fs.statSync(full).isDirectory();
254
- } catch {
255
- isDir = false;
256
- }
257
- const prefix = dirPart === '' ? '' : dirPart + '/';
258
- out.push({ value: prefix + name + (isDir ? '/' : ''), label: name + (isDir ? '/' : ''), kind: isDir ? 'dir' : 'file' });
259
- if (out.length >= 30) break;
260
- }
261
- return out.sort((a, b) => (a.kind === b.kind ? a.label.localeCompare(b.label) : a.kind === 'dir' ? -1 : 1));
262
- }
263
-
264
- // 命令补全
265
- const seen = new Set();
266
- const out = [];
267
- for (const cmd of COMMON_CMDS) {
268
- if (!prefixOf(cmd, last)) continue;
269
- if (seen.has(cmd)) continue;
270
- seen.add(cmd);
271
- out.push({ value: cmd, label: cmd, kind: 'cmd' });
272
- }
273
- return out.slice(0, 20);
274
- }
@@ -1,105 +0,0 @@
1
- # DSH 看门狗:每 5 分钟检查一次,DSH 没跑就拉起来,连续不健康就重启。
2
- # 设计原则:只在"确实不健康"时动手,避免把正在启动的进程误杀。
3
- $ErrorActionPreference = 'SilentlyContinue'
4
-
5
- $root = Join-Path $env:USERPROFILE '.dsh\watchdog'
6
- New-Item -ItemType Directory -Force -Path $root | Out-Null
7
- $logFile = Join-Path $root 'watchdog.log'
8
- $stateFile = Join-Path $root 'state.json'
9
-
10
- $exe = Find-DshExe
11
- $procName = 'DeepSeek Harness'
12
-
13
- /**
14
- * 找 DeepSeek Harness 的可执行文件。
15
- * 不能写死路径:换台电脑后用户名和安装位置都可能不同。
16
- */
17
- function Find-DshExe {
18
- $candidates = @(
19
- (Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'),
20
- (Join-Path $env:ProgramFiles 'DeepSeek Harness\DeepSeek Harness.exe'),
21
- (Join-Path ${env:ProgramFiles(x86)} 'DeepSeek Harness\DeepSeek Harness.exe'),
22
- (Join-Path $env:ProgramData 'DeepSeek Harness\DeepSeek Harness.exe')
23
- )
24
- foreach ($candidate in $candidates) {
25
- if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
26
- }
27
- # 兜底:正在运行的进程能告诉我们它装在哪
28
- $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Select-Object -First 1
29
- if ($running -and $running.Path) { return $running.Path }
30
- return $null
31
- }
32
- # 健康判据:进程存在,且它自己至少有一个 LISTEN 端口。
33
- # 不写死端口号 —— DSH Web 每次启动可能换端口(实测 57291 → 56218),
34
- # 写死会把健康实例误判成故障,反复重启。
35
- $failThreshold = 3
36
- $startupGraceSeconds = 180
37
-
38
- function Write-Log([string]$message) {
39
- $line = '{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $message
40
- Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8
41
- try {
42
- $all = @(Get-Content -LiteralPath $logFile)
43
- if ($all.Count -gt 2000) {
44
- $all | Select-Object -Last 1500 | Set-Content -LiteralPath $logFile -Encoding UTF8
45
- }
46
- }
47
- catch { }
48
- }
49
-
50
- function Test-Port([int]$port) {
51
- $client = New-Object System.Net.Sockets.TcpClient
52
- try {
53
- $iar = $client.BeginConnect('127.0.0.1', $port, $null, $null)
54
- if (-not $iar.AsyncWaitHandle.WaitOne(1200)) { return $false }
55
- $client.EndConnect($iar)
56
- return $true
57
- }
58
- catch { return $false }
59
- finally { $client.Close() }
60
- }
61
-
62
- $failures = 0
63
- if (Test-Path -LiteralPath $stateFile) {
64
- try { $failures = [int](Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json).failures } catch { $failures = 0 }
65
- }
66
-
67
- $processes = @(Get-Process -Name $procName -ErrorAction SilentlyContinue)
68
-
69
- if ($processes.Count -eq 0) {
70
- Write-Log 'DSH 未运行 -> 启动'
71
- Start-Process -FilePath $exe | Out-Null
72
- $failures = 0
73
- }
74
- else {
75
- # 最新启动的那个进程刚起来的话,给足启动时间,不计数
76
- $newest = $processes | Sort-Object StartTime -Descending | Select-Object -First 1
77
- $ageSeconds = if ($newest.StartTime) { ((Get-Date) - $newest.StartTime).TotalSeconds } else { 9999 }
78
-
79
- $listening = @(Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue |
80
- Where-Object { $processes.Id -contains $_.OwningProcess } |
81
- Select-Object -ExpandProperty LocalPort -Unique)
82
- $down = if ($listening.Count -eq 0) { @('none') } else { @() }
83
-
84
- if ($down.Count -eq 0) {
85
- if ($failures -ne 0) { Write-Log "已恢复正常(之前累计 $failures 次)" } else { Write-Log '检查: 健康' }
86
- $failures = 0
87
- }
88
- elseif ($ageSeconds -lt $startupGraceSeconds) {
89
- Write-Log ('启动中,暂不计数(已运行 {0:N0} 秒,缺端口 {1})' -f $ageSeconds, ($down -join ','))
90
- }
91
- else {
92
- $failures += 1
93
- Write-Log ('没有任何监听端口(连续第 {0} 次)' -f $failures)
94
- if ($failures -ge $failThreshold) {
95
- Write-Log "连续 $failThreshold 次不健康 -> 重启 DSH"
96
- $processes | Stop-Process -Force
97
- Start-Sleep -Seconds 5
98
- Start-Process -FilePath $exe | Out-Null
99
- $failures = 0
100
- }
101
- }
102
- }
103
-
104
- @{ failures = $failures; checkedAt = (Get-Date).ToString('o') } | ConvertTo-Json |
105
- Set-Content -LiteralPath $stateFile -Encoding UTF8
@@ -1,7 +0,0 @@
1
- ' ???? restart-now.ps1?????????????????????
2
- Set shell = CreateObject("WScript.Shell")
3
- cmd = "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ""C:\Users\andyi\.dsh\watchdog\restart-now.ps1"""
4
- For Each a In WScript.Arguments
5
- cmd = cmd & " """ & a & """"
6
- Next
7
- shell.Run cmd, 0, False
@@ -1,261 +0,0 @@
1
- # 一次性重启 DSH:由计划任务(或手动)独立执行,不依赖被重启的进程本身。
2
- #
3
- # 两种模式(关键区别就是"等多久"):
4
- # -Mode immediate 用户说了"立马重启":这边一空下来(没有在途对话、没有键盘/点击活动)
5
- # 就立刻重启,安静阈值默认 3 秒。
6
- # -Mode default 默认保守模式:安静 120 秒才算空闲,宁可晚一点也不打断。
7
- #
8
- # 用法:
9
- # powershell -File restart-now.ps1 -Mode immediate -Reason "部署 v1.15.0"
10
- # powershell -File restart-now.ps1 # 等同 -Mode default
11
- # powershell -File restart-now.ps1 -Check # 只体检,不杀不启(安全)
12
- # powershell -File restart-now.ps1 -DryRun # 走完整逻辑但不杀不启
13
- #
14
- # 流程:抢锁 -> **等空闲** -> 优雅关闭 -> 强杀兜底 -> 等端口释放 -> 启动 -> 等就绪 -> 写日志 -> 删任务 -> 放锁
15
- #
16
- # 硬规则(都是被坑出来的):
17
- # 1. 同一时刻只允许一个重启在跑(restart.lock),否则会出现两个实例抢 8787;
18
- # 2. 端口没释放干净就**不要启动**(宁可失败也不要 EADDRINUSE 半死不活);
19
- # 3. 每次重启都记录触发原因,方便事后看"到底谁让它重启的";
20
- # 4. **用户还在操作就不许重启**:会话文件在写、或手机端还在敲键盘/滑动(activity.json 信标),
21
- # 都算"忙";等不到空闲就放弃(人可以再叫一次)。
22
- param(
23
- [switch]$Check,
24
- [switch]$DryRun,
25
- [ValidateSet('immediate', 'default')]
26
- [string]$Mode = 'default',
27
- [string]$Reason = '未注明',
28
- [int]$IdleSeconds = -1,
29
- [int]$MaxWaitMinutes = 10
30
- )
31
-
32
- $ErrorActionPreference = 'SilentlyContinue'
33
-
34
- $root = Join-Path $env:USERPROFILE '.dsh\watchdog'
35
- $log = Join-Path $root 'restart.log'
36
- $lockFile = Join-Path $root 'restart.lock'
37
- $sessionsDir = Join-Path $env:USERPROFILE '.dsh\storages\session_projcache\sessions'
38
- $activityFile = Join-Path $env:USERPROFILE '.dsh\integrations\dsh-mobile\activity.json'
39
- $exe = Find-DshExe
40
- $procName = 'DeepSeek Harness'
41
-
42
- /**
43
- * 找 DeepSeek Harness 的可执行文件。
44
- * 不能写死路径:换台电脑后用户名和安装位置都可能不同。
45
- */
46
- function Find-DshExe {
47
- $candidates = @(
48
- (Join-Path $env:LOCALAPPDATA 'Programs\DeepSeek Harness\DeepSeek Harness.exe'),
49
- (Join-Path $env:ProgramFiles 'DeepSeek Harness\DeepSeek Harness.exe'),
50
- (Join-Path ${env:ProgramFiles(x86)} 'DeepSeek Harness\DeepSeek Harness.exe'),
51
- (Join-Path $env:ProgramData 'DeepSeek Harness\DeepSeek Harness.exe')
52
- )
53
- foreach ($candidate in $candidates) {
54
- if ($candidate -and (Test-Path -LiteralPath $candidate)) { return $candidate }
55
- }
56
- # 兜底:正在运行的进程能告诉我们它装在哪
57
- $running = Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Select-Object -First 1
58
- if ($running -and $running.Path) { return $running.Path }
59
- return $null
60
- }
61
- $bridgePort = 8787
62
-
63
- # 安静阈值:immediate 只要 3 秒(用户明确要求"一空闲就重启"),default 保持 120 秒
64
- if ($IdleSeconds -lt 0) {
65
- $IdleSeconds = if ($Mode -eq 'immediate') { 3 } else { 120 }
66
- }
67
-
68
- # 两个活动信号取"最近的":
69
- # - 会话 json 的修改时间:一轮对话在跑时会不断更新
70
- # - activity.json:手机端键盘/触摸信标(打字时不会改会话文件,只有这个能反映"人在用")
71
- function Get-Activity {
72
- $age = 99999
73
- $source = 'none'
74
- if (Test-Path $sessionsDir) {
75
- $newest = Get-ChildItem -LiteralPath $sessionsDir -Filter *.json -ErrorAction SilentlyContinue |
76
- Sort-Object LastWriteTime -Descending | Select-Object -First 1
77
- if ($newest) { $age = ((Get-Date) - $newest.LastWriteTime).TotalSeconds; $source = 'session:' + $newest.Name }
78
- }
79
- if (Test-Path $activityFile) {
80
- $stamp = (Get-Item $activityFile).LastWriteTime
81
- $age2 = ((Get-Date) - $stamp).TotalSeconds
82
- if ($age2 -lt $age) { $age = $age2; $source = 'beacon' }
83
- }
84
- return @{ ageSeconds = $age; source = $source }
85
- }
86
-
87
- function Test-Idle {
88
- $activity = Get-Activity
89
- return @{ idle = ($activity.ageSeconds -ge $IdleSeconds); age = $activity.ageSeconds; source = $activity.source }
90
- }
91
-
92
-
93
- function Write-Log([string]$message) {
94
- $line = '{0} {1}' -f (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'), $message
95
- Add-Content -LiteralPath $log -Value $line -Encoding UTF8
96
- }
97
-
98
- function Test-Port([int]$port) {
99
- $client = New-Object System.Net.Sockets.TcpClient
100
- try {
101
- $iar = $client.BeginConnect('127.0.0.1', $port, $null, $null)
102
- if (-not $iar.AsyncWaitHandle.WaitOne(1000)) { return $false }
103
- $client.EndConnect($iar)
104
- return $true
105
- }
106
- catch { return $false }
107
- finally { $client.Close() }
108
- }
109
-
110
- function Get-DshProcesses {
111
- return @(Get-Process -Name $procName -ErrorAction SilentlyContinue)
112
- }
113
-
114
- # ---------- 体检模式:只看状态,不动任何东西 ----------
115
- if ($Check) {
116
- $procs = Get-DshProcesses
117
- Write-Output ("进程数: " + $procs.Count)
118
- $procs | ForEach-Object { Write-Output (" PID " + $_.Id + " 启动 " + $_.StartTime) }
119
- Write-Output ("8787 监听: " + (Test-Port $bridgePort))
120
- $idle = Test-Idle
121
- Write-Output ("活动信号: 最近 {0:N0} 秒前(来源 {1}) -> {2}" -f $idle.age, $idle.source, $(if ($idle.idle) { '空闲,可重启' } else { '活跃,不应重启' }))
122
- Write-Output ("判定阈值: 空闲需静默 " + $IdleSeconds + " 秒")
123
- Write-Output ("锁文件存在: " + (Test-Path $lockFile))
124
- $task = Get-ScheduledTask -TaskName 'DSH-Restart-Now' -ErrorAction SilentlyContinue
125
- Write-Output ("待执行重启任务: " + $(if ($task) { $task.State } else { '无' }))
126
- Write-Output ("最近一次重启: " + ((Get-Content $log -Tail 1) -join ''))
127
- exit 0
128
- }
129
-
130
- # ---------- 抢锁:防止两个重启同时跑 ----------
131
- # 特例:immediate 允许**抢占**正在等待的 default。
132
- # 场景:先排了 default 在等 120 秒空闲,用户改口"立马重启"——不该被锁挡回去,
133
- # 而应停掉那个等待中的进程,立刻按立即模式执行。
134
- if (Test-Path $lockFile) {
135
- $age = (Get-Date) - (Get-Item $lockFile).LastWriteTime
136
- if ($age.TotalSeconds -lt 180) {
137
- if ($Mode -eq 'immediate') {
138
- Write-Log ('立即模式抢占:停掉正在等待的重启(锁 {0:N0} 秒前创建)' -f $age.TotalSeconds)
139
- $mine = $PID
140
- Get-CimInstance Win32_Process -Filter "Name = 'powershell.exe'" -ErrorAction SilentlyContinue |
141
- Where-Object { $_.CommandLine -like '*restart-now.ps1*' -and $_.ProcessId -ne $mine } |
142
- ForEach-Object {
143
- Write-Log (' 终止等待进程 PID ' + $_.ProcessId)
144
- Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
145
- }
146
- Start-Sleep -Seconds 1
147
- Remove-Item $lockFile -Force -ErrorAction SilentlyContinue
148
- }
149
- else {
150
- Write-Log ("跳过:已有重启在进行(锁 {0:N0} 秒前创建;要抢占请用 -Mode immediate)" -f $age.TotalSeconds)
151
- exit 1
152
- }
153
- }
154
- else {
155
- Write-Log ("清理过期锁({0:N0} 秒前)" -f $age.TotalSeconds)
156
- Remove-Item $lockFile -Force -ErrorAction SilentlyContinue
157
- }
158
- }
159
- Set-Content -LiteralPath $lockFile -Value (Get-Date -Format 'o') -Encoding UTF8
160
-
161
- try {
162
- Write-Log ("=== 重启请求(模式:{0},安静阈值 {1}s,原因:{2}){3}===" -f $Mode, $IdleSeconds, $Reason, $(if ($DryRun) { ' [DryRun]' } else { '' }))
163
-
164
- # ---------- 关键:等会话空闲,别在别人对话中途把进程杀掉 ----------
165
- $waitStart = Get-Date
166
- $deferred = $false
167
- while ($true) {
168
- $idle = Test-Idle
169
- if ($idle.idle) {
170
- Write-Log ("已空闲(最近活动 {0:N0} 秒前,来源 {1},阈值 {2} 秒)-> 继续重启" -f $idle.age, $idle.source, $IdleSeconds)
171
- break
172
- }
173
- $waited = ((Get-Date) - $waitStart).TotalMinutes
174
- if ($waited -ge $MaxWaitMinutes) {
175
- Write-Log ("放弃重启:仍在活跃(最近活动 {0:N0} 秒前,来源 {1},已等待 {2:N1} 分钟)" -f $idle.age, $idle.source, $waited)
176
- Write-Log '=== 重启结束(因会话活跃而放弃)==='
177
- $deferred = $true
178
- break
179
- }
180
- if ($waited -eq 0 -or [int]($waited * 4) -ne [int](($waited - 0.05) * 4)) {
181
- Write-Log ("等空闲…(最近活动 {0:N0} 秒前,来源 {1},已等 {2:N0} 秒)" -f $idle.age, $idle.source, ($waited * 60))
182
- }
183
- Start-Sleep -Seconds 15
184
- }
185
- if ($deferred) { exit 2 }
186
-
187
- if ($DryRun) {
188
- $procs = Get-DshProcesses
189
- Write-Log ("[DryRun] 到这里会关闭 {0} 个进程并重启;本次不执行" -f $procs.Count)
190
- Write-Log '=== 重启结束(DryRun)==='
191
- exit 0
192
- }
193
-
194
- $before = Get-DshProcesses
195
- Write-Log ("关闭前进程数:{0}" -f $before.Count)
196
-
197
- if ($before.Count -gt 0) {
198
- $before | ForEach-Object { $_.CloseMainWindow() | Out-Null }
199
- Start-Sleep -Seconds 4
200
- $left = Get-DshProcesses
201
- if ($left.Count -gt 0) {
202
- # 先杀 Electron 主进程(根):否则它把 Host 退出当崩溃,弹原生对话框+提示音
203
- $ids = @($left | ForEach-Object { $_.Id })
204
- $cim = @(Get-CimInstance Win32_Process -Filter ("Name = '" + $procName + ".exe'") -ErrorAction SilentlyContinue)
205
- $roots = @($cim | Where-Object { $ids -notcontains $_.ParentProcessId })
206
- foreach ($root in $roots) { Write-Log ('先终止主进程 PID ' + $root.ProcessId); Stop-Process -Id $root.ProcessId -Force -ErrorAction SilentlyContinue }
207
- if ($roots.Count -gt 0) { $w = 0; while ($w -lt 20 -and (Get-DshProcesses).Count -gt 0) { Start-Sleep -Milliseconds 250; $w += 1 } }
208
- $rest = Get-DshProcesses
209
- if ($rest.Count -gt 0) { Write-Log ('再终止其余 ' + $rest.Count + ' 个进程'); $rest | Stop-Process -Force -ErrorAction SilentlyContinue; Start-Sleep -Seconds 3 }
210
- }
211
- }
212
- $still = Get-DshProcesses
213
- Write-Log ("关闭后进程数:{0}" -f $still.Count)
214
-
215
- # 端口必须释放干净;释放不了就失败退出,绝不硬起第二个实例
216
- $waited = 0
217
- while ($waited -lt 60 -and (Test-Port $bridgePort)) {
218
- Start-Sleep -Milliseconds 500
219
- $waited += 1
220
- }
221
- if (Test-Port $bridgePort) {
222
- Write-Log ("失败:8787 仍被占用(等待 {0} 次),已放弃启动以避免双实例" -f $waited)
223
- Write-Log '=== 重启结束(失败)==='
224
- exit 1
225
- }
226
- Write-Log ("8787 已释放(等待 {0} 次)" -f $waited)
227
-
228
- Start-Process -FilePath $exe
229
- Write-Log '已发起启动'
230
- # 等窗口:拿到 MainWindowHandle 才算真的起来了
231
- $winWait = 0
232
- $haveWindow = $false
233
- while ($winWait -lt 40) {
234
- Start-Sleep -Milliseconds 500
235
- $winWait += 1
236
- $live = Get-Process -Name $procName -ErrorAction SilentlyContinue
237
- if (@($live | Where-Object { $_.MainWindowHandle -ne 0 }).Count -gt 0) { $haveWindow = $true; break }
238
- }
239
- if ($haveWindow) { Write-Log ('窗口已出现(等待 ' + $winWait + ' 次)') } else { Write-Log ('已启动但未拿到窗口(等待 ' + $winWait + ' 次)—— relaunched-no-window') }
240
-
241
- # 就绪判断:进程活着 + 8787 在听
242
- $ok = $false
243
- for ($i = 0; $i -lt 120; $i += 1) {
244
- Start-Sleep -Seconds 1
245
- if ((Get-DshProcesses).Count -gt 0 -and (Test-Port $bridgePort)) { $ok = $true; break }
246
- }
247
- $main = Get-DshProcesses | Sort-Object StartTime | Select-Object -First 1
248
- Write-Log ("启动结果:{0};首次进程启动时间 {1};8787 监听 {2}" -f `
249
- $(if ($ok) { '成功' } else { '超时未就绪' }), $main.StartTime, (Test-Port $bridgePort))
250
-
251
- $entry = Join-Path $env:USERPROFILE '.dsh\integrations\dsh-mobile\entry.txt'
252
- if (Test-Path $entry) {
253
- Write-Log ("entry.txt 更新时间:{0}" -f (Get-Item $entry).LastWriteTime)
254
- }
255
- Write-Log '=== 重启结束 ==='
256
- }
257
- finally {
258
- Remove-Item $lockFile -Force
259
- # 无论成功失败都删掉一次性任务,避免下次意外又触发
260
- schtasks /Delete /TN 'DSH-Restart-Now' /F 2>$null | Out-Null
261
- }
@@ -1,4 +0,0 @@
1
- ' ?? WScript ?????????? PowerShell ????????????????????
2
- Set shell = CreateObject("WScript.Shell")
3
- script = WScript.Arguments(0)
4
- shell.Run "powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File """ & script & """", 0, False