dsh-uitest 2.3.0 → 2.3.1

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
@@ -60,6 +60,8 @@ flow 不是执行前提。自然语言用例才是事实来源。
60
60
  - POST /plan
61
61
  - GET/POST /batch
62
62
  - POST /batch/stop
63
+ - POST /batch/distill(异步重新沉淀;重复启动返回 started:false、alreadyRunning:true)
64
+ - GET /batch/distill/status(沉淀阶段 phase/done/total/mode 与 active)
63
65
  - POST /batch/backfill
64
66
  - GET /flows
65
67
  - POST /flows/delete(批量删除关联 flow)
@@ -153,7 +155,9 @@ flow 不是执行前提。自然语言用例才是事实来源。
153
155
  - 知识页默认打开中心知识库:可浏览近况/事实/实体、按关键词服务端检索、查看 Episode 全文,并直接导入知识文件或文件夹(支持仅预览)。
154
156
  - 知识提取与语义索引由中心服务自动、持续运行:服务定时扫描未提取知识与未索引条目,测试工作室知识页实时显示管线阶段、提取/索引进度和最近一次运行。页面的手动按钮只用于补跑、重跑或排查问题。
155
157
  - 全量迁移:`node scripts/knowledge-central-sync.mjs --project .`;预演加 `--dry-run`。同步状态文件在 `.uitest/studio/knowledge-central-ingested.json`,相同内容自动跳过。
156
- - 批次 case-run 用稳定键 `case:<caseId>`(batchId 在正文);中心 `/ingest` 按 group+name+内容幂等,同内容跳过,内容变化替换旧版本并清理 `case:<caseId>:*` 旧键;学习事件按 `kind|runDir|stepId` 幂等。
158
+ - 批次 case-run 用稳定键 `case:<caseId>`(batchId 在正文);中心 `/ingest` 与 `/ingest-fast` 按 group+name+内容幂等,同内容跳过,内容变化替换旧版本并清理 `case:<caseId>:*` 旧键;学习事件按 `kind|runDir|stepId` 幂等。
159
+ - 批次沉淀优先走 `/ingest-fast`:先读 `/health` 的 `fast_upsert`,支持时只写原始 Episode 并带 `upsert:true`,旧版本按 `replace_prefix` 清理,实体抽取交给中心自动管线在后台继续;旧服务没有该能力时回退 `/ingest` 同步抽取。
160
+ - 重新沉淀是后台任务:`POST /batch/distill` 立即返回 `{started:true}`,进度写入批次 stage 的 `phase`/`done`/`total`/`mode`;前端约每 1.2 秒轮询 `GET /batch/distill/status`,完成后刷新批次。阶段仍是 `running` 但 `active:false` 视为上次中断或在其它进程运行,可直接重新沉淀。
157
161
  - 规范 Episode 归最新一次实际执行所有:旧批次重新沉淀不覆盖更新批次;手动/阻断执行没有 run 目录,不发 case Episode。
158
162
  - 批次内重跑累计页面、动作与等待,观察变少不缩小正文;页面/流程 Episode 与 `knowledge-central-sync.mjs` 共用同一套序列化,避免互相替换。
159
163
  - 导入文档本地编辑后,重新导入源文件会跳过该文档;服务端同内容跳过计为 skipped。
package/client.js CHANGED
@@ -18,6 +18,7 @@ window.__ModuleLoader__.load({
18
18
  const RECENT_PROJECTS_KEY = 'uitest.studio.recentProjects';
19
19
  const POLL_RUNNING = 1600;
20
20
  const POLL_IDLE = 9000;
21
+ const POLL_DISTILL = 1200;
21
22
 
22
23
  /* ------------------------------------------------------------------ */
23
24
  /* 纯工具 */
@@ -530,7 +531,7 @@ window.__ModuleLoader__.load({
530
531
  const elapsed = useElapsed(props.startedAt, props.active !== false);
531
532
  return h('div', { className: 'studio-op', role: 'status', 'aria-live': 'polite' },
532
533
  h('div', { className: 'studio-op-head' },
533
- h(Spinner),
534
+ props.active === false ? h(Icon, { name: 'clock', size: 14 }) : h(Spinner),
534
535
  h('span', { className: 'studio-op-title' }, props.label || '正在处理'),
535
536
  h('span', { className: 'studio-op-time' }, formatDuration(elapsed))
536
537
  ),
@@ -543,10 +544,62 @@ window.__ModuleLoader__.load({
543
544
  }, h('span', { className: 'studio-op-step-dot' }), step.label))
544
545
  )
545
546
  : null,
546
- h('div', { className: 'studio-op-bar' }, h(Progress, { indeterminate: true, tone: 'business' }))
547
+ h('div', { className: 'studio-op-bar' }, h(Progress, {
548
+ percent: props.percent,
549
+ indeterminate: props.indeterminate !== false,
550
+ tone: 'business',
551
+ }))
547
552
  );
548
553
  }
549
554
 
555
+ const DISTILL_PHASES = [
556
+ { id: 'learn', label: '页面学习' },
557
+ { id: 'process', label: '流程知识合并' },
558
+ { id: 'episodes', label: '整理中心知识' },
559
+ { id: 'central', label: '写入中心知识库' },
560
+ { id: 'finalize', label: '写入批次知识' },
561
+ ];
562
+ const DISTILL_PHASE_LABELS = {
563
+ starting: '正在启动沉淀',
564
+ learn: '页面学习',
565
+ process: '流程知识合并',
566
+ episodes: '整理中心知识',
567
+ central: '写入中心知识库',
568
+ finalize: '写入批次知识',
569
+ };
570
+
571
+ function distillSteps(stage) {
572
+ const phase = String(stage?.phase || '');
573
+ const activeIndex = phase === 'done'
574
+ ? DISTILL_PHASES.length
575
+ : phase === 'starting'
576
+ ? 0
577
+ : DISTILL_PHASES.findIndex((item) => item.id === phase);
578
+ return DISTILL_PHASES.map((item, index) => ({
579
+ label: item.label,
580
+ status: phase === 'done' || index < activeIndex ? 'done' : index === activeIndex ? 'active' : '',
581
+ }));
582
+ }
583
+
584
+ function distillPhaseText(stage) {
585
+ if (!stage) return '';
586
+ if (stage.status === 'failed') return '沉淀失败,可重新沉淀。';
587
+ if (stage.status === 'done') return '沉淀完成。';
588
+ const phase = String(stage.phase || 'starting');
589
+ const label = DISTILL_PHASE_LABELS[phase] || '正在沉淀';
590
+ const total = Number(stage.total) || 0;
591
+ const done = Number(stage.done) || 0;
592
+ const count = total > 0 ? ' · ' + done + ' / ' + total : '';
593
+ const mode = phase === 'central'
594
+ ? stage.mode === 'fast'
595
+ ? ' · 只写原始 Episode,实体抽取由中心服务后台继续'
596
+ : stage.mode === 'classic'
597
+ ? ' · 正在同步写入并等待中心服务抽取'
598
+ : ''
599
+ : '';
600
+ return label + count + mode;
601
+ }
602
+
550
603
  function Field(props) {
551
604
  return h('label', { className: 'studio-field' },
552
605
  h('span', { className: 'studio-field-label' }, props.label),
@@ -3902,8 +3955,11 @@ window.__ModuleLoader__.load({
3902
3955
  const [deleteOpen, setDeleteOpen] = useState(false);
3903
3956
  const [deleting, setDeleting] = useState(false);
3904
3957
  const [deleteError, setDeleteError] = useState('');
3905
- const [distilling, setDistilling] = useState(false);
3958
+ const [startingDistill, setStartingDistill] = useState(false);
3906
3959
  const [distillError, setDistillError] = useState('');
3960
+ const [liveDistill, setLiveDistill] = useState(null);
3961
+ const [distillPolling, setDistillPolling] = useState(false);
3962
+ const [distillInterrupted, setDistillInterrupted] = useState(false);
3907
3963
  const [writebackOpen, setWritebackOpen] = useState(false);
3908
3964
  const [exportOpen, setExportOpen] = useState(false);
3909
3965
  const [liveFocus, setLiveFocus] = useState(null);
@@ -3914,6 +3970,50 @@ window.__ModuleLoader__.load({
3914
3970
  const [selectedRunIds, setSelectedRunIds] = useState([]);
3915
3971
  const [bulkBusy, setBulkBusy] = useState('');
3916
3972
  const [resuming, setResuming] = useState(false);
3973
+ useEffect(() => {
3974
+ if (!distillPolling) return undefined;
3975
+ let cancelled = false;
3976
+ let timer = null;
3977
+ const tick = async () => {
3978
+ try {
3979
+ const payload = await api('/batch/distill/status', {
3980
+ project: props.project,
3981
+ query: { id: batch.id },
3982
+ });
3983
+ const next = payload?.distill;
3984
+ if (cancelled) return;
3985
+ if (!next) {
3986
+ timer = setTimeout(tick, POLL_DISTILL);
3987
+ return;
3988
+ }
3989
+ setLiveDistill(next);
3990
+ if (String(next.status) === 'done') {
3991
+ const fresh = await refreshNow();
3992
+ if (cancelled) return;
3993
+ setLiveDistill(fresh ? null : next);
3994
+ setDistillPolling(false);
3995
+ setDistillInterrupted(false);
3996
+ if (props.onDistilled) props.onDistilled();
3997
+ return;
3998
+ }
3999
+ if (String(next.status) === 'failed') {
4000
+ setDistillPolling(false);
4001
+ setDistillInterrupted(false);
4002
+ return;
4003
+ }
4004
+ if (next.active !== true) {
4005
+ setDistillPolling(false);
4006
+ if (String(next.status) === 'running') setDistillInterrupted(true);
4007
+ return;
4008
+ }
4009
+ } catch {
4010
+ /* 轮询失败时保留当前进度,下一轮重试 */
4011
+ }
4012
+ if (!cancelled) timer = setTimeout(tick, POLL_DISTILL);
4013
+ };
4014
+ timer = setTimeout(tick, POLL_DISTILL);
4015
+ return () => { cancelled = true; if (timer) clearTimeout(timer); };
4016
+ }, [distillPolling, batch.id, props.project, refreshNow]);
3917
4017
  const progress = batchProgress(batch);
3918
4018
  const rawCases = asArray(batch.cases);
3919
4019
  const cases = useMemo(() => sortRunsForDisplay(rawCases), [rawCases]);
@@ -3961,9 +4061,18 @@ window.__ModuleLoader__.load({
3961
4061
  };
3962
4062
  const stoppable = ['running', 'preparing', 'queued'].includes(String(batch.status || ''));
3963
4063
  const deletable = !['running', 'queued', 'preparing'].includes(String(batch.status || ''));
3964
- const distillStage = String(batch.stages?.distill?.status || '');
4064
+ const distillStage = liveDistill || batch.stages?.distill || null;
4065
+ const distillStageStatus = String(distillStage?.status || '');
4066
+ const distillBusy = startingDistill || distillPolling;
4067
+ const showDistillProgress = distillBusy || distillStageStatus === 'running';
4068
+ const stageDistillError = distillStageStatus === 'failed' ? String(distillStage?.error || '') : '';
4069
+ const distillTotal = Number(distillStage?.total) || 0;
4070
+ const distillPercent = distillTotal > 0
4071
+ ? Math.round(((Number(distillStage?.done) || 0) / distillTotal) * 100)
4072
+ : 0;
4073
+ const distillIndeterminate = distillTotal <= 0;
3965
4074
  const needsDistill = !['running', 'queued', 'preparing'].includes(String(batch.status || ''))
3966
- && (!batch.knowledge || distillStage === 'running' || distillStage === 'failed');
4075
+ && (distillBusy || !batch.knowledge || distillStageStatus === 'running' || distillStageStatus === 'failed');
3967
4076
  const caseRun = cases.find((run) => String(run.caseId) === String(caseId)) || null;
3968
4077
  const runAction = async (kind, run) => {
3969
4078
  const handler = kind === 'stop' ? props.onStopCase : kind === 'prioritize' ? props.onPrioritizeCase : props.onRequeueCase;
@@ -4013,6 +4122,10 @@ window.__ModuleLoader__.load({
4013
4122
  setDeleteOpen(false);
4014
4123
  setDeleteError('');
4015
4124
  setDistillError('');
4125
+ setStartingDistill(false);
4126
+ setLiveDistill(null);
4127
+ setDistillInterrupted(false);
4128
+ setDistillPolling(batch.distillActive === true || String(batch.stages?.distill?.status) === 'running');
4016
4129
  setLogOpen(false);
4017
4130
  setArchiveOpen(false);
4018
4131
  setRunFilter('all');
@@ -4023,16 +4136,24 @@ window.__ModuleLoader__.load({
4023
4136
  setBulkBusy('');
4024
4137
  }, [batch.id]);
4025
4138
  const distillBatchNow = async () => {
4026
- setDistilling(true);
4139
+ setStartingDistill(true);
4027
4140
  setDistillError('');
4141
+ setDistillInterrupted(false);
4142
+ setLiveDistill({ status: 'running', phase: 'starting', startedAt: new Date().toISOString() });
4143
+ setDistillPolling(true);
4028
4144
  try {
4029
- const payload = await api('/batch/distill', { method: 'POST', project: props.project, body: { id: batch.id }, timeoutMs: 600000 });
4145
+ const payload = await api('/batch/distill', { method: 'POST', project: props.project, body: { id: batch.id } });
4030
4146
  if (payload?.batch) applyBatch(payload.batch);
4031
- if (props.onDistilled) props.onDistilled();
4147
+ if (payload?.started !== true && payload?.alreadyRunning !== true) {
4148
+ setLiveDistill(null);
4149
+ setDistillPolling(false);
4150
+ }
4032
4151
  } catch (err) {
4033
4152
  setDistillError(err.message);
4153
+ setLiveDistill(null);
4154
+ setDistillPolling(false);
4034
4155
  } finally {
4035
- setDistilling(false);
4156
+ setStartingDistill(false);
4036
4157
  }
4037
4158
  };
4038
4159
  const deleteBatchNow = async () => {
@@ -4069,10 +4190,10 @@ window.__ModuleLoader__.load({
4069
4190
  needsDistill ? h('button', {
4070
4191
  key: 'distill',
4071
4192
  className: 'studio-btn studio-btn-primary',
4072
- disabled: distilling,
4193
+ disabled: distillBusy,
4073
4194
  title: '重新学习本批页面与流程并写入中心知识库',
4074
4195
  onClick: distillBatchNow,
4075
- }, distilling ? h(Spinner) : h(Icon, { name: 'knowledge', size: 13 }), distilling ? '沉淀中…' : '重新沉淀') : null,
4196
+ }, distillBusy ? h(Spinner) : h(Icon, { name: 'knowledge', size: 13 }), distillBusy ? '沉淀中…' : '重新沉淀') : null,
4076
4197
  h(MenuButton, { key: 'more', label: '更多', icon: 'more' }, [
4077
4198
  h('button', { key: 'export', className: 'studio-btn', disabled: !cases.length, title: cases.length ? '导出本批次测试结果 xlsx' : '批次还没有用例结果', onClick: () => setExportOpen(true) }, h(Icon, { name: 'file', size: 13 }), '导出结果'),
4078
4199
  h('button', { key: 'log', className: 'studio-btn', onClick: () => setLogOpen(true) }, h(Icon, { name: 'terminal', size: 13 }), '执行日志'),
@@ -4082,11 +4203,17 @@ window.__ModuleLoader__.load({
4082
4203
  ],
4083
4204
  }),
4084
4205
 
4085
- distilling ? h('div', { style: { marginTop: 12 } }, h(OperationProgress, {
4086
- label: '正在重新沉淀本批知识',
4087
- detail: '重新学习本批页面与流程,合并后写入中心知识库。完成后列表会自动刷新。',
4088
- steps: [{ label: '页面学习', status: 'active' }, { label: '流程知识合并' }, { label: '写入中心知识库' }],
4206
+ showDistillProgress ? h('div', { style: { marginTop: 12 } }, h(OperationProgress, {
4207
+ label: distillInterrupted ? '上一次沉淀未完成' : '正在重新沉淀本批知识',
4208
+ detail: distillPhaseText(distillStage),
4209
+ steps: distillSteps(distillStage),
4210
+ startedAt: distillStage?.startedAt,
4211
+ percent: distillPercent,
4212
+ indeterminate: distillIndeterminate,
4213
+ active: !distillInterrupted,
4089
4214
  })) : null,
4215
+ distillInterrupted ? h('div', { className: 'studio-note tone-warn', style: { marginTop: 10 } }, '上一次沉淀可能已中断,或在另一个进程中运行;可以直接重新沉淀。') : null,
4216
+ stageDistillError ? h('div', { className: 'studio-note tone-danger', style: { marginTop: 10 } }, '重新沉淀失败:' + stageDistillError) : null,
4090
4217
  distillError ? h('div', { className: 'studio-note tone-danger', style: { marginTop: 10 } }, '重新沉淀失败:' + distillError) : null,
4091
4218
 
4092
4219
  h('div', { className: 'studio-meta-strip' },
@@ -47,6 +47,23 @@ export function stableHash(value) {
47
47
  return crypto.createHash('sha1').update(text).digest('hex');
48
48
  }
49
49
 
50
+ const fastUpsertCache = new Map();
51
+
52
+ async function centralSupportsFastUpsert(config) {
53
+ const central = centralConfig(config);
54
+ const cached = fastUpsertCache.get(central.url);
55
+ if (cached && Date.now() - cached.at < 60000) return cached.value;
56
+ let value = false;
57
+ try {
58
+ const payload = await requestJson(config, '/health', { timeoutMs: 5000 });
59
+ value = payload?.fast_upsert === true;
60
+ } catch {
61
+ value = false;
62
+ }
63
+ fastUpsertCache.set(central.url, { at: Date.now(), value });
64
+ return value;
65
+ }
66
+
50
67
  async function requestJson(config, pathname, { method = 'GET', body, timeoutMs } = {}) {
51
68
  const central = centralConfig(config);
52
69
  if (!central.enabled) throw new CentralKnowledgeError('中心知识库未启用', { code: 'CENTRAL_DISABLED' });
@@ -358,13 +375,14 @@ export function saveCentralSyncState(config, state) {
358
375
 
359
376
  /**
360
377
  * 增量写入中心库。相同 key + 相同内容的 Episode 默认跳过,避免重复导入。
361
- * @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[]}>}
378
+ * @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[], mode:string}>}
362
379
  */
363
- export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true } = {}) {
380
+ export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true, fast = false, onProgress = null } = {}) {
364
381
  const central = centralConfig(config);
365
382
  if (!central.enabled) {
366
- return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [] };
383
+ return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [], mode: 'classic' };
367
384
  }
385
+ const mode = fast && (await centralSupportsFastUpsert(config)) ? 'fast' : 'classic';
368
386
  const state = dedupe ? readCentralSyncState(config) : { version: 1, entries: {} };
369
387
  const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
370
388
  const pending = [];
@@ -381,11 +399,14 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
381
399
  const results = [];
382
400
  const errors = [];
383
401
  let ingested = 0;
384
- const batchSize = Math.max(1, Number(central.batchSize) || 5);
402
+ const batchSize = mode === 'fast'
403
+ ? Math.max(10, Number(central.batchSize || 2) * 5)
404
+ : Math.max(1, Number(central.batchSize) || 5);
405
+ if (onProgress) await onProgress({ done: 0, total: pending.length, mode });
385
406
  for (let offset = 0; offset < pending.length; offset += batchSize) {
386
407
  const chunk = pending.slice(offset, offset + batchSize);
387
408
  try {
388
- const payload = await requestJson(config, '/ingest', {
409
+ const payload = await requestJson(config, mode === 'fast' ? '/ingest-fast' : '/ingest', {
389
410
  method: 'POST',
390
411
  body: {
391
412
  group_id: groupId || central.groupId,
@@ -397,6 +418,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
397
418
  source: episode.source || 'json',
398
419
  group_id: episode.group_id || groupId || central.groupId,
399
420
  replace_prefix: episode.replace_prefix || null,
421
+ ...(mode === 'fast' ? { upsert: true } : {}),
400
422
  })),
401
423
  },
402
424
  timeoutMs: central.timeoutMs,
@@ -415,6 +437,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
415
437
  } catch (error) {
416
438
  errors.push({ ok: false, error: String(error.message || error), count: chunk.length, names: chunk.map((entry) => entry.name) });
417
439
  }
440
+ if (onProgress) await onProgress({ done: offset + chunk.length, total: pending.length, mode });
418
441
  }
419
442
  if (dedupe) saveCentralSyncState(config, { version: 1, updatedAt: nowIso(), entries });
420
443
  const failed = errors.reduce((sum, item) => sum + (Number(item.count) || 1), 0);
@@ -426,6 +449,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
426
449
  failed,
427
450
  results,
428
451
  errors,
452
+ mode,
429
453
  groupId: groupId || central.groupId,
430
454
  url: central.url,
431
455
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-uitest",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
4
4
  "type": "module",
5
5
  "description": "Test Studio for DSH: import cases into natural-language tests, seed preconditions, run flow and Agent cases concurrently with agent-browser, archive evidence, write back by batch, and accumulate reusable flows and page knowledge.",
6
6
  "icon": "./icon.svg",
package/studio/host.mjs CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  syncCentralDocuments,
22
22
  } from '../lib/knowledge-docs.mjs';
23
23
  import { isKnowledgeCategory } from '../lib/knowledge-categories.mjs';
24
- import { commitBatchKnowledge } from './knowledge.mjs';
24
+ import { commitBatchKnowledge, isDistillActive } from './knowledge.mjs';
25
25
  import { buildStudioPlan, compactPlan } from './plan.mjs';
26
26
  import { accountsPayload, deleteAccount, importAccountsText, saveAccount, setDefaultAccount } from './accounts.mjs';
27
27
  import { readLiveInfo } from './live.mjs';
@@ -276,6 +276,7 @@ function batchDetail(config, batchId) {
276
276
  summary: summarizeCaseRuns(mergedRuns),
277
277
  queue: batch.queue || null,
278
278
  stages: batch.stages || null,
279
+ distillActive: isDistillActive(config, batchId),
279
280
  cases: merged,
280
281
  events: readEvents(config, batchId, { limit: 200 }),
281
282
  log,
@@ -675,8 +676,26 @@ async function handleBatchDistill(ctx, request) {
675
676
  if (['running', 'queued', 'preparing'].includes(String(batch.status || ''))) {
676
677
  throw hostError(409, 'BATCH_RUNNING', '批次正在执行,结束后再沉淀');
677
678
  }
678
- const knowledge = await commitBatchKnowledge(config, id, { logger: ctx?.logger });
679
- return ok({ knowledge, batch: batchDetail(config, id) });
679
+ if (isDistillActive(config, id)) {
680
+ return ok({ started: false, alreadyRunning: true, batch: batchDetail(config, id) });
681
+ }
682
+ commitBatchKnowledge(config, id, { logger: ctx?.logger });
683
+ return ok({ started: true, batch: batchDetail(config, id) });
684
+ }
685
+
686
+ async function handleBatchDistillStatus(ctx, request) {
687
+ const url = new URL(request.url, 'http://localhost');
688
+ const { config } = projectFor(ctx, url.searchParams.get('project') || '');
689
+ const id = url.searchParams.get('id') || '';
690
+ if (!id) throw hostError(400, 'BATCH_REQUIRED', '缺少批次 id');
691
+ const batch = readBatch(config, id);
692
+ return ok({
693
+ distill: {
694
+ ...(batch.stages?.distill || { status: 'pending' }),
695
+ active: isDistillActive(config, id),
696
+ batchStatus: batch.status || '',
697
+ },
698
+ });
680
699
  }
681
700
 
682
701
  async function handleBackfill(ctx, request) {
@@ -1439,6 +1458,7 @@ export function registerStudioRoutes({ ctx, panel }) {
1439
1458
  ['/batch/case/prioritize', ['POST'], (request) => handleCasePrioritize(ctx, request)],
1440
1459
  ['/batch/delete', ['POST'], (request) => handleBatchDelete(ctx, request)],
1441
1460
  ['/batch/distill', ['POST'], (request) => handleBatchDistill(ctx, request)],
1461
+ ['/batch/distill/status', ['GET'], (request) => handleBatchDistillStatus(ctx, request)],
1442
1462
  ['/batch/backfill', ['POST'], (request) => handleBackfill(ctx, request)],
1443
1463
  ['/accounts', ['GET'], (request) => handleAccounts(ctx, request)],
1444
1464
  ['/accounts/save', ['POST'], (request) => handleAccountSave(ctx, request)],
@@ -10,6 +10,20 @@ import { nowIso, sleep, slug } from '../lib/util.mjs';
10
10
  import { acquireLock, listBatches, patchBatch, patchStage, readBatch, readCaseRun, readCaseRuns, writeBatchText } from './store.mjs';
11
11
  import { correctionKey, correctionText, detectSelfCorrections } from './experience.mjs';
12
12
 
13
+ const distillJobs = new Map();
14
+
15
+ function distillJobKey(config, batchId) {
16
+ return String(config.projectDir || '') + '\0' + String(batchId || '');
17
+ }
18
+
19
+ export function isDistillActive(config, batchId) {
20
+ return distillJobs.has(distillJobKey(config, batchId));
21
+ }
22
+
23
+ function yieldEventLoop() {
24
+ return new Promise((resolve) => setImmediate(resolve));
25
+ }
26
+
13
27
  function pageSummary(page) {
14
28
  return {
15
29
  id: page.id,
@@ -464,19 +478,42 @@ function mergeLearnedItem(item, previous) {
464
478
  * 3) 成功执行与自我纠错 → 流程经验;
465
479
  * 4) 写批次 knowledge.json 并把统计挂到 batch。
466
480
  */
467
- export async function commitBatchKnowledge(config, batchId, { logger = null } = {}) {
468
- await patchStage(config, batchId, 'distill', { status: 'running', error: null });
469
- const lock = await acquireKnowledgeLock(config);
481
+ async function runBatchKnowledgeDistill(config, batchId, { logger = null, startedAt = nowIso() } = {}) {
482
+ let lock = null;
470
483
  try {
484
+ await patchStage(config, batchId, 'distill', {
485
+ status: 'running', phase: 'learn', done: 0, total: 0, startedAt, error: null,
486
+ });
487
+ lock = await acquireKnowledgeLock(config);
471
488
  // 上一轮汇总必须在锁内读取,否则并发重试会用旧统计覆盖先完成的一轮。
472
489
  const runs = readCaseRuns(config, batchId);
490
+ if (runs.length) {
491
+ await patchStage(config, batchId, 'distill', {
492
+ status: 'running', phase: 'learn', done: 0, total: runs.length, startedAt, error: null,
493
+ });
494
+ }
473
495
  const previousByCase = new Map(
474
496
  (readBatch(config, batchId).knowledge?.learned || []).map((item) => [String(item.caseId), item]),
475
497
  );
476
498
  const learned = [];
477
499
  const errors = [];
478
500
  const pageRecords = new Map();
479
- for (const run of runs) {
501
+ const learnTotal = runs.length;
502
+ let learnWrites = 1;
503
+ let learnAt = Date.now();
504
+ const writeLearnProgress = async (done, force = false) => {
505
+ const now = Date.now();
506
+ if (!force && (learnWrites >= 20 || now - learnAt < 500)) return;
507
+ learnWrites += 1;
508
+ learnAt = now;
509
+ await patchStage(config, batchId, 'distill', {
510
+ status: 'running', phase: 'learn', done, total: learnTotal, startedAt, error: null,
511
+ });
512
+ };
513
+ for (let index = 0; index < runs.length; index += 1) {
514
+ // 本地学习是同步文件操作,定期让出事件循环,Host 才能响应进度轮询。
515
+ if (index > 0 && index % 25 === 0) await yieldEventLoop();
516
+ const run = runs[index];
480
517
  const runCorrections = Array.isArray(run.corrections) && run.corrections.length
481
518
  ? run.corrections
482
519
  : detectSelfCorrections(run.steps);
@@ -501,6 +538,7 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
501
538
  };
502
539
  if (!run.runDir) {
503
540
  learned.push(mergeLearnedItem(item, previousByCase.get(String(item.caseId))));
541
+ await writeLearnProgress(index + 1, index + 1 === runs.length);
504
542
  continue;
505
543
  }
506
544
  try {
@@ -545,7 +583,11 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
545
583
  if (logger?.warn) logger.warn('知识沉淀失败 ' + run.caseId + ':' + item.error);
546
584
  }
547
585
  learned.push(mergeLearnedItem(item, previousByCase.get(String(item.caseId))));
586
+ await writeLearnProgress(index + 1, index + 1 === runs.length);
548
587
  }
588
+ await patchStage(config, batchId, 'distill', {
589
+ status: 'running', phase: 'process', done: 0, total: 1, startedAt, error: null,
590
+ });
549
591
  const skipCaseIds = staleCaseIds(config, batchId, runs);
550
592
  let processes;
551
593
  try {
@@ -555,6 +597,9 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
555
597
  errors.push({ caseId: '', message: '流程知识合并失败:' + String(error.message || error) });
556
598
  if (logger?.warn) logger.warn('流程知识合并失败:' + String(error.message || error));
557
599
  }
600
+ await patchStage(config, batchId, 'distill', {
601
+ status: 'running', phase: 'process', done: 1, total: 1, startedAt, error: null,
602
+ });
558
603
  const processByCase = new Map((processes.items || []).map((item) => [String(item.caseId), item]));
559
604
  for (const item of learned) {
560
605
  item.process = processByCase.get(String(item.caseId)) || null;
@@ -566,12 +611,18 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
566
611
  } catch {
567
612
  /* 本地知识不可用时只靠本轮观察 */
568
613
  }
614
+ await patchStage(config, batchId, 'distill', {
615
+ status: 'running', phase: 'episodes', done: 0, total: 1, startedAt, error: null,
616
+ });
569
617
  const centralEpisodes = buildBatchCentralEpisodes(batchId, runs, learned, {
570
618
  pageRecords,
571
619
  processRecords: processes.records || new Map(),
572
620
  knownPages,
573
621
  skipCaseIds,
574
622
  });
623
+ await patchStage(config, batchId, 'distill', {
624
+ status: 'running', phase: 'episodes', done: 1, total: 1, startedAt, error: null,
625
+ });
575
626
  const centralBase = centralConfig(config);
576
627
  let central = {
577
628
  enabled: centralBase.enabled,
@@ -584,12 +635,21 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
584
635
  failed: 0,
585
636
  results: [],
586
637
  errors: [],
638
+ mode: null,
587
639
  at: nowIso(),
588
640
  };
589
641
  try {
590
642
  if (centralBase.enabled) {
591
643
  if (centralEpisodes.length) {
592
- const report = await centralIngest(config, { episodes: centralEpisodes });
644
+ const report = await centralIngest(config, {
645
+ episodes: centralEpisodes,
646
+ fast: true,
647
+ onProgress: async ({ done, total, mode }) => {
648
+ await patchStage(config, batchId, 'distill', {
649
+ status: 'running', phase: 'central', done, total, startedAt, error: null, mode,
650
+ });
651
+ },
652
+ });
593
653
  central = {
594
654
  ...central,
595
655
  ...report,
@@ -625,19 +685,46 @@ export async function commitBatchKnowledge(config, batchId, { logger = null } =
625
685
  knowledge: snapshot.summary,
626
686
  central,
627
687
  };
688
+ await patchStage(config, batchId, 'distill', {
689
+ status: 'running', phase: 'finalize', done: 0, total: 1, startedAt, error: null,
690
+ });
628
691
  writeBatchText(config, batchId, 'knowledge.json', JSON.stringify(summary, null, 2) + '\n');
629
692
  await patchBatch(config, batchId, { knowledge: summary });
693
+ await patchStage(config, batchId, 'distill', {
694
+ status: 'running', phase: 'finalize', done: 1, total: 1, startedAt, error: null,
695
+ });
630
696
  await patchStage(config, batchId, 'distill', {
631
697
  status: 'done',
698
+ phase: 'done',
699
+ done: 1,
700
+ total: 1,
632
701
  at: summary.at,
633
702
  pages: summary.totals.pages,
634
703
  actions: summary.totals.actions,
635
704
  processes: processes.added + processes.merged,
636
705
  central: central.enabled ? central.ingested : 0,
637
706
  errors: errors.length,
707
+ mode: central.mode || null,
638
708
  });
639
709
  return summary;
710
+ } catch (error) {
711
+ await patchStage(config, batchId, 'distill', {
712
+ status: 'failed',
713
+ phase: 'failed',
714
+ error: String(error.message || error),
715
+ }).catch(() => {});
716
+ throw error;
640
717
  } finally {
641
- lock.release();
718
+ if (lock) lock.release();
642
719
  }
643
720
  }
721
+
722
+ export function commitBatchKnowledge(config, batchId, options = {}) {
723
+ const key = distillJobKey(config, batchId);
724
+ const promise = runBatchKnowledgeDistill(config, batchId, options);
725
+ distillJobs.set(key, promise);
726
+ promise.catch(() => {}).finally(() => {
727
+ if (distillJobs.get(key) === promise) distillJobs.delete(key);
728
+ });
729
+ return promise;
730
+ }