dsh-uitest 2.1.3 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/studio/import.mjs CHANGED
@@ -8,17 +8,21 @@ import path from 'node:path';
8
8
  import {
9
9
  clearCaseTombstones,
10
10
  deleteCases,
11
+ docIdForKey,
11
12
  importCases,
12
13
  keepDocumentCases,
13
14
  loadImportedCases,
14
15
  loadProjectCases,
16
+ normalizeDocumentRecord,
15
17
  rekeyDocumentCases,
16
18
  removeDocumentCases,
17
19
  removeDocumentOverrides,
18
20
  } from '../lib/cases-import.mjs';
19
21
  import { UitestError, ensureDir, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
22
+ import { findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
20
23
  import { dataNeedsFromText, normalizeStudioCase, splitNatural } from './model.mjs';
21
- import { readDocs, saveDocs } from './store.mjs';
24
+ import { readDocs } from './store.mjs';
25
+ import { acquireWritebackLock, writeDocumentResults } from './writeback.mjs';
22
26
 
23
27
  const TEXT_EXT = new Set(['.md', '.markdown', '.txt']);
24
28
  const XLSX_EXT = new Set(['.xlsx']);
@@ -41,11 +45,6 @@ for (const [field, aliases] of Object.entries(FIELD_ALIASES)) {
41
45
  for (const alias of aliases) ALIAS_LOOKUP.set(alias.toLowerCase(), field);
42
46
  }
43
47
 
44
- /** 文档对象 identity:名称归一化(大小写、空白、扩展名不敏感)。 */
45
- function docIdForKey(docKey) {
46
- return 'doc-' + crypto.createHash('sha1').update(String(docKey)).digest('hex').slice(0, 10);
47
- }
48
-
49
48
  /** 用例内容摘要:覆盖导入时用来区分「更新」与「未变」。来源路径不属于用例内容。 */
50
49
  export function digestCase(caseItem) {
51
50
  const remark = String(caseItem?.remark ?? '')
@@ -429,22 +428,16 @@ function sameFile(a, b) {
429
428
  function findPreviousDoc(config, { docKey, sourcePath }) {
430
429
  const store = readDocs(config);
431
430
  const key = normalizeDocKey(docKey);
432
- return (store.docs || []).find((item) => {
433
- const itemKey = item.docKey || normalizeDocKey(item.name);
434
- return itemKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
431
+ return (store.docs || []).map(normalizeDocumentRecord).find((item) => {
432
+ return item.docKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
435
433
  }) || null;
436
434
  }
437
435
 
438
- function saveDocRecord(config, record) {
439
- const store = readDocs(config);
440
- const key = record.docKey || normalizeDocKey(record.name);
441
- const docs = (store.docs || []).filter((item) => {
442
- const itemKey = item.docKey || normalizeDocKey(item.name);
443
- return itemKey !== key && normalizeDocKey(item.name) !== key && item.sourcePath !== record.sourcePath;
444
- });
445
- docs.unshift({ ...record, docKey: key, id: record.id || docIdForKey(key) });
446
- saveDocs(config, { ...store, version: 2, docs, updatedAt: nowIso() });
447
- return docs[0];
436
+ function findTargetDoc(config, docId) {
437
+ if (!docId) return null;
438
+ const doc = findDocument(config, { docId });
439
+ if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
440
+ return doc;
448
441
  }
449
442
 
450
443
  function digestsForCases(cases) {
@@ -517,7 +510,7 @@ function compactDiff(diff) {
517
510
  * mode=merge 保留文档中已移除的旧用例;mode=overwrite 以当前文档为准删除旧用例。
518
511
  * @returns {Promise<{doc:object, docs:object[], cases:object[], warnings:object[], diff:object}>}
519
512
  */
520
- export async function importDocument(config, { file, name = '', mode = 'merge', originalName = '' } = {}) {
513
+ export async function importDocument(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
521
514
  const sourcePath = path.resolve(config.projectDir, String(file || ''));
522
515
  if (!fs.existsSync(sourcePath)) throw new UitestError('路径不存在:' + sourcePath, { code: 'IMPORT_PATH_NOT_FOUND' });
523
516
  const stat = fs.statSync(sourcePath);
@@ -547,10 +540,11 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
547
540
  }
548
541
  if (stat.size > MAX_BYTES) throw new UitestError('文件超过 20MB 上限:' + sourcePath, { code: 'IMPORT_TOO_LARGE' });
549
542
  const ext = path.extname(sourcePath).toLowerCase();
550
- const docName = name || path.basename(sourcePath, ext);
543
+ const explicitDoc = findTargetDoc(config, docId);
544
+ const docName = name || explicitDoc?.name || path.basename(sourcePath, ext);
551
545
  const docKey = normalizeDocKey(docName) || normalizeDocKey(path.basename(sourcePath, ext)) || 'document';
552
546
  const overwrite = mode === 'overwrite';
553
- const previousDoc = findPreviousDoc(config, { docKey, sourcePath });
547
+ const previousDoc = explicitDoc || findPreviousDoc(config, { docKey, sourcePath });
554
548
  const previousIds = Array.isArray(previousDoc?.caseIds) ? previousDoc.caseIds.map(String) : [];
555
549
  const previousLibrary = new Map(loadProjectCases(config).cases.map((item) => [String(item.tcId), item]));
556
550
  const previousDigests = { ...digestsForIds(config, previousIds, previousLibrary), ...(previousDoc?.digests || {}) };
@@ -687,7 +681,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
687
681
  }
688
682
 
689
683
  const ownedIds = overwrite ? newIds : [...new Set([...previousIds, ...newIds])];
690
- const doc = saveDocRecord(config, {
684
+ const doc = await saveDocumentRecord(config, {
691
685
  id: previousDoc?.id || docIdForKey(docKey),
692
686
  docKey,
693
687
  name: docName,
@@ -695,7 +689,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
695
689
  originalName: originalName || previousDoc?.originalName || '',
696
690
  generatedPath,
697
691
  kind: XLSX_EXT.has(ext) ? 'xlsx' : JSON_EXT.has(ext) ? 'json' : 'markdown',
698
- importedAt: nowIso(),
692
+ importedAt: previousDoc?.importedAt || nowIso(),
699
693
  updatedAt: nowIso(),
700
694
  count: ownedIds.length,
701
695
  lastCount: newIds.length,
@@ -706,17 +700,121 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
706
700
  diff: compactDiff(diff),
707
701
  digests: overwrite ? newDigests : { ...(previousDoc?.digests || {}), ...newDigests },
708
702
  warnings: (warnings || []).slice(0, 5).map((item) => String(item?.message || item).slice(0, 240)),
703
+ lastRead: previousDoc?.lastRead || null,
704
+ writeback: previousDoc?.writeback || null,
705
+ }, {
706
+ // 导入字段算自导入前快照。锁内重读后版本按磁盘递增,并保留并发重新导读/回写的状态。
707
+ reconcile: (existing, input) => (existing
708
+ ? {
709
+ ...input,
710
+ version: (Number(existing.version) || 0) + 1,
711
+ lastRead: existing.lastRead ?? input.lastRead,
712
+ writeback: existing.writeback ?? input.writeback,
713
+ }
714
+ : input),
709
715
  });
716
+ const stamped = cases.map((item) => ({
717
+ ...item,
718
+ source: {
719
+ ...item.source,
720
+ docId: doc.id,
721
+ docKey: doc.docKey,
722
+ docName: doc.name,
723
+ docKind: doc.kind,
724
+ },
725
+ }));
710
726
  return {
711
727
  doc,
712
728
  docs: [doc],
713
- cases: cases.map((item) => normalizeStudioCase(item)),
729
+ cases: stamped.map((item) => normalizeStudioCase(item)),
714
730
  warnings,
715
731
  diff,
716
732
  diffSummary: compactDiff(diff),
717
733
  };
718
734
  }
719
735
 
736
+ /**
737
+ * 重新导读:按文档 id 重读存储的源文件,保留文档身份;源文件缺失时不改任何状态。
738
+ * Markdown 重新生成用例文件后会尽力重放最近一次结果回写。
739
+ * 全程持有回写锁:重新导读会重写用例文件,不能和批次回写互相覆盖。
740
+ */
741
+ export async function reReadDocument(config, { docId = '', mode = '', reapplyResults = true } = {}) {
742
+ const lock = await acquireWritebackLock(config);
743
+ try {
744
+ const doc = findTargetDoc(config, docId);
745
+ if (!doc) throw new UitestError('缺少文档 id', { code: 'DOC_NOT_FOUND', detail: { docId } });
746
+ const sourcePath = String(doc.sourcePath || '');
747
+ let sourceReady = false;
748
+ try {
749
+ sourceReady = Boolean(sourcePath) && fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile();
750
+ } catch {
751
+ sourceReady = false;
752
+ }
753
+ if (!sourceReady) {
754
+ throw new UitestError('文档源文件不存在:' + (sourcePath || '(未记录)'), {
755
+ code: 'DOC_SOURCE_MISSING',
756
+ detail: { docId: doc.id, path: sourcePath },
757
+ });
758
+ }
759
+ const imported = await importDocument(config, {
760
+ file: sourcePath,
761
+ name: doc.name,
762
+ mode: mode || doc.mode || 'merge',
763
+ originalName: doc.originalName || '',
764
+ docId: doc.id,
765
+ });
766
+ const lastRead = {
767
+ at: nowIso(),
768
+ version: imported.doc.version,
769
+ sourcePath,
770
+ diff: imported.diffSummary || null,
771
+ };
772
+ let nextDoc = await updateDocumentRecord(config, imported.doc.id, (current) => ({
773
+ ...current,
774
+ lastRead,
775
+ updatedAt: lastRead.at,
776
+ }));
777
+ const warnings = [...(imported.warnings || [])];
778
+ let resultReapplied = false;
779
+ const recorded = imported.doc.writeback;
780
+ if (reapplyResults && recorded?.batchId && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
781
+ const survivingIds = loadProjectCases(config).cases
782
+ .filter((item) => item.source?.docId === imported.doc.id)
783
+ .map((item) => String(item.tcId));
784
+ try {
785
+ const reapplied = await writeDocumentResults(config, {
786
+ docId: imported.doc.id,
787
+ batchId: recorded.batchId,
788
+ caseIds: survivingIds,
789
+ });
790
+ if (reapplied.writeback) {
791
+ resultReapplied = true;
792
+ nextDoc = findDocument(config, { docId: imported.doc.id }) || nextDoc;
793
+ } else {
794
+ warnings.push({
795
+ code: 'WRITEBACK_REAPPLY_SKIPPED',
796
+ message: '最近一次回写的批次结果已不存在,用例文件已重新导读但未带回结果块',
797
+ });
798
+ }
799
+ } catch (error) {
800
+ warnings.push({
801
+ code: 'WRITEBACK_REAPPLY_FAILED',
802
+ message: '重新回写最近结果失败,用例文件已重新导读:' + String(error.message || error),
803
+ });
804
+ }
805
+ }
806
+ return {
807
+ ...imported,
808
+ doc: nextDoc,
809
+ docs: [nextDoc],
810
+ warnings,
811
+ resultReapplied,
812
+ };
813
+ } finally {
814
+ lock.release();
815
+ }
816
+ }
817
+
720
818
  /** 从当前用例库读取统一形态;用于 UI 与批次。 */
721
819
  export function loadStudioCases(config, { flows = [] } = {}) {
722
820
  const loaded = loadProjectCases(config);
@@ -743,6 +841,7 @@ export function loadStudioCases(config, { flows = [] } = {}) {
743
841
  })),
744
842
  summary: loaded.summary,
745
843
  warnings: loaded.warnings,
844
+ deletedCaseIds: loaded.deletedCaseIds || [],
746
845
  counts: {
747
846
  config: loaded.configCount,
748
847
  markdown: loaded.markdownCount,
package/studio/model.mjs CHANGED
@@ -139,6 +139,7 @@ export function normalizeStudioCase(caseItem, { flow = null, preconditionFlows =
139
139
  tcId,
140
140
  seq: caseItem?.seq ?? tcId,
141
141
  title: caseItem?.functionPoint || caseItem?.title || tcId,
142
+ type: caseItem?.type || '',
142
143
  module: caseItem?.module || caseItem?.l1 || '',
143
144
  l1: caseItem?.l1 || '',
144
145
  l2: caseItem?.l2 || '',
@@ -149,6 +150,9 @@ export function normalizeStudioCase(caseItem, { flow = null, preconditionFlows =
149
150
  expected: String(caseItem?.expected || ''),
150
151
  remark: String(caseItem?.remark || ''),
151
152
  source: caseItem?.source || null,
153
+ docId: String(caseItem?.docId || caseItem?.source?.docId || ''),
154
+ docName: String(caseItem?.docName || caseItem?.source?.docName || ''),
155
+ docKind: String(caseItem?.docKind || caseItem?.source?.docKind || ''),
152
156
  mode: inferCaseMode(caseItem, { hasFlow: Boolean(flow) }),
153
157
  flow: flow
154
158
  ? {
@@ -9,7 +9,8 @@ import { readFlows } from '../host/state.mjs';
9
9
  import { loadStudioCases } from './import.mjs';
10
10
  import { knowledgeSnapshot } from './knowledge.mjs';
11
11
  import { readRunFeedbacks } from '../lib/run-feedback.mjs';
12
- import { listBatches, mergeBatchRuns, readCaseRuns, readDocs } from './store.mjs';
12
+ import { listBatches, mergeBatchRuns, readCaseRuns } from './store.mjs';
13
+ import { documentRegistry, documentView } from './documents.mjs';
13
14
  import { accountsPayload } from './accounts.mjs';
14
15
  import { statusFromRun } from './model.mjs';
15
16
 
@@ -127,7 +128,8 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
127
128
  const activeRuns = active ? mergeBatchRuns(active, readCaseRuns(config, active.id)) : [];
128
129
  const activeById = new Map(activeRuns.map((run) => [String(run.caseId), run]));
129
130
 
130
- const cases = studio.cases.slice(0, caseLimit).map((item) => {
131
+ // 文档视图和用例行共用完整用例库的状态:先切片会让文档汇总漏掉真实结果。
132
+ const enriched = studio.cases.map((item) => {
131
133
  const result = latest.get(String(item.tcId));
132
134
  const activeRun = activeById.get(String(item.tcId));
133
135
  const runKnowledge = knowledgeByCase.get(String(item.tcId)) || null;
@@ -178,6 +180,7 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
178
180
  lastFeedback: feedbackByCase.get(String(item.tcId)) || null,
179
181
  };
180
182
  });
183
+ const cases = enriched.slice(0, caseLimit);
181
184
 
182
185
  const counts = {
183
186
  total: studio.cases.length,
@@ -190,29 +193,13 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
190
193
  untested: cases.filter((item) => item.status === 'untested').length,
191
194
  running: cases.filter((item) => item.status === 'running').length,
192
195
  feedback: feedbackByCase.size,
196
+ unassigned: studio.cases.filter((item) => !item.docId && !item.source?.docId).length,
193
197
  };
194
198
  const knowledge = knowledgeSnapshot(config, { limit: 100 });
195
- const visibleIds = new Set(studio.cases.map((item) => String(item.tcId)));
196
- const docs = (readDocs(config).docs || []).map((doc) => {
197
- const caseIds = Array.isArray(doc.caseIds) ? doc.caseIds : [];
198
- const visibleCount = caseIds.length ? caseIds.filter((id) => visibleIds.has(String(id))).length : (Number(doc.count) || 0);
199
- return {
200
- id: doc.id,
201
- docKey: doc.docKey || '',
202
- name: doc.name || '',
203
- sourcePath: doc.sourcePath || '',
204
- generatedPath: doc.generatedPath || '',
205
- kind: doc.kind || '',
206
- count: visibleCount,
207
- importedCount: Number(doc.count) || caseIds.length,
208
- lastCount: doc.lastCount ?? caseIds.length,
209
- version: doc.version || 1,
210
- mode: doc.mode || 'merge',
211
- importedAt: doc.importedAt || '',
212
- updatedAt: doc.updatedAt || doc.importedAt || '',
213
- diff: doc.diff || null,
214
- };
215
- });
199
+ // 文档视图必须基于完整用例库计算,先切片会让文档看起来缺用例。
200
+ const docs = documentRegistry(config).docs.map((doc) => documentView(config, doc, enriched, {
201
+ deletedCaseIds: studio.deletedCaseIds || [],
202
+ }));
216
203
  return {
217
204
  project: config.projectDir,
218
205
  capabilities: { importUpload: true, accountsImport: true, caseDelete: true, export: true },
package/studio/store.mjs CHANGED
@@ -329,6 +329,37 @@ export function saveDocs(config, docs) {
329
329
  return docs;
330
330
  }
331
331
 
332
+ const docsQueues = new Map();
333
+
334
+ /** docs.json 读改写按工作区串行化,避免并发导入互相覆盖。 */
335
+ export function withDocsLock(config, fn) {
336
+ const key = path.resolve(config.projectDir);
337
+ const previous = docsQueues.get(key) || Promise.resolve();
338
+ const current = previous.then(() => fn());
339
+ const stored = current.catch(() => {});
340
+ docsQueues.set(key, stored);
341
+ stored.finally(() => {
342
+ if (docsQueues.get(key) === stored) docsQueues.delete(key);
343
+ });
344
+ return current;
345
+ }
346
+
347
+ /** 文档记录的读改写入口:回调修改 draft,函数负责原子落盘。 */
348
+ export function updateDocs(config, mutate) {
349
+ return withDocsLock(config, () => {
350
+ const current = readDocs(config);
351
+ const draft = {
352
+ ...current,
353
+ version: Number(current.version) || STUDIO_VERSION,
354
+ docs: Array.isArray(current.docs) ? current.docs : [],
355
+ };
356
+ const result = mutate(draft);
357
+ const next = { ...draft, updatedAt: nowIso() };
358
+ saveDocs(config, next);
359
+ return result === undefined ? next : result;
360
+ });
361
+ }
362
+
332
363
  export function lockFile(config, name) {
333
364
  return path.join(studioRoot(config), 'locks', String(name).replace(/[^A-Za-z0-9._-]/g, '_') + '.lock');
334
365
  }
@@ -2,9 +2,12 @@
2
2
  // 这是并发安全的关键:worker 只写自己的 case-run,回写由协调器串行完成。
3
3
  import path from 'node:path';
4
4
 
5
- import { evidenceOfResult, runBackfill, resolveEvidencePath } from '../lib/backfill.mjs';
6
- import { formatDuration, sleep } from '../lib/util.mjs';
5
+ import { applyMarkdownResults, applyXlsxResults, evidenceOfResult, runBackfill, resolveEvidencePath, selectBackfillResults } from '../lib/backfill.mjs';
6
+ import { loadProjectCases } from '../lib/cases-import.mjs';
7
+ import { parseMarkdownCases } from '../lib/cases-md.mjs';
8
+ import { UitestError, formatDate, formatDuration, nowIso, sleep } from '../lib/util.mjs';
7
9
  import { acquireLock, batchDir, caseRunFile, mergeBatchRuns, patchBatch, patchStage, readBatch, readCaseRuns, writeBatchText } from './store.mjs';
10
+ import { documentWriteTarget, findDocument, recordDocumentWriteback } from './documents.mjs';
8
11
 
9
12
  function statusBadge(status) {
10
13
  if (status === 'passed') return '通过';
@@ -105,6 +108,18 @@ export function renderBatchDoc({ config, batch, caseRuns = [] }) {
105
108
  if (batch.writeback.xlsx?.path) lines.push('- xlsx 副本:' + batch.writeback.xlsx.path);
106
109
  lines.push('');
107
110
  }
111
+ if (Array.isArray(batch.writeback?.documents) && batch.writeback.documents.length) {
112
+ lines.push('## 文档回写', '');
113
+ lines.push('| 文档 | 类型 | 结果 | 目标 | 状态 |');
114
+ lines.push('|---|---|---|---|---|');
115
+ for (const doc of batch.writeback.documents) {
116
+ const status = doc.error
117
+ ? '失败:' + String(doc.error.message || doc.error).replace(/\|/g, '\\|')
118
+ : '已写入';
119
+ lines.push('| ' + String(doc.name || doc.id || '').replace(/\|/g, '\\|') + ' | ' + (doc.kind || '-') + ' | ' + (doc.results || 0) + ' | ' + String(doc.targetPath || '-').replace(/\|/g, '\\|') + ' | ' + status + ' |');
120
+ }
121
+ lines.push('');
122
+ }
108
123
  if (batch.knowledge) {
109
124
  lines.push('## 知识沉淀', '');
110
125
  lines.push('- 页面:' + (batch.knowledge.totals?.pages || 0));
@@ -143,28 +158,214 @@ export async function writeBatchResultDoc(config, batchId) {
143
158
  return { file, batch, caseRuns, text };
144
159
  }
145
160
 
161
+ /**
162
+ * 把一批结果写回单个文档:Markdown 写解析出的用例文件,xlsx 生成该文档专属执行副本。
163
+ * 源文件只读;dryRun 不写文件也不写文档记录。
164
+ */
165
+ export async function writeDocumentResults(config, {
166
+ docId = '',
167
+ batchId = '',
168
+ caseIds = [],
169
+ date = formatDate(new Date()),
170
+ dryRun = false,
171
+ embedShots = true,
172
+ maxShotsPerCase = 4,
173
+ } = {}) {
174
+ const doc = findDocument(config, { docId });
175
+ if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
176
+ const wanted = new Set((Array.isArray(caseIds) ? caseIds : []).map(String));
177
+ const docCases = loadProjectCases(config).cases.filter((item) => {
178
+ if (item.source?.docId !== doc.id) return false;
179
+ return !wanted.size || wanted.has(String(item.tcId));
180
+ });
181
+ const resultsByCase = docCases.length
182
+ ? selectBackfillResults({ config, batchId, caseIds: docCases.map((item) => String(item.tcId)) })
183
+ : new Map();
184
+ if (!docCases.length || !resultsByCase.size) {
185
+ return { docId: doc.id, doc, writeback: null, results: 0, skipped: true, dryRun };
186
+ }
187
+ const target = documentWriteTarget(config, doc, date);
188
+ if (target.kind === 'none') {
189
+ throw new UitestError('文档没有可写回的用例文件:' + doc.name, { code: target.reason || 'DOC_CASE_FILE_MISSING', detail: { docId: doc.id } });
190
+ }
191
+ if (target.kind === 'xlsx' && target.sourceState !== 'ready') {
192
+ throw new UitestError('文档源文件不存在,无法生成执行副本:' + (target.sourcePath || doc.name), {
193
+ code: 'DOC_SOURCE_MISSING',
194
+ detail: { docId: doc.id, path: target.sourcePath || '' },
195
+ });
196
+ }
197
+
198
+ let summary;
199
+ if (target.kind === 'xlsx') {
200
+ const xlsx = await applyXlsxResults({
201
+ config,
202
+ cases: docCases,
203
+ resultsByCase,
204
+ sourceFile: doc.sourcePath,
205
+ outputPath: target.path,
206
+ date,
207
+ dryRun,
208
+ embedShots,
209
+ maxShotsPerCase,
210
+ });
211
+ // 用例来源指向别的工作簿时 applyXlsxResults 不写盘;不报失败会让批次误报“已写入”。
212
+ if (!xlsx.written && !xlsx.dryRun) {
213
+ throw new UitestError('文档的用例已不在该工作簿来源中:' + (doc.sourcePath || doc.name), {
214
+ code: 'DOC_CASE_FILE_MISSING',
215
+ detail: { docId: doc.id, path: doc.sourcePath || '', reason: xlsx.reason || '' },
216
+ });
217
+ }
218
+ summary = {
219
+ at: nowIso(),
220
+ batchId,
221
+ results: Number(xlsx.cases) || 0,
222
+ targetPath: xlsx.path || target.path,
223
+ kind: 'xlsx',
224
+ files: [],
225
+ markdown: null,
226
+ xlsx,
227
+ };
228
+ } else {
229
+ const parsed = parseMarkdownCases(target.path, { rootDir: config.projectDir });
230
+ const applied = applyMarkdownResults({
231
+ config,
232
+ file: target.path,
233
+ sourceCases: parsed.cases,
234
+ resultsByCase,
235
+ maxShotsPerCase,
236
+ dryRun,
237
+ });
238
+ const files = applied.inserted || applied.replaced ? [target.path] : [];
239
+ summary = {
240
+ at: nowIso(),
241
+ batchId,
242
+ results: resultsByCase.size,
243
+ targetPath: target.path,
244
+ kind: doc.kind,
245
+ files,
246
+ markdown: { files: files.length, inserted: applied.inserted, replaced: applied.replaced },
247
+ xlsx: null,
248
+ };
249
+ }
250
+ 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 };
252
+ }
253
+
254
+ /** 批次回写计划:按文档分组写各自目标,未归属用例仍走原 runBackfill。 */
255
+ async function planBatchWriteback(config, batchId, { dryRun = false } = {}) {
256
+ const batch = readBatch(config, batchId);
257
+ const inBatch = new Set((batch.caseIds || []).map(String));
258
+ const byDoc = new Map();
259
+ const unassigned = [];
260
+ for (const item of loadProjectCases(config).cases) {
261
+ if (!inBatch.has(String(item.tcId))) continue;
262
+ const docId = String(item.source?.docId || '');
263
+ if (!docId) {
264
+ unassigned.push(item);
265
+ continue;
266
+ }
267
+ if (!byDoc.has(docId)) byDoc.set(docId, []);
268
+ byDoc.get(docId).push(item);
269
+ }
270
+
271
+ const documents = [];
272
+ const errors = [];
273
+ const files = [];
274
+ let results = 0;
275
+ let markdownFiles = 0;
276
+ let inserted = 0;
277
+ let replaced = 0;
278
+ for (const [docId, docCases] of byDoc) {
279
+ const doc = findDocument(config, { docId });
280
+ try {
281
+ const written = await writeDocumentResults(config, {
282
+ docId,
283
+ batchId,
284
+ caseIds: docCases.map((item) => String(item.tcId)),
285
+ dryRun,
286
+ });
287
+ const wb = written.writeback || {};
288
+ documents.push({
289
+ id: docId,
290
+ name: doc?.name || '',
291
+ kind: doc?.kind || '',
292
+ results: Number(wb.results) || 0,
293
+ targetPath: wb.targetPath || '',
294
+ files: wb.files || [],
295
+ markdown: wb.markdown || null,
296
+ xlsx: wb.xlsx || null,
297
+ error: null,
298
+ });
299
+ results += Number(wb.results) || 0;
300
+ markdownFiles += Number(wb.markdown?.files) || 0;
301
+ inserted += Number(wb.markdown?.inserted) || 0;
302
+ replaced += Number(wb.markdown?.replaced) || 0;
303
+ files.push(...(wb.files || []));
304
+ } catch (error) {
305
+ const failure = { code: error?.code || 'WRITEBACK_FAILED', message: String(error?.message || error) };
306
+ documents.push({
307
+ id: docId,
308
+ name: doc?.name || '',
309
+ kind: doc?.kind || '',
310
+ results: 0,
311
+ targetPath: '',
312
+ files: [],
313
+ markdown: null,
314
+ xlsx: null,
315
+ error: failure,
316
+ });
317
+ errors.push({ docId, ...failure });
318
+ }
319
+ }
320
+
321
+ let legacy = null;
322
+ if (unassigned.length) {
323
+ legacy = await runBackfill({
324
+ config,
325
+ batchId,
326
+ caseIds: unassigned.map((item) => String(item.tcId)),
327
+ markdown: true,
328
+ xlsx: true,
329
+ dryRun,
330
+ });
331
+ results += Number(legacy.results) || 0;
332
+ markdownFiles += Number(legacy.markdown?.files) || 0;
333
+ inserted += Number(legacy.markdown?.inserted) || 0;
334
+ replaced += Number(legacy.markdown?.replaced) || 0;
335
+ files.push(...(legacy.markdown?.filesTouched || []));
336
+ }
337
+
338
+ return {
339
+ dryRun,
340
+ documents,
341
+ errors,
342
+ results,
343
+ markdownFiles,
344
+ inserted,
345
+ replaced,
346
+ files,
347
+ xlsx: legacy?.xlsx || null,
348
+ summaryPath: legacy?.summaryPath || null,
349
+ legacyResults: Number(legacy?.results) || 0,
350
+ };
351
+ }
352
+
146
353
  /** 预览回写会修改哪些文件;不写盘。 */
147
354
  export async function previewBatchWriteback(config, batchId) {
148
- const batch = readBatch(config, batchId);
149
- const result = await runBackfill({
150
- config,
151
- batchId,
152
- caseIds: batch.caseIds,
153
- markdown: true,
154
- xlsx: true,
155
- dryRun: true,
156
- });
355
+ const plan = await planBatchWriteback(config, batchId, { dryRun: true });
157
356
  return {
158
357
  batchId,
159
358
  dryRun: true,
160
- results: result.results,
161
- markdown: result.markdown,
162
- xlsx: result.xlsx,
163
- files: result.markdown?.filesTouched || [],
359
+ results: plan.results,
360
+ markdown: { files: plan.markdownFiles, inserted: plan.inserted, replaced: plan.replaced, filesTouched: plan.files },
361
+ xlsx: plan.xlsx,
362
+ files: plan.files,
363
+ documents: plan.documents,
364
+ errors: plan.errors,
164
365
  };
165
366
  }
166
367
 
167
- /** 整个批次结束后回写一次;由单写者锁保护。 */
368
+ /** 整个批次结束后回写一次;由单写者锁保护,单个文档失败不影响其它文档。 */
168
369
  export async function applyBatchWriteback(config, batchId, { dryRun = false } = {}) {
169
370
  const batch = readBatch(config, batchId);
170
371
  if (batch.status === 'queued' || batch.status === 'preparing' || batch.status === 'running') {
@@ -174,26 +375,29 @@ export async function applyBatchWriteback(config, batchId, { dryRun = false } =
174
375
  const lock = await acquireWritebackLock(config);
175
376
  try {
176
377
  await patchStage(config, batchId, 'writeback', { status: 'running', error: null });
177
- const result = await runBackfill({
178
- config,
179
- batchId,
180
- caseIds: batch.caseIds,
181
- markdown: true,
182
- xlsx: true,
183
- dryRun: false,
184
- });
378
+ const plan = await planBatchWriteback(config, batchId, { dryRun: false });
185
379
  const summary = {
186
- at: new Date().toISOString(),
187
- results: result.results,
188
- markdownFiles: result.markdown?.files || 0,
189
- inserted: result.markdown?.inserted || 0,
190
- replaced: result.markdown?.replaced || 0,
191
- files: result.markdown?.filesTouched || [],
192
- xlsx: result.xlsx || null,
193
- summaryPath: result.summaryPath || null,
380
+ at: nowIso(),
381
+ results: plan.results,
382
+ markdownFiles: plan.markdownFiles,
383
+ inserted: plan.inserted,
384
+ replaced: plan.replaced,
385
+ files: plan.files,
386
+ xlsx: plan.xlsx,
387
+ summaryPath: plan.summaryPath,
388
+ documents: plan.documents,
389
+ errors: plan.errors,
194
390
  };
195
391
  await patchBatch(config, batchId, { writeback: summary });
196
- await patchStage(config, batchId, 'writeback', { status: 'done', at: summary.at, files: summary.files.length });
392
+ const allFailed = plan.documents.length > 0
393
+ && plan.documents.every((item) => item.error)
394
+ && plan.legacyResults === 0;
395
+ await patchStage(config, batchId, 'writeback', {
396
+ status: allFailed ? 'failed' : 'done',
397
+ at: summary.at,
398
+ files: summary.files.length,
399
+ ...(allFailed ? { error: plan.errors.map((item) => item.message).join(';') } : {}),
400
+ });
197
401
  return summary;
198
402
  } catch (error) {
199
403
  patchStage(config, batchId, 'writeback', { status: 'failed', error: String(error.message || error) });
@@ -3,7 +3,7 @@
3
3
  "browser": {
4
4
  "executablePath": "/usr/bin/chromium",
5
5
  "headless": true,
6
- "viewport": { "width": 1600, "height": 1000 },
6
+ "viewport": { "width": 1920, "height": 1280 },
7
7
  "args": ["--no-sandbox", "--disable-dev-shm-usage"],
8
8
  "locale": "zh-CN",
9
9
  "timezoneId": "Asia/Shanghai"