@leiyi-works/dsh-auto-restart 0.1.0 → 0.1.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 +23 -10
- package/client.js +427 -0
- package/index.js +194 -93
- package/lib/restart-supervisor.ps1 +46 -3
- package/package.json +15 -2
package/README.md
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
# dsh-auto-restart · 自动重启
|
|
2
2
|
|
|
3
|
-
装完/更新完插件后,不用再自己关掉 DSH
|
|
3
|
+
装完/更新完插件后,不用再自己关掉 DSH 再打开:它会发现插件文件变了,等所有会话空闲,然后把整个桌面应用重启一次,回到原来的会话,**窗口默认最大化**。
|
|
4
4
|
|
|
5
5
|
只支持 **Windows 桌面端**(Electron 外壳 + Host 子进程的形态)。`dsh web` / headless 不会重启(插件会写日志说明不支持)。
|
|
6
6
|
|
|
7
|
+
左侧菜单有一个「自动重启」面板:状态、上次重启回执、开关与参数都在那里改,改完即时生效。
|
|
8
|
+
|
|
7
9
|
## 它怎么判断"插件变了"
|
|
8
10
|
|
|
9
11
|
盯着当前 profile 的这几处,每 2 秒取一次指纹:
|
|
@@ -19,22 +21,31 @@
|
|
|
19
21
|
1. 等所有会话空闲(`api-session/status` + `agent/status`),默认最多等 2 分钟;
|
|
20
22
|
2. 等插件管理器安静 3 秒(不打断进行中的安装/更新);
|
|
21
23
|
3. 由 WMI 起一个**脱离进程树、隐藏控制台**的 PowerShell 守护进程;
|
|
22
|
-
4. 守护进程等 `restartDelayMs`(默认 2 秒)→ **先杀 Electron 主进程**(否则 Host 先退出会让主进程弹「DeepSeek Harness 无法使用」并响一声)→ 清掉残留应用进程 → `Start-Process` 拉起应用 → 等主窗口出现 → 写回执。
|
|
24
|
+
4. 守护进程等 `restartDelayMs`(默认 2 秒)→ **先杀 Electron 主进程**(否则 Host 先退出会让主进程弹「DeepSeek Harness 无法使用」并响一声)→ 清掉残留应用进程 → `Start-Process` 拉起应用 → 等主窗口出现 → 按 `maximizeOnRestart` 把窗口最大化 → 写回执。
|
|
23
25
|
|
|
24
|
-
|
|
26
|
+
会话记录在磁盘上,重启后回到同一个会话。**没有每小时次数上限**,只有 60 秒冷却防止连环重启。
|
|
25
27
|
|
|
26
28
|
## 安装后第一次
|
|
27
29
|
|
|
28
30
|
第一次安装需要手动重启一次 DSH(托盘「退出」再打开),让 Host 半边的代码加载。之后就不用再管了。
|
|
29
31
|
|
|
30
|
-
**首次默认 `dryRun: true`**:只写日志、不真重启。确认日志里看到「检测到插件文件变化」和「[dry-run]
|
|
31
|
-
|
|
32
|
-
```json
|
|
33
|
-
{ "dryRun": false }
|
|
34
|
-
```
|
|
32
|
+
**首次默认 `dryRun: true`**:只写日志、不真重启。确认日志里看到「检测到插件文件变化」和「[dry-run] 本应重启」之后,在左侧「自动重启」面板里关掉试运行即可(也可以在 `config.json` 里把 `dryRun` 改成 `false`,改完即时生效,不用重启)。
|
|
35
33
|
|
|
36
34
|
配置文件:`%USERPROFILE%\.dsh\dsh-auto-restart\config.json`(也可以放 `~/...` 形式的可移植路径)。
|
|
37
35
|
|
|
36
|
+
## 左侧面板
|
|
37
|
+
|
|
38
|
+
| 控件 | 说明 |
|
|
39
|
+
|---|---|
|
|
40
|
+
| 启用自动重启 | 总开关 |
|
|
41
|
+
| 试运行(dryRun) | 只记日志不重启 |
|
|
42
|
+
| 重启后最大化窗口 | 守护进程拉起应用后把主窗口最大化 |
|
|
43
|
+
| 等所有会话空闲再重启 | 有回答在跑时先等 |
|
|
44
|
+
| 文件稳定判定 | 默认 10 秒 |
|
|
45
|
+
| 两次重启冷却 | 默认 60 秒 |
|
|
46
|
+
| 等空闲上限 | 默认 120 秒,超时放弃本次 |
|
|
47
|
+
| 立即重启 | 手动触发一次(有会话在跑时会被拒绝) |
|
|
48
|
+
|
|
38
49
|
## 配置
|
|
39
50
|
|
|
40
51
|
| 键 | 默认 | 说明 |
|
|
@@ -45,11 +56,12 @@
|
|
|
45
56
|
| `pollIntervalMs` | `2000` | 轮询间隔 |
|
|
46
57
|
| `managerQuietMs` | `3000` | 插件管理器最后一次活动后至少安静多久 |
|
|
47
58
|
| `cooldownMs` | `60000` | 两次重启最小间隔(跨重启持久化) |
|
|
48
|
-
| `maxPerHour` | `
|
|
59
|
+
| `maxPerHour` | `0` | 每小时上限;`0` = 不限制 |
|
|
49
60
|
| `waitForIdle` | `true` | 等会话空闲再重启 |
|
|
50
61
|
| `maxIdleWaitMs` | `120000` | 等空闲上限,超时放弃本次 |
|
|
51
62
|
| `forceWhenBusy` | `false` | 超时后是否强重启 |
|
|
52
63
|
| `restartDelayMs` | `2000` | 守护进程收到请求后等多久动手 |
|
|
64
|
+
| `maximizeOnRestart` | `true` | 重启后最大化主窗口 |
|
|
53
65
|
| `exePath` | `''` | 应用可执行文件,留空自动推导 |
|
|
54
66
|
| `launchArgs` | `[]` | 拉起应用时的附加参数 |
|
|
55
67
|
| `supervisorScript` | `''` | 自定义守护脚本路径 |
|
|
@@ -65,7 +77,8 @@
|
|
|
65
77
|
|
|
66
78
|
- 日志:`%USERPROFILE%\.dsh\dsh-auto-restart\auto-restart.log`
|
|
67
79
|
- 上次重启回执:`restart-result.json`;上次请求:`last-restart.json`
|
|
68
|
-
- 状态:`GET http://127.0.0.1:<Host 端口>/auto-restart/status
|
|
80
|
+
- 状态:`GET http://127.0.0.1:<Host 端口>/auto-restart/status`(只接受本机回环)
|
|
81
|
+
- 配置:`GET/POST /auto-restart/config`
|
|
69
82
|
|
|
70
83
|
## 卸载
|
|
71
84
|
|
package/client.js
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-auto-restart — Client half.
|
|
3
|
+
*
|
|
4
|
+
* 左侧菜单一个「自动重启」入口,打开全页面板;面板读写 Host 的
|
|
5
|
+
* /auto-restart 路由:
|
|
6
|
+
* GET /auto-restart/status 运行状态、基线、上次重启回执
|
|
7
|
+
* GET /auto-restart/config 当前生效配置
|
|
8
|
+
* POST /auto-restart/config 保存配置(只提交改动的键)
|
|
9
|
+
* POST /auto-restart/restart 立即重启(有会话在跑时由 Host 拒绝)
|
|
10
|
+
*
|
|
11
|
+
* 面板只做展示与改配置,真正的重启由 Host + 守护进程完成。
|
|
12
|
+
*/
|
|
13
|
+
window.__ModuleLoader__.load({
|
|
14
|
+
id: '@leiyi-works/dsh-auto-restart',
|
|
15
|
+
factory(require) {
|
|
16
|
+
const React = require('react')
|
|
17
|
+
const h = React.createElement
|
|
18
|
+
const { useCallback, useEffect, useRef, useState } = React
|
|
19
|
+
|
|
20
|
+
/** Global panel id shared by the sidebar row and the main page. */
|
|
21
|
+
const PANEL_ID = 'auto-restart'
|
|
22
|
+
const API = '/auto-restart'
|
|
23
|
+
const REFRESH_MS = 5000
|
|
24
|
+
|
|
25
|
+
const styles = {
|
|
26
|
+
root: {
|
|
27
|
+
height: '100%',
|
|
28
|
+
overflow: 'auto',
|
|
29
|
+
boxSizing: 'border-box',
|
|
30
|
+
padding: '14px 16px 28px',
|
|
31
|
+
color: 'var(--dsw-alias-label-primary)',
|
|
32
|
+
fontSize: 13,
|
|
33
|
+
lineHeight: 1.55,
|
|
34
|
+
},
|
|
35
|
+
inner: { display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 760 },
|
|
36
|
+
header: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' },
|
|
37
|
+
title: { margin: 0, fontSize: 16, fontWeight: 600 },
|
|
38
|
+
badge: {
|
|
39
|
+
fontSize: 11,
|
|
40
|
+
lineHeight: '18px',
|
|
41
|
+
padding: '0 8px',
|
|
42
|
+
borderRadius: 999,
|
|
43
|
+
background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,.10))',
|
|
44
|
+
color: 'var(--dsw-alias-label-secondary)',
|
|
45
|
+
},
|
|
46
|
+
badgeGood: {
|
|
47
|
+
fontSize: 11,
|
|
48
|
+
lineHeight: '18px',
|
|
49
|
+
padding: '0 8px',
|
|
50
|
+
borderRadius: 999,
|
|
51
|
+
background: 'rgba(46,160,67,.16)',
|
|
52
|
+
color: 'var(--dsw-alias-state-success-primary, #2ea043)',
|
|
53
|
+
},
|
|
54
|
+
badgeWarn: {
|
|
55
|
+
fontSize: 11,
|
|
56
|
+
lineHeight: '18px',
|
|
57
|
+
padding: '0 8px',
|
|
58
|
+
borderRadius: 999,
|
|
59
|
+
background: 'rgba(210,120,0,.16)',
|
|
60
|
+
color: 'var(--dsw-alias-state-warning-primary, #c27c00)',
|
|
61
|
+
},
|
|
62
|
+
subtitle: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
|
|
63
|
+
card: {
|
|
64
|
+
display: 'flex',
|
|
65
|
+
flexDirection: 'column',
|
|
66
|
+
gap: 10,
|
|
67
|
+
border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.22))',
|
|
68
|
+
borderRadius: 10,
|
|
69
|
+
padding: '12px 14px',
|
|
70
|
+
background: 'var(--dsw-alias-bg-layer-2, rgba(127,127,127,.04))',
|
|
71
|
+
},
|
|
72
|
+
cardTitle: { margin: 0, fontSize: 13, fontWeight: 600 },
|
|
73
|
+
row: { display: 'flex', alignItems: 'center', gap: 10, justifyContent: 'space-between' },
|
|
74
|
+
rowMain: { display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 },
|
|
75
|
+
rowLabel: { fontSize: 13 },
|
|
76
|
+
rowHint: { fontSize: 11.5, color: 'var(--dsw-alias-label-secondary)' },
|
|
77
|
+
kvs: { display: 'grid', gridTemplateColumns: 'auto 1fr', columnGap: 12, rowGap: 4, fontSize: 12 },
|
|
78
|
+
key: { color: 'var(--dsw-alias-label-secondary)' },
|
|
79
|
+
val: { fontFamily: 'ui-monospace, Consolas, monospace', fontSize: 11.5, wordBreak: 'break-all' },
|
|
80
|
+
switch: { width: 16, height: 16, accentColor: 'var(--dsw-alias-accent-primary, #4f7cff)', cursor: 'pointer' },
|
|
81
|
+
num: {
|
|
82
|
+
width: 92,
|
|
83
|
+
padding: '3px 8px',
|
|
84
|
+
borderRadius: 7,
|
|
85
|
+
border: '1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.35))',
|
|
86
|
+
background: 'transparent',
|
|
87
|
+
color: 'var(--dsw-alias-label-primary)',
|
|
88
|
+
fontSize: 12,
|
|
89
|
+
},
|
|
90
|
+
btn: {
|
|
91
|
+
appearance: 'none',
|
|
92
|
+
cursor: 'pointer',
|
|
93
|
+
borderRadius: 7,
|
|
94
|
+
padding: '5px 14px',
|
|
95
|
+
fontSize: 12,
|
|
96
|
+
lineHeight: '18px',
|
|
97
|
+
border: '1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.35))',
|
|
98
|
+
background: 'transparent',
|
|
99
|
+
color: 'var(--dsw-alias-label-primary)',
|
|
100
|
+
},
|
|
101
|
+
btnPrimary: {
|
|
102
|
+
appearance: 'none',
|
|
103
|
+
cursor: 'pointer',
|
|
104
|
+
borderRadius: 7,
|
|
105
|
+
padding: '5px 14px',
|
|
106
|
+
fontSize: 12,
|
|
107
|
+
lineHeight: '18px',
|
|
108
|
+
border: '1px solid var(--dsw-alias-accent-primary, #4f7cff)',
|
|
109
|
+
background: 'var(--dsw-alias-accent-primary, #4f7cff)',
|
|
110
|
+
color: '#fff',
|
|
111
|
+
},
|
|
112
|
+
bar: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' },
|
|
113
|
+
note: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
|
|
114
|
+
ok: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-state-success-primary, #2ea043)' },
|
|
115
|
+
err: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-state-error-primary, #d14a4a)' },
|
|
116
|
+
loading: { margin: 0, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function fmtTime(iso) {
|
|
120
|
+
if (typeof iso !== 'string' || iso === '') return '—'
|
|
121
|
+
try {
|
|
122
|
+
const date = new Date(iso)
|
|
123
|
+
if (Number.isNaN(date.getTime())) return iso
|
|
124
|
+
const two = (n) => String(n).padStart(2, '0')
|
|
125
|
+
return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}:${two(date.getSeconds())}`
|
|
126
|
+
} catch {
|
|
127
|
+
return iso
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function phaseLabel(phase) {
|
|
132
|
+
if (phase === 'relaunched') return '成功(窗口已出现)'
|
|
133
|
+
if (phase === 'relaunched-no-window') return '已拉起,但没等到窗口'
|
|
134
|
+
if (phase === 'stopped') return '进行中(旧进程已停)'
|
|
135
|
+
if (phase === 'aborted') return '已中止'
|
|
136
|
+
if (phase === 'failed') return '失败'
|
|
137
|
+
return phase === undefined || phase === null ? '—' : String(phase)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function getJson(url) {
|
|
141
|
+
const response = await fetch(url, { headers: { accept: 'application/json' } })
|
|
142
|
+
const body = await response.json().catch(() => ({}))
|
|
143
|
+
if (!response.ok || body.ok === false) throw new Error(body.error ?? `HTTP ${response.status}`)
|
|
144
|
+
return body
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function postJson(url, payload) {
|
|
148
|
+
const response = await fetch(url, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { 'content-type': 'application/json', 'x-dsh-auto-restart': '1' },
|
|
151
|
+
body: JSON.stringify(payload ?? {}),
|
|
152
|
+
})
|
|
153
|
+
const body = await response.json().catch(() => ({}))
|
|
154
|
+
if (!response.ok || body.ok === false) throw new Error(body.error ?? `HTTP ${response.status}`)
|
|
155
|
+
return body
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function SwitchRow({ label, hint, checked, onChange, disabled }) {
|
|
159
|
+
return h(
|
|
160
|
+
'div',
|
|
161
|
+
{ style: styles.row },
|
|
162
|
+
h('div', { style: styles.rowMain }, h('div', { style: styles.rowLabel }, label), hint ? h('div', { style: styles.rowHint }, hint) : null),
|
|
163
|
+
h('input', {
|
|
164
|
+
type: 'checkbox',
|
|
165
|
+
style: styles.switch,
|
|
166
|
+
checked: checked === true,
|
|
167
|
+
disabled: disabled === true,
|
|
168
|
+
onChange: (event) => onChange(event.target.checked),
|
|
169
|
+
}),
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function NumberRow({ label, hint, value, min, max, step, suffix, onChange, disabled }) {
|
|
174
|
+
return h(
|
|
175
|
+
'div',
|
|
176
|
+
{ style: styles.row },
|
|
177
|
+
h('div', { style: styles.rowMain }, h('div', { style: styles.rowLabel }, label), hint ? h('div', { style: styles.rowHint }, hint) : null),
|
|
178
|
+
h(
|
|
179
|
+
'span',
|
|
180
|
+
{ style: { display: 'flex', alignItems: 'center', gap: 6 } },
|
|
181
|
+
h('input', {
|
|
182
|
+
type: 'number',
|
|
183
|
+
style: styles.num,
|
|
184
|
+
value: Number.isFinite(value) ? Math.round(value) : 0,
|
|
185
|
+
min,
|
|
186
|
+
max,
|
|
187
|
+
step: step ?? 1,
|
|
188
|
+
disabled: disabled === true,
|
|
189
|
+
onChange: (event) => onChange(Number(event.target.value)),
|
|
190
|
+
}),
|
|
191
|
+
h('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, suffix ?? ''),
|
|
192
|
+
),
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function AutoRestartPanel() {
|
|
197
|
+
const [state, setState] = useState({ loading: true, error: '', status: null, config: null })
|
|
198
|
+
const [save, setSave] = useState({ busy: false, error: '', ok: '' })
|
|
199
|
+
const [restarting, setRestarting] = useState(false)
|
|
200
|
+
const dirty = useRef(false)
|
|
201
|
+
|
|
202
|
+
const load = useCallback(async () => {
|
|
203
|
+
try {
|
|
204
|
+
const [status, config] = await Promise.all([getJson(`${API}/status`), getJson(`${API}/config`)])
|
|
205
|
+
setState({ loading: false, error: '', status, config: config.config })
|
|
206
|
+
} catch (error) {
|
|
207
|
+
setState((current) => ({ ...current, loading: false, error: String(error?.message ?? error) }))
|
|
208
|
+
}
|
|
209
|
+
}, [])
|
|
210
|
+
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
load()
|
|
213
|
+
const timer = setInterval(() => {
|
|
214
|
+
if (!dirty.current) load()
|
|
215
|
+
}, REFRESH_MS)
|
|
216
|
+
return () => clearInterval(timer)
|
|
217
|
+
}, [load])
|
|
218
|
+
|
|
219
|
+
const saveConfig = useCallback(async (patch) => {
|
|
220
|
+
dirty.current = false
|
|
221
|
+
setSave({ busy: true, error: '', ok: '' })
|
|
222
|
+
try {
|
|
223
|
+
const body = await postJson(`${API}/config`, patch)
|
|
224
|
+
setState((current) => ({ ...current, config: body.config }))
|
|
225
|
+
setSave({ busy: false, error: '', ok: '已保存' })
|
|
226
|
+
setTimeout(() => setSave((current) => (current.ok === '已保存' ? { busy: false, error: '', ok: '' } : current)), 2500)
|
|
227
|
+
} catch (error) {
|
|
228
|
+
setSave({ busy: false, error: String(error?.message ?? error), ok: '' })
|
|
229
|
+
}
|
|
230
|
+
}, [])
|
|
231
|
+
|
|
232
|
+
const change = useCallback((patch) => {
|
|
233
|
+
dirty.current = true
|
|
234
|
+
setState((current) => (current.config === null ? current : { ...current, config: { ...current.config, ...patch } }))
|
|
235
|
+
saveConfig(patch)
|
|
236
|
+
}, [saveConfig])
|
|
237
|
+
|
|
238
|
+
const restartNow = useCallback(async () => {
|
|
239
|
+
setRestarting(true)
|
|
240
|
+
setSave({ busy: false, error: '', ok: '' })
|
|
241
|
+
try {
|
|
242
|
+
const body = await postJson(`${API}/restart`, {})
|
|
243
|
+
setSave({
|
|
244
|
+
busy: false,
|
|
245
|
+
error: '',
|
|
246
|
+
ok: body.dryRun === true ? '当前是试运行模式,只记录了日志,没有真的重启' : '已派发重启,DSH 会在这条消息送达后关闭并重新打开',
|
|
247
|
+
})
|
|
248
|
+
} catch (error) {
|
|
249
|
+
setSave({ busy: false, error: String(error?.message ?? error), ok: '' })
|
|
250
|
+
} finally {
|
|
251
|
+
setRestarting(false)
|
|
252
|
+
}
|
|
253
|
+
}, [])
|
|
254
|
+
|
|
255
|
+
const status = state.status
|
|
256
|
+
const config = state.config
|
|
257
|
+
const badge = config === null
|
|
258
|
+
? h('span', { style: styles.badge }, '读取中')
|
|
259
|
+
: config.enabled === false
|
|
260
|
+
? h('span', { style: styles.badgeWarn }, '已停用')
|
|
261
|
+
: config.dryRun === true
|
|
262
|
+
? h('span', { style: styles.badgeWarn }, '试运行(只记日志)')
|
|
263
|
+
: h('span', { style: styles.badgeGood }, '运行中')
|
|
264
|
+
|
|
265
|
+
const statusCard = h(
|
|
266
|
+
'section',
|
|
267
|
+
{ style: styles.card },
|
|
268
|
+
h('h2', { style: styles.cardTitle }, '运行状态'),
|
|
269
|
+
state.loading
|
|
270
|
+
? h('p', { style: styles.loading }, '正在读取…')
|
|
271
|
+
: status === null
|
|
272
|
+
? h('p', { style: styles.err }, state.error || '读取失败')
|
|
273
|
+
: h(
|
|
274
|
+
'div',
|
|
275
|
+
{ style: styles.kvs },
|
|
276
|
+
h('span', { style: styles.key }, '上次重启'),
|
|
277
|
+
h('span', { style: styles.val }, status.lastResult === null ? '—' : `${phaseLabel(status.lastResult.phase)} · ${fmtTime(status.lastResult.at)}`),
|
|
278
|
+
h('span', { style: styles.key }, '上次原因'),
|
|
279
|
+
h('span', { style: styles.val }, status.lastResult?.detail ?? '—'),
|
|
280
|
+
h('span', { style: styles.key }, '待重启'),
|
|
281
|
+
h('span', { style: styles.val }, status.pending ? '是(等条件满足就重启)' : '否'),
|
|
282
|
+
h('span', { style: styles.key }, '会话忙闲'),
|
|
283
|
+
h('span', { style: styles.val }, (status.busySessions ?? []).length === 0 ? '空闲' : `${status.busySessions.length} 个在跑`),
|
|
284
|
+
h('span', { style: styles.key }, '插件基线'),
|
|
285
|
+
h('span', { style: styles.val }, `${status.baseline ?? '—'} / 当前 ${status.current ?? '—'}`),
|
|
286
|
+
h('span', { style: styles.key }, '日志'),
|
|
287
|
+
h('span', { style: styles.val }, status.logPath ?? '—'),
|
|
288
|
+
status.disabled
|
|
289
|
+
? [h('span', { key: 'k', style: styles.key }, '急停'), h('span', { key: 'v', style: styles.err }, 'disabled 文件存在:插件不会做任何事')]
|
|
290
|
+
: null,
|
|
291
|
+
),
|
|
292
|
+
h(
|
|
293
|
+
'div',
|
|
294
|
+
{ style: styles.bar },
|
|
295
|
+
h('button', { type: 'button', style: styles.btnPrimary, onClick: restartNow, disabled: restarting || config === null }, restarting ? '正在派发…' : '立即重启'),
|
|
296
|
+
h('button', { type: 'button', style: styles.btn, onClick: load }, '刷新'),
|
|
297
|
+
status?.desktopHost === false ? h('span', { style: styles.err }, '当前宿主不是 Windows 桌面端,重启不可用') : null,
|
|
298
|
+
),
|
|
299
|
+
save.error ? h('p', { style: styles.err }, `操作失败:${save.error}`) : null,
|
|
300
|
+
save.ok ? h('p', { style: styles.ok }, save.ok) : null,
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
const settingsCard = config === null
|
|
304
|
+
? null
|
|
305
|
+
: h(
|
|
306
|
+
'section',
|
|
307
|
+
{ style: styles.card },
|
|
308
|
+
h('h2', { style: styles.cardTitle }, '设置'),
|
|
309
|
+
h(SwitchRow, {
|
|
310
|
+
label: '启用自动重启',
|
|
311
|
+
hint: '关闭后不会因为插件变化而重启;状态接口和这个面板仍然可用。',
|
|
312
|
+
checked: config.enabled !== false,
|
|
313
|
+
onChange: (value) => change({ enabled: value }),
|
|
314
|
+
}),
|
|
315
|
+
h(SwitchRow, {
|
|
316
|
+
label: '试运行(dryRun)',
|
|
317
|
+
hint: '只写日志、不真的重启。用来确认它会在什么时候动手。',
|
|
318
|
+
checked: config.dryRun === true,
|
|
319
|
+
onChange: (value) => change({ dryRun: value }),
|
|
320
|
+
}),
|
|
321
|
+
h(SwitchRow, {
|
|
322
|
+
label: '重启后最大化窗口',
|
|
323
|
+
hint: '守护进程拉起应用后,把主窗口最大化。',
|
|
324
|
+
checked: config.maximizeOnRestart !== false,
|
|
325
|
+
onChange: (value) => change({ maximizeOnRestart: value }),
|
|
326
|
+
}),
|
|
327
|
+
h(SwitchRow, {
|
|
328
|
+
label: '等所有会话空闲再重启',
|
|
329
|
+
hint: '有回答或任务在跑时先等它们结束,避免截断。',
|
|
330
|
+
checked: config.waitForIdle !== false,
|
|
331
|
+
onChange: (value) => change({ waitForIdle: value }),
|
|
332
|
+
}),
|
|
333
|
+
h(NumberRow, {
|
|
334
|
+
label: '文件稳定判定',
|
|
335
|
+
hint: '插件文件停止变化多久才算安装完成。',
|
|
336
|
+
value: Math.round((config.stableMs ?? 10000) / 1000),
|
|
337
|
+
min: 1,
|
|
338
|
+
max: 600,
|
|
339
|
+
suffix: '秒',
|
|
340
|
+
onChange: (value) => change({ stableMs: Math.max(0, Math.round(value)) * 1000 }),
|
|
341
|
+
}),
|
|
342
|
+
h(NumberRow, {
|
|
343
|
+
label: '两次重启冷却',
|
|
344
|
+
hint: '两次自动重启之间至少间隔这么久。',
|
|
345
|
+
value: Math.round((config.cooldownMs ?? 60000) / 1000),
|
|
346
|
+
min: 0,
|
|
347
|
+
max: 3600,
|
|
348
|
+
suffix: '秒',
|
|
349
|
+
onChange: (value) => change({ cooldownMs: Math.max(0, Math.round(value)) * 1000 }),
|
|
350
|
+
}),
|
|
351
|
+
h(NumberRow, {
|
|
352
|
+
label: '等空闲上限',
|
|
353
|
+
hint: '超时还没有空闲就按「放弃本次」处理(除非另开了强制重启)。',
|
|
354
|
+
value: Math.round((config.maxIdleWaitMs ?? 120000) / 1000),
|
|
355
|
+
min: 10,
|
|
356
|
+
max: 3600,
|
|
357
|
+
suffix: '秒',
|
|
358
|
+
onChange: (value) => change({ maxIdleWaitMs: Math.max(0, Math.round(value)) * 1000 }),
|
|
359
|
+
}),
|
|
360
|
+
h('p', { style: styles.note }, '改动即时保存、即时生效,不需要重启 DSH。'),
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
return h(
|
|
364
|
+
'div',
|
|
365
|
+
{ style: styles.root },
|
|
366
|
+
h(
|
|
367
|
+
'div',
|
|
368
|
+
{ style: styles.inner },
|
|
369
|
+
h('header', { style: styles.header }, h('h1', { style: styles.title }, '自动重启'), badge),
|
|
370
|
+
h('p', { style: styles.subtitle }, '装完或更新完插件后,等所有会话空闲,自动重启 DSH 并回到原会话;重启后默认最大化窗口。'),
|
|
371
|
+
save.busy ? h('p', { style: styles.note }, '正在保存…') : null,
|
|
372
|
+
statusCard,
|
|
373
|
+
settingsCard,
|
|
374
|
+
h('p', { style: styles.note }, '配置文件:' + (status?.configPath ?? '—') + ' 急停:在同目录新建空文件 disabled'),
|
|
375
|
+
),
|
|
376
|
+
)
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function AutoRestartIcon(props) {
|
|
380
|
+
const size = typeof props?.size === 'number' && props.size > 0 ? props.size : 18
|
|
381
|
+
return h(
|
|
382
|
+
'svg',
|
|
383
|
+
{
|
|
384
|
+
width: size,
|
|
385
|
+
height: size,
|
|
386
|
+
viewBox: '0 0 24 24',
|
|
387
|
+
fill: 'none',
|
|
388
|
+
'aria-hidden': true,
|
|
389
|
+
style: { display: 'block' },
|
|
390
|
+
},
|
|
391
|
+
h('path', {
|
|
392
|
+
d: 'M19.5 12a7.5 7.5 0 1 1-2.6-5.7',
|
|
393
|
+
stroke: 'currentColor',
|
|
394
|
+
strokeWidth: 1.7,
|
|
395
|
+
strokeLinecap: 'round',
|
|
396
|
+
}),
|
|
397
|
+
h('path', {
|
|
398
|
+
d: 'M18.6 3.6v5h-5',
|
|
399
|
+
stroke: 'currentColor',
|
|
400
|
+
strokeWidth: 1.7,
|
|
401
|
+
strokeLinecap: 'round',
|
|
402
|
+
strokeLinejoin: 'round',
|
|
403
|
+
}),
|
|
404
|
+
)
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
return {
|
|
408
|
+
name: '@leiyi-works/dsh-auto-restart',
|
|
409
|
+
inject: ['slots', 'layout'],
|
|
410
|
+
apply(ctx) {
|
|
411
|
+
// 左侧菜单入口。
|
|
412
|
+
ctx.effect(
|
|
413
|
+
() =>
|
|
414
|
+
ctx.slots.inject('sidebar.panellist', () =>
|
|
415
|
+
ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, order: 48, label: '自动重启' }, AutoRestartIcon),
|
|
416
|
+
),
|
|
417
|
+
'dsh-auto-restart: sidebar entry',
|
|
418
|
+
)
|
|
419
|
+
// 点入口打开全页面板。
|
|
420
|
+
ctx.effect(
|
|
421
|
+
() => ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, AutoRestartPanel)),
|
|
422
|
+
'dsh-auto-restart: panel page',
|
|
423
|
+
)
|
|
424
|
+
},
|
|
425
|
+
}
|
|
426
|
+
},
|
|
427
|
+
})
|
package/index.js
CHANGED
|
@@ -11,15 +11,16 @@
|
|
|
11
11
|
* 弹出原生「DeepSeek Harness 无法使用」并响一声 —— 所以必须先杀主进程。
|
|
12
12
|
* 2. Host 进程没法调用父进程的 app.relaunch(),也没法在自己被拆掉后继续干活,
|
|
13
13
|
* 所以守护进程必须由 WMI 创建、跑在进程树之外。
|
|
14
|
-
* 3. 拉起 GUI
|
|
14
|
+
* 3. 拉起 GUI 应用后要等主窗口出现,不能只等进程起来;需要的话再把它最大化。
|
|
15
15
|
*
|
|
16
|
-
* 安全阀:默认 dryRun=true(只写日志不真重启);冷却 60s
|
|
17
|
-
*
|
|
18
|
-
*
|
|
16
|
+
* 安全阀:默认 dryRun=true(只写日志不真重启);冷却 60s;会话忙时等(默认最多
|
|
17
|
+
* 2 分钟,超时放弃本次,等下次变化);`disabled` 文件存在时完全不动;所有失败
|
|
18
|
+
* 只写日志,绝不让插件加载失败拖垮 profile。
|
|
19
19
|
*
|
|
20
20
|
* 运行参数:<DSH_HOME>/dsh-auto-restart/config.json(改文件即时生效,无需重启),
|
|
21
|
-
*
|
|
22
|
-
*
|
|
21
|
+
* 也可以在左侧菜单「自动重启」面板里改。
|
|
22
|
+
* 诊断:<DSH_HOME>/dsh-auto-restart/auto-restart.log,
|
|
23
|
+
* 状态:GET /auto-restart/status(回环),配置:GET/POST /auto-restart/config。
|
|
23
24
|
*/
|
|
24
25
|
import { createHash } from 'node:crypto'
|
|
25
26
|
import { spawn } from 'node:child_process'
|
|
@@ -35,7 +36,7 @@ import {
|
|
|
35
36
|
writeFileSync,
|
|
36
37
|
} from 'node:fs'
|
|
37
38
|
import { homedir } from 'node:os'
|
|
38
|
-
import {
|
|
39
|
+
import { dirname, join, resolve } from 'node:path'
|
|
39
40
|
import { fileURLToPath } from 'node:url'
|
|
40
41
|
|
|
41
42
|
/** Loader row id (the patch in cordis.patch.yml inserts this id). */
|
|
@@ -45,6 +46,16 @@ const MARK = 'dsh-auto-restart'
|
|
|
45
46
|
const PKG_DIR = fileURLToPath(new URL('./', import.meta.url))
|
|
46
47
|
const STATE_KEY = Symbol.for('dsh-auto-restart.state')
|
|
47
48
|
|
|
49
|
+
function readVersion() {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(readFileSync(join(PKG_DIR, 'package.json'), 'utf8')).version ?? '0.0.0'
|
|
52
|
+
} catch {
|
|
53
|
+
return '0.0.0'
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const VERSION = readVersion()
|
|
58
|
+
|
|
48
59
|
/** Defaults; config.json overrides them field by field. */
|
|
49
60
|
const DEFAULTS = Object.freeze({
|
|
50
61
|
enabled: true,
|
|
@@ -58,8 +69,8 @@ const DEFAULTS = Object.freeze({
|
|
|
58
69
|
managerQuietMs: 3000,
|
|
59
70
|
/** 两次重启之间最小间隔(毫秒),跨重启持久化。 */
|
|
60
71
|
cooldownMs: 60000,
|
|
61
|
-
/**
|
|
62
|
-
maxPerHour:
|
|
72
|
+
/** 每小时最多重启几次;0 = 不限制。 */
|
|
73
|
+
maxPerHour: 0,
|
|
63
74
|
/** 有会话在跑时先等它们空闲。 */
|
|
64
75
|
waitForIdle: true,
|
|
65
76
|
/** 等空闲的最长时间(毫秒),超时按下面 forceWhenBusy 处理。 */
|
|
@@ -68,6 +79,8 @@ const DEFAULTS = Object.freeze({
|
|
|
68
79
|
forceWhenBusy: false,
|
|
69
80
|
/** 守护进程收到请求后等多久动手(毫秒),留时间给当前回合收尾。 */
|
|
70
81
|
restartDelayMs: 2000,
|
|
82
|
+
/** 重启后把主窗口最大化(开关在左侧「自动重启」面板里)。 */
|
|
83
|
+
maximizeOnRestart: true,
|
|
71
84
|
/** 覆盖应用可执行文件路径;留空 = 用 Host 的 process.execPath。 */
|
|
72
85
|
exePath: '',
|
|
73
86
|
/** 拉起应用时附加的参数(数组,通常为空)。 */
|
|
@@ -140,6 +153,19 @@ function profileDirOf(cfg) {
|
|
|
140
153
|
return process.cwd()
|
|
141
154
|
}
|
|
142
155
|
|
|
156
|
+
/** JSON.parse that tolerates a UTF-8 BOM (PowerShell 5.1 writes one). */
|
|
157
|
+
function parseJsonLoose(text) {
|
|
158
|
+
return JSON.parse(String(text).replace(/^\uFEFF/u, ''))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function readJsonFile(file) {
|
|
162
|
+
try {
|
|
163
|
+
return parseJsonLoose(readFileSync(file, 'utf8'))
|
|
164
|
+
} catch {
|
|
165
|
+
return undefined
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
143
169
|
// ---------------------------------------------------------------------------
|
|
144
170
|
// logging
|
|
145
171
|
// ---------------------------------------------------------------------------
|
|
@@ -171,12 +197,8 @@ function logLine(level, message) {
|
|
|
171
197
|
}
|
|
172
198
|
|
|
173
199
|
function readLastResult() {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
return parsed !== null && typeof parsed === 'object' ? parsed : null
|
|
177
|
-
} catch {
|
|
178
|
-
return null
|
|
179
|
-
}
|
|
200
|
+
const parsed = readJsonFile(resultPath())
|
|
201
|
+
return parsed !== null && typeof parsed === 'object' ? parsed : null
|
|
180
202
|
}
|
|
181
203
|
|
|
182
204
|
// ---------------------------------------------------------------------------
|
|
@@ -198,11 +220,12 @@ function sanitizeConfig(raw) {
|
|
|
198
220
|
cfg.dryRun = bool(raw.dryRun, cfg.dryRun)
|
|
199
221
|
cfg.waitForIdle = bool(raw.waitForIdle, cfg.waitForIdle)
|
|
200
222
|
cfg.forceWhenBusy = bool(raw.forceWhenBusy, cfg.forceWhenBusy)
|
|
223
|
+
cfg.maximizeOnRestart = bool(raw.maximizeOnRestart, cfg.maximizeOnRestart)
|
|
201
224
|
cfg.pollIntervalMs = num(raw.pollIntervalMs, cfg.pollIntervalMs, 500, 60000)
|
|
202
225
|
cfg.stableMs = num(raw.stableMs, cfg.stableMs, 0, 600000)
|
|
203
226
|
cfg.managerQuietMs = num(raw.managerQuietMs, cfg.managerQuietMs, 0, 60000)
|
|
204
227
|
cfg.cooldownMs = num(raw.cooldownMs, cfg.cooldownMs, 0, 3600000)
|
|
205
|
-
cfg.maxPerHour = num(raw.maxPerHour, cfg.maxPerHour,
|
|
228
|
+
cfg.maxPerHour = num(raw.maxPerHour, cfg.maxPerHour, 0, 100)
|
|
206
229
|
cfg.maxIdleWaitMs = num(raw.maxIdleWaitMs, cfg.maxIdleWaitMs, 0, 3600000)
|
|
207
230
|
cfg.restartDelayMs = num(raw.restartDelayMs, cfg.restartDelayMs, 0, 600000)
|
|
208
231
|
cfg.logMaxBytes = num(raw.logMaxBytes, cfg.logMaxBytes, 4096, 64 * 1024 * 1024)
|
|
@@ -228,23 +251,30 @@ function readConfig(base) {
|
|
|
228
251
|
if (configCache.key === key && configCache.value !== null) {
|
|
229
252
|
return sanitizeConfig({ ...base, ...configCache.value })
|
|
230
253
|
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
configCache.value = parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
235
|
-
} catch {
|
|
236
|
-
configCache.key = key
|
|
237
|
-
configCache.value = {}
|
|
238
|
-
}
|
|
254
|
+
const parsed = readJsonFile(file)
|
|
255
|
+
configCache.key = key
|
|
256
|
+
configCache.value = parsed !== null && typeof parsed === 'object' ? parsed : {}
|
|
239
257
|
return sanitizeConfig({ ...base, ...configCache.value })
|
|
240
258
|
}
|
|
241
259
|
|
|
242
260
|
function readConfigUncached() {
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
261
|
+
const parsed = readJsonFile(configPath())
|
|
262
|
+
return sanitizeConfig(parsed !== null && typeof parsed === 'object' ? parsed : null)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Merge one patch into config.json (BOM-less, atomic) and return the effective config. */
|
|
266
|
+
function saveConfig(base, patch) {
|
|
267
|
+
const current = readConfigUncached()
|
|
268
|
+
const merged = { ...current, ...(patch !== null && typeof patch === 'object' ? patch : {}) }
|
|
269
|
+
const next = sanitizeConfig(merged)
|
|
270
|
+
const file = configPath()
|
|
271
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
272
|
+
const tmp = `${file}.tmp-${process.pid}`
|
|
273
|
+
writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
274
|
+
renameSync(tmp, file)
|
|
275
|
+
configCache.key = ''
|
|
276
|
+
configCache.value = null
|
|
277
|
+
return readConfig(base)
|
|
248
278
|
}
|
|
249
279
|
|
|
250
280
|
function writeJsonAtomic(file, value) {
|
|
@@ -255,16 +285,12 @@ function writeJsonAtomic(file, value) {
|
|
|
255
285
|
}
|
|
256
286
|
|
|
257
287
|
function readStateFile() {
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
return { lastRestartAt: Number(parsed.lastRestartAt) || 0, restarts }
|
|
265
|
-
} catch {
|
|
266
|
-
return { lastRestartAt: 0, restarts: [] }
|
|
267
|
-
}
|
|
288
|
+
const parsed = readJsonFile(statePath())
|
|
289
|
+
if (parsed === null || typeof parsed !== 'object') return { lastRestartAt: 0, restarts: [] }
|
|
290
|
+
const restarts = Array.isArray(parsed.restarts)
|
|
291
|
+
? parsed.restarts.map(Number).filter((n) => Number.isFinite(n) && n > 0)
|
|
292
|
+
: []
|
|
293
|
+
return { lastRestartAt: Number(parsed.lastRestartAt) || 0, restarts }
|
|
268
294
|
}
|
|
269
295
|
|
|
270
296
|
function saveState(state) {
|
|
@@ -327,16 +353,13 @@ function listTree(root) {
|
|
|
327
353
|
|
|
328
354
|
/** Content signature of the two manifest fields that decide which plugins load. */
|
|
329
355
|
function manifestSignature(profileDir) {
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
} catch {
|
|
338
|
-
return 'unreadable'
|
|
339
|
-
}
|
|
356
|
+
const pkg = readJsonFile(join(profileDir, 'package.json'))
|
|
357
|
+
if (pkg === null || typeof pkg !== 'object') return 'unreadable'
|
|
358
|
+
const dependencies = pkg.dependencies !== null && typeof pkg.dependencies === 'object' ? pkg.dependencies : {}
|
|
359
|
+
const bundles = pkg?.dsh?.profile?.bundles
|
|
360
|
+
const sortedDeps = {}
|
|
361
|
+
for (const key of Object.keys(dependencies).sort()) sortedDeps[key] = dependencies[key]
|
|
362
|
+
return createHash('sha1').update(JSON.stringify([sortedDeps, Array.isArray(bundles) ? bundles : []])).digest('hex')
|
|
340
363
|
}
|
|
341
364
|
|
|
342
365
|
function fingerprint(profileDir) {
|
|
@@ -394,34 +417,34 @@ function abortPending(state, reason) {
|
|
|
394
417
|
state.baseline = state.lastFp
|
|
395
418
|
}
|
|
396
419
|
|
|
397
|
-
function dispatchRestart(state, cfg, reason) {
|
|
420
|
+
function dispatchRestart(state, cfg, reason, options = {}) {
|
|
398
421
|
const exe = resolveExe(cfg)
|
|
399
422
|
|
|
400
423
|
// Dry run is checked first so it works on any host and never touches anything.
|
|
401
424
|
if (cfg.dryRun) {
|
|
402
425
|
logLine('info', `[dry-run] 本应重启:${reason};desktop=${isDesktopHost()} exe=${exe} root=${process.ppid} delay=${cfg.restartDelayMs}ms(config.json 里把 dryRun 改成 false 才会真重启)`)
|
|
403
426
|
settled(state)
|
|
404
|
-
return
|
|
427
|
+
return { ok: true, dryRun: true }
|
|
405
428
|
}
|
|
406
429
|
|
|
407
430
|
if (!isDesktopHost()) {
|
|
408
431
|
abortPending(state, '当前宿主不是 Windows 桌面端(dsh web / headless 不支持)')
|
|
409
|
-
return false
|
|
432
|
+
return { ok: false, error: '当前宿主不是 Windows 桌面端,无法重启' }
|
|
410
433
|
}
|
|
411
434
|
if (!existsSync(exe)) {
|
|
412
435
|
abortPending(state, `应用可执行文件不存在:${exe}`)
|
|
413
|
-
return false
|
|
436
|
+
return { ok: false, error: `应用可执行文件不存在:${exe}` }
|
|
414
437
|
}
|
|
415
438
|
const delay = Math.max(0, Number(cfg.restartDelayMs) || 0)
|
|
416
439
|
const supervisor = expandHome(cfg.supervisorScript) || join(PKG_DIR, 'lib', 'restart-supervisor.ps1')
|
|
417
440
|
const launcher = join(PKG_DIR, 'lib', 'launch-supervisor.ps1')
|
|
418
441
|
if (!existsSync(supervisor)) {
|
|
419
442
|
abortPending(state, `守护脚本不存在:${supervisor}`)
|
|
420
|
-
return false
|
|
443
|
+
return { ok: false, error: '守护脚本不存在' }
|
|
421
444
|
}
|
|
422
445
|
if (!existsSync(launcher)) {
|
|
423
446
|
abortPending(state, `启动脚本不存在:${launcher}`)
|
|
424
|
-
return false
|
|
447
|
+
return { ok: false, error: '启动脚本不存在' }
|
|
425
448
|
}
|
|
426
449
|
|
|
427
450
|
const request = {
|
|
@@ -429,10 +452,12 @@ function dispatchRestart(state, cfg, reason) {
|
|
|
429
452
|
rootPid: process.ppid,
|
|
430
453
|
hostPid: process.pid,
|
|
431
454
|
delayMs: delay,
|
|
455
|
+
maximize: cfg.maximizeOnRestart !== false,
|
|
432
456
|
launchArgs: Array.isArray(cfg.launchArgs) ? cfg.launchArgs : [],
|
|
433
457
|
log: logPath(),
|
|
434
458
|
result: resultPath(),
|
|
435
459
|
reason,
|
|
460
|
+
manual: options.manual === true,
|
|
436
461
|
requestedAt: new Date().toISOString(),
|
|
437
462
|
}
|
|
438
463
|
try {
|
|
@@ -453,7 +478,7 @@ function dispatchRestart(state, cfg, reason) {
|
|
|
453
478
|
} catch (error) {
|
|
454
479
|
logLine('error', `派发重启失败:${String(error?.message ?? error)}`)
|
|
455
480
|
abortPending(state, '守护进程未能启动')
|
|
456
|
-
return false
|
|
481
|
+
return { ok: false, error: String(error?.message ?? error) }
|
|
457
482
|
}
|
|
458
483
|
|
|
459
484
|
const now = Date.now()
|
|
@@ -464,21 +489,29 @@ function dispatchRestart(state, cfg, reason) {
|
|
|
464
489
|
state.lastReason = reason
|
|
465
490
|
saveState(state)
|
|
466
491
|
settled(state)
|
|
467
|
-
logLine('warn', `已派发重启:${reason};exe=${exe} root=${process.ppid} delay=${delay}ms`)
|
|
492
|
+
logLine('warn', `已派发重启:${reason};exe=${exe} root=${process.ppid} delay=${delay}ms maximize=${request.maximize}`)
|
|
468
493
|
try {
|
|
469
494
|
writeJsonAtomic(join(dataDir(), 'last-restart.json'), {
|
|
470
495
|
at: new Date(now).toISOString(),
|
|
471
496
|
reason,
|
|
472
|
-
reasonOf: 'plugin files changed',
|
|
473
497
|
exe,
|
|
474
498
|
rootPid: process.ppid,
|
|
475
499
|
hostPid: process.pid,
|
|
476
500
|
delayMs: delay,
|
|
501
|
+
maximize: request.maximize,
|
|
477
502
|
})
|
|
478
503
|
} catch {
|
|
479
504
|
// informational only
|
|
480
505
|
}
|
|
481
|
-
return true
|
|
506
|
+
return { ok: true, dryRun: false, delayMs: delay, maximize: request.maximize }
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/** Manual restart from the panel: bypasses cooldown and the hourly cap, not busy sessions. */
|
|
510
|
+
function requestManualRestart(state, cfg) {
|
|
511
|
+
if (state.busy.size > 0) {
|
|
512
|
+
return { ok: false, error: `还有 ${state.busy.size} 个会话在跑,等它们结束再重启;确实要现在重启就把 waitForIdle 关掉再点`, busy: [...state.busy] }
|
|
513
|
+
}
|
|
514
|
+
return dispatchRestart(state, cfg, '面板手动重启', { manual: true })
|
|
482
515
|
}
|
|
483
516
|
|
|
484
517
|
// ---------------------------------------------------------------------------
|
|
@@ -506,7 +539,7 @@ function createState(profileDir) {
|
|
|
506
539
|
}
|
|
507
540
|
}
|
|
508
541
|
|
|
509
|
-
function tick(
|
|
542
|
+
function tick(baseConfig) {
|
|
510
543
|
const cfg = readConfig(baseConfig)
|
|
511
544
|
if (!cfg.enabled) return
|
|
512
545
|
if (existsSync(disabledPath())) return
|
|
@@ -562,7 +595,7 @@ function tick(ctx, baseConfig) {
|
|
|
562
595
|
return
|
|
563
596
|
}
|
|
564
597
|
|
|
565
|
-
if (state.restarts.length >= cfg.maxPerHour) {
|
|
598
|
+
if (cfg.maxPerHour > 0 && state.restarts.length >= cfg.maxPerHour) {
|
|
566
599
|
if (now - state.lastSkipLog > 15000) {
|
|
567
600
|
state.lastSkipLog = now
|
|
568
601
|
logLine('warn', `本小时已重启 ${state.restarts.length} 次,达到上限 ${cfg.maxPerHour},本次不重启`)
|
|
@@ -600,34 +633,67 @@ function safeOn(ctx, event, handler, label) {
|
|
|
600
633
|
}
|
|
601
634
|
}
|
|
602
635
|
|
|
603
|
-
|
|
636
|
+
function sendJson(res, status, payload) {
|
|
637
|
+
try {
|
|
638
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
639
|
+
res.end(JSON.stringify(payload))
|
|
640
|
+
} catch {
|
|
641
|
+
// response already gone
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function readBody(req, limit = 64 * 1024) {
|
|
646
|
+
return new Promise((resolvePromise) => {
|
|
647
|
+
let size = 0
|
|
648
|
+
const chunks = []
|
|
649
|
+
req.on('data', (chunk) => {
|
|
650
|
+
size += chunk.length
|
|
651
|
+
if (size > limit) {
|
|
652
|
+
resolvePromise('')
|
|
653
|
+
req.destroy()
|
|
654
|
+
return
|
|
655
|
+
}
|
|
656
|
+
chunks.push(chunk)
|
|
657
|
+
})
|
|
658
|
+
req.on('end', () => resolvePromise(Buffer.concat(chunks).toString('utf8')))
|
|
659
|
+
req.on('error', () => resolvePromise(''))
|
|
660
|
+
})
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** Register the panel routes (loopback + same-origin + explicit header for writes). */
|
|
604
664
|
function installRoutes(ctx, baseConfig) {
|
|
605
665
|
try {
|
|
606
666
|
ctx.inject(['webServer'], (scope) => {
|
|
607
667
|
scope.effect(() => scope.webServer.register({
|
|
608
668
|
kind: 'prefix',
|
|
609
669
|
path: '/auto-restart',
|
|
610
|
-
handler: (req, res) => {
|
|
670
|
+
handler: async (req, res) => {
|
|
611
671
|
try {
|
|
612
672
|
const address = String(req.socket?.remoteAddress ?? '')
|
|
613
673
|
const loopback = address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
|
|
614
|
-
if (!loopback) {
|
|
615
|
-
res.writeHead(403, { 'content-type': 'application/json; charset=utf-8' })
|
|
616
|
-
res.end(JSON.stringify({ ok: false, error: 'loopback only' }))
|
|
617
|
-
return
|
|
618
|
-
}
|
|
674
|
+
if (!loopback) return sendJson(res, 403, { ok: false, error: 'loopback only' })
|
|
619
675
|
const url = String(req.url ?? '/')
|
|
620
|
-
const cfg = readConfig(baseConfig)
|
|
621
676
|
const state = globalThis[STATE_KEY]
|
|
622
|
-
|
|
677
|
+
const cfg = readConfig(baseConfig)
|
|
678
|
+
const method = req.method ?? 'GET'
|
|
679
|
+
const write = method !== 'GET'
|
|
680
|
+
if (write) {
|
|
681
|
+
if (req.headers['x-dsh-auto-restart'] !== '1') return sendJson(res, 403, { ok: false, error: 'missing x-dsh-auto-restart header' })
|
|
682
|
+
const contentType = String(req.headers['content-type'] ?? '').toLowerCase()
|
|
683
|
+
if (!contentType.startsWith('application/json')) return sendJson(res, 415, { ok: false, error: 'expected application/json' })
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
if (url.startsWith('/auto-restart/status') && method === 'GET') {
|
|
623
687
|
const now = Date.now()
|
|
624
|
-
|
|
688
|
+
return sendJson(res, 200, {
|
|
625
689
|
ok: true,
|
|
626
|
-
version:
|
|
690
|
+
version: VERSION,
|
|
627
691
|
desktopHost: isDesktopHost(),
|
|
628
692
|
profileDir: state?.profileDir ?? null,
|
|
629
693
|
enabled: cfg.enabled,
|
|
630
694
|
dryRun: cfg.dryRun,
|
|
695
|
+
maximizeOnRestart: cfg.maximizeOnRestart,
|
|
696
|
+
waitForIdle: cfg.waitForIdle,
|
|
631
697
|
busySessions: state ? [...state.busy] : [],
|
|
632
698
|
pending: state ? state.pendingSince > 0 : false,
|
|
633
699
|
baseline: state?.baseline?.slice(0, 10) ?? null,
|
|
@@ -640,32 +706,45 @@ function installRoutes(ctx, baseConfig) {
|
|
|
640
706
|
logPath: logPath(),
|
|
641
707
|
configPath: configPath(),
|
|
642
708
|
disabled: existsSync(disabledPath()),
|
|
709
|
+
})
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
if (url.startsWith('/auto-restart/config') && method === 'GET') {
|
|
713
|
+
return sendJson(res, 200, { ok: true, config: cfg })
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
if (url.startsWith('/auto-restart/config') && method === 'POST') {
|
|
717
|
+
const raw = await readBody(req)
|
|
718
|
+
let patch
|
|
719
|
+
try {
|
|
720
|
+
patch = parseJsonLoose(raw)
|
|
721
|
+
} catch {
|
|
722
|
+
return sendJson(res, 400, { ok: false, error: 'invalid JSON body' })
|
|
643
723
|
}
|
|
644
|
-
|
|
645
|
-
res
|
|
646
|
-
return
|
|
724
|
+
if (patch === null || typeof patch !== 'object') return sendJson(res, 400, { ok: false, error: 'object body required' })
|
|
725
|
+
return sendJson(res, 200, { ok: true, config: saveConfig(baseConfig, patch) })
|
|
647
726
|
}
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
res
|
|
653
|
-
res.end(JSON.stringify({ ok: false, error: String(error?.message ?? error) }))
|
|
654
|
-
} catch {
|
|
655
|
-
// response already gone
|
|
727
|
+
|
|
728
|
+
if (url.startsWith('/auto-restart/restart') && method === 'POST') {
|
|
729
|
+
if (state === undefined) return sendJson(res, 503, { ok: false, error: 'plugin state unavailable' })
|
|
730
|
+
const result = requestManualRestart(state, cfg)
|
|
731
|
+
return sendJson(res, result.ok ? 200 : 409, result)
|
|
656
732
|
}
|
|
733
|
+
|
|
734
|
+
return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
735
|
+
} catch (error) {
|
|
736
|
+
return sendJson(res, 500, { ok: false, error: String(error?.message ?? error) })
|
|
657
737
|
}
|
|
658
738
|
},
|
|
659
|
-
}), 'auto-restart:
|
|
739
|
+
}), 'auto-restart: panel routes')
|
|
660
740
|
try {
|
|
661
|
-
|
|
662
|
-
logLine('info', `状态接口:${origin ?? '?'}/auto-restart/status`)
|
|
741
|
+
logLine('info', `面板接口:${scope.webServer.getOrigin?.() ?? '?'}/auto-restart/status`)
|
|
663
742
|
} catch {
|
|
664
743
|
// informational
|
|
665
744
|
}
|
|
666
745
|
})
|
|
667
746
|
} catch (error) {
|
|
668
|
-
logLine('warn',
|
|
747
|
+
logLine('warn', `注册面板接口失败:${String(error?.message ?? error)}`)
|
|
669
748
|
}
|
|
670
749
|
}
|
|
671
750
|
|
|
@@ -687,13 +766,33 @@ export function apply(ctx, config) {
|
|
|
687
766
|
const state = globalThis[STATE_KEY]
|
|
688
767
|
|
|
689
768
|
// Report the outcome of the restart this process may have just survived.
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
769
|
+
// The supervisor writes `stopped` first and `relaunched` only after the new
|
|
770
|
+
// window shows, so the first read can race and must be re-checked.
|
|
771
|
+
const describeResult = (result) => `${result.phase ?? '?'} ${result.detail ?? ''}`.trim()
|
|
772
|
+
const initialResult = readLastResult()
|
|
773
|
+
if (initialResult !== null) {
|
|
774
|
+
if (initialResult.phase === 'stopped') {
|
|
775
|
+
logLine('info', '上次重启正在进行(守护进程已停掉旧进程,等它拉起新窗口)')
|
|
776
|
+
try {
|
|
777
|
+
const timer = setTimeout(() => {
|
|
778
|
+
const final = readLastResult()
|
|
779
|
+
if (final !== null && (final.phase === 'relaunched' || final.phase === 'relaunched-no-window')) {
|
|
780
|
+
logLine('info', `上次重启结果:${describeResult(final)}`)
|
|
781
|
+
} else {
|
|
782
|
+
logLine('warn', `上次重启没有确认完成:${final === null ? 'missing' : describeResult(final)}`)
|
|
783
|
+
}
|
|
784
|
+
}, 5000)
|
|
785
|
+
timer.unref?.()
|
|
786
|
+
} catch {
|
|
787
|
+
// diagnostics only
|
|
788
|
+
}
|
|
789
|
+
} else {
|
|
790
|
+
logLine(initialResult.phase === 'relaunched' || initialResult.phase === 'relaunched-no-window' ? 'info' : 'warn',
|
|
791
|
+
`上次重启结果:${describeResult(initialResult)}`)
|
|
792
|
+
}
|
|
694
793
|
}
|
|
695
794
|
|
|
696
|
-
logLine('info', `${MARK}
|
|
795
|
+
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()}`)
|
|
697
796
|
|
|
698
797
|
// Track busy sessions so a restart never cuts an answer.
|
|
699
798
|
ctx.effect(() => ctx.on('api-session/status', (sessionId, running) => {
|
|
@@ -720,7 +819,7 @@ export function apply(ctx, config) {
|
|
|
720
819
|
ctx.effect(() => {
|
|
721
820
|
const timer = setInterval(() => {
|
|
722
821
|
try {
|
|
723
|
-
tick(
|
|
822
|
+
tick(baseConfig)
|
|
724
823
|
} catch (error) {
|
|
725
824
|
logLine('error', `tick 失败:${String(error?.message ?? error)}`)
|
|
726
825
|
}
|
|
@@ -742,9 +841,11 @@ export function apply(ctx, config) {
|
|
|
742
841
|
/** Test-only surface: pure helpers, no side effects. */
|
|
743
842
|
export const _internals = {
|
|
744
843
|
DEFAULTS,
|
|
844
|
+
VERSION,
|
|
745
845
|
fingerprint,
|
|
746
846
|
listTree,
|
|
747
847
|
manifestSignature,
|
|
748
848
|
sanitizeConfig,
|
|
849
|
+
parseJsonLoose,
|
|
749
850
|
isDesktopHost,
|
|
750
851
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
param(
|
|
2
2
|
[Parameter(Mandatory=$true)][string]$Request
|
|
3
3
|
)
|
|
4
4
|
|
|
@@ -14,6 +14,9 @@ $ErrorActionPreference = 'Stop'
|
|
|
14
14
|
$spec = Get-Content -LiteralPath $Request -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
15
15
|
$Log = [string]$spec.log
|
|
16
16
|
$Result = [string]$spec.result
|
|
17
|
+
# Maximize by default: older Host halves do not send this field.
|
|
18
|
+
$Maximize = $true
|
|
19
|
+
if ($spec.PSObject.Properties['maximize'] -ne $null) { $Maximize = [bool]$spec.maximize }
|
|
17
20
|
|
|
18
21
|
function Write-Log([string]$Message) {
|
|
19
22
|
try {
|
|
@@ -33,6 +36,30 @@ function Test-ProcessAlive([int]$ProcessId) {
|
|
|
33
36
|
return (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue) -ne $null
|
|
34
37
|
}
|
|
35
38
|
|
|
39
|
+
# Bring the relaunched window up maximized (SW_MAXIMIZE = 3). Electron shows the
|
|
40
|
+
# window itself first, so this runs after MainWindowHandle exists; a second call a
|
|
41
|
+
# moment later wins if the shell re-applies its own window placement.
|
|
42
|
+
function Set-WindowMaximized([IntPtr]$Handle) {
|
|
43
|
+
if ($Handle -eq [IntPtr]::Zero) { return $false }
|
|
44
|
+
try {
|
|
45
|
+
if (-not ('DshArWin32' -as [type])) {
|
|
46
|
+
Add-Type -TypeDefinition @"
|
|
47
|
+
using System;
|
|
48
|
+
using System.Runtime.InteropServices;
|
|
49
|
+
public static class DshArWin32 {
|
|
50
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
51
|
+
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
|
|
52
|
+
}
|
|
53
|
+
"@ -ErrorAction Stop
|
|
54
|
+
}
|
|
55
|
+
[void][DshArWin32]::ShowWindow($Handle, 3)
|
|
56
|
+
return $true
|
|
57
|
+
} catch {
|
|
58
|
+
Write-Log ('maximize failed: ' + $_.Exception.Message)
|
|
59
|
+
return $false
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
36
63
|
function Wait-ProcessGone([int]$ProcessId, [int]$TimeoutMs) {
|
|
37
64
|
$deadline = (Get-Date).AddMilliseconds($TimeoutMs)
|
|
38
65
|
while ((Get-Date) -lt $deadline) {
|
|
@@ -165,9 +192,25 @@ try {
|
|
|
165
192
|
if ($alive.MainWindowHandle -ne 0) { $windowUp = $true; break }
|
|
166
193
|
Start-Sleep -Milliseconds 500
|
|
167
194
|
}
|
|
195
|
+
$maximized = $false
|
|
168
196
|
if ($windowUp) {
|
|
169
|
-
Write-Result 'relaunched' ('window up, pid=' + $newProcess.Id)
|
|
170
197
|
Write-Log 'window is up'
|
|
198
|
+
if ($Maximize) {
|
|
199
|
+
$handle = [IntPtr]::Zero
|
|
200
|
+
$current = Get-Process -Id $newProcess.Id -ErrorAction SilentlyContinue
|
|
201
|
+
if ($current -ne $null) { $handle = $current.MainWindowHandle }
|
|
202
|
+
$maximized = Set-WindowMaximized $handle
|
|
203
|
+
if ($maximized) {
|
|
204
|
+
# The shell may apply its own placement right after showing; do it once more.
|
|
205
|
+
Start-Sleep -Milliseconds 700
|
|
206
|
+
$again = Get-Process -Id $newProcess.Id -ErrorAction SilentlyContinue
|
|
207
|
+
if ($again -ne $null) { [void](Set-WindowMaximized $again.MainWindowHandle) }
|
|
208
|
+
Write-Log 'window maximized'
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
$detail = 'window up, pid=' + $newProcess.Id
|
|
212
|
+
if ($maximized) { $detail = $detail + ', maximized' }
|
|
213
|
+
Write-Result 'relaunched' $detail
|
|
171
214
|
} else {
|
|
172
215
|
Write-Result 'relaunched-no-window' ('pid=' + $newProcess.Id + ' no window within 60s')
|
|
173
216
|
Write-Log 'relaunched without a window within 60s'
|
|
@@ -178,4 +221,4 @@ try {
|
|
|
178
221
|
Write-Result 'failed' $_.Exception.Message
|
|
179
222
|
exit 1
|
|
180
223
|
}
|
|
181
|
-
|
|
224
|
+
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leiyi-works/dsh-auto-restart",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"title": "自动重启",
|
|
6
|
-
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile
|
|
6
|
+
"description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,等所有会话空闲,由脱离进程树的守护者先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和左侧「自动重启」面板。",
|
|
7
7
|
"main": "index.js",
|
|
8
8
|
"exports": {
|
|
9
9
|
".": "./index.js",
|
|
10
|
+
"./client": "./client.js",
|
|
10
11
|
"./locale/*.json": "./locale/*.json",
|
|
11
12
|
"./icon": "./icon.svg",
|
|
12
13
|
"./package.json": "./package.json"
|
|
@@ -14,6 +15,7 @@
|
|
|
14
15
|
"icon": "icon.svg",
|
|
15
16
|
"files": [
|
|
16
17
|
"index.js",
|
|
18
|
+
"client.js",
|
|
17
19
|
"cordis.patch.yml",
|
|
18
20
|
"lib/*.ps1",
|
|
19
21
|
"locale/*.json",
|
|
@@ -23,6 +25,17 @@
|
|
|
23
25
|
"dsh": {
|
|
24
26
|
"bundle": {
|
|
25
27
|
"patch": "./cordis.patch.yml"
|
|
28
|
+
},
|
|
29
|
+
"client": {
|
|
30
|
+
"platform": "web",
|
|
31
|
+
"immediately": true,
|
|
32
|
+
"inject": [
|
|
33
|
+
"@deepseek-ai/dsh-client-modules",
|
|
34
|
+
"@deepseek-ai/dsh-client-locale",
|
|
35
|
+
"@deepseek-ai/dsh-client-ui-slots",
|
|
36
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
37
|
+
"@deepseek-ai/dsh-client-ui-sidebar"
|
|
38
|
+
]
|
|
26
39
|
}
|
|
27
40
|
},
|
|
28
41
|
"engines": {
|