@leiyi-works/dsh-auto-restart 0.3.0 → 0.3.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.
Files changed (4) hide show
  1. package/README.md +2 -2
  2. package/client.js +2 -11
  3. package/index.js +126 -24
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -18,7 +18,7 @@
18
18
 
19
19
  ## 它怎么重启
20
20
 
21
- 1. 等所有会话空闲(`api-session/status` + `agent/status`):最多等 `maxIdleWaitMs`(默认 **10 分钟**),超时就按计划重启并记录被中断的会话;设 `0` 表示一直等;
21
+ 1. 等所有会话空闲(`api-session/status` + `agent/status`):正在回答/干活的会一直等;**只卡在后台任务(`job_*`)上的会话不算忙**——这些 job 随 Host 被杀、不会自动恢复,所以重启会直接打断它们并在重启后发「继续」;停在选择题/审批上的会话永远不打断,答完且任务跑完才重新计 10 秒;
22
22
  2. 最后一次会话活动(发消息、回合开始/结束)之后再安静 10 秒,避免刚发出、回合还没起来的消息被重启吞掉、文字回到输入框;
23
23
  3. 等插件管理器安静 3 秒(不打断进行中的安装/更新);
24
24
  4. **优先交给常驻后台看门狗**:看门狗只在登录 Windows 时由「启动文件夹」里的引线自动启动,插件把请求写进 `~/.dsh/dsh-auto-restart/watchdog-request.json`,由它先杀 Electron 主进程、清残留、拉起应用并最大化——**不碰 WMI,也不会触发安全软件的 WMI 提示**;
@@ -47,7 +47,7 @@
47
47
 
48
48
  ### 重启后自动继续
49
49
 
50
- 被重启打断的会话(重启派发时正忙的那些)会在新进程启动后各收到一条 **「继续」**:用宿主服务 `sessionController.prompt()` 作为用户消息发回去。可通过 `continueInterrupted` 关闭、`continueText` 改文字;在等用户做选择/授权的会话(`pendingInput` 非空)会跳过,避免替你回答。适合"等 npm 发布窗口/等版本对齐"这类后台等待任务。**没有每小时次数上限**,只有 60 秒冷却防止连环重启。
50
+ 被重启打断的会话里,**只有正在跑后台任务(`job_*`,如 npm 轮询、版本对齐脚本、长命令)的那些**会在新进程启动后收到一条 **「继续」**:这些 job 随 Host 被杀、不会自动恢复。插件在重启前用 `jobs.list(sessionId)` 判断会话是否持有运行中的 job,并把 job 标签写进提示,方便模型接着做。可通过 `continueInterrupted` 关闭、`continueText` 改文字;**正在回答或等用户做选择/授权的会话不会被打扰**(`pendingInput` 非空会跳过)。**没有每小时次数上限**,只有 60 秒冷却防止连环重启。
51
51
 
52
52
  ## 安装后第一次
53
53
 
package/client.js CHANGED
@@ -308,22 +308,13 @@ window.__ModuleLoader__.load({
308
308
  }),
309
309
  h(SwitchRow, {
310
310
  label: '等所有会话空闲再重启',
311
- hint: '有回答或任务在跑时一直等它们结束,避免截断。',
311
+ hint: '正在回答/干活的会话会等它们结束;只卡在后台任务(job_*,如 npm 轮询、长命令)上的会话不算忙,会被本次重启打断并在重启后收到“继续”。',
312
312
  checked: config.waitForIdle !== false,
313
313
  onChange: (value) => change({ waitForIdle: value }),
314
314
  }),
315
- h(NumberRow, {
316
- label: '等空闲上限',
317
- hint: '忙超过这么久就按计划重启,不再无限等(重启后自动给被中断的会话发“继续”);0 表示一直等。',
318
- value: Math.round((config.maxIdleWaitMs ?? 600000) / 60000),
319
- min: 0,
320
- max: 240,
321
- suffix: '分钟',
322
- onChange: (value) => change({ maxIdleWaitMs: Math.max(0, Math.round(value)) * 60000 }),
323
- }),
324
315
  h(SwitchRow, {
325
316
  label: '重启后自动继续',
326
- hint: '给被这次重启打断的会话自动发一条“继续”;在等用户做选择/授权的会话会跳过。',
317
+ hint: '只给被后台任务(job_*,如 npm 轮询、长命令)打断的会话自动发“继续”;正在回答或等用户选择/授权的会话不动。',
327
318
  checked: config.continueInterrupted !== false,
328
319
  onChange: (value) => change({ continueInterrupted: value }),
329
320
  }),
package/index.js CHANGED
@@ -72,11 +72,9 @@ const DEFAULTS = Object.freeze({
72
72
  cooldownMs: 60000,
73
73
  /** 每小时最多重启几次;0 = 不限制。 */
74
74
  maxPerHour: 0,
75
- /** 有会话在跑时一直等它们空闲(没有上限,不会硬切)。 */
75
+ /** 有会话在跑时等它们空闲;等空闲的会话若只是卡在后台任务(job_*)上,会被本次重启打断并在重启后收到“继续”。 */
76
76
  waitForIdle: true,
77
- /** 等空闲最多等多久;超过就按计划重启(重启后会给被中断的会话发“继续”);0 = 一直等。 */
78
- maxIdleWaitMs: 600000,
79
- /** 重启后是否自动给被中断的会话发一条“继续”。 */
77
+ /** 重启后是否自动给被后台任务打断的会话发一条“继续”。 */
80
78
  continueInterrupted: true,
81
79
  /** 自动继续时发送的文本。 */
82
80
  continueText: '继续',
@@ -173,10 +171,39 @@ function interruptedPath() {
173
171
  return join(dataDir(), 'interrupted.json')
174
172
  }
175
173
 
174
+ /** The plugin context, kept for the one-time boot resume and the jobs lookup. */
175
+ let activeCtx = null
176
+
177
+ /** Background jobs still running for one Session (empty when the service is absent). */
178
+ function runningJobsFor(sessionId) {
179
+ try {
180
+ const jobs = activeCtx === null ? null : (activeCtx.get ? activeCtx.get('jobs') : null)
181
+ if (!jobs || typeof jobs.list !== 'function') return []
182
+ return jobs.list(sessionId).filter((job) => job && (job.status === 'running' || job.status === 'stopping'))
183
+ } catch {
184
+ return []
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Records only the Sessions that a restart would interrupt while a BACKGROUND JOB
190
+ * (job_*, e.g. an npm polling loop or a long command) is running: those jobs die
191
+ * with the Host and never recover on their own, so they get one "继续" after the
192
+ * restart. Sessions that are merely answering are left alone.
193
+ */
176
194
  function recordInterrupted(state, reason) {
177
195
  const file = interruptedPath()
178
- const ids = [...state.busy]
179
- if (ids.length === 0) {
196
+ const entries = []
197
+ for (const id of state.busy) {
198
+ const sessionId = String(id)
199
+ const jobs = runningJobsFor(sessionId)
200
+ if (jobs.length === 0) continue
201
+ entries.push({
202
+ sessionId,
203
+ jobs: jobs.slice(0, 5).map((job) => ({ id: String(job.id), label: String(job.label || job.kind || job.id) })),
204
+ })
205
+ }
206
+ if (entries.length === 0) {
180
207
  try { rmSync(file, { force: true }) } catch {}
181
208
  return
182
209
  }
@@ -184,26 +211,30 @@ function recordInterrupted(state, reason) {
184
211
  writeJsonAtomic(file, {
185
212
  at: new Date().toISOString(),
186
213
  reason,
187
- ids,
214
+ entries,
188
215
  exe: resolveExe(readConfig({})),
189
216
  })
190
- logLine('info', `已记录 ${ids.length} 个可能被中断的会话(重启后自动发“继续”):${ids.map((id) => String(id).slice(0, 18)).join(', ')}`)
217
+ const summary = entries.map((entry) => `${entry.sessionId.slice(0, 18)}(${entry.jobs.map((job) => job.label).join('、')})`).join(';')
218
+ logLine('info', `已记录 ${entries.length} 个因后台任务被中断的会话(重启后自动发“继续”):${summary}`)
191
219
  } catch (error) {
192
220
  logLine('warn', `记录被中断会话失败:${String(error?.message ?? error)}`)
193
221
  }
194
222
  }
195
223
 
196
224
  /**
197
- * After a restart, tell the Sessions that were interrupted to keep going.
198
- * Waiting-for-input sessions are skipped: resuming those would answer a question
199
- * the user never answered.
225
+ * After a restart, tell the Sessions whose background jobs were killed to keep
226
+ * going. Waiting-for-input sessions are skipped: resuming those would answer a
227
+ * question the user never answered.
200
228
  */
201
229
  async function resumeInterrupted(ctx, cfg) {
202
230
  const file = interruptedPath()
203
231
  const record = readJsonFile(file)
204
232
  if (record === null) return
205
233
  try {
206
- if (cfg.continueInterrupted === false || !Array.isArray(record.ids) || record.ids.length === 0) {
234
+ const entries = Array.isArray(record.entries)
235
+ ? record.entries
236
+ : (Array.isArray(record.ids) ? record.ids.map((sessionId) => ({ sessionId: String(sessionId), jobs: [] })) : [])
237
+ if (cfg.continueInterrupted === false || entries.length === 0) {
207
238
  try { rmSync(file, { force: true }) } catch {}
208
239
  return
209
240
  }
@@ -220,9 +251,14 @@ async function resumeInterrupted(ctx, cfg) {
220
251
  logLine('warn', '拿不到 sessionController,无法自动给被中断的会话发“继续”')
221
252
  return
222
253
  }
223
- for (let index = 0; index < record.ids.length; index += 1) {
224
- const sessionId = String(record.ids[index])
254
+ for (let index = 0; index < entries.length; index += 1) {
255
+ const entry = entries[index]
256
+ const sessionId = String(entry.sessionId)
225
257
  const short = sessionId.slice(0, 18)
258
+ const labels = Array.isArray(entry.jobs) ? entry.jobs.map((job) => String(job.label || job.id)).join('、') : ''
259
+ const text = labels === ''
260
+ ? String(cfg.continueText || '继续')
261
+ : `${String(cfg.continueText || '继续')}(刚才的后台任务因 DSH 重启被中断,不会自动恢复:${labels.slice(0, 120)}。请继续原来的工作)`
226
262
  try {
227
263
  let sessionState = null
228
264
  try { sessionState = await controller.state({ sessionId }) } catch {}
@@ -238,10 +274,10 @@ async function resumeInterrupted(ctx, cfg) {
238
274
  requestId: `auto-restart-continue-${Date.now()}-${index}`,
239
275
  sessionId,
240
276
  mode: 'queue',
241
- content: [{ type: 'text', text: String(cfg.continueText || '继续') }],
277
+ content: [{ type: 'text', text }],
242
278
  clientTimeZone: 'Asia/Shanghai',
243
279
  })
244
- logLine('info', `已给被中断的会话发“${cfg.continueText}”:${short}`)
280
+ logLine('info', `已给被中断的会话发“继续”:${short}`)
245
281
  } catch (error) {
246
282
  logLine('warn', `给 ${short} 发“继续”失败:${String(error?.message ?? error)}`)
247
283
  }
@@ -521,7 +557,6 @@ function sanitizeConfig(raw) {
521
557
  cfg.enabled = bool(raw.enabled, cfg.enabled)
522
558
  cfg.dryRun = bool(raw.dryRun, cfg.dryRun)
523
559
  cfg.waitForIdle = bool(raw.waitForIdle, cfg.waitForIdle)
524
- cfg.maxIdleWaitMs = num(raw.maxIdleWaitMs, cfg.maxIdleWaitMs, 0, 86400000)
525
560
  cfg.continueInterrupted = bool(raw.continueInterrupted, cfg.continueInterrupted)
526
561
  cfg.continueWindowMs = num(raw.continueWindowMs, cfg.continueWindowMs, 60000, 86400000)
527
562
  if (typeof raw.continueText === 'string' && raw.continueText.trim() !== '') cfg.continueText = raw.continueText.slice(0, 200)
@@ -841,6 +876,7 @@ function createState(profileDir) {
841
876
  pendingSince: 0,
842
877
  waitingSince: 0,
843
878
  lastActivityAt: 0,
879
+ pendingInputIds: new Set(),
844
880
  lastRestartAt: persisted.lastRestartAt,
845
881
  restarts: persisted.restarts.filter((t) => now - t < 3600000),
846
882
  lastManagerAt: 0,
@@ -854,6 +890,40 @@ function createState(profileDir) {
854
890
  }
855
891
  }
856
892
 
893
+ /**
894
+ * Refreshes which busy Sessions are stopped waiting for the user (a question or
895
+ * an approval). Those Sessions pause the idle timeout; when the answer arrives
896
+ * and the task finishes, both 10s counters restart so a restart never races the
897
+ * just-answered work.
898
+ */
899
+ async function refreshPendingInputs(ctx, state) {
900
+ let controller = null
901
+ try { controller = ctx.get('sessionController') } catch { controller = null }
902
+ if (!controller || typeof controller.state !== 'function') return
903
+ const next = new Set()
904
+ for (const id of state.busy) {
905
+ try {
906
+ const sessionState = await controller.state({ sessionId: String(id) })
907
+ if (sessionState && Array.isArray(sessionState.pendingInput) && sessionState.pendingInput.length > 0) {
908
+ next.add(String(id))
909
+ }
910
+ } catch {
911
+ // a cold or disposed Session simply does not contribute to the set
912
+ }
913
+ }
914
+ const previous = state.pendingInputIds instanceof Set ? state.pendingInputIds : new Set()
915
+ state.pendingInputIds = next
916
+ let answered = false
917
+ for (const id of previous) {
918
+ if (!next.has(id)) { answered = true; break }
919
+ }
920
+ if (answered) {
921
+ state.lastActivityAt = Date.now()
922
+ state.lastChangeAt = Date.now()
923
+ logLine('info', '选择/审批已处理:重新开始 10 秒安静/文件稳定计时')
924
+ }
925
+ }
926
+
857
927
  function tick(baseConfig) {
858
928
  const cfg = readConfig(baseConfig)
859
929
  if (!cfg.enabled) return
@@ -920,16 +990,38 @@ function tick(baseConfig) {
920
990
  }
921
991
 
922
992
  if (cfg.waitForIdle && state.busy.size > 0) {
923
- const busyForMs = state.waitingSince > 0 ? now - state.waitingSince : 0
924
- const overLimit = cfg.maxIdleWaitMs > 0 && busyForMs >= cfg.maxIdleWaitMs
925
- if (!overLimit) {
993
+ // A Session stopped on a choice/approval must never time out: the user is
994
+ // deciding. Pause the idle clock, and once the answer is in and that task has
995
+ // finished, the 10s quiet/stability counters start over.
996
+ const pendingCount = state.pendingInputIds instanceof Set ? state.pendingInputIds.size : 0
997
+ if (pendingCount > 0) {
998
+ state.waitingSince = now
999
+ if (now - state.lastSkipLog > 15000) {
1000
+ state.lastSkipLog = now
1001
+ logLine('info', `有 ${pendingCount} 个会话在等你选择/审批,暂停等空闲计时(答完并跑完后重新开始 10 秒计时)`)
1002
+ }
1003
+ return
1004
+ }
1005
+
1006
+ // A Session blocked on a running background job (job_*, e.g. an npm polling
1007
+ // loop) is deliberately NOT counted as busy: its job dies with the Host and
1008
+ // cannot recover on its own, so the restart interrupts it and resumeInterrupted
1009
+ // sends one "继续" after the new process is up. Only Sessions doing real work
1010
+ // (streaming an answer, running the model) keep the restart waiting.
1011
+ const jobBlocked = []
1012
+ const hardBusy = []
1013
+ for (const id of state.busy) {
1014
+ if (runningJobsFor(String(id)).length > 0) jobBlocked.push(String(id))
1015
+ else hardBusy.push(String(id))
1016
+ }
1017
+ if (hardBusy.length > 0) {
926
1018
  if (state.waitingSince === 0) {
927
1019
  state.waitingSince = now
928
- logLine('info', `有 ${state.busy.size} 个会话在跑,等它们空闲后再重启(最多等 ${cfg.maxIdleWaitMs > 0 ? Math.round(cfg.maxIdleWaitMs / 60000) + ' 分钟' : '一直等'})`)
1020
+ logLine('info', `有 ${hardBusy.length} 个会话正在回答/干活,等它们空闲后再重启(会一直等)${jobBlocked.length > 0 ? `;另外 ${jobBlocked.length} 个会话在等后台任务,重启会打断它们并在重启后发“继续”` : ''}`)
929
1021
  }
930
1022
  return
931
1023
  }
932
- logLine('warn', `等空闲已超过 ${Math.round(cfg.maxIdleWaitMs / 60000)} 分钟(${state.busy.size} 个会话还在跑),按计划重启;重启后会给它们发“继续”`)
1024
+ logLine('info', `其余 ${jobBlocked.length} 个会话都在等后台任务(job_*);本次重启会打断它们,重启后自动发“继续”`)
933
1025
  }
934
1026
  state.waitingSince = 0
935
1027
 
@@ -1027,7 +1119,6 @@ function installRoutes(ctx, baseConfig) {
1027
1119
  logPath: watchdogLogPath(),
1028
1120
  },
1029
1121
  waitForIdle: cfg.waitForIdle,
1030
- maxIdleWaitMs: cfg.maxIdleWaitMs,
1031
1122
  continueInterrupted: cfg.continueInterrupted,
1032
1123
  continueText: cfg.continueText,
1033
1124
  busySessions: state ? [...state.busy] : [],
@@ -1085,7 +1176,8 @@ function installRoutes(ctx, baseConfig) {
1085
1176
  }
1086
1177
 
1087
1178
  export function apply(ctx, config) {
1088
- try {
1179
+ activeCtx = ctx
1180
+ try {
1089
1181
  try {
1090
1182
  const scoped = typeof ctx.logger === 'function' ? ctx.logger(MARK) : ctx.logger
1091
1183
  if (scoped && typeof scoped.info === 'function') logger = (level, message) => scoped[level]?.(message)
@@ -1189,6 +1281,16 @@ export function apply(ctx, config) {
1189
1281
  return () => clearInterval(timer)
1190
1282
  }, 'auto-restart: watcher')
1191
1283
 
1284
+ // Poll pending question/approval state: a waiting Session pauses the idle
1285
+ // timeout until the user answers and the task finishes.
1286
+ ctx.effect(() => {
1287
+ const timer = setInterval(() => {
1288
+ void refreshPendingInputs(ctx, state)
1289
+ }, 3000)
1290
+ timer.unref?.()
1291
+ return () => clearInterval(timer)
1292
+ }, 'auto-restart: pending input watch')
1293
+
1192
1294
  installRoutes(ctx, baseConfig)
1193
1295
  } catch (error) {
1194
1296
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-auto-restart",
3
- "version": "0.3.0",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "title": "自动重启",
6
6
  "description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",