@restregular/dsh-powerup 0.11.0 → 0.12.0

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 CHANGED
@@ -142,6 +142,18 @@ entries other plugins add) become an icon grid instead of a one-per-row list:
142
142
  its own (chat glyph + label) that calls `layout.selectPanel(null)` to return
143
143
  to the Conversation; it highlights when no global panel is selected and can be
144
144
  placed anywhere by dragging, including into a folder.
145
+ - **Task-aware restart and close.** `GET /dsh-powerup/api/restart|close` also
146
+ reports `runningTasks` (live running Agents and running background jobs). When
147
+ any task is unfinished the normal confirm is blocked: the dialog lists the
148
+ sessions and offers a **Force restart / Force close** path that stops every
149
+ running Agent and job first. That forced path has an extra **Resume tasks after
150
+ restart / Resume tasks on next launch** option (on by default, with an optional
151
+ custom continuation prompt). With resume enabled the Host cancels each running
152
+ Agent, kills running jobs, and records the affected sessions in
153
+ `~/.dsh/dsh-powerup/task-resume.json`; on the next successful startup it sends
154
+ each session a queued "continue" prompt through `sessionController.prompt`
155
+ (which resumes cold sessions), then removes the delivered records. With resume
156
+ disabled the forced path only stops the work and keeps no records.
145
157
  - **A synthetic "Restart DSH" tile.** A second Power-Up tile (a ring with the
146
158
  arrowhead tangent to the top, i.e. the arrow lines up with the arc) plus
147
159
  `重启` / `Restart` opens the same restart confirmation the pending-restart
package/client.js CHANGED
@@ -310,6 +310,18 @@
310
310
  'restart.desc': '重启会关闭并重新打开 DSH,正在运行的任务会中断。',
311
311
  'restart.cancel': '取消',
312
312
  'restart.confirm': '立即重启',
313
+ 'restart.tasksTitle': '有 {count} 个任务尚未完成',
314
+ 'restart.tasksHint': '普通重启不允许中断未完成任务。可以强制停止它们后再重启。',
315
+ 'restart.forceLabel': '强制重启',
316
+ 'restart.forceCloseLabel': '强制关闭',
317
+ 'restart.resumeLabel': '重启后自动继续任务',
318
+ 'restart.resumeLabelClose': '下次打开后自动继续任务',
319
+ 'restart.resumeHint': '停止前记录这些会话,下次打开 DSH 时自动发送「继续」提示词。',
320
+ 'restart.resumePromptLabel': '继续提示词(可选)',
321
+ 'restart.resumePromptPlaceholder': '默认:继续之前未完成的任务。',
322
+ 'restart.taskLine': '会话 {id}',
323
+ 'restart.forceConfirm': '强制停止并重启',
324
+ 'force.done': '已停止 {count} 个任务,将自动继续 {resumed} 个会话。',
313
325
  'update.doneTitle': '安装完成',
314
326
  'update.doneInstalled': '{name} 已安装 {version}。',
315
327
  'update.doneDisabled': '{name} 已安装 {version},尚未启用。',
@@ -632,6 +644,18 @@
632
644
  'restart.desc': 'Restarting closes and reopens DSH; running tasks are interrupted.',
633
645
  'restart.cancel': 'Cancel',
634
646
  'restart.confirm': 'Restart now',
647
+ 'restart.tasksTitle': '{count} unfinished task(s)',
648
+ 'restart.tasksHint': 'A normal restart cannot interrupt unfinished tasks. Force-stop them first, then restart.',
649
+ 'restart.forceLabel': 'Force restart',
650
+ 'restart.forceCloseLabel': 'Force close',
651
+ 'restart.resumeLabel': 'Resume tasks after restart',
652
+ 'restart.resumeLabelClose': 'Resume tasks on next launch',
653
+ 'restart.resumeHint': 'Record these sessions before stopping; on next launch DSH sends a "continue" prompt automatically.',
654
+ 'restart.resumePromptLabel': 'Continuation prompt (optional)',
655
+ 'restart.resumePromptPlaceholder': 'Default: Continue the previous unfinished task.',
656
+ 'restart.taskLine': 'Session {id}',
657
+ 'restart.forceConfirm': 'Force-stop and restart',
658
+ 'force.done': 'Stopped {count} task(s); {resumed} session(s) will resume automatically.',
635
659
  'update.doneTitle': 'Install complete',
636
660
  'update.doneInstalled': '{name} installed {version}.',
637
661
  'update.doneDisabled': '{name} {version} is installed but not enabled.',
@@ -1237,11 +1261,21 @@
1237
1261
  window.alert(t(options.unsupportedKey, { reason: capability?.reason ?? '' }));
1238
1262
  return;
1239
1263
  }
1264
+ const tasks = Array.isArray(capability?.runningTasks) ? capability.runningTasks : [];
1240
1265
  if (window.confirm(t(options.titleKey) + ' ' + t(options.descKey)) !== true) return;
1266
+ // With unfinished tasks, the last-resort path offers the forced
1267
+ // variant through a second confirmation and resumes by default.
1268
+ let force = false;
1269
+ let resume = false;
1270
+ if (tasks.length > 0) {
1271
+ if (window.confirm(t('restart.tasksTitle', { count: tasks.length }) + '\n' + t('restart.tasksHint')) !== true) return;
1272
+ force = true;
1273
+ resume = window.confirm(t(options.action === 'close' ? 'restart.resumeLabelClose' : 'restart.resumeLabel') + '\n' + t('restart.resumeHint')) === true;
1274
+ }
1241
1275
  const response = await fetch(options.api, {
1242
1276
  method: 'POST',
1243
1277
  headers: { 'content-type': 'application/json' },
1244
- body: JSON.stringify({ action: options.action }),
1278
+ body: JSON.stringify({ action: options.action, force, resume }),
1245
1279
  });
1246
1280
  const data = await response.json().catch(() => null);
1247
1281
  if (!response.ok || data?.ok !== true) throw new Error(data?.error ?? 'HTTP ' + response.status);
@@ -4097,6 +4131,17 @@ nav.dsh-powerup-launcher.dsh-powerup-launcher-wide>[data-powerup-grid]:hover [cl
4097
4131
  .dsh-powerup-update-field{display:flex;flex-direction:column;gap:8px;min-width:0}
4098
4132
  .dsh-powerup-update-label{display:block;color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;font-weight:500}
4099
4133
  .dsh-powerup-update-note{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px;overflow-wrap:anywhere}
4134
+ .dsh-powerup-update-tasks{display:flex;flex-direction:column;gap:8px;padding:12px;border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-2)}
4135
+ .dsh-powerup-update-tasks>strong{color:var(--dsw-alias-label-primary);font-size:12.5px;line-height:18px}
4136
+ .dsh-powerup-update-task-list{display:flex;flex-direction:column;gap:4px;max-height:150px;overflow-y:auto;margin:2px 0;padding:0;list-style:none}
4137
+ .dsh-powerup-update-task-list li{display:flex;align-items:center;gap:7px;min-width:0;padding:4px 8px;border-radius:var(--dsw-radius-sm,6px);background:var(--dsw-alias-bg-layer-3);color:var(--dsw-alias-label-secondary);font-size:11.5px;line-height:16px}
4138
+ .dsh-powerup-update-task-list code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--dsw-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace);font-size:11px}
4139
+ .dsh-powerup-update-task-dot{flex:none;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-state-warning-foreground,var(--dsw-alias-brand-primary))}
4140
+ .dsh-powerup-app-check{display:flex;align-items:flex-start;gap:9px;padding:4px 0;cursor:pointer}
4141
+ .dsh-powerup-app-check input{flex:none;margin:2px 0 0;accent-color:var(--dsw-alias-brand-primary)}
4142
+ .dsh-powerup-app-check span{display:flex;flex-direction:column;gap:1px;min-width:0}
4143
+ .dsh-powerup-app-check strong{color:var(--dsw-alias-label-primary);font-size:12px;line-height:18px;font-weight:500}
4144
+ .dsh-powerup-app-check small{color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:16px}
4100
4145
  .dsh-powerup-update-name{color:var(--dsw-alias-label-tertiary);font-family:var(--dsw-font-family-code,ui-monospace,SFMono-Regular,Consolas,monospace);font-size:11.5px;line-height:18px;overflow-wrap:anywhere}
4101
4146
  .dsh-powerup-update-summary{display:flex;flex-direction:column;gap:2px;min-width:0}
4102
4147
  .dsh-powerup-update-list-state{display:flex;flex-direction:column;gap:10px;padding:12px}
@@ -7137,6 +7182,12 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7137
7182
  const [appCapability, setAppCapability] = useState(null);
7138
7183
  const [appBusy, setAppBusy] = useState(false);
7139
7184
  const [appError, setAppError] = useState(null);
7185
+ /** Running tasks reported by the Host for the app action dialog. */
7186
+ const [appTasks, setAppTasks] = useState([]);
7187
+ /** Checkbox: force-stopped tasks are resumed on next launch. */
7188
+ const [appResume, setAppResume] = useState(true);
7189
+ /** Optional custom continuation prompt. */
7190
+ const [appResumePrompt, setAppResumePrompt] = useState('');
7140
7191
  const tokenRef = useRef(null);
7141
7192
  const abortRef = useRef(null);
7142
7193
  const buttonsRef = useRef(new Set());
@@ -7822,15 +7873,31 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7822
7873
  const readRestartCapability = () => readAppCapability(UPDATE_API);
7823
7874
 
7824
7875
  /** POST one app-control command; throws when the Host refuses. */
7825
- const requestAppAction = async (action) => {
7876
+ const requestAppAction = async (action, options = {}) => {
7826
7877
  const api = action === 'close' ? CLOSE_API : UPDATE_API;
7878
+ // Sending a body opts into the task-aware path. The plugin self-update
7879
+ // flow calls requestAppRestart() with no options and keeps its old
7880
+ // behaviour (no task gate) by not sending a body.
7881
+ const aware = options.aware === true;
7882
+ const body = aware ? JSON.stringify({
7883
+ action,
7884
+ force: options.force === true,
7885
+ resume: options.resume === true,
7886
+ resumePrompt: typeof options.resumePrompt === 'string' ? options.resumePrompt : '',
7887
+ }) : undefined;
7827
7888
  const response = await fetch(api, {
7828
7889
  method: 'POST',
7829
- headers: { 'content-type': 'application/json' },
7830
- body: JSON.stringify({ action }),
7890
+ headers: body === undefined ? undefined : { 'content-type': 'application/json' },
7891
+ ...(body === undefined ? {} : { body }),
7831
7892
  });
7832
7893
  const data = await response.json().catch(() => null);
7833
- if (!response.ok || data?.ok !== true) throw new Error(data?.error ?? `HTTP ${response.status}`);
7894
+ if (!response.ok || data?.ok !== true) {
7895
+ if (data?.code === 'tasks-running' && Array.isArray(data.runningTasks)) {
7896
+ setAppTasks(data.runningTasks);
7897
+ }
7898
+ throw new Error(data?.error ?? `HTTP ${response.status}`);
7899
+ }
7900
+ return data;
7834
7901
  };
7835
7902
 
7836
7903
  /** The restart command, as the install flow spells it. */
@@ -7842,8 +7909,20 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7842
7909
  setAppCapability(null);
7843
7910
  setAppError(null);
7844
7911
  setAppBusy(false);
7845
- void readAppCapability(action === 'close' ? CLOSE_API : UPDATE_API)
7846
- .then((capability) => setAppCapability(capability));
7912
+ setAppTasks([]);
7913
+ setAppResume(true);
7914
+ setAppResumePrompt('');
7915
+ const api = action === 'close' ? CLOSE_API : UPDATE_API;
7916
+ void fetch(api, { headers: { accept: 'application/json' } })
7917
+ .then((response) => response.json())
7918
+ .then((data) => {
7919
+ setAppCapability({
7920
+ supported: data?.ok === true && data.supported === true,
7921
+ reason: typeof data?.reason === 'string' ? data.reason : '',
7922
+ });
7923
+ if (Array.isArray(data?.runningTasks)) setAppTasks(data.runningTasks);
7924
+ })
7925
+ .catch((error) => setAppCapability({ supported: false, reason: errorText(error) }));
7847
7926
  };
7848
7927
  const openAppActionRef = useRef(() => {});
7849
7928
  openAppActionRef.current = openAppAction;
@@ -7863,12 +7942,20 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7863
7942
  }, []);
7864
7943
 
7865
7944
  /** Confirm the app-level action (restart or close). */
7866
- const confirmAppAction = async () => {
7945
+ const confirmAppAction = async (forced = false) => {
7867
7946
  if (appBusy) return;
7947
+ if (!forced && appTasks.length > 0) return;
7868
7948
  setAppBusy(true);
7869
7949
  setAppError(null);
7870
7950
  try {
7871
- await requestAppAction(appAsk === 'close' ? 'close' : 'restart');
7951
+ const data = await requestAppAction(appAsk === 'close' ? 'close' : 'restart', {
7952
+ aware: true,
7953
+ force: forced,
7954
+ resume: forced && appResume,
7955
+ resumePrompt: appResumePrompt,
7956
+ });
7957
+ // The app is about to exit; nothing more to render.
7958
+ void data;
7872
7959
  } catch (error) {
7873
7960
  setAppBusy(false);
7874
7961
  setAppError(errorText(error) || tRef.current('update.unknown'));
@@ -7961,6 +8048,41 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7961
8048
  ),
7962
8049
  h('div', { className: 'dsh-powerup-update-body' },
7963
8050
  h('p', { className: 'dsh-powerup-update-note' }, t(appAction === 'close' ? 'close.desc' : 'restart.desc')),
8051
+ appTasks.length > 0
8052
+ ? h('div', { className: 'dsh-powerup-update-tasks' },
8053
+ h('strong', null, t('restart.tasksTitle', { count: appTasks.length })),
8054
+ h('p', { className: 'dsh-powerup-update-note' }, t('restart.tasksHint')),
8055
+ h('ul', { className: 'dsh-powerup-update-task-list' },
8056
+ appTasks.slice(0, 8).map((task, index) => h('li', { key: `${task.kind}-${task.id}-${index}` },
8057
+ h('span', { className: 'dsh-powerup-update-task-dot' }),
8058
+ h('code', null, t('restart.taskLine', { id: task.id })),
8059
+ task.title && task.title !== 'session' ? h('span', null, ` — ${task.title}`) : null,
8060
+ )),
8061
+ ),
8062
+ h('label', { className: 'dsh-powerup-app-check' },
8063
+ h('input', {
8064
+ type: 'checkbox',
8065
+ checked: appResume,
8066
+ onChange: (event) => setAppResume(event.target.checked === true),
8067
+ disabled: appBusy,
8068
+ }),
8069
+ h('span', null,
8070
+ h('strong', null, t(appAction === 'close' ? 'restart.resumeLabelClose' : 'restart.resumeLabel')),
8071
+ h('small', null, t('restart.resumeHint')),
8072
+ ),
8073
+ ),
8074
+ appResume
8075
+ ? h('input', {
8076
+ className: 'dsh-powerup-prompt-input',
8077
+ type: 'text',
8078
+ value: appResumePrompt,
8079
+ placeholder: t('restart.resumePromptPlaceholder'),
8080
+ disabled: appBusy,
8081
+ onChange: (event) => setAppResumePrompt(event.target.value),
8082
+ })
8083
+ : null,
8084
+ )
8085
+ : null,
7964
8086
  appCapability !== null && appCapability.supported !== true
7965
8087
  ? notice('warn', h(WarnIcon, { size: 14 }), null, t(appAction === 'close' ? 'close.unsupported' : 'update.restartUnsupported', { reason: appCapability.reason ?? '' }))
7966
8088
  : null,
@@ -7974,12 +8096,19 @@ html[data-platform="darwin"] .dsh-powerup-scrolltop:hover{background:var(--dsw-s
7974
8096
  ),
7975
8097
  h('div', { className: 'dsh-powerup-update-foot' },
7976
8098
  h('button', { type: 'button', className: 'dsh-powerup-update-ghost', disabled: appBusy, onClick: () => setAppAsk(null) }, t(appAction === 'close' ? 'close.cancel' : 'restart.cancel')),
7977
- h('button', {
7978
- type: 'button',
7979
- className: 'dsh-powerup-update-primary',
7980
- disabled: appBusy || appCapability?.supported !== true,
7981
- onClick: confirmAppAction,
7982
- }, appBusy ? t(appAction === 'close' ? 'close.closing' : 'update.restarting') : t(appAction === 'close' ? 'close.confirm' : 'restart.confirm')),
8099
+ appTasks.length > 0
8100
+ ? h('button', {
8101
+ type: 'button',
8102
+ className: 'dsh-powerup-update-primary',
8103
+ disabled: appBusy || appCapability?.supported !== true,
8104
+ onClick: () => void confirmAppAction(true),
8105
+ }, appBusy ? t(appAction === 'close' ? 'close.closing' : 'update.restarting') : t(appAction === 'close' ? 'restart.forceCloseLabel' : 'restart.forceLabel'))
8106
+ : h('button', {
8107
+ type: 'button',
8108
+ className: 'dsh-powerup-update-primary',
8109
+ disabled: appBusy || appCapability?.supported !== true,
8110
+ onClick: () => void confirmAppAction(false),
8111
+ }, appBusy ? t(appAction === 'close' ? 'close.closing' : 'update.restarting') : t(appAction === 'close' ? 'close.confirm' : 'restart.confirm')),
7983
8112
  ),
7984
8113
  ),
7985
8114
  );
package/index.js CHANGED
@@ -39,6 +39,15 @@ import { dirname, join, resolve as resolvePath, sep } from 'node:path';
39
39
  import { homedir } from 'node:os';
40
40
  import { defineTool } from '@deepseek-ai/dsh-tools';
41
41
  import { describeClose, describeRestart, requestRestart, requestShutdown } from './lib/restart.js';
42
+ import {
43
+ TASK_RESUME_FILE,
44
+ collectRunningTasks,
45
+ createResumeRecord,
46
+ mergeResumeQueue,
47
+ readResumeQueue,
48
+ replayPendingResumes,
49
+ stopUnfinishedTasks,
50
+ } from './lib/task-resume.js';
42
51
  import { createStepReadTool } from './lib/step-tool.js';
43
52
  import { createProgressManager } from './lib/progress-manager.js';
44
53
 
@@ -64,6 +73,8 @@ const BODY_LIMIT = 16 * 1024;
64
73
  const STORE_DIR_NAME = 'dsh-powerup';
65
74
  const PROMPTS_FILE = 'prompts.json';
66
75
  const MASK_RULES_FILE = 'mask-rules.json';
76
+ /** Pending continuation prompts recorded by forced restart / close. */
77
+ const TASK_RESUME_FILE_NAME = TASK_RESUME_FILE;
67
78
  /** Legacy relative location inside a workspace, used only for migration. */
68
79
  const LEGACY_STORE_DIR = join('.dsh', 'dsh-powerup');
69
80
 
@@ -163,6 +174,8 @@ function sendJson(res, payload, status = 200) {
163
174
  * @returns {Promise<unknown>}
164
175
  */
165
176
  async function readJsonBody(req) {
177
+ // Some callers (and older test doubles) send no stream at all.
178
+ if (req === null || typeof req !== 'object' || typeof req[Symbol.asyncIterator] !== 'function') return {};
166
179
  const chunks = [];
167
180
  let size = 0;
168
181
  for await (const chunk of req) {
@@ -247,6 +260,12 @@ function normalizeStopReason(value) {
247
260
  * @param {unknown} value
248
261
  * @returns {string}
249
262
  */
263
+ /** Bound the optional resume prompt supplied by the UI. */
264
+ function cleanResumePrompt(value) {
265
+ if (typeof value !== 'string') return '';
266
+ return value.replace(/[\u0000-\u001f\u007f]+/gu, ' ').replace(/\s+/gu, ' ').trim().slice(0, 4000);
267
+ }
268
+
250
269
  function killReasonFor(value) {
251
270
  const reason = normalizeStopReason(value);
252
271
  return reason === '' ? HUMAN_KILL_REASON : `${HUMAN_KILL_REASON}: ${reason}`;
@@ -618,14 +637,85 @@ async function handle(req, res, ctx) {
618
637
 
619
638
  if (op === '' || op === 'restart' || op === 'close') {
620
639
  const action = op === 'close' ? 'close' : 'restart';
640
+ const capability = action === 'close' ? describeClose() : describeRestart();
621
641
  if (req.method === 'GET') {
622
- sendJson(res, { ok: true, action, ...(action === 'close' ? describeClose() : describeRestart()) });
642
+ // Expose unfinished work so the UI can gate the normal action and offer
643
+ // the forced variant. A runtime that cannot restart still reports tasks.
644
+ const tasks = collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') });
645
+ sendJson(res, {
646
+ ok: true,
647
+ action,
648
+ ...capability,
649
+ runningTasks: tasks,
650
+ hasRunningTasks: tasks.length > 0,
651
+ });
623
652
  return;
624
653
  }
625
654
  if (req.method === 'POST') {
655
+ let body;
656
+ try {
657
+ body = await readJsonBody(req);
658
+ } catch (error) {
659
+ sendJson(res, { ok: false, error: String(error?.message ?? error) }, 400);
660
+ return;
661
+ }
662
+ // A client that sends no body (older UI, plugin self-update flow) keeps
663
+ // the historical behaviour: scheduled directly, no task gate.
664
+ const force = body?.force === true;
665
+ const requested = body?.force === true || body?.resume === true || body?.action !== undefined;
666
+ const tasks = requested
667
+ ? collectRunningTasks({ agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') })
668
+ : [];
669
+ if (requested && tasks.length > 0 && !force) {
670
+ sendJson(res, {
671
+ ok: false,
672
+ code: 'tasks-running',
673
+ error: 'unfinished tasks are running; use force to stop them',
674
+ runningTasks: tasks,
675
+ }, 409);
676
+ return;
677
+ }
678
+ let stopped = { cancelledAgents: [], killedJobs: [], errors: [] };
679
+ let recorded = 0;
680
+ if (requested && tasks.length > 0 && force) {
681
+ stopped = stopUnfinishedTasks(
682
+ { agents: ctx?.get?.('agents'), jobs: ctx?.get?.('jobs') },
683
+ `dsh-powerup forced ${action}`,
684
+ );
685
+ if (body?.resume === true) {
686
+ try {
687
+ const filePath = storePath(TASK_RESUME_FILE_NAME);
688
+ const records = [];
689
+ const seen = new Set();
690
+ for (const task of tasks) {
691
+ if (task.kind !== 'agent' || seen.has(task.id)) continue;
692
+ seen.add(task.id);
693
+ records.push(createResumeRecord({
694
+ sessionId: task.id,
695
+ title: task.title,
696
+ prompt: cleanResumePrompt(body?.resumePrompt),
697
+ }, randomUUID));
698
+ }
699
+ if (records.length > 0) {
700
+ mkdirSync(dirname(filePath), { recursive: true });
701
+ const queue = mergeResumeQueue(readResumeQueue(filePath, readFileSync), records);
702
+ writeFileSync(filePath, JSON.stringify(queue, null, 2) + '\n', 'utf8');
703
+ recorded = records.length;
704
+ }
705
+ } catch (error) {
706
+ appendSelfUpdateLog(`task-resume: could not record resumes: ${String(error?.message ?? error)}`);
707
+ }
708
+ }
709
+ }
626
710
  try {
627
711
  const scheduled = action === 'close' ? requestShutdown() : requestRestart();
628
- sendJson(res, { ok: true, [action === 'close' ? 'closing' : 'restarting']: true, ...scheduled });
712
+ sendJson(res, {
713
+ ok: true,
714
+ [action === 'close' ? 'closing' : 'restarting']: true,
715
+ ...scheduled,
716
+ stopped,
717
+ recorded,
718
+ });
629
719
  } catch (error) {
630
720
  sendJson(res, { ok: false, code: error?.code, error: String(error?.message ?? error) }, 409);
631
721
  }
@@ -689,6 +779,29 @@ export function apply(ctx) {
689
779
  if (ctx.__powerupProgress === manager) ctx.__powerupProgress = undefined;
690
780
  }, 'dsh-powerup: progress manager');
691
781
  });
782
+ // Replay continuation prompts recorded by a forced restart/close once the
783
+ // application has fully started. `sessionController.prompt` resumes cold
784
+ // sessions internally, so no session needs to be opened by the user first.
785
+ ctx.inject(['sessionController'], (scope) => {
786
+ const controller = scope.get('sessionController');
787
+ if (controller === null || typeof controller?.prompt !== 'function') return;
788
+ const ready = ctx.appReady;
789
+ if (ready === null || typeof ready?.onReady !== 'function') return;
790
+ scope.effect(() => ready.onReady(() => {
791
+ void replayPendingResumes({
792
+ filePath: storePath(TASK_RESUME_FILE_NAME),
793
+ sessionController: controller,
794
+ readFile: readFileSync,
795
+ writeFile: writeFileSync,
796
+ mkdir: mkdirSync,
797
+ dirname,
798
+ randomUUID,
799
+ logger: (line) => appendSelfUpdateLog(line),
800
+ }).catch((error) => {
801
+ appendSelfUpdateLog(`task-resume: uncaught ${String(error?.stack ?? error)}`);
802
+ });
803
+ }), 'dsh-powerup: resume tasks after restart');
804
+ });
692
805
  }
693
806
 
694
807
  /** Exported for tests only; the Host never reads this. */
@@ -715,5 +828,7 @@ export const __test = {
715
828
  ROUTE,
716
829
  MODULE_ID,
717
830
  STORE_DIR_NAME,
831
+ TASK_RESUME_FILE_NAME,
718
832
  createProgressManager,
833
+ cleanResumePrompt,
719
834
  };
@@ -0,0 +1,256 @@
1
+ /**
2
+ * dsh-powerup — task-aware restart / shutdown helpers.
3
+ *
4
+ * Plain JS, dependency-free so the offline suites can exercise it. The Host
5
+ * passes live services in at call time; nothing here imports `@deepseek-ai/*`
6
+ * at module load.
7
+ *
8
+ * Two responsibilities:
9
+ * 1. Snapshot unfinished work (live running Agents plus running background
10
+ * jobs) so a restart/close request can refuse the normal path.
11
+ * 2. Persist a small "pending resume" queue to disk when a forced restart /
12
+ * close is requested with `resume: true`, and replay it on the next
13
+ * successful application startup by sending each session a continuation
14
+ * prompt through `sessionController.prompt` (which resumes cold sessions).
15
+ */
16
+
17
+ /** Central store file name, next to prompts.json / mask-rules.json. */
18
+ export const TASK_RESUME_FILE = 'task-resume.json';
19
+
20
+ /** Default continuation prompt; the user sees it as a real user message. */
21
+ export const DEFAULT_RESUME_PROMPT = '继续之前未完成的任务。';
22
+
23
+ /** Max number of records kept in the queue, so a corrupt file cannot explode startup. */
24
+ const MAX_RECORDS = 500;
25
+
26
+ /** Max characters kept for a session title in the queue. */
27
+ const TITLE_LIMIT = 200;
28
+
29
+ /**
30
+ * Clamp arbitrary text to a single line of bounded length (control chars gone).
31
+ * @param {unknown} value
32
+ * @param {number} [limit]
33
+ * @returns {string}
34
+ */
35
+ export function cleanText(value, limit = TITLE_LIMIT) {
36
+ if (typeof value !== 'string') return '';
37
+ return value
38
+ .replace(/[\u0000-\u001f\u007f]+/gu, ' ')
39
+ .replace(/\s+/gu, ' ')
40
+ .trim()
41
+ .slice(0, limit);
42
+ }
43
+
44
+ /**
45
+ * Collect unfinished work from live Host services.
46
+ * @param {{agents?: any, jobs?: any}} services
47
+ * @returns {Array<{id: string, title: string, kind: 'agent'|'job', running: boolean}>}
48
+ */
49
+ export function collectRunningTasks(services = {}) {
50
+ const tasks = [];
51
+ const agents = services.agents;
52
+ try {
53
+ const list = typeof agents?.list === 'function' ? agents.list() : [];
54
+ for (const agent of Array.isArray(list) ? list : []) {
55
+ if (agent === null || typeof agent !== 'object') continue;
56
+ // Cold sessions are never `running`; only the live driver knows.
57
+ if (agent.status !== 'running') continue;
58
+ const id = typeof agent.id === 'string' ? agent.id : agent.session?.id;
59
+ if (typeof id !== 'string' || id === '') continue;
60
+ tasks.push({
61
+ id,
62
+ title: taskTitle(agent),
63
+ kind: 'agent',
64
+ running: true,
65
+ });
66
+ }
67
+ } catch {
68
+ /* A service that is still warming up contributes no tasks. */
69
+ }
70
+ const jobs = services.jobs;
71
+ try {
72
+ const list = typeof jobs?.list === 'function' ? jobs.list() : [];
73
+ for (const job of Array.isArray(list) ? list : []) {
74
+ if (job === null || typeof job !== 'object') continue;
75
+ if (job.status !== 'running') continue;
76
+ const id = typeof job.id === 'string' ? job.id : '';
77
+ if (id === '') continue;
78
+ // Avoid duplicating the same work when a job view carries its owner.
79
+ if (tasks.some((task) => task.id === id)) continue;
80
+ tasks.push({
81
+ id,
82
+ title: cleanText(job.title ?? job.kind ?? 'background job', TITLE_LIMIT),
83
+ kind: 'job',
84
+ running: true,
85
+ });
86
+ }
87
+ } catch {
88
+ /* Optional service. */
89
+ }
90
+ return tasks.slice(0, MAX_RECORDS);
91
+ }
92
+
93
+ /** Best-effort human label for one live Agent. */
94
+ function taskTitle(agent) {
95
+ try {
96
+ const title = agent.session?.title?.();
97
+ if (typeof title === 'string' && title.trim() !== '') return cleanText(title);
98
+ } catch {
99
+ /* fall through */
100
+ }
101
+ return 'session';
102
+ }
103
+
104
+ /**
105
+ * Read the pending-resume queue from a JSON file.
106
+ * @param {string} filePath
107
+ * @returns {Array<object>}
108
+ */
109
+ export function readResumeQueue(filePath, readFile) {
110
+ try {
111
+ const parsed = JSON.parse(readFile(filePath, 'utf8'));
112
+ if (!Array.isArray(parsed)) return [];
113
+ return parsed.filter((record) => record !== null && typeof record === 'object'
114
+ && typeof record.sessionId === 'string' && record.sessionId !== '').slice(0, MAX_RECORDS);
115
+ } catch (error) {
116
+ if (error?.code === 'ENOENT') return [];
117
+ return [];
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Build one resume record.
123
+ * @param {{sessionId: string, title?: string, prompt?: string, forcedAt?: number}} input
124
+ * @returns {{sessionId: string, requestId: string, title: string, prompt: string, createdAt: number}}
125
+ */
126
+ export function createResumeRecord(input, randomUUID) {
127
+ const sessionId = typeof input?.sessionId === 'string' ? input.sessionId : '';
128
+ if (sessionId === '') throw new TypeError('sessionId is required');
129
+ const prompt = cleanText(input.prompt, 4000) || DEFAULT_RESUME_PROMPT;
130
+ return {
131
+ sessionId,
132
+ requestId: typeof randomUUID === 'function' ? randomUUID() : `resume-${Date.now()}-${Math.random().toString(36).slice(2)}`,
133
+ title: cleanText(input.title),
134
+ prompt,
135
+ createdAt: Number.isFinite(input.forcedAt) ? input.forcedAt : Date.now(),
136
+ };
137
+ }
138
+
139
+ /**
140
+ * Append resume records to the queue, deduplicated by sessionId.
141
+ * @param {Array<object>} queue
142
+ * @param {Array<object>} records
143
+ * @returns {Array<object>}
144
+ */
145
+ export function mergeResumeQueue(queue, records) {
146
+ const merged = Array.isArray(queue) ? queue.slice() : [];
147
+ const seen = new Set(merged.map((record) => record.sessionId));
148
+ for (const record of Array.isArray(records) ? records : []) {
149
+ if (record === null || typeof record !== 'object') continue;
150
+ if (typeof record.sessionId !== 'string' || record.sessionId === '') continue;
151
+ if (seen.has(record.sessionId)) continue;
152
+ seen.add(record.sessionId);
153
+ merged.push(record);
154
+ }
155
+ return merged.slice(-MAX_RECORDS);
156
+ }
157
+
158
+ /**
159
+ * Cancel each running live Agent and kill each running job. Best effort: the
160
+ * restart proceeds even if one cancellation fails.
161
+ * @param {{agents?: any, jobs?: any}} services
162
+ * @param {string} [reason]
163
+ * @returns {{cancelledAgents: string[], killedJobs: string[], errors: string[]}}
164
+ */
165
+ export function stopUnfinishedTasks(services = {}, reason = 'dsh-powerup forced app action') {
166
+ const result = { cancelledAgents: [], killedJobs: [], errors: [] };
167
+ const agents = services.agents;
168
+ try {
169
+ const list = typeof agents?.list === 'function' ? agents.list() : [];
170
+ for (const agent of Array.isArray(list) ? list : []) {
171
+ if (agent?.status !== 'running') continue;
172
+ const id = typeof agent.id === 'string' ? agent.id : agent.session?.id;
173
+ try {
174
+ if (typeof agent.cancel !== 'function') continue;
175
+ agent.cancel({ kind: 'user', reason }, { keepInbox: false });
176
+ if (typeof id === 'string' && id !== '') result.cancelledAgents.push(id);
177
+ } catch (error) {
178
+ result.errors.push(`agent ${id ?? '?'}: ${String(error?.message ?? error)}`);
179
+ }
180
+ }
181
+ } catch (error) {
182
+ result.errors.push(`agents: ${String(error?.message ?? error)}`);
183
+ }
184
+ const jobs = services.jobs;
185
+ try {
186
+ const list = typeof jobs?.list === 'function' ? jobs.list() : [];
187
+ for (const job of Array.isArray(list) ? list : []) {
188
+ if (job?.status !== 'running') continue;
189
+ const id = typeof job.id === 'string' ? job.id : '';
190
+ if (id === '') continue;
191
+ try {
192
+ const owner = typeof job.sessionId === 'string' ? job.sessionId : typeof job.owner === 'string' ? job.owner : undefined;
193
+ jobs.kill(id, owner, reason);
194
+ result.killedJobs.push(id);
195
+ } catch (error) {
196
+ result.errors.push(`job ${id}: ${String(error?.message ?? error)}`);
197
+ }
198
+ }
199
+ } catch (error) {
200
+ result.errors.push(`jobs: ${String(error?.message ?? error)}`);
201
+ }
202
+ return result;
203
+ }
204
+
205
+ /**
206
+ * Replay pending resumes once startup is committed. Each prompt is sent
207
+ * through `sessionController.prompt`, which resumes a cold session internally.
208
+ * A record is removed from the queue only after its prompt is accepted.
209
+ *
210
+ * @param {{sessionController?: any, readFile: Function, writeFile: Function, mkdir: Function, dirname: Function, randomUUID: Function, logger?: Function}} deps
211
+ * @returns {Promise<{delivered: string[], failed: Array<{sessionId: string, error: string}>, remaining: number}>}
212
+ */
213
+ export async function replayPendingResumes(deps) {
214
+ const { readFile, writeFile, mkdir, dirname, randomUUID } = deps;
215
+ const filePath = deps.filePath;
216
+ const queue = readResumeQueue(filePath, readFile);
217
+ if (queue.length === 0) return { delivered: [], failed: [], remaining: 0 };
218
+
219
+ const result = { delivered: [], failed: [], remaining: 0 };
220
+ const pending = [];
221
+ const controller = deps.sessionController;
222
+
223
+ for (const record of queue) {
224
+ if (controller === null || typeof controller?.prompt !== 'function') {
225
+ pending.push(record);
226
+ continue;
227
+ }
228
+ const signal = deps.signal ?? new AbortController().signal;
229
+ try {
230
+ await controller.prompt({
231
+ requestId: randomUUID(),
232
+ sessionId: record.sessionId,
233
+ mode: 'queue',
234
+ content: [{ type: 'text', text: record.prompt || DEFAULT_RESUME_PROMPT }],
235
+ }, signal);
236
+ result.delivered.push(record.sessionId);
237
+ } catch (error) {
238
+ result.failed.push({ sessionId: record.sessionId, error: String(error?.message ?? error) });
239
+ pending.push(record);
240
+ if (typeof deps.logger === 'function') {
241
+ deps.logger(`[dsh-powerup] resume prompt failed for ${record.sessionId}: ${String(error?.message ?? error)}`);
242
+ }
243
+ }
244
+ }
245
+
246
+ result.remaining = pending.length;
247
+ try {
248
+ mkdir(dirname(filePath), { recursive: true });
249
+ writeFile(filePath, JSON.stringify(pending, null, 2) + '\n', 'utf8');
250
+ } catch (error) {
251
+ if (typeof deps.logger === 'function') {
252
+ deps.logger(`[dsh-powerup] could not persist resume queue: ${String(error?.message ?? error)}`);
253
+ }
254
+ }
255
+ return result;
256
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-powerup",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "为 DeepSeek Harness 提供一组可选的小型增强:轨迹右键菜单与步骤引用、后台任务停止原因、插件一键安装、侧边栏图标网格、会话切换、定位当前会话、工作区提示词、旁路模型生成的结构化任务进度;所有功能均可在 Power-Up 页面独立开关。 · Opt-in upgrades for DeepSeek Harness: Trajectory context menu and step references, job stop reasons, one-click plugin install, an adaptive sidebar launcher, session switching, locating the current session, workspace prompts, and non-blocking model-generated structured task progress — each toggled independently on the Power-Up page.",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",
@@ -23,6 +23,7 @@
23
23
  "lib/step-tool.js",
24
24
  "lib/progress-tool.js",
25
25
  "lib/progress-manager.js",
26
+ "lib/task-resume.js",
26
27
  "locale/*.json",
27
28
  "icon.svg",
28
29
  "README.md",
@@ -96,7 +97,7 @@
96
97
  "node": ">=22.13.0"
97
98
  },
98
99
  "scripts": {
99
- "test": "node test/smoke.mjs && node test/host.mjs && node test/progress.mjs"
100
+ "test": "node test/smoke.mjs && node test/host.mjs && node test/progress.mjs && node test/task-resume.mjs"
100
101
  },
101
102
  "license": "MIT",
102
103
  "author": "RestRegular"