dsh-uitest 2.2.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 +35 -10
- package/bin/studio.mjs +117 -17
- package/bin/uitest.mjs +3 -3
- package/client.js +1030 -192
- package/index.js +90 -5
- package/lib/backfill.mjs +37 -22
- package/lib/cases-import.mjs +67 -43
- package/lib/cases-md.mjs +5 -0
- package/lib/csv.mjs +207 -0
- package/lib/knowledge-central.mjs +29 -5
- package/lib/xlsx.mjs +2 -1
- package/package.json +1 -1
- package/skills/uitest/SKILL.md +9 -4
- package/studio/documents.mjs +86 -16
- package/studio/host.mjs +126 -17
- package/studio/import.mjs +115 -21
- package/studio/knowledge.mjs +93 -6
- package/studio/runner.mjs +55 -0
- package/studio/snapshot.mjs +23 -12
- package/studio/store.mjs +25 -1
- package/studio/writeback.mjs +85 -23
package/studio/knowledge.mjs
CHANGED
|
@@ -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
|
-
|
|
468
|
-
|
|
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
|
-
|
|
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, {
|
|
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
|
+
}
|
package/studio/runner.mjs
CHANGED
|
@@ -1350,6 +1350,61 @@ export async function requeueCase({ config, batchId, caseId, panel, planItem })
|
|
|
1350
1350
|
});
|
|
1351
1351
|
}
|
|
1352
1352
|
|
|
1353
|
+
/** 停止后的批次继续执行:只重排没有终态判定的用例,已判定结果保留。 */
|
|
1354
|
+
export async function resumeBatch({ config, batchId, panel }) {
|
|
1355
|
+
const now = nowIso();
|
|
1356
|
+
return withBatchLock(batchId, () => {
|
|
1357
|
+
const current = readBatch(config, batchId);
|
|
1358
|
+
if (['running', 'preparing', 'queued'].includes(String(current.status || '')) || panel?.studioAborts?.has(batchId)) {
|
|
1359
|
+
throw new UitestError('批次正在执行,不能继续执行', { code: 'BATCH_ACTIVE', detail: { batchId } });
|
|
1360
|
+
}
|
|
1361
|
+
if (current.status !== 'stopped') {
|
|
1362
|
+
throw new UitestError('只有已停止的批次可以继续执行', { code: 'BATCH_NOT_STOPPED', detail: { batchId, status: current.status } });
|
|
1363
|
+
}
|
|
1364
|
+
const runs = readCaseRuns(config, batchId);
|
|
1365
|
+
const byId = new Map(mergeBatchRuns(current, runs).map((run) => [String(run.caseId), run]));
|
|
1366
|
+
let queue = queueForBatch(current, runs);
|
|
1367
|
+
const resumedIds = [];
|
|
1368
|
+
for (const item of current.plan?.items || []) {
|
|
1369
|
+
if (item.mode !== 'flow' && item.mode !== 'agent') continue;
|
|
1370
|
+
const caseId = String(item.caseId);
|
|
1371
|
+
const entry = queue.entries[caseId];
|
|
1372
|
+
const run = byId.get(caseId);
|
|
1373
|
+
// 已判定的用例不重跑;停止时还没跑完的入口重新排队,保留历史结果。
|
|
1374
|
+
// 判定结果先落盘、队列项后置 done,崩溃或非活跃停止会留下 stopped 入口,不能只看 entry.state。
|
|
1375
|
+
if (run && ['passed', 'partial', 'failed', 'blocked'].includes(run.status)) continue;
|
|
1376
|
+
if (entry?.state === 'queued') {
|
|
1377
|
+
resumedIds.push(caseId);
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
if (entry?.state === 'running') queue = finishEntry(queue, caseId, 'stopped', now).queue;
|
|
1381
|
+
const next = enqueue(queue, caseId, now);
|
|
1382
|
+
queue = next.queue;
|
|
1383
|
+
if (next.added) resumedIds.push(caseId);
|
|
1384
|
+
}
|
|
1385
|
+
if (!resumedIds.length) {
|
|
1386
|
+
throw new UitestError('没有需要继续执行的用例', { code: 'NOTHING_TO_RESUME', detail: { batchId } });
|
|
1387
|
+
}
|
|
1388
|
+
const next = {
|
|
1389
|
+
...current,
|
|
1390
|
+
queue,
|
|
1391
|
+
status: 'queued',
|
|
1392
|
+
stage: 'execute',
|
|
1393
|
+
stages: {
|
|
1394
|
+
...(current.stages || {}),
|
|
1395
|
+
execute: { status: 'pending', at: null, startedAt: null, endedAt: null, error: null },
|
|
1396
|
+
},
|
|
1397
|
+
endedAt: null,
|
|
1398
|
+
stopRequested: false,
|
|
1399
|
+
error: null,
|
|
1400
|
+
updatedAt: now,
|
|
1401
|
+
};
|
|
1402
|
+
next.summary = summarizeCaseRuns(mergeBatchRuns(next, runs));
|
|
1403
|
+
saveBatch(config, next);
|
|
1404
|
+
return { batch: next, resumed: resumedIds.length };
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1353
1408
|
export async function requestCaseStopInBatch({ config, batchId, caseId, panel }) {
|
|
1354
1409
|
const id = String(caseId || '');
|
|
1355
1410
|
await withBatchLock(batchId, () => {
|
package/studio/snapshot.mjs
CHANGED
|
@@ -181,25 +181,33 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
181
181
|
};
|
|
182
182
|
});
|
|
183
183
|
const cases = enriched.slice(0, caseLimit);
|
|
184
|
-
|
|
184
|
+
// 文档视图与状态统计必须基于完整用例库计算,先切片会让文档看起来缺用例。
|
|
185
|
+
const docRegistry = documentRegistry(config);
|
|
186
|
+
const docRecords = docRegistry.docs;
|
|
187
|
+
const docIds = new Set(docRecords.map((doc) => doc.id));
|
|
188
|
+
const docs = docRecords.map((doc) => documentView(config, doc, enriched, {
|
|
189
|
+
deletedCaseIds: studio.deletedCaseIds || [],
|
|
190
|
+
}));
|
|
191
|
+
const statusCounts = { passed: 0, partial: 0, failed: 0, blocked: 0, queued: 0, running: 0, stopped: 0, untested: 0 };
|
|
192
|
+
for (const item of enriched) {
|
|
193
|
+
const status = String(item?.status || '');
|
|
194
|
+
const key = Object.hasOwn(statusCounts, status) ? status : 'untested';
|
|
195
|
+
statusCounts[key] += 1;
|
|
196
|
+
}
|
|
185
197
|
const counts = {
|
|
186
198
|
total: studio.cases.length,
|
|
187
199
|
flow: studio.cases.filter((item) => item.mode === 'flow').length,
|
|
188
200
|
agent: studio.cases.filter((item) => item.mode === 'agent').length,
|
|
189
201
|
manual: studio.cases.filter((item) => item.mode === 'manual').length,
|
|
190
|
-
|
|
191
|
-
failed: cases.filter((item) => item.status === 'failed').length,
|
|
192
|
-
blocked: cases.filter((item) => item.status === 'blocked').length,
|
|
193
|
-
untested: cases.filter((item) => item.status === 'untested').length,
|
|
194
|
-
running: cases.filter((item) => item.status === 'running').length,
|
|
202
|
+
...statusCounts,
|
|
195
203
|
feedback: feedbackByCase.size,
|
|
196
|
-
unassigned:
|
|
204
|
+
unassigned: enriched.filter((item) => !docIds.has(String(item.docId || item.source?.docId || ''))).length,
|
|
205
|
+
archivedDocs: docs.filter((doc) => doc.archived).length,
|
|
197
206
|
};
|
|
198
207
|
const knowledge = knowledgeSnapshot(config, { limit: 100 });
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}));
|
|
208
|
+
const docsWarning = docRegistry.invalid
|
|
209
|
+
? '文档注册表损坏,文档写入已暂停:' + docRegistry.file + '(' + (docRegistry.error || '无法解析') + ')'
|
|
210
|
+
: '';
|
|
203
211
|
return {
|
|
204
212
|
project: config.projectDir,
|
|
205
213
|
capabilities: { importUpload: true, accountsImport: true, caseDelete: true, export: true },
|
|
@@ -233,9 +241,12 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
|
|
|
233
241
|
batches: batches.map((batch) => batchSummary(batch, batch.status === 'running' ? readCaseRuns(config, batch.id) : [])),
|
|
234
242
|
activeBatch: active ? batchSummary(active, activeRuns) : null,
|
|
235
243
|
docs,
|
|
244
|
+
docsError: docRegistry.invalid
|
|
245
|
+
? { code: 'DOCS_INVALID', file: docRegistry.file, message: docsWarning }
|
|
246
|
+
: null,
|
|
236
247
|
accounts: accountsPayload(config),
|
|
237
248
|
knowledge,
|
|
238
|
-
warnings: [...(studio.warnings || []), ...(flowResult.errors || [])].slice(0, 30),
|
|
249
|
+
warnings: [docsWarning, ...(studio.warnings || []), ...(flowResult.errors || [])].filter(Boolean).slice(0, 30),
|
|
239
250
|
};
|
|
240
251
|
}
|
|
241
252
|
|
package/studio/store.mjs
CHANGED
|
@@ -320,7 +320,25 @@ export function docsFile(config) {
|
|
|
320
320
|
}
|
|
321
321
|
|
|
322
322
|
export function readDocs(config) {
|
|
323
|
-
|
|
323
|
+
const file = docsFile(config);
|
|
324
|
+
let text;
|
|
325
|
+
try {
|
|
326
|
+
text = fs.readFileSync(file, 'utf8');
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if (error?.code === 'ENOENT') return { version: STUDIO_VERSION, docs: [] };
|
|
329
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: String(error?.message || error), file };
|
|
330
|
+
}
|
|
331
|
+
let raw;
|
|
332
|
+
try {
|
|
333
|
+
raw = JSON.parse(text);
|
|
334
|
+
} catch (error) {
|
|
335
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: String(error?.message || error), file };
|
|
336
|
+
}
|
|
337
|
+
if (Array.isArray(raw)) return { version: STUDIO_VERSION, docs: raw };
|
|
338
|
+
if (!raw || typeof raw !== 'object' || !Array.isArray(raw.docs)) {
|
|
339
|
+
return { version: STUDIO_VERSION, docs: [], invalid: true, error: 'docs 字段不是数组', file };
|
|
340
|
+
}
|
|
341
|
+
return raw;
|
|
324
342
|
}
|
|
325
343
|
|
|
326
344
|
export function saveDocs(config, docs) {
|
|
@@ -348,6 +366,12 @@ export function withDocsLock(config, fn) {
|
|
|
348
366
|
export function updateDocs(config, mutate) {
|
|
349
367
|
return withDocsLock(config, () => {
|
|
350
368
|
const current = readDocs(config);
|
|
369
|
+
if (current.invalid) {
|
|
370
|
+
throw new UitestError('文档注册表损坏,已停止写入:' + (current.file || docsFile(config)), {
|
|
371
|
+
code: 'DOCS_INVALID',
|
|
372
|
+
detail: { file: current.file || docsFile(config), error: current.error || '' },
|
|
373
|
+
});
|
|
374
|
+
}
|
|
351
375
|
const draft = {
|
|
352
376
|
...current,
|
|
353
377
|
version: Number(current.version) || STUDIO_VERSION,
|
package/studio/writeback.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// 批次归档与回写:整个批次结束后只写一次结果文档 / 用例文档。
|
|
2
2
|
// 这是并发安全的关键:worker 只写自己的 case-run,回写由协调器串行完成。
|
|
3
|
+
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
|
|
5
6
|
import { applyMarkdownResults, applyXlsxResults, evidenceOfResult, runBackfill, resolveEvidencePath, selectBackfillResults } from '../lib/backfill.mjs';
|
|
@@ -27,6 +28,12 @@ function absoluteEvidence(config, file) {
|
|
|
27
28
|
return resolveEvidencePath(config, text) || path.resolve(config.paths.outputDir, text);
|
|
28
29
|
}
|
|
29
30
|
|
|
31
|
+
function projectPath(config, file) {
|
|
32
|
+
const text = String(file || '');
|
|
33
|
+
if (!text) return '';
|
|
34
|
+
return path.isAbsolute(text) ? path.resolve(text) : path.resolve(config.projectDir, text);
|
|
35
|
+
}
|
|
36
|
+
|
|
30
37
|
function relativeToBatch(config, batchId, file) {
|
|
31
38
|
const abs = absoluteEvidence(config, file);
|
|
32
39
|
if (!abs) return '';
|
|
@@ -174,35 +181,55 @@ export async function writeDocumentResults(config, {
|
|
|
174
181
|
const doc = findDocument(config, { docId });
|
|
175
182
|
if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
|
|
176
183
|
const wanted = new Set((Array.isArray(caseIds) ? caseIds : []).map(String));
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
return !wanted.size || wanted.has(String(item.tcId));
|
|
180
|
-
});
|
|
184
|
+
const allDocCases = loadProjectCases(config).cases.filter((item) => (item.docId || item.source?.docId) === doc.id);
|
|
185
|
+
const docCases = allDocCases.filter((item) => !wanted.size || wanted.has(String(item.tcId)));
|
|
181
186
|
const resultsByCase = docCases.length
|
|
182
187
|
? selectBackfillResults({ config, batchId, caseIds: docCases.map((item) => String(item.tcId)) })
|
|
183
188
|
: new Map();
|
|
184
189
|
if (!docCases.length || !resultsByCase.size) {
|
|
185
|
-
return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun };
|
|
190
|
+
return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun, cases: [] };
|
|
186
191
|
}
|
|
192
|
+
const caseSummaries = docCases.map((item) => {
|
|
193
|
+
const result = resultsByCase.get(String(item.tcId));
|
|
194
|
+
return {
|
|
195
|
+
caseId: String(item.tcId),
|
|
196
|
+
title: item.title || item.functionPoint || '',
|
|
197
|
+
status: result?.status || '',
|
|
198
|
+
};
|
|
199
|
+
});
|
|
187
200
|
const target = documentWriteTarget(config, doc, date);
|
|
188
201
|
if (target.kind === 'none') {
|
|
189
202
|
throw new UitestError('文档没有可写回的用例文件:' + doc.name, { code: target.reason || 'DOC_CASE_FILE_MISSING', detail: { docId: doc.id } });
|
|
190
203
|
}
|
|
204
|
+
// docs.json 可能保存相对路径;读写统一按 projectDir 解析,不能只让状态检查认相对路径。
|
|
205
|
+
const targetPath = projectPath(config, target.path);
|
|
206
|
+
const sourceFile = projectPath(config, doc.sourcePath);
|
|
191
207
|
if (target.kind === 'xlsx' && target.sourceState !== 'ready') {
|
|
192
|
-
throw new UitestError('文档源文件不存在,无法生成执行副本:' + (
|
|
208
|
+
throw new UitestError('文档源文件不存在,无法生成执行副本:' + (sourceFile || doc.name), {
|
|
193
209
|
code: 'DOC_SOURCE_MISSING',
|
|
194
|
-
detail: { docId: doc.id, path:
|
|
210
|
+
detail: { docId: doc.id, path: sourceFile },
|
|
195
211
|
});
|
|
196
212
|
}
|
|
213
|
+
if ((target.kind === 'markdown' || target.kind === 'json') && !fs.existsSync(targetPath)) {
|
|
214
|
+
throw new UitestError('文档的用例文件不存在:' + (targetPath || doc.name), {
|
|
215
|
+
code: 'DOC_CASE_FILE_MISSING',
|
|
216
|
+
detail: { docId: doc.id, path: targetPath },
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
const mode = batchId ? 'batch' : 'latest';
|
|
220
|
+
const sourceBatchIds = [...new Set([...resultsByCase.values()].map((result) => String(result?.batchId || '')).filter(Boolean))];
|
|
197
221
|
|
|
198
222
|
let summary;
|
|
199
223
|
if (target.kind === 'xlsx') {
|
|
224
|
+
// 同一份执行副本保留其他批次的最近结果,本批次结果覆盖对应行,避免后跑的批次清空先跑的行。
|
|
225
|
+
const mergedResults = selectBackfillResults({ config, caseIds: allDocCases.map((item) => String(item.tcId)) });
|
|
226
|
+
for (const [caseId, result] of resultsByCase) mergedResults.set(caseId, result);
|
|
200
227
|
const xlsx = await applyXlsxResults({
|
|
201
228
|
config,
|
|
202
|
-
cases:
|
|
203
|
-
resultsByCase,
|
|
204
|
-
sourceFile
|
|
205
|
-
outputPath:
|
|
229
|
+
cases: allDocCases,
|
|
230
|
+
resultsByCase: mergedResults,
|
|
231
|
+
sourceFile,
|
|
232
|
+
outputPath: targetPath,
|
|
206
233
|
date,
|
|
207
234
|
dryRun,
|
|
208
235
|
embedShots,
|
|
@@ -210,45 +237,80 @@ export async function writeDocumentResults(config, {
|
|
|
210
237
|
});
|
|
211
238
|
// 用例来源指向别的工作簿时 applyXlsxResults 不写盘;不报失败会让批次误报“已写入”。
|
|
212
239
|
if (!xlsx.written && !xlsx.dryRun) {
|
|
213
|
-
throw new UitestError('文档的用例已不在该工作簿来源中:' + (
|
|
240
|
+
throw new UitestError('文档的用例已不在该工作簿来源中:' + (sourceFile || doc.name), {
|
|
214
241
|
code: 'DOC_CASE_FILE_MISSING',
|
|
215
|
-
detail: { docId: doc.id, path:
|
|
242
|
+
detail: { docId: doc.id, path: sourceFile, reason: xlsx.reason || '' },
|
|
216
243
|
});
|
|
217
244
|
}
|
|
245
|
+
// results 只算本次回写范围内的结果;writtenIds 还包含同日其它批次合并保留下来的行。
|
|
246
|
+
const writtenIds = new Set((xlsx.writtenIds || []).map(String));
|
|
247
|
+
const scopeCaseIds = [...resultsByCase.keys()];
|
|
248
|
+
const skippedCaseIds = scopeCaseIds.filter((caseId) => !writtenIds.has(String(caseId)));
|
|
218
249
|
summary = {
|
|
219
250
|
at: nowIso(),
|
|
220
251
|
batchId,
|
|
221
|
-
|
|
222
|
-
|
|
252
|
+
mode,
|
|
253
|
+
sourceBatchIds,
|
|
254
|
+
results: scopeCaseIds.length - skippedCaseIds.length,
|
|
255
|
+
targetPath: xlsx.path || targetPath,
|
|
223
256
|
kind: 'xlsx',
|
|
224
257
|
files: [],
|
|
225
258
|
markdown: null,
|
|
259
|
+
skippedCaseIds,
|
|
226
260
|
xlsx,
|
|
227
261
|
};
|
|
228
262
|
} else {
|
|
229
|
-
const parsed = parseMarkdownCases(
|
|
263
|
+
const parsed = parseMarkdownCases(targetPath, { rootDir: config.projectDir });
|
|
264
|
+
const parsedIds = new Set(parsed.cases.map((item) => String(item.tcId)));
|
|
265
|
+
const skippedCaseIds = [...resultsByCase.keys()].filter((caseId) => !parsedIds.has(String(caseId)));
|
|
266
|
+
const writableResults = new Map([...resultsByCase].filter(([caseId]) => parsedIds.has(String(caseId))));
|
|
267
|
+
if (!writableResults.size) {
|
|
268
|
+
throw new UitestError('用例文件里找不到要回写的用例:' + skippedCaseIds.join('、') + ';请先重新导读文档', {
|
|
269
|
+
code: 'DOC_CASE_FILE_STALE',
|
|
270
|
+
detail: { docId: doc.id, path: targetPath, caseIds: skippedCaseIds },
|
|
271
|
+
});
|
|
272
|
+
}
|
|
230
273
|
const applied = applyMarkdownResults({
|
|
231
274
|
config,
|
|
232
|
-
file:
|
|
275
|
+
file: targetPath,
|
|
233
276
|
sourceCases: parsed.cases,
|
|
234
|
-
resultsByCase,
|
|
277
|
+
resultsByCase: writableResults,
|
|
235
278
|
maxShotsPerCase,
|
|
236
279
|
dryRun,
|
|
237
280
|
});
|
|
238
|
-
const
|
|
281
|
+
const written = applied.inserted + applied.replaced;
|
|
282
|
+
const files = written ? [targetPath] : [];
|
|
239
283
|
summary = {
|
|
240
284
|
at: nowIso(),
|
|
241
285
|
batchId,
|
|
242
|
-
|
|
243
|
-
|
|
286
|
+
mode,
|
|
287
|
+
sourceBatchIds,
|
|
288
|
+
results: written,
|
|
289
|
+
targetPath,
|
|
244
290
|
kind: doc.kind,
|
|
245
291
|
files,
|
|
246
|
-
markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced },
|
|
292
|
+
markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced, skipped: skippedCaseIds.length },
|
|
293
|
+
skippedCaseIds,
|
|
247
294
|
xlsx: null,
|
|
248
295
|
};
|
|
249
296
|
}
|
|
250
297
|
const saved = dryRun ? doc : await recordDocumentWriteback(config, doc.id, summary);
|
|
251
|
-
return { docId: doc.id, doc: saved, writeback: summary, results: summary.results, skipped: false, dryRun };
|
|
298
|
+
return { docId: doc.id, doc: saved, writeback: summary, results: summary.results, skipped: false, dryRun, cases: caseSummaries };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** 单文档回写预览:使用最近结果或指定批次,只读不落盘。 */
|
|
302
|
+
export async function previewDocumentWriteback(config, docId, { batchId = '', caseIds = [] } = {}) {
|
|
303
|
+
return writeDocumentResults(config, { docId, batchId, caseIds, dryRun: true });
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** 单文档回写:持有回写锁,避免和重新导读或批次回写互相覆盖。 */
|
|
307
|
+
export async function applyDocumentWriteback(config, docId, { batchId = '', caseIds = [] } = {}) {
|
|
308
|
+
const lock = await acquireWritebackLock(config);
|
|
309
|
+
try {
|
|
310
|
+
return await writeDocumentResults(config, { docId, batchId, caseIds, dryRun: false });
|
|
311
|
+
} finally {
|
|
312
|
+
lock.release();
|
|
313
|
+
}
|
|
252
314
|
}
|
|
253
315
|
|
|
254
316
|
/** 批次回写计划:按文档分组写各自目标,未归属用例仍走原 runBackfill。 */
|