@leiyi-works/dsh-auto-restart 0.3.0 → 0.3.2

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 +1 -1
  2. package/client.js +1 -1
  3. package/index.js +109 -13
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -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
@@ -323,7 +323,7 @@ window.__ModuleLoader__.load({
323
323
  }),
324
324
  h(SwitchRow, {
325
325
  label: '重启后自动继续',
326
- hint: '给被这次重启打断的会话自动发一条“继续”;在等用户做选择/授权的会话会跳过。',
326
+ hint: '只给被后台任务(job_*,如 npm 轮询、长命令)打断的会话自动发“继续”;正在回答或等用户选择/授权的会话不动。',
327
327
  checked: config.continueInterrupted !== false,
328
328
  onChange: (value) => change({ continueInterrupted: value }),
329
329
  }),
package/index.js CHANGED
@@ -173,10 +173,39 @@ function interruptedPath() {
173
173
  return join(dataDir(), 'interrupted.json')
174
174
  }
175
175
 
176
+ /** The plugin context, kept for the one-time boot resume and the jobs lookup. */
177
+ let activeCtx = null
178
+
179
+ /** Background jobs still running for one Session (empty when the service is absent). */
180
+ function runningJobsFor(sessionId) {
181
+ try {
182
+ const jobs = activeCtx === null ? null : (activeCtx.get ? activeCtx.get('jobs') : null)
183
+ if (!jobs || typeof jobs.list !== 'function') return []
184
+ return jobs.list(sessionId).filter((job) => job && (job.status === 'running' || job.status === 'stopping'))
185
+ } catch {
186
+ return []
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Records only the Sessions that a restart would interrupt while a BACKGROUND JOB
192
+ * (job_*, e.g. an npm polling loop or a long command) is running: those jobs die
193
+ * with the Host and never recover on their own, so they get one "继续" after the
194
+ * restart. Sessions that are merely answering are left alone.
195
+ */
176
196
  function recordInterrupted(state, reason) {
177
197
  const file = interruptedPath()
178
- const ids = [...state.busy]
179
- if (ids.length === 0) {
198
+ const entries = []
199
+ for (const id of state.busy) {
200
+ const sessionId = String(id)
201
+ const jobs = runningJobsFor(sessionId)
202
+ if (jobs.length === 0) continue
203
+ entries.push({
204
+ sessionId,
205
+ jobs: jobs.slice(0, 5).map((job) => ({ id: String(job.id), label: String(job.label || job.kind || job.id) })),
206
+ })
207
+ }
208
+ if (entries.length === 0) {
180
209
  try { rmSync(file, { force: true }) } catch {}
181
210
  return
182
211
  }
@@ -184,26 +213,30 @@ function recordInterrupted(state, reason) {
184
213
  writeJsonAtomic(file, {
185
214
  at: new Date().toISOString(),
186
215
  reason,
187
- ids,
216
+ entries,
188
217
  exe: resolveExe(readConfig({})),
189
218
  })
190
- logLine('info', `已记录 ${ids.length} 个可能被中断的会话(重启后自动发“继续”):${ids.map((id) => String(id).slice(0, 18)).join(', ')}`)
219
+ const summary = entries.map((entry) => `${entry.sessionId.slice(0, 18)}(${entry.jobs.map((job) => job.label).join('、')})`).join(';')
220
+ logLine('info', `已记录 ${entries.length} 个因后台任务被中断的会话(重启后自动发“继续”):${summary}`)
191
221
  } catch (error) {
192
222
  logLine('warn', `记录被中断会话失败:${String(error?.message ?? error)}`)
193
223
  }
194
224
  }
195
225
 
196
226
  /**
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.
227
+ * After a restart, tell the Sessions whose background jobs were killed to keep
228
+ * going. Waiting-for-input sessions are skipped: resuming those would answer a
229
+ * question the user never answered.
200
230
  */
201
231
  async function resumeInterrupted(ctx, cfg) {
202
232
  const file = interruptedPath()
203
233
  const record = readJsonFile(file)
204
234
  if (record === null) return
205
235
  try {
206
- if (cfg.continueInterrupted === false || !Array.isArray(record.ids) || record.ids.length === 0) {
236
+ const entries = Array.isArray(record.entries)
237
+ ? record.entries
238
+ : (Array.isArray(record.ids) ? record.ids.map((sessionId) => ({ sessionId: String(sessionId), jobs: [] })) : [])
239
+ if (cfg.continueInterrupted === false || entries.length === 0) {
207
240
  try { rmSync(file, { force: true }) } catch {}
208
241
  return
209
242
  }
@@ -220,9 +253,14 @@ async function resumeInterrupted(ctx, cfg) {
220
253
  logLine('warn', '拿不到 sessionController,无法自动给被中断的会话发“继续”')
221
254
  return
222
255
  }
223
- for (let index = 0; index < record.ids.length; index += 1) {
224
- const sessionId = String(record.ids[index])
256
+ for (let index = 0; index < entries.length; index += 1) {
257
+ const entry = entries[index]
258
+ const sessionId = String(entry.sessionId)
225
259
  const short = sessionId.slice(0, 18)
260
+ const labels = Array.isArray(entry.jobs) ? entry.jobs.map((job) => String(job.label || job.id)).join('、') : ''
261
+ const text = labels === ''
262
+ ? String(cfg.continueText || '继续')
263
+ : `${String(cfg.continueText || '继续')}(刚才的后台任务因 DSH 重启被中断,不会自动恢复:${labels.slice(0, 120)}。请继续原来的工作)`
226
264
  try {
227
265
  let sessionState = null
228
266
  try { sessionState = await controller.state({ sessionId }) } catch {}
@@ -238,10 +276,10 @@ async function resumeInterrupted(ctx, cfg) {
238
276
  requestId: `auto-restart-continue-${Date.now()}-${index}`,
239
277
  sessionId,
240
278
  mode: 'queue',
241
- content: [{ type: 'text', text: String(cfg.continueText || '继续') }],
279
+ content: [{ type: 'text', text }],
242
280
  clientTimeZone: 'Asia/Shanghai',
243
281
  })
244
- logLine('info', `已给被中断的会话发“${cfg.continueText}”:${short}`)
282
+ logLine('info', `已给被中断的会话发“继续”:${short}`)
245
283
  } catch (error) {
246
284
  logLine('warn', `给 ${short} 发“继续”失败:${String(error?.message ?? error)}`)
247
285
  }
@@ -841,6 +879,7 @@ function createState(profileDir) {
841
879
  pendingSince: 0,
842
880
  waitingSince: 0,
843
881
  lastActivityAt: 0,
882
+ pendingInputIds: new Set(),
844
883
  lastRestartAt: persisted.lastRestartAt,
845
884
  restarts: persisted.restarts.filter((t) => now - t < 3600000),
846
885
  lastManagerAt: 0,
@@ -854,6 +893,40 @@ function createState(profileDir) {
854
893
  }
855
894
  }
856
895
 
896
+ /**
897
+ * Refreshes which busy Sessions are stopped waiting for the user (a question or
898
+ * an approval). Those Sessions pause the idle timeout; when the answer arrives
899
+ * and the task finishes, both 10s counters restart so a restart never races the
900
+ * just-answered work.
901
+ */
902
+ async function refreshPendingInputs(ctx, state) {
903
+ let controller = null
904
+ try { controller = ctx.get('sessionController') } catch { controller = null }
905
+ if (!controller || typeof controller.state !== 'function') return
906
+ const next = new Set()
907
+ for (const id of state.busy) {
908
+ try {
909
+ const sessionState = await controller.state({ sessionId: String(id) })
910
+ if (sessionState && Array.isArray(sessionState.pendingInput) && sessionState.pendingInput.length > 0) {
911
+ next.add(String(id))
912
+ }
913
+ } catch {
914
+ // a cold or disposed Session simply does not contribute to the set
915
+ }
916
+ }
917
+ const previous = state.pendingInputIds instanceof Set ? state.pendingInputIds : new Set()
918
+ state.pendingInputIds = next
919
+ let answered = false
920
+ for (const id of previous) {
921
+ if (!next.has(id)) { answered = true; break }
922
+ }
923
+ if (answered) {
924
+ state.lastActivityAt = Date.now()
925
+ state.lastChangeAt = Date.now()
926
+ logLine('info', '选择/审批已处理:重新开始 10 秒安静/文件稳定计时')
927
+ }
928
+ }
929
+
857
930
  function tick(baseConfig) {
858
931
  const cfg = readConfig(baseConfig)
859
932
  if (!cfg.enabled) return
@@ -920,6 +993,18 @@ function tick(baseConfig) {
920
993
  }
921
994
 
922
995
  if (cfg.waitForIdle && state.busy.size > 0) {
996
+ // A Session stopped on a choice/approval must never time out: the user is
997
+ // deciding. Pause the idle clock, and once the answer is in and that task has
998
+ // finished, the 10s quiet/stability counters start over.
999
+ const pendingCount = state.pendingInputIds instanceof Set ? state.pendingInputIds.size : 0
1000
+ if (pendingCount > 0) {
1001
+ state.waitingSince = now
1002
+ if (now - state.lastSkipLog > 15000) {
1003
+ state.lastSkipLog = now
1004
+ logLine('info', `有 ${pendingCount} 个会话在等你选择/审批,暂停等空闲计时(答完并跑完后重新开始 10 秒计时)`)
1005
+ }
1006
+ return
1007
+ }
923
1008
  const busyForMs = state.waitingSince > 0 ? now - state.waitingSince : 0
924
1009
  const overLimit = cfg.maxIdleWaitMs > 0 && busyForMs >= cfg.maxIdleWaitMs
925
1010
  if (!overLimit) {
@@ -1085,7 +1170,8 @@ function installRoutes(ctx, baseConfig) {
1085
1170
  }
1086
1171
 
1087
1172
  export function apply(ctx, config) {
1088
- try {
1173
+ activeCtx = ctx
1174
+ try {
1089
1175
  try {
1090
1176
  const scoped = typeof ctx.logger === 'function' ? ctx.logger(MARK) : ctx.logger
1091
1177
  if (scoped && typeof scoped.info === 'function') logger = (level, message) => scoped[level]?.(message)
@@ -1189,6 +1275,16 @@ export function apply(ctx, config) {
1189
1275
  return () => clearInterval(timer)
1190
1276
  }, 'auto-restart: watcher')
1191
1277
 
1278
+ // Poll pending question/approval state: a waiting Session pauses the idle
1279
+ // timeout until the user answers and the task finishes.
1280
+ ctx.effect(() => {
1281
+ const timer = setInterval(() => {
1282
+ void refreshPendingInputs(ctx, state)
1283
+ }, 3000)
1284
+ timer.unref?.()
1285
+ return () => clearInterval(timer)
1286
+ }, 'auto-restart: pending input watch')
1287
+
1192
1288
  installRoutes(ctx, baseConfig)
1193
1289
  } catch (error) {
1194
1290
  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.2",
4
4
  "type": "module",
5
5
  "title": "自动重启",
6
6
  "description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",