dsh-uitest 2.3.0 → 2.4.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.
Files changed (50) hide show
  1. package/README.md +76 -11
  2. package/bin/uitest.mjs +189 -11
  3. package/client.js +222 -25
  4. package/host/agent-bridge.mjs +9 -2
  5. package/host/agent-test.mjs +1 -1
  6. package/host/context-budget.mjs +1 -1
  7. package/index.js +14 -2
  8. package/lib/agent-session.mjs +81 -3
  9. package/lib/agent-tasks.mjs +212 -0
  10. package/lib/batch.mjs +204 -13
  11. package/lib/browser-ab.mjs +21 -6
  12. package/lib/browser.mjs +5 -5
  13. package/lib/config.mjs +1 -0
  14. package/lib/convert.mjs +178 -40
  15. package/lib/doc-structure.mjs +316 -0
  16. package/lib/flow.mjs +49 -14
  17. package/lib/knowledge-central-episodes.mjs +120 -0
  18. package/lib/knowledge-central-import.mjs +16 -1
  19. package/lib/knowledge-central.mjs +176 -25
  20. package/lib/knowledge-clean.mjs +749 -0
  21. package/lib/knowledge-consolidate.mjs +1271 -0
  22. package/lib/knowledge-coverage.mjs +150 -0
  23. package/lib/knowledge-docs.mjs +3 -3
  24. package/lib/knowledge-effect.mjs +148 -0
  25. package/lib/knowledge-facts.mjs +1008 -0
  26. package/lib/knowledge-maintain.mjs +185 -0
  27. package/lib/knowledge-permission.mjs +447 -0
  28. package/lib/knowledge-query.mjs +304 -26
  29. package/lib/knowledge-store.mjs +169 -14
  30. package/lib/knowledge-summarize.mjs +332 -0
  31. package/lib/knowledge.mjs +944 -47
  32. package/lib/learn-run.mjs +157 -51
  33. package/lib/run-learn.mjs +34 -0
  34. package/lib/run-observe.mjs +95 -27
  35. package/lib/run-stats.mjs +71 -0
  36. package/package.json +12 -2
  37. package/scripts/knowledge-central-purge.mjs +248 -0
  38. package/scripts/knowledge-central-sync.mjs +102 -20
  39. package/scripts/knowledge-consolidate.mjs +158 -0
  40. package/scripts/knowledge-coverage.mjs +94 -0
  41. package/scripts/knowledge-effect.mjs +82 -0
  42. package/scripts/knowledge-permission-probe.mjs +196 -0
  43. package/scripts/knowledge-permission-report.mjs +140 -0
  44. package/scripts/knowledge-report.mjs +492 -0
  45. package/scripts/knowledge-summarize.mjs +200 -0
  46. package/skills/uitest/SKILL.md +4 -2
  47. package/skills/uitest/references/convert-knowledge.md +66 -13
  48. package/studio/host.mjs +143 -6
  49. package/studio/knowledge.mjs +279 -42
  50. package/studio/snapshot.mjs +6 -1
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,85 @@ 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: 'maintain', label: '知识整理与同步' },
561
+ { id: 'finalize', label: '写入批次知识' },
562
+ ];
563
+ const DISTILL_PHASE_LABELS = {
564
+ starting: '正在启动沉淀',
565
+ learn: '页面学习',
566
+ process: '流程知识合并',
567
+ episodes: '整理中心知识',
568
+ central: '写入中心知识库',
569
+ maintain: '知识整理与同步',
570
+ finalize: '写入批次知识',
571
+ };
572
+
573
+ function distillSteps(stage) {
574
+ const phase = String(stage?.phase || '');
575
+ const activeIndex = phase === 'done'
576
+ ? DISTILL_PHASES.length
577
+ : phase === 'starting'
578
+ ? 0
579
+ : DISTILL_PHASES.findIndex((item) => item.id === phase);
580
+ return DISTILL_PHASES.map((item, index) => ({
581
+ label: item.label,
582
+ status: phase === 'done' || index < activeIndex ? 'done' : index === activeIndex ? 'active' : '',
583
+ }));
584
+ }
585
+
586
+ function distillPhaseText(stage) {
587
+ if (!stage) return '';
588
+ if (stage.status === 'failed') return '沉淀失败,可重新沉淀。';
589
+ if (stage.status === 'done') {
590
+ return stage.maintenance === 'failed'
591
+ ? '沉淀完成,但知识维护未全部完成;详见批次知识记录。'
592
+ : '沉淀完成。';
593
+ }
594
+ const phase = String(stage.phase || 'starting');
595
+ const label = DISTILL_PHASE_LABELS[phase] || '正在沉淀';
596
+ const total = Number(stage.total) || 0;
597
+ const done = Number(stage.done) || 0;
598
+ const count = total > 0 ? ' · ' + done + ' / ' + total : '';
599
+ const mode = phase === 'central'
600
+ ? stage.mode === 'fast'
601
+ ? ' · 只写原始 Episode,实体抽取由中心服务后台继续'
602
+ : stage.mode === 'classic'
603
+ ? ' · 正在同步写入并等待中心服务抽取'
604
+ : ''
605
+ : '';
606
+ return label + count + mode;
607
+ }
608
+
609
+ function maintenanceText(knowledge) {
610
+ const maintenance = knowledge?.maintenance;
611
+ if (!maintenance) return knowledge?.maintenanceError ? '未全部完成' : '未启用';
612
+ if (!maintenance.ok) return '未全部完成';
613
+ const stages = maintenance.stages || {};
614
+ const parts = [];
615
+ if (stages.consolidate && !stages.consolidate.skipped) {
616
+ parts.push('整理 '
617
+ + (stages.consolidate.stats?.pages?.merged || 0) + ' 合并 / '
618
+ + (stages.consolidate.stats?.pages?.archived || 0) + ' 归档 / '
619
+ + (stages.consolidate.stats?.learnings?.duplicates || 0) + ' 去重');
620
+ }
621
+ if (stages.summarize && !stages.summarize.skipped) parts.push('摘要 ' + (stages.summarize.applied || 0) + ' 条');
622
+ if (stages.sync && !stages.sync.skipped) parts.push('同步 知识 ' + (stages.sync.knowledgePending || 0) + ' / 证据 ' + (stages.sync.evidencePending || 0));
623
+ return parts.join(',') || '已完成';
624
+ }
625
+
550
626
  function Field(props) {
551
627
  return h('label', { className: 'studio-field' },
552
628
  h('span', { className: 'studio-field-label' }, props.label),
@@ -3902,8 +3978,11 @@ window.__ModuleLoader__.load({
3902
3978
  const [deleteOpen, setDeleteOpen] = useState(false);
3903
3979
  const [deleting, setDeleting] = useState(false);
3904
3980
  const [deleteError, setDeleteError] = useState('');
3905
- const [distilling, setDistilling] = useState(false);
3981
+ const [startingDistill, setStartingDistill] = useState(false);
3906
3982
  const [distillError, setDistillError] = useState('');
3983
+ const [liveDistill, setLiveDistill] = useState(null);
3984
+ const [distillPolling, setDistillPolling] = useState(false);
3985
+ const [distillInterrupted, setDistillInterrupted] = useState(false);
3907
3986
  const [writebackOpen, setWritebackOpen] = useState(false);
3908
3987
  const [exportOpen, setExportOpen] = useState(false);
3909
3988
  const [liveFocus, setLiveFocus] = useState(null);
@@ -3914,6 +3993,50 @@ window.__ModuleLoader__.load({
3914
3993
  const [selectedRunIds, setSelectedRunIds] = useState([]);
3915
3994
  const [bulkBusy, setBulkBusy] = useState('');
3916
3995
  const [resuming, setResuming] = useState(false);
3996
+ useEffect(() => {
3997
+ if (!distillPolling) return undefined;
3998
+ let cancelled = false;
3999
+ let timer = null;
4000
+ const tick = async () => {
4001
+ try {
4002
+ const payload = await api('/batch/distill/status', {
4003
+ project: props.project,
4004
+ query: { id: batch.id },
4005
+ });
4006
+ const next = payload?.distill;
4007
+ if (cancelled) return;
4008
+ if (!next) {
4009
+ timer = setTimeout(tick, POLL_DISTILL);
4010
+ return;
4011
+ }
4012
+ setLiveDistill(next);
4013
+ if (String(next.status) === 'done') {
4014
+ const fresh = await refreshNow();
4015
+ if (cancelled) return;
4016
+ setLiveDistill(fresh ? null : next);
4017
+ setDistillPolling(false);
4018
+ setDistillInterrupted(false);
4019
+ if (props.onDistilled) props.onDistilled();
4020
+ return;
4021
+ }
4022
+ if (String(next.status) === 'failed') {
4023
+ setDistillPolling(false);
4024
+ setDistillInterrupted(false);
4025
+ return;
4026
+ }
4027
+ if (next.active !== true) {
4028
+ setDistillPolling(false);
4029
+ if (String(next.status) === 'running') setDistillInterrupted(true);
4030
+ return;
4031
+ }
4032
+ } catch {
4033
+ /* 轮询失败时保留当前进度,下一轮重试 */
4034
+ }
4035
+ if (!cancelled) timer = setTimeout(tick, POLL_DISTILL);
4036
+ };
4037
+ timer = setTimeout(tick, POLL_DISTILL);
4038
+ return () => { cancelled = true; if (timer) clearTimeout(timer); };
4039
+ }, [distillPolling, batch.id, props.project, refreshNow]);
3917
4040
  const progress = batchProgress(batch);
3918
4041
  const rawCases = asArray(batch.cases);
3919
4042
  const cases = useMemo(() => sortRunsForDisplay(rawCases), [rawCases]);
@@ -3961,9 +4084,18 @@ window.__ModuleLoader__.load({
3961
4084
  };
3962
4085
  const stoppable = ['running', 'preparing', 'queued'].includes(String(batch.status || ''));
3963
4086
  const deletable = !['running', 'queued', 'preparing'].includes(String(batch.status || ''));
3964
- const distillStage = String(batch.stages?.distill?.status || '');
4087
+ const distillStage = liveDistill || batch.stages?.distill || null;
4088
+ const distillStageStatus = String(distillStage?.status || '');
4089
+ const distillBusy = startingDistill || distillPolling;
4090
+ const showDistillProgress = distillBusy || distillStageStatus === 'running';
4091
+ const stageDistillError = distillStageStatus === 'failed' ? String(distillStage?.error || '') : '';
4092
+ const distillTotal = Number(distillStage?.total) || 0;
4093
+ const distillPercent = distillTotal > 0
4094
+ ? Math.round(((Number(distillStage?.done) || 0) / distillTotal) * 100)
4095
+ : 0;
4096
+ const distillIndeterminate = distillTotal <= 0;
3965
4097
  const needsDistill = !['running', 'queued', 'preparing'].includes(String(batch.status || ''))
3966
- && (!batch.knowledge || distillStage === 'running' || distillStage === 'failed');
4098
+ && (distillBusy || !batch.knowledge || distillStageStatus === 'running' || distillStageStatus === 'failed');
3967
4099
  const caseRun = cases.find((run) => String(run.caseId) === String(caseId)) || null;
3968
4100
  const runAction = async (kind, run) => {
3969
4101
  const handler = kind === 'stop' ? props.onStopCase : kind === 'prioritize' ? props.onPrioritizeCase : props.onRequeueCase;
@@ -4013,6 +4145,10 @@ window.__ModuleLoader__.load({
4013
4145
  setDeleteOpen(false);
4014
4146
  setDeleteError('');
4015
4147
  setDistillError('');
4148
+ setStartingDistill(false);
4149
+ setLiveDistill(null);
4150
+ setDistillInterrupted(false);
4151
+ setDistillPolling(batch.distillActive === true || String(batch.stages?.distill?.status) === 'running');
4016
4152
  setLogOpen(false);
4017
4153
  setArchiveOpen(false);
4018
4154
  setRunFilter('all');
@@ -4023,16 +4159,24 @@ window.__ModuleLoader__.load({
4023
4159
  setBulkBusy('');
4024
4160
  }, [batch.id]);
4025
4161
  const distillBatchNow = async () => {
4026
- setDistilling(true);
4162
+ setStartingDistill(true);
4027
4163
  setDistillError('');
4164
+ setDistillInterrupted(false);
4165
+ setLiveDistill({ status: 'running', phase: 'starting', startedAt: new Date().toISOString() });
4166
+ setDistillPolling(true);
4028
4167
  try {
4029
- const payload = await api('/batch/distill', { method: 'POST', project: props.project, body: { id: batch.id }, timeoutMs: 600000 });
4168
+ const payload = await api('/batch/distill', { method: 'POST', project: props.project, body: { id: batch.id } });
4030
4169
  if (payload?.batch) applyBatch(payload.batch);
4031
- if (props.onDistilled) props.onDistilled();
4170
+ if (payload?.started !== true && payload?.alreadyRunning !== true) {
4171
+ setLiveDistill(null);
4172
+ setDistillPolling(false);
4173
+ }
4032
4174
  } catch (err) {
4033
4175
  setDistillError(err.message);
4176
+ setLiveDistill(null);
4177
+ setDistillPolling(false);
4034
4178
  } finally {
4035
- setDistilling(false);
4179
+ setStartingDistill(false);
4036
4180
  }
4037
4181
  };
4038
4182
  const deleteBatchNow = async () => {
@@ -4069,10 +4213,10 @@ window.__ModuleLoader__.load({
4069
4213
  needsDistill ? h('button', {
4070
4214
  key: 'distill',
4071
4215
  className: 'studio-btn studio-btn-primary',
4072
- disabled: distilling,
4216
+ disabled: distillBusy,
4073
4217
  title: '重新学习本批页面与流程并写入中心知识库',
4074
4218
  onClick: distillBatchNow,
4075
- }, distilling ? h(Spinner) : h(Icon, { name: 'knowledge', size: 13 }), distilling ? '沉淀中…' : '重新沉淀') : null,
4219
+ }, distillBusy ? h(Spinner) : h(Icon, { name: 'knowledge', size: 13 }), distillBusy ? '沉淀中…' : '重新沉淀') : null,
4076
4220
  h(MenuButton, { key: 'more', label: '更多', icon: 'more' }, [
4077
4221
  h('button', { key: 'export', className: 'studio-btn', disabled: !cases.length, title: cases.length ? '导出本批次测试结果 xlsx' : '批次还没有用例结果', onClick: () => setExportOpen(true) }, h(Icon, { name: 'file', size: 13 }), '导出结果'),
4078
4222
  h('button', { key: 'log', className: 'studio-btn', onClick: () => setLogOpen(true) }, h(Icon, { name: 'terminal', size: 13 }), '执行日志'),
@@ -4082,11 +4226,17 @@ window.__ModuleLoader__.load({
4082
4226
  ],
4083
4227
  }),
4084
4228
 
4085
- distilling ? h('div', { style: { marginTop: 12 } }, h(OperationProgress, {
4086
- label: '正在重新沉淀本批知识',
4087
- detail: '重新学习本批页面与流程,合并后写入中心知识库。完成后列表会自动刷新。',
4088
- steps: [{ label: '页面学习', status: 'active' }, { label: '流程知识合并' }, { label: '写入中心知识库' }],
4229
+ showDistillProgress ? h('div', { style: { marginTop: 12 } }, h(OperationProgress, {
4230
+ label: distillInterrupted ? '上一次沉淀未完成' : '正在重新沉淀本批知识',
4231
+ detail: distillPhaseText(distillStage),
4232
+ steps: distillSteps(distillStage),
4233
+ startedAt: distillStage?.startedAt,
4234
+ percent: distillPercent,
4235
+ indeterminate: distillIndeterminate,
4236
+ active: !distillInterrupted,
4089
4237
  })) : null,
4238
+ distillInterrupted ? h('div', { className: 'studio-note tone-warn', style: { marginTop: 10 } }, '上一次沉淀可能已中断,或在另一个进程中运行;可以直接重新沉淀。') : null,
4239
+ stageDistillError ? h('div', { className: 'studio-note tone-danger', style: { marginTop: 10 } }, '重新沉淀失败:' + stageDistillError) : null,
4090
4240
  distillError ? h('div', { className: 'studio-note tone-danger', style: { marginTop: 10 } }, '重新沉淀失败:' + distillError) : null,
4091
4241
 
4092
4242
  h('div', { className: 'studio-meta-strip' },
@@ -4246,7 +4396,9 @@ window.__ModuleLoader__.load({
4246
4396
  h('span', { className: 'studio-kv-key' }, '自我纠错'),
4247
4397
  h('span', { className: 'studio-kv-val' }, (batch.knowledge.totals?.corrections || 0) + ' 条经验'),
4248
4398
  h('span', { className: 'studio-kv-key' }, '中心知识库'),
4249
- h('span', { className: 'studio-kv-val' }, batch.knowledge.central?.enabled ? ('写入 ' + (batch.knowledge.central.ingested || 0) + ' / 跳过 ' + (batch.knowledge.central.skipped || 0) + ' / 失败 ' + (batch.knowledge.central.failed || 0)) : '未启用')
4399
+ h('span', { className: 'studio-kv-val' }, batch.knowledge.central?.enabled ? ('写入 ' + (batch.knowledge.central.ingested || 0) + ' / 跳过 ' + (batch.knowledge.central.skipped || 0) + ' / 失败 ' + (batch.knowledge.central.failed || 0)) : '未启用'),
4400
+ h('span', { className: 'studio-kv-key' }, '知识维护'),
4401
+ h('span', { className: 'studio-kv-val' }, maintenanceText(batch.knowledge))
4250
4402
  ),
4251
4403
  asArray(batch.knowledge.learned).length ? h('div', { className: 'studio-nl-block' },
4252
4404
  h('div', { className: 'studio-nl-label' }, '本批沉淀明细'),
@@ -4360,6 +4512,7 @@ window.__ModuleLoader__.load({
4360
4512
  finished ? h('span', { key: 'failed', className: 'studio-badge tone-danger' }, finished + ' 个批次有失败用例') : null,
4361
4513
  ],
4362
4514
  actions: [
4515
+ snapshot.agentTasks?.pending ? h('button', { key: 'handoff', className: 'studio-btn studio-btn-sm', onClick: props.onAdoptHandoff, disabled: Boolean(activeBatch) }, h(Icon, { name: 'spark', size: 14 }), '执行 Agent 交接(' + snapshot.agentTasks.pending + ' 条)') : null,
4363
4516
  h('button', { key: 'new', className: 'studio-btn studio-btn-primary', onClick: () => props.onNewBatch([]) }, h(Icon, { name: 'plus', size: 14 }), '新建批次'),
4364
4517
  ],
4365
4518
  }),
@@ -4523,11 +4676,11 @@ window.__ModuleLoader__.load({
4523
4676
  const [state, setState] = useState({ loading: true, item: null, error: '' });
4524
4677
  useEffect(() => {
4525
4678
  let cancelled = false;
4526
- api('/knowledge/central/episode', { project: props.project, query: { uuid: props.uuid } })
4679
+ api('/knowledge/central/episode', { project: props.project, query: { uuid: props.uuid, groupId: props.groupId || '' } })
4527
4680
  .then((payload) => { if (!cancelled) setState({ loading: false, item: payload.item || null, error: '' }); })
4528
4681
  .catch((err) => { if (!cancelled) setState({ loading: false, item: null, error: err.message }); });
4529
4682
  return () => { cancelled = true; };
4530
- }, [props.uuid, props.project]);
4683
+ }, [props.uuid, props.project, props.groupId]);
4531
4684
  const item = state.item || {};
4532
4685
  return h(Drawer, {
4533
4686
  title: item.name || props.name || '中心知识条目',
@@ -4884,6 +5037,7 @@ window.__ModuleLoader__.load({
4884
5037
  const nodeCount = asArray(central.nodes).reduce((sum, item) => sum + (Number(item.count) || 0), 0);
4885
5038
  const edgeCount = asArray(central.edges).reduce((sum, item) => sum + (Number(item.count) || 0), 0);
4886
5039
  const [kind, setKind] = useState('episodes');
5040
+ const [scope, setScope] = useState('knowledge');
4887
5041
  const [category, setCategory] = useState('');
4888
5042
  const [search, setSearch] = useState('');
4889
5043
  const [query, setQuery] = useState('');
@@ -4919,6 +5073,8 @@ window.__ModuleLoader__.load({
4919
5073
  const pipelineRevisionRef = useRef(-1);
4920
5074
  const [importMode, setImportMode] = useState('');
4921
5075
  const seqRef = useRef(0);
5076
+ const evidenceGroupId = String(central.evidenceGroupId || '');
5077
+ const activeGroupId = kind === 'episodes' && scope === 'evidence' ? evidenceGroupId : '';
4922
5078
 
4923
5079
  useEffect(() => {
4924
5080
  const timer = setTimeout(() => setQuery(search.trim()), 300);
@@ -5056,7 +5212,7 @@ window.__ModuleLoader__.load({
5056
5212
  seqRef.current = seq;
5057
5213
  setLoading(true);
5058
5214
  setListError('');
5059
- api('/knowledge/central/browse', { project: props.project, query: { kind, q: query, category, limit: 20, offset: 0 } })
5215
+ api('/knowledge/central/browse', { project: props.project, query: { kind, q: query, category, limit: 20, offset: 0, groupId: activeGroupId } })
5060
5216
  .then((payload) => {
5061
5217
  if (seqRef.current !== seq) return;
5062
5218
  setItems(asArray(payload.items));
@@ -5071,7 +5227,7 @@ window.__ModuleLoader__.load({
5071
5227
  setLoading(false);
5072
5228
  });
5073
5229
  return undefined;
5074
- }, [kind, query, category, reload, central.enabled, props.project]);
5230
+ }, [kind, query, category, reload, central.enabled, props.project, activeGroupId, scope]);
5075
5231
 
5076
5232
  useEffect(() => {
5077
5233
  if (!central.enabled || !query) {
@@ -5081,12 +5237,12 @@ window.__ModuleLoader__.load({
5081
5237
  }
5082
5238
  let cancelled = false;
5083
5239
  setSemanticLoading(true);
5084
- api('/knowledge/central/search', { project: props.project, query: { q: query, limit: 8 } })
5240
+ api('/knowledge/central/search', { project: props.project, query: { q: query, limit: 8, groupId: activeGroupId } })
5085
5241
  .then((payload) => { if (!cancelled) setSemantic(asArray(payload.results)); })
5086
5242
  .catch(() => { if (!cancelled) setSemantic([]); })
5087
5243
  .finally(() => { if (!cancelled) setSemanticLoading(false); });
5088
5244
  return () => { cancelled = true; };
5089
- }, [query, central.enabled, props.project]);
5245
+ }, [query, central.enabled, props.project, activeGroupId, scope]);
5090
5246
 
5091
5247
  const loadMore = async () => {
5092
5248
  if (loadingMore || !hasMore) return;
@@ -5095,7 +5251,7 @@ window.__ModuleLoader__.load({
5095
5251
  try {
5096
5252
  const payload = await api('/knowledge/central/browse', {
5097
5253
  project: props.project,
5098
- query: { kind, q: query, category, limit: 20, offset: items.length },
5254
+ query: { kind, q: query, category, limit: 20, offset: items.length, groupId: activeGroupId },
5099
5255
  });
5100
5256
  setItems((current) => [...current, ...asArray(payload.items)]);
5101
5257
  setHasMore(payload.hasMore === true);
@@ -5201,7 +5357,20 @@ window.__ModuleLoader__.load({
5201
5357
  active: kind,
5202
5358
  onChange: (value) => { setKind(value); setExtractError(''); },
5203
5359
  }),
5204
- kind === 'episodes' ? h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', margin: '0 0 10px' } },
5360
+ kind === 'episodes' ? h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', margin: '0 0 8px', alignItems: 'center' } },
5361
+ h('span', { className: 'studio-row-sub', style: { marginRight: 2 } }, '范围'),
5362
+ h('button', {
5363
+ className: 'studio-btn studio-btn-sm' + (scope === 'knowledge' ? ' studio-btn-primary' : ''),
5364
+ onClick: () => { setScope('knowledge'); setCategory(''); },
5365
+ }, '知识组'),
5366
+ h('button', {
5367
+ className: 'studio-btn studio-btn-sm' + (scope === 'evidence' ? ' studio-btn-primary' : ''),
5368
+ disabled: !evidenceGroupId,
5369
+ onClick: () => { setScope('evidence'); setCategory(''); },
5370
+ }, '证据组'),
5371
+ h('span', { className: 'studio-row-sub', style: { marginLeft: 4 } }, activeGroupId || central.groupId || '')
5372
+ ) : null,
5373
+ kind === 'episodes' && scope === 'knowledge' ? h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', margin: '0 0 10px' } },
5205
5374
  KNOWLEDGE_CATEGORY_TABS.map((item) => h('button', {
5206
5375
  key: item.id || 'all',
5207
5376
  className: 'studio-btn studio-btn-sm' + (category === item.id ? ' studio-btn-primary' : ''),
@@ -5355,6 +5524,7 @@ window.__ModuleLoader__.load({
5355
5524
  project: props.project,
5356
5525
  uuid: episode.uuid,
5357
5526
  name: episode.name,
5527
+ groupId: activeGroupId,
5358
5528
  onClose: () => setEpisode(null),
5359
5529
  }) : null,
5360
5530
  importMode ? h(CentralImportDialog, {
@@ -5863,6 +6033,7 @@ window.__ModuleLoader__.load({
5863
6033
  enabled: centralConfig.enabled !== false,
5864
6034
  url: centralConfig.url || '',
5865
6035
  groupId: centralConfig.groupId || 'oms-v2-test',
6036
+ evidenceGroupId: centralConfig.evidenceGroupId || '',
5866
6037
  timeoutMs: centralConfig.timeoutMs || 300000,
5867
6038
  batchSize: centralConfig.batchSize || 2,
5868
6039
  });
@@ -5875,6 +6046,16 @@ window.__ModuleLoader__.load({
5875
6046
  setCentralResult(null);
5876
6047
  setCentralError('');
5877
6048
  };
6049
+ const updateCentralGroup = (value) => {
6050
+ setCentralForm((current) => {
6051
+ const derived = (current.groupId || '') + '-evidence';
6052
+ const evidence = String(current.evidenceGroupId || '');
6053
+ const nextEvidence = !evidence || evidence === derived ? (value ? value + '-evidence' : '') : evidence;
6054
+ return { ...current, groupId: value, evidenceGroupId: nextEvidence };
6055
+ });
6056
+ setCentralResult(null);
6057
+ setCentralError('');
6058
+ };
5878
6059
  const save = async () => {
5879
6060
  setSaving(true);
5880
6061
  setError('');
@@ -6017,7 +6198,10 @@ window.__ModuleLoader__.load({
6017
6198
  ),
6018
6199
  h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12 } },
6019
6200
  h(Field, { label: 'Group ID', hint: '项目隔离,例如 oms-v2-test' },
6020
- h('input', { className: 'studio-input', value: centralForm.groupId, onChange: (e) => updateCentral('groupId', e.target.value) })
6201
+ h('input', { className: 'studio-input', value: centralForm.groupId, onChange: (e) => updateCentralGroup(e.target.value) })
6202
+ ),
6203
+ h(Field, { label: '证据组 ID', hint: '留空自动使用 <Group ID>-evidence' },
6204
+ h('input', { className: 'studio-input', value: centralForm.evidenceGroupId, placeholder: '留空自动派生', onChange: (e) => updateCentral('evidenceGroupId', e.target.value) })
6021
6205
  ),
6022
6206
  h(Field, { label: '同步批大小', hint: '每请求 Episode 数' },
6023
6207
  h('input', { className: 'studio-input', type: 'number', min: 1, max: 20, value: centralForm.batchSize, onChange: (e) => updateCentral('batchSize', Number(e.target.value)) })
@@ -6954,6 +7138,18 @@ window.__ModuleLoader__.load({
6954
7138
  showToast({ kind: 'success', text: '账号导入:新增 ' + (payload.added || 0) + ' / 更新 ' + (payload.updated || 0) });
6955
7139
  };
6956
7140
 
7141
+ const onAdoptHandoff = async () => {
7142
+ try {
7143
+ const payload = await api('/agent-tasks/adopt', { method: 'POST', project: studio.snapshot.project, body: {} });
7144
+ showToast({ kind: 'success', text: '已认领 ' + (payload.handoff?.tasks || 0) + ' 条 Agent 交接用例' });
7145
+ if (payload.batchId) setSelectedBatchId(payload.batchId);
7146
+ setView('batches');
7147
+ studio.reload();
7148
+ } catch (error) {
7149
+ showToast({ kind: 'error', text: error.message });
7150
+ }
7151
+ };
7152
+
6957
7153
  const snapshot = studio.snapshot;
6958
7154
  const content = () => {
6959
7155
  if (!snapshot && studio.loading) {
@@ -7016,6 +7212,7 @@ window.__ModuleLoader__.load({
7016
7212
  selectedBatchId,
7017
7213
  onSelectBatch: setSelectedBatchId,
7018
7214
  onNewBatch: openNewBatch,
7215
+ onAdoptHandoff,
7019
7216
  onStopBatch,
7020
7217
  onResumeBatch,
7021
7218
  onWritebackDone,
@@ -212,7 +212,7 @@ export function createJobFiles(projectDir, { jobId, request, context, promptText
212
212
  { id: 's2', action: 'comment', desc: '按实际观察补全步骤', needsReview: true },
213
213
  ],
214
214
  },
215
- knowledge: { pages: [], recipes: [], processes: [], business: [] },
215
+ knowledge: { pages: [], recipes: [], processes: [], business: [], system: { roles: [], permissions: [], glossary: [] }, documents: [] },
216
216
  explanation: '说明:参考了哪些知识/反馈/历史记录/页面观察,以及为什么这样拆分。',
217
217
  diagnostics: [{ level: 'info', code: 'AGENT_DRAFT', message: '子 Agent 初稿' }],
218
218
  });
@@ -463,9 +463,16 @@ export function applyAgentFlow({ projectDir, job, request, result, force = false
463
463
  export function writeKnowledgePatch(projectDir, jobId, knowledge) {
464
464
  if (!isRecord(knowledge)) return null;
465
465
  const patch = {};
466
- for (const key of ['pages', 'recipes', 'processes', 'business']) {
466
+ for (const key of ['pages', 'recipes', 'processes', 'business', 'documents']) {
467
467
  if (Array.isArray(knowledge[key]) && knowledge[key].length > 0) patch[key] = knowledge[key];
468
468
  }
469
+ if (isRecord(knowledge.system)) {
470
+ const system = {};
471
+ for (const key of ['roles', 'permissions', 'glossary']) {
472
+ if (Array.isArray(knowledge.system[key]) && knowledge.system[key].length > 0) system[key] = knowledge.system[key];
473
+ }
474
+ if (Object.keys(system).length > 0) patch.system = system;
475
+ }
469
476
  if (Object.keys(patch).length === 0) return null;
470
477
  const paths = jobPaths(projectDir, jobId);
471
478
  writeJson(paths.knowledgePatch, patch);
@@ -394,7 +394,7 @@ export function buildAgentTestPrompt({ project, jobDir, cliPath, request, contex
394
394
  ? '中心知识库未启用或不可用,以下是本地缓存。'
395
395
  : '';
396
396
  const knowledgeChecks = [
397
- ...guideCentral.slice(0, 6).map((item) => '中心知识:' + (item.fact || item.name || '')),
397
+ ...guideCentral.slice(0, 6).map((item) => (item.source === 'evidence' ? '中心证据:' : '中心知识:') + (item.fact || item.name || '')),
398
398
  ...guidePages.slice(0, 4).map((page) => '本地缓存·页面 ' + (page.title || page.urlName || page.id || '') + ':' + ((page.actions || []).slice(0, 3).map((action) => action.title || action.id).filter(Boolean).join(' / ') || '暂无已验证动作')),
399
399
  ...guideProcesses.slice(0, 4).map((process) => '本地缓存·流程 ' + (process.name || process.id || '') + ':' + ((process.steps || []).slice(0, 4).join(' → ') || '暂无步骤')),
400
400
  ...guideProcesses.flatMap((process) => (Array.isArray(process.corrections) ? process.corrections : []).slice(-3).map((correction) => '本地缓存·纠错:' + (correction.summary || correction))),
@@ -1535,7 +1535,7 @@ function buildPromptTemplate({ project = '', jobDir = '', cliPath = '', request
1535
1535
  '2. 用真实无头浏览器核实:`node <cli> open <urlName|URL> --project <project> --json`(可加 `--text`,只读);弹窗/交互如需观察,可用 `node <cli> do ...`;不得修改被测系统数据。',
1536
1536
  '3. 用户反馈优先:反馈 verdict=incorrect 的断言必须改写或降级为 comment 并保留说明;elementPosition 用于定位按钮/字段文本;反馈必须在 flow 的 comment/步骤或 generated.feedbackConsidered 中体现。',
1537
1537
  '4. 上次 run 失败的选择器/断言必须修正,并在 diagnostics 中说明依据。',
1538
- '5. 输出知识补丁:新页面(含 actions:id/title/keywords/steps)、新流程、新规则;source="agent",confidence 0.6–0.85;不要编造未观察到的 URL/选择器。',
1538
+ '5. 输出知识补丁:新页面(含 actions:id/title/keywords/steps)、新流程、新规则、系统角色/权限/术语、文档字段/状态/流转(documents[].fields/statuses/transitions);source="agent",confidence 0.6–0.85;不要编造未观察到的 URL/选择器,知识补丁不得含 TC 用例号或单据号(实例信息只写进 explanation/diagnostics)。',
1539
1539
  '6. 执行预算(硬性):整个作业 ≤6 分钟、浏览器 CLI 调用 ≤5 次;每次观察后更新 status.json(phase=observing,message 简述进展)。第 5 分钟必须开始写 result.json,第 6 分钟必须写完并置 status=done;无法确认的部分用 comment(needsReview=true)+ diagnostics 说明。',
1540
1540
  '7. 只写作业目录内的文件;完成后把 status.json 置为 {"status":"done","phase":"done","message":"...","updatedAt":"ISO","childId":"..."};异常置 status=error + message。',
1541
1541
  '8. 结果写入 result.json(必须);explanation 说明拆分依据与参考信息(用例/反馈/历史 run/页面观察)。',
package/index.js CHANGED
@@ -31,6 +31,7 @@ import { applyBatchWriteback, applyDocumentWriteback, previewBatchWriteback, pre
31
31
  import { registerTestApprovalAnswerer } from './host/agent-test.mjs';
32
32
  import {
33
33
  activeBatchFor,
34
+ adoptAgentTasks,
34
35
  attachStudioAgentServices,
35
36
  createStudioPanel,
36
37
  disposeStudioPanel,
@@ -352,15 +353,16 @@ function toolDefinitions(ctx, panel) {
352
353
  },
353
354
  {
354
355
  name: 'uitest_batch',
355
- description: 'Run the Test Studio batch pipeline. action=start creates a batch: it plans each case into flow (existing reusable flow) or agent (natural-language execution by a DSH subagent), resolves precondition data recipes, runs both lanes concurrently, archives evidence, and writes results back once after the batch. Returns a batchId immediately unless wait=true. action=status reads live progress, per-case results, evidence and logs. action=stop requests a graceful stop. action=writeback previews or applies the one-time document write-back. Use action=status to poll a running batch. Pass allowWrites=true only when the cases explicitly need to create business data.',
356
+ description: 'Run the Test Studio batch pipeline. action=start creates a batch: it plans each case into flow (existing reusable flow) or agent (natural-language execution by a DSH subagent), resolves precondition data recipes, runs both lanes concurrently, archives evidence, and writes results back once after the batch. action=handoff adopts the pending tasks in the CLI handoff file (agent-tasks.json) as an Agent-only batch and reconciles their conclusions when it ends. Returns a batchId immediately unless wait=true. action=status reads live progress, per-case results, evidence and logs. action=stop requests a graceful stop. action=writeback previews or applies the one-time document write-back. Use action=status to poll a running batch. Pass allowWrites=true only when the cases explicitly need to create business data.',
356
357
  parameters: {
357
358
  type: 'object',
358
359
  additionalProperties: false,
359
360
  required: ['action'],
360
361
  properties: {
361
- action: { type: 'string', enum: ['start', 'status', 'stop', 'writeback'], description: 'Batch operation.' },
362
+ action: { type: 'string', enum: ['start', 'handoff', 'status', 'stop', 'writeback'], description: 'Batch operation.' },
362
363
  project: { type: 'string', description: 'Test project directory. Defaults to the session cwd.' },
363
364
  batchId: { type: 'string', description: 'Required for status, stop and writeback.' },
365
+ manifestBatchId: { type: 'string', description: 'For action=handoff: the CLI handoff batch id. Defaults to the latest agent-tasks.json.' },
364
366
  caseIds: { type: 'array', items: { type: 'string' }, description: 'Case ids for action=start. Omit and pass all=true to use the full library.' },
365
367
  all: { type: 'boolean', description: 'Start with every case in the library.' },
366
368
  name: { type: 'string', description: 'Human-readable batch name.' },
@@ -378,6 +380,16 @@ function toolDefinitions(ctx, panel) {
378
380
  const input = asRecord(args);
379
381
  const { cwd } = projectContext(ctx, exec, input.project);
380
382
  const config = loadConfig(cwd);
383
+ if (input.action === 'handoff') {
384
+ return { ok: true, ...(await adoptAgentTasks({
385
+ ctx,
386
+ panel,
387
+ config,
388
+ batchId: input.manifestBatchId || '',
389
+ wait: input.wait === true,
390
+ writeBack: input.writeBack || 'batch',
391
+ })) };
392
+ }
381
393
  if (input.action === 'start') {
382
394
  const caseIds = Array.isArray(input.caseIds) ? input.caseIds.map(String) : [];
383
395
  if (!caseIds.length && input.all !== true) throw toolError('uitest_batch start requires caseIds or all=true');