@leiyi-works/dsh-auto-restart 0.3.6 → 0.3.8

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 (2) hide show
  1. package/index.js +77 -28
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -175,6 +175,58 @@ function interruptedPath() {
175
175
 
176
176
  /** The plugin context, kept for the one-time boot resume and the jobs lookup. */
177
177
  let activeCtx = null
178
+ /** In-memory restart state, kept for the on-demand tool tracker. */
179
+ let activeState = null
180
+ /** Disposer of the tools/execute listener; non-null only while a restart is pending. */
181
+ let toolsTrackingDispose = null
182
+
183
+ /** Records which tool each Session is executing right now. */
184
+ function trackToolExecution(exec, next) {
185
+ const agentId = exec?.agent?.id
186
+ const name = typeof exec?.name === 'string' ? exec.name : ''
187
+ const state = activeState
188
+ if (agentId === undefined || name === '' || state === null || !(state.activeTools instanceof Map)) return next()
189
+ const key = String(agentId)
190
+ const token = { name, at: Date.now() }
191
+ state.activeTools.set(key, token)
192
+ const settle = () => {
193
+ if (state.activeTools instanceof Map && state.activeTools.get(key) === token) state.activeTools.delete(key)
194
+ }
195
+ let pending
196
+ try {
197
+ pending = next()
198
+ } catch (error) {
199
+ settle()
200
+ throw error
201
+ }
202
+ return Promise.resolve(pending).then(
203
+ (result) => { settle(); return result },
204
+ (error) => { settle(); throw error },
205
+ )
206
+ }
207
+
208
+ /**
209
+ * Attach the tool tracker only while a restart is pending. Between restarts the
210
+ * plugin has no tools/execute listener at all, so idle memory and CPU are zero.
211
+ */
212
+ function startToolsTracking() {
213
+ if (toolsTrackingDispose !== null || activeCtx === null) return
214
+ try {
215
+ toolsTrackingDispose = activeCtx.on('tools/execute', trackToolExecution)
216
+ } catch {
217
+ toolsTrackingDispose = null
218
+ }
219
+ }
220
+
221
+ function stopToolsTracking() {
222
+ if (toolsTrackingDispose === null) return
223
+ const dispose = toolsTrackingDispose
224
+ toolsTrackingDispose = null
225
+ try { dispose() } catch {}
226
+ try {
227
+ if (activeState !== null && activeState.activeTools instanceof Map) activeState.activeTools.clear()
228
+ } catch {}
229
+ }
178
230
 
179
231
  /** Background jobs still running for one Session (empty when the service is absent). */
180
232
  function runningJobsFor(sessionId) {
@@ -193,6 +245,13 @@ function runningJobsFor(sessionId) {
193
245
  * with the Host and never recover on their own, so they get one "继续" after the
194
246
  * restart. Sessions that are merely answering are left alone.
195
247
  */
248
+ /** One-line, bounded label for a job (bash jobs carry the whole command line). */
249
+ function shortenLabel(text, max = 48) {
250
+ const clean = String(text ?? '').replace(/\s+/g, ' ').trim()
251
+ if (clean === '') return ''
252
+ return clean.length <= max ? clean : `${clean.slice(0, Math.max(1, max - 1))}…`
253
+ }
254
+
196
255
  function recordInterrupted(state, reason) {
197
256
  const file = interruptedPath()
198
257
  const entries = []
@@ -202,7 +261,7 @@ function recordInterrupted(state, reason) {
202
261
  if (jobs.length === 0) continue
203
262
  entries.push({
204
263
  sessionId,
205
- jobs: jobs.slice(0, 5).map((job) => ({ id: String(job.id), label: String(job.label || job.kind || job.id) })),
264
+ jobs: jobs.slice(0, 5).map((job) => ({ id: String(job.id), label: shortenLabel(job.label || job.kind || job.id) })),
206
265
  })
207
266
  }
208
267
  if (entries.length === 0) {
@@ -257,10 +316,12 @@ async function resumeInterrupted(ctx, cfg) {
257
316
  const entry = entries[index]
258
317
  const sessionId = String(entry.sessionId)
259
318
  const short = sessionId.slice(0, 18)
260
- const labels = Array.isArray(entry.jobs) ? entry.jobs.map((job) => String(job.label || job.id)).join('、') : ''
319
+ const labels = Array.isArray(entry.jobs)
320
+ ? entry.jobs.map((job) => shortenLabel(job.label || job.id, 40)).filter((label) => label !== '').join('、')
321
+ : ''
261
322
  const text = labels === ''
262
323
  ? String(cfg.continueText || '继续')
263
- : `${String(cfg.continueText || '继续')}(刚才的后台任务因 DSH 重启被中断,不会自动恢复:${labels.slice(0, 120)}。请继续原来的工作)`
324
+ : `${String(cfg.continueText || '继续')}(刚才的后台任务因 DSH 重启被中断,不会自动恢复:${labels.slice(0, 140)}。请继续原来的工作)`
264
325
  try {
265
326
  let sessionState = null
266
327
  try { sessionState = await controller.state({ sessionId }) } catch {}
@@ -1001,6 +1062,11 @@ function tick(baseConfig) {
1001
1062
  const now = Date.now()
1002
1063
  state.restarts = state.restarts.filter((t) => now - t < 3600000)
1003
1064
 
1065
+ // The tool tracker only exists while a restart is actually being considered:
1066
+ // attach it when a change armed the restart, drop it once nothing is pending.
1067
+ if (state.pendingSince > 0 && state.dispatchedAt === 0) startToolsTracking()
1068
+ else stopToolsTracking()
1069
+
1004
1070
  // A restart is already on its way; the process will disappear shortly.
1005
1071
  if (state.dispatchedAt > 0 && now - state.dispatchedAt < 60000) return
1006
1072
 
@@ -1267,6 +1333,7 @@ export function apply(ctx, config) {
1267
1333
  if (globalThis[STATE_KEY] === undefined) globalThis[STATE_KEY] = createState(profileDir)
1268
1334
  else globalThis[STATE_KEY].profileDir = profileDir
1269
1335
  const state = globalThis[STATE_KEY]
1336
+ activeState = state
1270
1337
 
1271
1338
  // Report the outcome of the restart this process may have just survived.
1272
1339
  // The supervisor writes `stopped` first and `relaunched` only after the new
@@ -1342,31 +1409,10 @@ export function apply(ctx, config) {
1342
1409
  if (state.sessionLastEventAt instanceof Map) state.sessionLastEventAt.set(String(id), Date.now())
1343
1410
  }), 'auto-restart: session events')
1344
1411
 
1345
- // The exact signal for "this Session is waiting on a background job": which
1346
- // tool it is executing right now. job_* calls mean the model is blocked on the
1347
- // job, everything else means the Session is really working.
1348
- ctx.effect(() => ctx.on('tools/execute', (exec, next) => {
1349
- const agentId = exec?.agent?.id
1350
- const name = typeof exec?.name === 'string' ? exec.name : ''
1351
- if (agentId === undefined || name === '' || !(state.activeTools instanceof Map)) return next()
1352
- const key = String(agentId)
1353
- const token = { name, at: Date.now() }
1354
- state.activeTools.set(key, token)
1355
- const settle = () => {
1356
- if (state.activeTools instanceof Map && state.activeTools.get(key) === token) state.activeTools.delete(key)
1357
- }
1358
- let pending
1359
- try {
1360
- pending = next()
1361
- } catch (error) {
1362
- settle()
1363
- throw error
1364
- }
1365
- return Promise.resolve(pending).then(
1366
- (result) => { settle(); return result },
1367
- (error) => { settle(); throw error },
1368
- )
1369
- }), 'auto-restart: active tools')
1412
+ // The exact signal for "this Session is waiting on a background job" is the
1413
+ // tool it is executing right now. That tracker is attached on demand by tick
1414
+ // only while a restart is pending (see startToolsTracking), so the plugin
1415
+ // carries no tools/execute listener while it is idle.
1370
1416
 
1371
1417
  // User-authored messages: the turn may not have started yet, but the text was
1372
1418
  // just sent, so a restart here would swallow it and restore the draft.
@@ -1378,6 +1424,9 @@ export function apply(ctx, config) {
1378
1424
  safeOn(ctx, event, () => { state.lastManagerAt = Date.now() }, `auto-restart: ${event}`)
1379
1425
  }
1380
1426
 
1427
+ // Drop the on-demand tool tracker when the plugin unloads.
1428
+ ctx.effect(() => () => stopToolsTracking())
1429
+
1381
1430
  // One timer for the whole plugin; disposal clears it.
1382
1431
  const interval = Math.max(500, Math.min(5000, cfg.pollIntervalMs))
1383
1432
  ctx.effect(() => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leiyi-works/dsh-auto-restart",
3
- "version": "0.3.6",
3
+ "version": "0.3.8",
4
4
  "type": "module",
5
5
  "title": "自动重启",
6
6
  "description": "装/更插件后自动重启 DSH 并回到原会话:检测 profile 插件文件变化,一直等所有会话空闲且最近活动安静,由常驻后台看门狗(登录自启、不碰 WMI)或 WMI 守护先杀主进程再拉起(可最大化窗口),带冷却、试运行、日志和右侧原生侧边栏面板。",