@cloud411716/fancy-webnovel 4.12.0 → 4.13.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
@@ -68,3 +68,14 @@ allowBuilds:
68
68
  ```
69
69
 
70
70
  具体用法见各命令的 `/fancy-* help` 和 `docs/`。
71
+
72
+ ## 命令中断恢复
73
+
74
+ DSH 在 `/fancy-*` 命令执行期间重启或异常退出时,命令可能来不及写入配对的 `command/done`。会话重新打开时,插件会做一次收尾:
75
+
76
+ - 给孤立的 `/fancy-*` 命令补一条 error 类型的 `command/done`,命令卡片会打印“DSH 重启或异常退出,命令已中断”,不再一直显示“执行中…”;
77
+ - 把遗留任务列表里 `in_progress` 的步骤改为 `pending`,停止转圈;
78
+ - 如果之后已经有新的 LLM 回合或新命令,不复活旧任务列表;
79
+ - 只处理 fancy-webnovel 自己的命令,不碰其他插件。
80
+
81
+ 这不是伪造成功:被中断的命令仍然需要重新运行。
@@ -144,6 +144,8 @@ FANCY_DOUYIN_SUBAGENTS=0 # 关闭子 Agent,回退单 Agent 串行
144
144
 
145
145
  子 Agent 不操作 Chrome,不修改 `crawled.json`,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
146
146
 
147
+ 采集和分析重叠时,任务列表会同时把“采集作品”和“分析素材”标为进行中:采集行显示已扫描账号数和已入队作品数,分析行显示已分析/已入队和当前并发数。所有账号采集完成后,“采集作品”才标记完成,“分析素材”继续转圈直到子 Agent 队列清空。
148
+
147
149
  子 Agent 是独立的新会话,不继承父 Agent 当前对话。因此 `.tmp` 临时文件规则、完整分析提示词和“不要删除测试文件/不要执行 rm”的约束都会直接写进子 Agent 任务提示,而不是依赖父对话。
148
150
 
149
151
  有子 Agent 服务时,视觉能力自检和视频前 5 秒相关性判断也会交给子 Agent:
@@ -0,0 +1,217 @@
1
+ /**
2
+ * command-recovery.js — 收尾 DSH 重启/异常退出遗留的命令生命周期。
3
+ *
4
+ * DSH 的 slash 命令用一对事件记录执行过程:
5
+ *
6
+ * command/run → 处理函数开始时追加
7
+ * command/done → 处理函数结束时追加
8
+ *
9
+ * 如果 DSH 在命令执行期间被重启或异常退出,第二条事件可能永远没有写入。
10
+ * 会话重新打开时 UI 只能看到孤立的 command/run,于是命令卡片会一直显示
11
+ * “执行中…”;同样,命令最后一次 todo/write 里 in_progress 的步骤也会一直
12
+ * 转圈。
13
+ *
14
+ * 这里在会话恢复时做一次插件侧收尾:
15
+ *
16
+ * - 为 fancy-webnovel 命令的孤立 command/run 补一条 command/done(error);
17
+ * - 把遗留任务列表里的 in_progress 改成 pending,避免继续转圈;
18
+ * - 不伪造成功,命令卡片会明确打印“DSH 重启或异常退出,命令已中断”。
19
+ *
20
+ * 只处理 fancy-webnovel 自己的命令,不碰其它插件的事件。
21
+ */
22
+
23
+ const INSTALLED_ROOTS = new WeakSet();
24
+
25
+ /** 已通过 registerCommandWithTasks 注册的命令名。 */
26
+ const MANAGED_COMMANDS = new Set();
27
+
28
+ /** 记录一个 fancy-webnovel 命令名。 */
29
+ export function registerManagedCommand(name) {
30
+ const text = String(name == null ? '' : name).trim();
31
+ if (text) MANAGED_COMMANDS.add(text);
32
+ }
33
+
34
+ function isManagedCommand(name) {
35
+ return typeof name === 'string'
36
+ && (MANAGED_COMMANDS.has(name) || name.startsWith('fancy-'));
37
+ }
38
+
39
+ /**
40
+ * 找出会话里没有配对 command/done 的 fancy-webnovel command/run。
41
+ *
42
+ * @param {readonly object[]} events 会话事件快照
43
+ * @param {number} [inheritedEventCount] fork 继承前缀长度
44
+ * @returns {{commandId: string, name: string, seq: number}[]}
45
+ */
46
+ export function findInterruptedCommands(events, inheritedEventCount = 0) {
47
+ const inherited = Number.isInteger(inheritedEventCount) ? inheritedEventCount : 0;
48
+ const runs = new Map();
49
+ const settled = new Set();
50
+ for (const event of Array.isArray(events) ? events : []) {
51
+ if (!event || typeof event !== 'object') continue;
52
+ const seq = Number(event.seq);
53
+ if (Number.isInteger(seq) && seq < inherited) continue;
54
+ const data = event.data;
55
+ if (!data || typeof data !== 'object') continue;
56
+ const commandId = typeof data.commandId === 'string' ? data.commandId : '';
57
+ if (!commandId) continue;
58
+ if (event.type === 'command/run') {
59
+ runs.set(commandId, {
60
+ commandId,
61
+ name: typeof data.name === 'string' ? data.name : '',
62
+ seq: Number.isInteger(seq) ? seq : 0,
63
+ });
64
+ } else if (event.type === 'command/done') {
65
+ settled.add(commandId);
66
+ }
67
+ }
68
+ return [...runs.values()]
69
+ .filter((run) => !settled.has(run.commandId) && isManagedCommand(run.name))
70
+ .sort((left, right) => left.seq - right.seq);
71
+ }
72
+
73
+ function lastEvent(events, type, afterSeq, inheritedEventCount) {
74
+ let found = null;
75
+ for (const event of Array.isArray(events) ? events : []) {
76
+ if (!event || event.type !== type) continue;
77
+ const seq = Number(event.seq);
78
+ if (Number.isInteger(seq) && seq < inheritedEventCount) continue;
79
+ if (Number.isInteger(afterSeq) && (!Number.isInteger(seq) || seq <= afterSeq)) continue;
80
+ found = event;
81
+ }
82
+ return found;
83
+ }
84
+
85
+ function hasEventAfter(events, type, seq, inheritedEventCount) {
86
+ for (const event of Array.isArray(events) ? events : []) {
87
+ if (!event || event.type !== type) continue;
88
+ const current = Number(event.seq);
89
+ if (!Number.isInteger(current) || current < inheritedEventCount) continue;
90
+ if (current > seq) return true;
91
+ }
92
+ return false;
93
+ }
94
+
95
+ function todoSnapshot(event) {
96
+ const todos = event && event.data && Array.isArray(event.data.todos) ? event.data.todos : [];
97
+ const clean = [];
98
+ for (const item of todos) {
99
+ if (!item || typeof item !== 'object') continue;
100
+ const content = String(item.content == null ? '' : item.content).trim();
101
+ if (!content) continue;
102
+ if (item.status !== 'pending' && item.status !== 'in_progress' && item.status !== 'completed') continue;
103
+ clean.push({ content, status: item.status });
104
+ }
105
+ return clean;
106
+ }
107
+
108
+ function interruptedTodo(event) {
109
+ const todos = todoSnapshot(event);
110
+ if (!todos.some((item) => item.status === 'in_progress')) return null;
111
+ return todos.map((item) => item.status === 'in_progress'
112
+ ? { content: item.content, status: 'pending' }
113
+ : item);
114
+ }
115
+
116
+ /**
117
+ * 收尾一个已恢复会话中的中断命令。
118
+ *
119
+ * 调用方应在 session/created 的同一同步栈里先取好 findAll 结果,再把这个
120
+ * 函数放到微任务里执行;DSH 在 session/created 派发完成前不允许 append。
121
+ *
122
+ * @param {object} session 已恢复的 DSH session
123
+ * @param {{orphans?: object[], inheritedEventCount?: number}} [options]
124
+ * @returns {{commands: string[], todo: boolean}}
125
+ */
126
+ export function recoverInterruptedSession(session, options = {}) {
127
+ const result = { commands: [], todo: false };
128
+ if (!session || typeof session.append !== 'function' || typeof session.snapshotEvents !== 'function') {
129
+ return result;
130
+ }
131
+ const inherited = Number.isInteger(options.inheritedEventCount)
132
+ ? options.inheritedEventCount
133
+ : (Number.isInteger(session.inheritedEventCount) ? session.inheritedEventCount : 0);
134
+ let events;
135
+ try {
136
+ events = session.snapshotEvents();
137
+ } catch {
138
+ return result;
139
+ }
140
+ const orphans = Array.isArray(options.orphans)
141
+ ? options.orphans
142
+ : findInterruptedCommands(events, inherited);
143
+ const settled = new Set();
144
+ for (const event of events) {
145
+ if (event && event.type === 'command/done' && event.data && typeof event.data.commandId === 'string') {
146
+ settled.add(event.data.commandId);
147
+ }
148
+ }
149
+
150
+ let latestOrphanSeq = -1;
151
+ for (const run of orphans) {
152
+ if (!run || typeof run.commandId !== 'string' || settled.has(run.commandId)) continue;
153
+ const name = typeof run.name === 'string' && run.name ? run.name : 'fancy-webnovel 命令';
154
+ const seq = Number.isInteger(run.seq) ? run.seq : 0;
155
+ latestOrphanSeq = Math.max(latestOrphanSeq, seq);
156
+ try {
157
+ session.append('command/done', {
158
+ commandId: run.commandId,
159
+ kind: 'error',
160
+ text: 'DSH 在 /' + name + ' 执行期间重启或异常退出,命令已中断。请重新运行 /' + name + '。',
161
+ });
162
+ result.commands.push(run.commandId);
163
+ } catch {
164
+ // 会话可能已经再次卸载;恢复失败不能反过来影响打开会话。
165
+ }
166
+ }
167
+
168
+ if (latestOrphanSeq < 0) return result;
169
+
170
+ // 只修复仍然停留在界面上的最后一份任务列表:
171
+ // - 它必须写在中止命令之后;
172
+ // - 之后不能再有新的 turn/start(turn 开始会清空旧列表);
173
+ // - 之后不能再有新的 command/run(否则可能属于另一条正在执行的命令)。
174
+ const todoEvent = lastEvent(events, 'todo/write', latestOrphanSeq, inherited);
175
+ if (!todoEvent || !Number.isInteger(Number(todoEvent.seq))) return result;
176
+ const todoSeq = Number(todoEvent.seq);
177
+ if (hasEventAfter(events, 'turn/start', todoSeq, inherited)) return result;
178
+ if (hasEventAfter(events, 'command/run', todoSeq, inherited)) return result;
179
+ const todos = interruptedTodo(todoEvent);
180
+ if (!todos) return result;
181
+ try {
182
+ session.append('todo/write', { todos });
183
+ result.todo = true;
184
+ } catch {
185
+ // 同上:任务列表只是展示,恢复失败不影响会话打开。
186
+ }
187
+ return result;
188
+ }
189
+
190
+ /**
191
+ * 在每个 fancy-webnovel 插件注册命令时调用;整个进程只安装一次监听。
192
+ *
193
+ * @param {object} ctx DSH 插件上下文
194
+ */
195
+ export function installCommandRecovery(ctx) {
196
+ const root = ctx && ctx.root ? ctx.root : ctx;
197
+ if (!root || typeof root.on !== 'function' || INSTALLED_ROOTS.has(root)) return;
198
+ INSTALLED_ROOTS.add(root);
199
+ root.on('session/created', (session) => {
200
+ let events;
201
+ try {
202
+ events = session && typeof session.snapshotEvents === 'function'
203
+ ? session.snapshotEvents()
204
+ : null;
205
+ } catch {
206
+ return;
207
+ }
208
+ if (!Array.isArray(events)) return;
209
+ const inherited = Number.isInteger(session.inheritedEventCount) ? session.inheritedEventCount : 0;
210
+ const orphans = findInterruptedCommands(events, inherited);
211
+ if (!orphans.length) return;
212
+ // session/created 派发完成前 DSH 拒绝 append;派发结束后再收尾。
213
+ queueMicrotask(() => {
214
+ recoverInterruptedSession(session, { orphans, inheritedEventCount: inherited });
215
+ });
216
+ });
217
+ }
package/lib/task-list.js CHANGED
@@ -25,6 +25,8 @@
25
25
  * 保持 pending,不谎报完成。
26
26
  */
27
27
 
28
+ import { installCommandRecovery, registerManagedCommand } from './command-recovery.js';
29
+
28
30
  const VALID_STATUSES = new Set(['pending', 'in_progress', 'completed']);
29
31
  const WATCH_INTERVAL_MS = 200;
30
32
 
@@ -130,11 +132,35 @@ class TaskListController {
130
132
  * 只改文案,不改状态;用于长循环里让用户看到进度。
131
133
  */
132
134
  progress(text) {
135
+ return this.progressAt(this.index, text);
136
+ }
137
+
138
+ /**
139
+ * 修改指定步骤的文案,不改状态。
140
+ * 用于多个步骤同时进行时,各自刷新自己的进度。
141
+ */
142
+ progressAt(index, text) {
143
+ const target = Number(index);
144
+ if (!Number.isInteger(target) || target < 0 || target >= this.items.length) return this;
133
145
  const content = String(text == null ? '' : text).trim();
134
- if (!content || !this.items[this.index]) return this;
146
+ if (!content) return this;
135
147
  // content 不能和已有项重复(DSH 会拒绝整表)
136
- if (this.items.some((item, i) => i !== this.index && item.content === content)) return this;
137
- this.items[this.index].content = content;
148
+ if (this.items.some((item, i) => i !== target && item.content === content)) return this;
149
+ if (this.items[target].content === content) return this;
150
+ this.items[target].content = content;
151
+ this._write();
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * 把一个 pending 步骤也标记为 in_progress,不影响当前步骤。
157
+ * DSH 允许并行任务同时进行;用于“采集作品”和“分析素材”重叠的阶段。
158
+ */
159
+ activate(index) {
160
+ const target = Number(index);
161
+ if (!Number.isInteger(target) || target < 0 || target >= this.items.length) return this;
162
+ if (this.items[target].status !== 'pending') return this;
163
+ this.items[target].status = 'in_progress';
138
164
  this._write();
139
165
  return this;
140
166
  }
@@ -348,6 +374,8 @@ export function registerCommandWithTasks(ctx, definition, titles) {
348
374
  if (typeof original !== 'function') {
349
375
  throw new Error('registerCommandWithTasks: definition.handler 必须是函数');
350
376
  }
377
+ registerManagedCommand(definition.name);
378
+ installCommandRecovery(ctx);
351
379
  return ctx.commands.register({
352
380
  ...definition,
353
381
  handler: (invocation) => withTaskList(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.12.0",
3
+ "version": "4.13.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -1053,14 +1053,13 @@ async function runCrawl(ctx, invocation, session, taskList) {
1053
1053
  let skippedMaterials = 0;
1054
1054
  let aborted = false;
1055
1055
 
1056
- const progressText = () => {
1057
- if (taskList.index <= 3) {
1058
- return `采集作品(已入队 ${queueStats.queued},已分析 ${queueStats.finished})`;
1059
- }
1060
- if (queue) {
1061
- return `分析素材(子 Agent 并行:${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`;
1062
- }
1063
- return `分析素材(${queueStats.finished}/${jobs.length})`;
1056
+ const collectText = () => `采集作品(已扫描 ${scannedAccounts}/${accounts.length},已入队 ${queueStats.queued})`;
1057
+ const analysisText = () => queue
1058
+ ? `分析素材(已分析 ${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`
1059
+ : `分析素材(${queueStats.finished}/${jobs.length})`;
1060
+ const refreshProgress = () => {
1061
+ if (taskList.index <= 3) taskList.progressAt(3, collectText());
1062
+ if (queue || taskList.index >= 4) taskList.progressAt(4, analysisText());
1064
1063
  };
1065
1064
 
1066
1065
  const jobRecord = (job, extra = {}) => ({
@@ -1101,7 +1100,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
1101
1100
  failures.push({ id: job.id, url: job.url, reason });
1102
1101
  await markJobFailedLocked(job, reason);
1103
1102
  queueStats.finished += 1;
1104
- taskList.progress(progressText());
1103
+ refreshProgress();
1105
1104
  return;
1106
1105
  }
1107
1106
  if (analyzed.skipped) {
@@ -1142,7 +1141,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
1142
1141
  }
1143
1142
  crawled[job.id] = true;
1144
1143
  queueStats.finished += 1;
1145
- taskList.progress(progressText());
1144
+ refreshProgress();
1146
1145
  });
1147
1146
  };
1148
1147
 
@@ -1160,11 +1159,13 @@ async function runCrawl(ctx, invocation, session, taskList) {
1160
1159
  }
1161
1160
  queueStats.queued += 1;
1162
1161
  if (queue) {
1162
+ // 子 Agent 已开始处理第一个作品:采集尚未结束,但分析也进入进行中。
1163
+ taskList.activate(4);
1163
1164
  queue.push(job);
1164
1165
  } else {
1165
1166
  jobs.push(job);
1166
1167
  }
1167
- taskList.progress(progressText());
1168
+ refreshProgress();
1168
1169
  };
1169
1170
 
1170
1171
  const runWorker = async () => {
@@ -1702,13 +1703,13 @@ async function runCrawl(ctx, invocation, session, taskList) {
1702
1703
  if (queue) {
1703
1704
  if (taskList.index < 4) {
1704
1705
  taskList.advance(4);
1705
- taskList.progress(progressText());
1706
+ refreshProgress();
1706
1707
  }
1707
1708
  queue.close();
1708
1709
  await Promise.all(workerPromises);
1709
1710
  } else if (jobs.length) {
1710
1711
  taskList.advance(4);
1711
- taskList.progress(progressText());
1712
+ refreshProgress();
1712
1713
  for (const job of jobs) {
1713
1714
  if (abortRequested(invocation)) { aborted = true; break; }
1714
1715
  const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {