@cloud411716/fancy-webnovel 4.0.3 → 4.1.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.
@@ -51,20 +51,24 @@ export function resolveTessdata() {
51
51
  // ---------------------------------------------------------------------------
52
52
 
53
53
  /**
54
- * 番茄的两种扫描方式。
54
+ * 番茄的三种扫描方式。
55
55
  *
56
- * api —— 书名/作者/简介取自番茄自家明文接口 /api/book/info。
57
- * 实测该接口返回与榜单页完全相同的文本(明文),零识别误差,
58
- * 整榜耗时约为 OCR 路径的 1/5。
59
- * ocr —— 渲染后截图 + tesseract 识别。不依赖番茄内部接口,接口失效时
60
- * 仍能采到,但存在认字误差(实测简介字符错误率 8%~17%)。
56
+ * api —— 书名/作者/简介取自番茄自家明文接口 /api/book/info。
57
+ * 实测该接口返回与榜单页完全相同的文本(明文),零识别误差,
58
+ * 整榜耗时约为 OCR 路径的 1/5。
59
+ * ocr —— 渲染后截图 + tesseract 识别。不依赖番茄内部接口,接口失效时
60
+ * 仍能采到,但存在认字误差(实测简介字符错误率 8%~17%)。
61
+ * vision —— 渲染后截图,把截图绝对路径交给当前 LLM 视觉模型识别。
62
+ * scraper 只负责截图和写 manifest,**不调用任何 OCR**;
63
+ * 当前模型不支持视觉时必须停止,不能降级到 OCR。
61
64
  *
62
65
  * 这是插件层(templates/index)、编排层(run-scan)与 scraper 层之间的契约,
63
66
  * 三处必须用同一套 id —— 不能各写各的字面量。
64
67
  */
65
68
  export const SCAN_MODE_API = 'api';
66
69
  export const SCAN_MODE_OCR = 'ocr';
67
- export const SCAN_MODES = [SCAN_MODE_API, SCAN_MODE_OCR];
70
+ export const SCAN_MODE_VISION = 'vision';
71
+ export const SCAN_MODES = [SCAN_MODE_API, SCAN_MODE_OCR, SCAN_MODE_VISION];
68
72
  export const DEFAULT_SCAN_MODE = SCAN_MODE_API;
69
73
 
70
74
  /**
@@ -0,0 +1,359 @@
1
+ /**
2
+ * task-list.js — DSH 内置任务列表的共享封装
3
+ *
4
+ * DSH 的任务列表不是插件自绘的 UI,而是 session 上的 `todo/write` 事件:
5
+ *
6
+ * session.append('todo/write', { todos: [{ content, status }] })
7
+ *
8
+ * 规则(来自 @deepseek-ai/dsh-tool-todo):
9
+ * - 每次写入都是**整表替换**,不是增量;
10
+ * - status 只有 pending / in_progress / completed;
11
+ * - content 必须非空且不能重复;
12
+ * - 列表属于当前 agent session,下一次 turn/start 会自动清空。
13
+ *
14
+ * 本模块的价值不是再包一层 API,而是把三个实际会踩的坑处理掉:
15
+ *
16
+ * 1. **整表替换**:调用方只关心“第几步了”,这里负责把前面的步骤
17
+ * 标成 completed、当前步骤标成 in_progress、后面的保持 pending。
18
+ * 2. **turn/start 清空**:派发 LLM 的命令(scan/topic/material/import/
19
+ * build…)在新 turn 开始时列表会被清空。这里提供一个轻量 watcher,
20
+ * 在新 turn 开始和结束时把列表写回去,让用户在整个 LLM 回合里
21
+ * 都能看到命令自己的进度,而不是被模型的临时 todo 顶掉。
22
+ * 3. **结束语义**:命令成功结束后保留“全部 completed”的列表,
23
+ * 不手动清空 —— 用户还能看到刚才做了哪些事,下一次对话开始时
24
+ * DSH 自己会清掉。失败时已完成步骤保持 completed,当前及后续
25
+ * 保持 pending,不谎报完成。
26
+ */
27
+
28
+ const VALID_STATUSES = new Set(['pending', 'in_progress', 'completed']);
29
+ const WATCH_INTERVAL_MS = 200;
30
+
31
+ function normalizeTitles(titles) {
32
+ const seen = new Set();
33
+ const out = [];
34
+ for (const raw of Array.isArray(titles) ? titles : []) {
35
+ const content = String(raw == null ? '' : raw).trim();
36
+ if (!content || seen.has(content)) continue;
37
+ seen.add(content);
38
+ out.push(content);
39
+ }
40
+ // 任务列表至少要有一项:空表在 UI 上等于“没有开始”,
41
+ // 而命令已经执行了,用户会以为任务列表坏了。
42
+ if (!out.length) out.push('执行命令');
43
+ return out;
44
+ }
45
+
46
+ function snapshot(items) {
47
+ return items.map(({ content, status }) => ({ content, status }));
48
+ }
49
+
50
+ /**
51
+ * 直接写入一份任务列表。写入失败只记日志,不能反过来把命令打挂:
52
+ * 任务列表是辅助展示,不是业务结果。
53
+ */
54
+ export function writeTaskList(session, todos) {
55
+ if (!session || typeof session.append !== 'function') return false;
56
+ const clean = [];
57
+ const seen = new Set();
58
+ for (const item of Array.isArray(todos) ? todos : []) {
59
+ const content = String(item && item.content != null ? item.content : '').trim();
60
+ const status = String(item && item.status != null ? item.status : '');
61
+ if (!content || seen.has(content) || !VALID_STATUSES.has(status)) continue;
62
+ seen.add(content);
63
+ clean.push({ content, status });
64
+ }
65
+ if (!clean.length) return false;
66
+ try {
67
+ session.append('todo/write', { todos: clean });
68
+ return true;
69
+ } catch (e) {
70
+ console.error('[task-list] 写入任务列表失败:' + (e && e.message ? e.message : String(e)));
71
+ return false;
72
+ }
73
+ }
74
+
75
+ class TaskListController {
76
+ constructor(session, titles) {
77
+ this.session = session;
78
+ this.index = 0;
79
+ this.failed = false;
80
+ this.closed = false;
81
+ this.detached = false;
82
+ this._watcher = null;
83
+ this._watchState = null;
84
+ this.items = normalizeTitles(titles).map((content, i) => ({
85
+ content,
86
+ status: i === 0 ? 'in_progress' : 'pending',
87
+ }));
88
+ this._write();
89
+ }
90
+
91
+ _write() {
92
+ if (this.closed) return false;
93
+ return writeTaskList(this.session, snapshot(this.items));
94
+ }
95
+
96
+ /** 当前整表快照(测试与调试用)。 */
97
+ get todos() {
98
+ return snapshot(this.items);
99
+ }
100
+
101
+ /** 当前步骤的文案。 */
102
+ get current() {
103
+ return this.items[this.index] ? this.items[this.index].content : '';
104
+ }
105
+
106
+ /**
107
+ * 重新定义任务表。用于“用户选完扫描方式后才知道要不要加视觉识别步骤”
108
+ * 这类前置信息不足的场景。
109
+ *
110
+ * @param {string[]} titles
111
+ * @param {{completed?: number}} [opts]
112
+ * completed 表示前 N 项已经做完;其余从第 N 项开始重新排。
113
+ */
114
+ reset(titles, opts = {}) {
115
+ const next = normalizeTitles(titles);
116
+ const completed = Math.max(0, Math.min(Number(opts.completed) || 0, next.length));
117
+ this.items = next.map((content, i) => ({
118
+ content,
119
+ status: i < completed ? 'completed' : (i === completed ? 'in_progress' : 'pending'),
120
+ }));
121
+ this.index = completed >= next.length ? next.length : completed;
122
+ this.closed = false;
123
+ this.failed = false;
124
+ this._write();
125
+ return this;
126
+ }
127
+
128
+ /**
129
+ * 把当前步骤的文案改成带进度的形式(例如“视觉识别截图(3/20)”)。
130
+ * 只改文案,不改状态;用于长循环里让用户看到进度。
131
+ */
132
+ progress(text) {
133
+ const content = String(text == null ? '' : text).trim();
134
+ if (!content || !this.items[this.index]) return this;
135
+ // content 不能和已有项重复(DSH 会拒绝整表)
136
+ if (this.items.some((item, i) => i !== this.index && item.content === content)) return this;
137
+ this.items[this.index].content = content;
138
+ this._write();
139
+ return this;
140
+ }
141
+
142
+ /**
143
+ * 前进到第 index 步。前面的步骤一律 completed,index 为 in_progress,
144
+ * 后面的保持 pending。index >= 长度时表示全部完成。
145
+ */
146
+ advance(index = this.index + 1) {
147
+ const target = Math.max(0, Math.min(Number(index) || 0, this.items.length));
148
+ for (let i = 0; i < this.items.length; i += 1) {
149
+ this.items[i].status = i < target ? 'completed' : (i === target ? 'in_progress' : 'pending');
150
+ }
151
+ this.index = target;
152
+ this._write();
153
+ return this;
154
+ }
155
+
156
+ /** 全部完成(命令成功结束的默认收尾)。 */
157
+ complete() {
158
+ for (const item of this.items) item.status = 'completed';
159
+ this.index = this.items.length;
160
+ this._write();
161
+ return this;
162
+ }
163
+
164
+ /**
165
+ * 命令失败:已完成的保持 completed,当前及后续保持 pending。
166
+ * 不把当前项标成 completed,避免用户误以为这一步成功了。
167
+ */
168
+ fail() {
169
+ this.failed = true;
170
+ for (let i = 0; i < this.items.length; i += 1) {
171
+ if (i < this.index) this.items[i].status = 'completed';
172
+ else if (this.items[i].status !== 'completed') this.items[i].status = 'pending';
173
+ }
174
+ if (this.index >= this.items.length && this.items.length) {
175
+ // 全部完成之后才失败(例如写盘复核失败):最后一项退回 pending,
176
+ // 否则列表会显示“全绿”,与命令的错误结果矛盾。
177
+ this.items[this.items.length - 1].status = 'pending';
178
+ this.index = this.items.length - 1;
179
+ }
180
+ this._write();
181
+ return this;
182
+ }
183
+
184
+ _stopWatcher() {
185
+ if (this._watcher) {
186
+ clearInterval(this._watcher);
187
+ this._watcher = null;
188
+ }
189
+ this._watchState = null;
190
+ }
191
+
192
+ /**
193
+ * 在后续 LLM 回合期间保持任务列表可见。
194
+ *
195
+ * 命令处理器本身不包在 turn 里(DSH 的 command/run 是 log-only append),
196
+ * 所以 command handler 里写的 todo 会一直保留到下一个 LLM turn 开始;
197
+ * 而 turn/start 的投影会把它清成 null。这里每 200ms 看一次 agent.status:
198
+ *
199
+ * idle → running:新 turn 开始,列表刚被清空,立刻写回;
200
+ * running → idle:本 turn 结束,模型可能用 todo_write 改过列表,
201
+ * 写回命令自己的版本。
202
+ *
203
+ * @param {object} invocation DSH command invocation
204
+ * @param {{onTurnEnd?: Function, stopAfterFirstEnd?: boolean}} [opts]
205
+ */
206
+ watchTurns(invocation, opts = {}) {
207
+ const agent = invocation && invocation.agent;
208
+ if (!agent || typeof agent.status !== 'string') return this;
209
+ const onTurnEnd = typeof opts.onTurnEnd === 'function' ? opts.onTurnEnd : null;
210
+ const stopAfterFirstEnd = opts.stopAfterFirstEnd === true;
211
+ const timeoutMs = Number(opts.timeoutMs) > 0 ? Number(opts.timeoutMs) : 0;
212
+ const startedAt = Date.now();
213
+
214
+ this._stopWatcher();
215
+ let running = agent.status === 'running';
216
+ this._watchState = { running };
217
+ // 启动时如果已经在 running,说明 turn/start 已经发生过,
218
+ // 当前列表可能刚被清空;先补写一次。
219
+ if (running) this._write();
220
+
221
+ this._watcher = setInterval(() => {
222
+ if (this.closed) {
223
+ this._stopWatcher();
224
+ return;
225
+ }
226
+ // fire-and-forget 场景的兜底:模型可能永远不会启动下一轮
227
+ //(例如 provider 直接拒绝)。没有这个上限的话 watcher 会一直挂着。
228
+ if (timeoutMs > 0 && Date.now() - startedAt > timeoutMs) {
229
+ this._stopWatcher();
230
+ return;
231
+ }
232
+ let current = false;
233
+ try { current = agent.status === 'running'; } catch { current = false; }
234
+ if (current && !running) {
235
+ // turn/start:DSH 已把列表投影清空,立刻写回
236
+ this._write();
237
+ } else if (!current && running) {
238
+ // turn/end:写回命令自己的列表,再执行调用方的收尾回调
239
+ this._write();
240
+ if (onTurnEnd) {
241
+ try { onTurnEnd(this); } catch (e) {
242
+ console.error('[task-list] onTurnEnd 失败:' + (e && e.message ? e.message : String(e)));
243
+ }
244
+ }
245
+ if (stopAfterFirstEnd) {
246
+ this._stopWatcher();
247
+ return;
248
+ }
249
+ }
250
+ running = current;
251
+ }, WATCH_INTERVAL_MS);
252
+ if (this._watcher && typeof this._watcher.unref === 'function') this._watcher.unref();
253
+ return this;
254
+ }
255
+
256
+ /**
257
+ * 命令处理器已经返回,但后面还有 LLM 回合要跑(fire-and-forget 派活)。
258
+ * 保持 watcher 存活,等第一个 turn 结束后执行 onTurnEnd 并自动收尾。
259
+ */
260
+ detachUntilTurnEnd(invocation, onTurnEnd) {
261
+ this.detached = true;
262
+ this.watchTurns(invocation, {
263
+ stopAfterFirstEnd: true,
264
+ // 正常情况下一轮 LLM 几秒内就会启动;5 分钟足够覆盖排队/重试。
265
+ timeoutMs: 5 * 60 * 1000,
266
+ onTurnEnd: (tasks) => {
267
+ if (onTurnEnd) {
268
+ try { onTurnEnd(tasks); } catch (e) {
269
+ console.error('[task-list] 回合结束回调失败:' + (e && e.message ? e.message : String(e)));
270
+ }
271
+ }
272
+ tasks.close();
273
+ },
274
+ });
275
+ return this;
276
+ }
277
+
278
+ /** 停止 watcher,保留当前列表作为最终展示。 */
279
+ close() {
280
+ if (this.closed) return this;
281
+ this.closed = true;
282
+ this._stopWatcher();
283
+ // close 前再写一次最终快照:watcher 可能在 close 的同一个 tick 里
284
+ // 刚写过,这里重复写没有副作用(整表替换)。
285
+ writeTaskList(this.session, snapshot(this.items));
286
+ return this;
287
+ }
288
+ }
289
+
290
+ /**
291
+ * 创建任务列表并立即写入第一项(in_progress)。
292
+ *
293
+ * @param {object} session DSH agent session
294
+ * @param {string[]} titles 任务文案;第一项自动 in_progress
295
+ * @returns {TaskListController}
296
+ */
297
+ export function createTaskList(session, titles) {
298
+ return new TaskListController(session, titles);
299
+ }
300
+
301
+ /**
302
+ * 包住一个命令处理器:开始时建表,成功时全部完成,失败时保留未完成状态。
303
+ *
304
+ * 命令处理器返回 `{ kind: 'error' }`(notify 的形态)也会被判为失败,
305
+ * 这样不需要在每个 early return 前手动调用 fail()。
306
+ *
307
+ * @param {object} session
308
+ * @param {string[]} titles
309
+ * @param {(tasks: TaskListController) => Promise<any>} fn
310
+ */
311
+ export async function withTaskList(session, titles, fn) {
312
+ const tasks = createTaskList(session, titles);
313
+ try {
314
+ const result = await fn(tasks);
315
+ // detached 表示命令处理器已经返回、但后面还有 LLM 回合要跑
316
+ //(topic setup / analyze summary 等 fire-and-forget 派活)。
317
+ // 这时不能提前把列表标成全完成 —— 收尾由 detachUntilTurnEnd 负责。
318
+ if (!tasks.closed && !tasks.detached) {
319
+ if (result && result.kind === 'error') tasks.fail();
320
+ else tasks.complete();
321
+ }
322
+ return result;
323
+ } catch (e) {
324
+ tasks.fail();
325
+ throw e;
326
+ } finally {
327
+ // fire-and-forget 的命令由 detachUntilTurnEnd 自己收尾,
328
+ // 这里不能提前关掉 watcher。
329
+ if (!tasks.detached) tasks.close();
330
+ }
331
+ }
332
+
333
+ /**
334
+ * 注册 slash 命令,并自动套上任务列表。
335
+ *
336
+ * 这样各个插件的 handler 主体不用再包一层箭头函数、也不用整体缩进:
337
+ *
338
+ * registerCommandWithTasks(ctx, {
339
+ * name: 'fancy-xxx',
340
+ * handler: async (invocation, tasks) => { ... },
341
+ * }, (invocation) => ['步骤一', '步骤二']);
342
+ *
343
+ * titles 可以是数组,也可以是 (invocation) => string[](用于 help/子命令
344
+ * 需要不同任务表的场景)。handler 的第二个参数就是任务列表控制器。
345
+ */
346
+ export function registerCommandWithTasks(ctx, definition, titles) {
347
+ const original = definition && definition.handler;
348
+ if (typeof original !== 'function') {
349
+ throw new Error('registerCommandWithTasks: definition.handler 必须是函数');
350
+ }
351
+ return ctx.commands.register({
352
+ ...definition,
353
+ handler: (invocation) => withTaskList(
354
+ invocation && invocation.agent ? invocation.agent.session : null,
355
+ typeof titles === 'function' ? titles(invocation) : titles,
356
+ (tasks) => original(invocation, tasks)
357
+ ),
358
+ });
359
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.0.3",
3
+ "version": "4.1.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -28,7 +28,8 @@
28
28
  "#surreal-server": "./lib/surreal-server.js",
29
29
  "#material-db": "./lib/material-db.js",
30
30
  "#material-topic": "./lib/material-topic.js",
31
- "#topic-candidates": "./lib/topic-candidates.js"
31
+ "#topic-candidates": "./lib/topic-candidates.js",
32
+ "#task-list": "./lib/task-list.js"
32
33
  },
33
34
  "engines": {
34
35
  "node": ">=18.0.0",
@@ -22,6 +22,7 @@ import { fileURLToPath } from 'url';
22
22
  import { atomicWriteFile } from '#atomic-write';
23
23
  import { askUserQuestion, spawnScript } from '#infra';
24
24
  import { notify, llmFollowup } from '#infra';
25
+ import { registerCommandWithTasks } from '#task-list';
25
26
  import { describeFetchError, llmWikiError, readJsonSafe } from '#llm-wiki';
26
27
  import { readDeployedState, DEPLOYED_STATUS } from '#deployed-state';
27
28
  import { resolveWorkspace } from '#workspace';
@@ -694,14 +695,32 @@ function schemaNeedsRefresh(projectRoot) {
694
695
  }
695
696
  }
696
697
 
698
+ function analyzeTaskTitles(invocation) {
699
+ const raw = String(invocation.rawInput || '').trim().toLowerCase();
700
+ if (raw.startsWith('help')) return ['显示拆解帮助'];
701
+ if (raw.startsWith('status') || raw.startsWith('summary-status')) {
702
+ return ['检查项目与拆解产物', '输出进度'];
703
+ }
704
+ if (raw.startsWith('fix')) {
705
+ return ['检查项目与重试文件', '重新 ingest 缺失文件', '汇总 fix 结果'];
706
+ }
707
+ if (raw.startsWith('resummary')) {
708
+ return ['检查项目与已有总结', 'LLM 重写指定技法', '写入总结'];
709
+ }
710
+ if (raw.startsWith('summary')) {
711
+ return ['检查项目与拆解产物', 'LLM 生成技法总结', '写入总结'];
712
+ }
713
+ return ['检查项目与对标配置', '准备拆解目录与 schema', '提交对标拆解', '汇总拆解结果'];
714
+ }
715
+
697
716
  export async function apply(ctx) {
698
- ctx.commands.register({
717
+ registerCommandWithTasks(ctx, {
699
718
  name: 'fancy-analyze',
700
719
  description: '🔍 拆解爆款小说(参考对标) ( usage: /fancy-analyze [书名] | status | fix | summary | summary-status | resummary [技法名] | help )',
701
720
  input: {
702
721
  hint: '.',
703
722
  },
704
- handler: async (invocation) => {
723
+ handler: async (invocation, taskList) => {
705
724
  const session = invocation.agent.session;
706
725
  const { signal } = invocation;
707
726
 
@@ -752,6 +771,10 @@ export async function apply(ctx) {
752
771
  ? rawInput.slice('resummary'.length).trim()
753
772
  : '';
754
773
 
774
+ // 子命令已经确定,进入具体阶段。help 在上面的 early return 里,
775
+ // 不会走到这里。
776
+ taskList.advance(1);
777
+
755
778
  // 2.1 fix 模式:重新 ingest 缺失的文件
756
779
  if (isFix) {
757
780
  const { config: deployedConfig, errorText: configError } = loadDeployedConfig(projectRoot);
@@ -1750,6 +1773,7 @@ export async function apply(ctx) {
1750
1773
  '❌ 重置完成,但提示词投递失败:' + ((follow && follow.error) || '未知错误') +
1751
1774
  '\n旧总结已备份,用 /fancy-analyze summary-status 确认当前状态');
1752
1775
  }
1776
+ taskList.detachUntilTurnEnd(invocation, (t) => t.advance(2));
1753
1777
  dispatched = tasks.length;
1754
1778
  }
1755
1779
 
@@ -1833,6 +1857,7 @@ export async function apply(ctx) {
1833
1857
  if (!follow || follow.ok !== true) {
1834
1858
  return notify(session, 'error', '❌ 提示词投递失败:' + ((follow && follow.error) || '未知错误'));
1835
1859
  }
1860
+ taskList.detachUntilTurnEnd(invocation, (t) => t.advance(2));
1836
1861
 
1837
1862
  return notify(session, 'success', analyze.notify({
1838
1863
  type: 'summary_dispatched',
@@ -1956,6 +1981,7 @@ export async function apply(ctx) {
1956
1981
  }
1957
1982
 
1958
1983
  // 5. 拷贝 schema-analyze.md → 对标/schema.md
1984
+ taskList.advance(1);
1959
1985
  const duiBiaoDir = join(projectRoot, '对标');
1960
1986
  try {
1961
1987
  copySchemaFile(duiBiaoDir);
@@ -1977,6 +2003,7 @@ export async function apply(ctx) {
1977
2003
  }
1978
2004
 
1979
2005
  // 7. 调用 llm_wiki sources/ingest 接口
2006
+ taskList.advance(2);
1980
2007
  //
1981
2008
  // 这里必须把失败**报给用户**。
1982
2009
  // 之前只是 try/catch + console.error,可 HTTP 4xx/5xx 根本不抛异常,
@@ -2014,11 +2041,12 @@ export async function apply(ctx) {
2014
2041
  }
2015
2042
 
2016
2043
  // 8. 通知用户
2044
+ taskList.advance(3);
2017
2045
  return notify(session, 'success', analyze.notify({
2018
2046
  type: 'done',
2019
2047
  bookNameClean,
2020
2048
  projectRoot,
2021
2049
  }));
2022
2050
  },
2023
- });
2051
+ }, analyzeTaskTitles);
2024
2052
  }
@@ -10,6 +10,7 @@ import { existsSync, realpathSync, statSync } from 'fs';
10
10
  import { homedir } from 'os';
11
11
  import { basename, dirname, isAbsolute, join, resolve } from 'path';
12
12
  import { askUserQuestion, notify } from '#infra';
13
+ import { registerCommandWithTasks } from '#task-list';
13
14
  import { isSensitiveProjectPath, isValidProjectPath } from '#path-guard';
14
15
  import { readDeployedState, deployedStateProblemText, DEPLOYED_STATUS } from '#deployed-state';
15
16
  import { initWorkspaceDatabase } from '#db-init';
@@ -104,12 +105,20 @@ function formatWorkspace(root) {
104
105
  ].join('\n');
105
106
  }
106
107
 
108
+ function bootstrapTaskTitles(rawInput) {
109
+ const raw = String(rawInput || '').trim().toLowerCase();
110
+ if (raw === 'help') return ['显示初始化帮助'];
111
+ if (raw === 'status') return ['读取工作区状态', '探测 SurrealDB 服务'];
112
+ if (raw === 'list') return ['读取全局工作区注册表', '探测各工作区服务状态'];
113
+ return ['检查工作区路径与状态', '准备 SurrealDB', '初始化目录与数据库', '输出初始化结果'];
114
+ }
115
+
107
116
  export async function apply(ctx) {
108
- ctx.commands.register({
117
+ registerCommandWithTasks(ctx, {
109
118
  name: 'fancy-bootstrap',
110
119
  description: '📁 初始化 fancy-webnovel 工作区 ( usage: /fancy-bootstrap [目录] | status | list | help )',
111
120
  input: { hint: '[目录] | status | list' },
112
- handler: async (invocation) => {
121
+ handler: async (invocation, tasks) => {
113
122
  const session = invocation.agent.session;
114
123
  const rawInput = String(invocation.rawInput || '').trim();
115
124
 
@@ -147,6 +156,7 @@ export async function apply(ctx) {
147
156
  ? [currentEntry, ...entries.filter((entry) => entry !== currentEntry)]
148
157
  : entries;
149
158
 
159
+ tasks.advance(1);
150
160
  const details = await Promise.all(ordered.map(async (entry) => {
151
161
  let surreal = null;
152
162
  try { surreal = readWorkspace(entry.workspace).surreal || null; } catch { /* missing/lightweight */ }
@@ -275,6 +285,7 @@ export async function apply(ctx) {
275
285
  const choice = confirmed.answer?.answers?.[0]?.selected?.[0];
276
286
  if (choice !== '确认创建') return notify(session, 'error', '🚫 操作已取消。');
277
287
 
288
+ tasks.advance(1);
278
289
  try {
279
290
  // First init may need the standalone binary. Install it into the
280
291
  // workspace so it survives PATH changes and is easy to remove.
@@ -283,7 +294,9 @@ export async function apply(ctx) {
283
294
  notes.push('⏬ 未找到 surreal,已自动下载到工作区 .fancy/bin/。');
284
295
  await installSurreal(target);
285
296
  }
297
+ tasks.advance(2);
286
298
  const result = await initWorkspaceDatabase(target);
299
+ tasks.advance(3);
287
300
  return notify(session, 'success', [
288
301
  '✅ 工作区初始化完成',
289
302
  ...(notes.length ? ['', ...notes] : []),
@@ -309,5 +322,5 @@ export async function apply(ctx) {
309
322
  return notify(session, 'error', '❌ 初始化失败:' + (err && err.message ? err.message : String(err)));
310
323
  }
311
324
  },
312
- });
325
+ }, (invocation) => bootstrapTaskTitles(invocation.rawInput));
313
326
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { askUserQuestion, notify } from '#infra';
14
+ import { registerCommandWithTasks } from '#task-list';
14
15
  import { readWorkspace, resolveWorkspace } from '#workspace';
15
16
  import { deleteProject, listProjects, getProject } from '#projects';
16
17
  import { initDatabases, initProjectDatabase, initWorkspaceDatabase } from '#db-init';
@@ -72,12 +73,31 @@ function formatProjects(projects) {
72
73
  return lines.join('\n');
73
74
  }
74
75
 
76
+ function dbTaskTitles(invocation) {
77
+ const tokens = String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean);
78
+ const command = (tokens[0] || 'status').toLowerCase();
79
+ if (command === 'help' || command === '?') return ['显示数据库帮助'];
80
+ if (command === 'status') return ['读取工作区', '探测 SurrealDB 状态'];
81
+ if (command === 'install') return ['读取工作区', '安装 SurrealDB'];
82
+ if (command === 'start') return ['读取工作区', '启动 SurrealDB', '探测服务状态'];
83
+ if (command === 'stop') return ['读取工作区', '停止 SurrealDB'];
84
+ if (command === 'list') return ['读取工作区', '读取项目库列表'];
85
+ if (command === 'remove') return ['读取工作区', '确认删除范围', '删除项目数据库', '清理项目目录'];
86
+ if (command === 'init') {
87
+ if ((tokens[1] || '').toLowerCase() === 'project') {
88
+ return ['读取工作区', '解析目标项目', '初始化项目库', '输出结果'];
89
+ }
90
+ return ['读取工作区', '初始化工作区数据库', '初始化素材库', '汇总结果'];
91
+ }
92
+ return ['读取工作区', '执行数据库操作'];
93
+ }
94
+
75
95
  export async function apply(ctx) {
76
- ctx.commands.register({
96
+ registerCommandWithTasks(ctx, {
77
97
  name: 'fancy-db',
78
98
  description: '🗄️ 数据库管理 ( usage: /fancy-db status|install|start|stop|init|list|remove | help )',
79
99
  input: { hint: '.' },
80
- handler: async (invocation) => {
100
+ handler: async (invocation, tasks) => {
81
101
  const session = invocation.agent.session;
82
102
  const raw = String(invocation.rawInput || '').trim();
83
103
  const tokens = raw.split(/\s+/).filter(Boolean);
@@ -92,6 +112,7 @@ export async function apply(ctx) {
92
112
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
93
113
  }
94
114
 
115
+ tasks.advance(1);
95
116
  try {
96
117
  if (command === 'status') {
97
118
  return notify(session, 'success', formatStatus(await serverStatus(root)));
@@ -104,6 +125,7 @@ export async function apply(ctx) {
104
125
 
105
126
  if (command === 'start') {
106
127
  const result = await startServer(root);
128
+ tasks.advance(2);
107
129
  return notify(session, 'success', (result.started ? '✅ 已启动' : 'ℹ️ 已在运行') + '\n' + formatStatus(await serverStatus(root)));
108
130
  }
109
131
 
@@ -117,10 +139,13 @@ export async function apply(ctx) {
117
139
  if (target === 'project') {
118
140
  const name = tokens.slice(2).join(' ').trim();
119
141
  if (!name) return notify(session, 'error', '用法:/fancy-db init project <名字|UUID>');
142
+ tasks.advance(2);
120
143
  const result = await initProjectDatabase(root, name);
144
+ tasks.advance(3);
121
145
  return notify(session, 'success', '✅ 已初始化项目库:' + result.project.name + '\n库:' + result.project.database + '\nschema ' + result.schema_version + ' / validation ' + result.validation_version);
122
146
  }
123
147
  const result = await initDatabases(root, { all: true });
148
+ tasks.advance(2);
124
149
  const failed = result.projects.filter((p) => !p.ok);
125
150
  return notify(session, failed.length ? 'error' : 'success', [
126
151
  '✅ 工作区数据库初始化完成',
@@ -156,10 +181,12 @@ export async function apply(ctx) {
156
181
  if (selected !== '删除数据库' && selected !== '删除数据库并清除目录') {
157
182
  return notify(session, 'success', '操作已取消。');
158
183
  }
184
+ tasks.advance(2);
159
185
  const result = await deleteProject(root, project.project_id, {
160
186
  confirm: true,
161
187
  purge: selected === '删除数据库并清除目录',
162
188
  });
189
+ tasks.advance(3);
163
190
  return notify(session, 'success', '✅ 已删除《' + result.project.name + '》的数据库' + (result.purged ? '和项目目录' : ',项目目录已移入 .fancy/trash'));
164
191
  }
165
192
 
@@ -168,5 +195,5 @@ export async function apply(ctx) {
168
195
  return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
169
196
  }
170
197
  },
171
- });
198
+ }, dbTaskTitles);
172
199
  }