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/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';
@@ -29,11 +29,12 @@ import { readAgentLive } from './agent-live.mjs';
29
29
  import { importDocument, reReadDocument } from './import.mjs';
30
30
  import { defaultExportDir, exportCasesWorkbook, exportResultsWorkbook } from './export.mjs';
31
31
  import { buildStudioSnapshot, batchSummary } from './snapshot.mjs';
32
- import { createBatch, deleteBatch, listBatches, mergeBatchRuns, patchBatch, readBatch, readCaseRuns, readEvents, refreshBatchSummary, saveBatch, withBatchLock } from './store.mjs';
32
+ import { acquireLock, createBatch, deleteBatch, listBatches, mergeBatchRuns, patchBatch, readBatch, readCaseRuns, readEvents, refreshBatchSummary, saveBatch, withBatchLock } from './store.mjs';
33
33
  import { finishEntry, queueForBatch, stopAllQueued } from './queue.mjs';
34
- import { summarizeCaseRuns } from './model.mjs';
35
- import { requestBatchStop, requestCasePrioritize, requestCaseStopInBatch, requeueCase, runBatch } from './runner.mjs';
36
- import { applyBatchWriteback, previewBatchWriteback } from './writeback.mjs';
34
+ import { summarizeCaseRuns, normalizeStudioCase } from './model.mjs';
35
+ import { requestBatchStop, requestCasePrioritize, requestCaseStopInBatch, requeueCase, resumeBatch, runBatch } from './runner.mjs';
36
+ import { applyBatchWriteback, applyDocumentWriteback, previewBatchWriteback, previewDocumentWriteback } from './writeback.mjs';
37
+ import { deleteDocumentRecord, setDocumentArchived } from './documents.mjs';
37
38
  import { appendRunFeedback, getRunFeedback, latestRunFeedback, readRunFeedbacks } from '../lib/run-feedback.mjs';
38
39
 
39
40
  const PREFIX = '/api/uitest/studio';
@@ -90,8 +91,9 @@ function errorResponse(error) {
90
91
  else if (code === 'PROJECT_NOT_FOUND') status = 404;
91
92
  else if (code === 'FLOW_FORBIDDEN') status = 403;
92
93
  else if (code === 'WRITEBACK_BUSY' || code === 'JOB_CONFLICT' || code === 'ACCOUNT_EXISTS') status = 409;
93
- else if (code === 'DOC_SOURCE_MISSING' || code === 'DOC_CASE_FILE_MISSING' || code === 'DOC_KIND_UNSUPPORTED') status = 409;
94
+ else if (code === 'DOC_SOURCE_MISSING' || code === 'DOC_CASE_FILE_MISSING' || code === 'DOC_KIND_UNSUPPORTED' || code === 'DOC_SOURCE_IN_USE' || code === 'DOC_CASE_FILE_STALE' || code === 'DOCS_INVALID') status = 409;
94
95
  else if (code === 'CASE_NOT_ACTIVE' || code === 'CASE_NOT_QUEUED') status = 409;
96
+ else if (code === 'BATCH_ACTIVE' || code === 'BATCH_NOT_STOPPED' || code === 'NOTHING_TO_RESUME') status = 409;
95
97
  else if (code === 'ACCOUNT_NOT_FOUND' || code === 'ACCOUNT_DOC_NOT_FOUND') status = 404;
96
98
  else if (code === 'NO_PICKER' || code === 'PICKER_UNAVAILABLE') status = 501;
97
99
  else if (String(code).startsWith('PROJECT_') || code === 'PICKER_FAILED' || code === 'PICK_PATH_FAILED') status = 400;
@@ -274,6 +276,7 @@ function batchDetail(config, batchId) {
274
276
  summary: summarizeCaseRuns(mergedRuns),
275
277
  queue: batch.queue || null,
276
278
  stages: batch.stages || null,
279
+ distillActive: isDistillActive(config, batchId),
277
280
  cases: merged,
278
281
  events: readEvents(config, batchId, { limit: 200 }),
279
282
  log,
@@ -326,6 +329,8 @@ function handleCase(ctx, request) {
326
329
  }
327
330
  return ok({
328
331
  case: found.case,
332
+ // 执行抽屉按需取用例定义;归一化后前端不必再理解原始表格字段。
333
+ studio: normalizeStudioCase(found.case, { flow, preconditionFlows }),
329
334
  flow: flow ? { name: flow.name, title: flow.title, file: flow.file, tags: flow.tags || [], steps } : null,
330
335
  preconditionFlows: preconditionFlows.map((item) => ({ name: item.name, title: item.title, file: item.file, provides: item.provides || [], cases: item.cases || [] })),
331
336
  });
@@ -438,6 +443,7 @@ async function handleImport(ctx, request) {
438
443
  file: body.file,
439
444
  name: body.name || '',
440
445
  mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
446
+ docId: String(body.docId || ''),
441
447
  });
442
448
  return ok({
443
449
  doc: result.doc,
@@ -456,7 +462,7 @@ async function handleImportUpload(ctx, request) {
456
462
  const { config } = projectFor(ctx, body.project || '');
457
463
  const name = path.basename(String(body.name || 'upload.xlsx'));
458
464
  const ext = path.extname(name).toLowerCase();
459
- if (!['.md', '.markdown', '.txt', '.xlsx', '.json'].includes(ext)) {
465
+ if (!['.md', '.markdown', '.txt', '.xlsx', '.csv', '.json'].includes(ext)) {
460
466
  throw hostError(400, 'IMPORT_UNSUPPORTED', '暂不支持该文件类型:' + ext);
461
467
  }
462
468
  const encoded = String(body.dataBase64 || '');
@@ -473,12 +479,13 @@ async function handleImportUpload(ctx, request) {
473
479
  const safeName = name.replace(/[^\p{L}\p{N}._-]+/gu, '_');
474
480
  const uploadFile = path.join(uploadDir, Date.now() + '-' + safeName);
475
481
  fs.writeFileSync(uploadFile, buffer);
476
- const docName = String(body.docName || path.basename(name, ext));
482
+ const docName = String(body.docName || (body.docId ? '' : path.basename(name, ext)));
477
483
  const result = await importDocument(config, {
478
484
  file: uploadFile,
479
485
  name: docName,
480
486
  originalName: name,
481
487
  mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
488
+ docId: String(body.docId || ''),
482
489
  });
483
490
  return ok({
484
491
  doc: result.doc,
@@ -631,6 +638,27 @@ async function handleStop(ctx, panel, request) {
631
638
  return ok({ stopped: requested, batch: batchDetail(config, id) });
632
639
  }
633
640
 
641
+ async function handleBatchResume(ctx, panel, request) {
642
+ const body = await readBody(request);
643
+ const { config } = projectFor(ctx, body.project || '');
644
+ const id = String(body.id || '');
645
+ if (!id) throw hostError(400, 'BATCH_REQUIRED', '缺少批次 id');
646
+ const busy = activeBatchResponse(config);
647
+ if (busy) return busy;
648
+ const result = await resumeBatch({ config, batchId: id, panel });
649
+ const logger = ctx?.logger || null;
650
+ Promise.resolve()
651
+ .then(() => runBatch({ config, batchId: id, panel, logger }))
652
+ .catch((error) => {
653
+ try {
654
+ patchBatch(config, id, { status: 'failed', error: String(error.message || error) });
655
+ } catch {
656
+ /* 状态更新失败不阻断响应 */
657
+ }
658
+ });
659
+ return ok({ resumed: result.resumed, batch: batchDetail(config, id) });
660
+ }
661
+
634
662
  async function handleBatchDelete(ctx, request) {
635
663
  const body = await readBody(request);
636
664
  const { config } = projectFor(ctx, body.project || '');
@@ -648,8 +676,26 @@ async function handleBatchDistill(ctx, request) {
648
676
  if (['running', 'queued', 'preparing'].includes(String(batch.status || ''))) {
649
677
  throw hostError(409, 'BATCH_RUNNING', '批次正在执行,结束后再沉淀');
650
678
  }
651
- const knowledge = await commitBatchKnowledge(config, id, { logger: ctx?.logger });
652
- 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
+ });
653
699
  }
654
700
 
655
701
  async function handleBackfill(ctx, request) {
@@ -1161,14 +1207,23 @@ function handleShot(ctx, request) {
1161
1207
  const file = url.searchParams.get('file') || '';
1162
1208
  if (!file) throw hostError(400, 'FILE_REQUIRED', '缺少 file');
1163
1209
  const abs = path.isAbsolute(file) ? path.resolve(file) : path.resolve(config.paths.outputDir, file);
1164
- const allowed = [path.resolve(config.projectDir), path.resolve(config.paths.outputDir)];
1165
- if (!allowed.some((root) => abs === root || abs.startsWith(root + path.sep))) {
1166
- throw hostError(403, 'FILE_FORBIDDEN', '只能读取项目目录内的证据文件');
1167
- }
1168
1210
  if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
1169
- const ext = path.extname(abs).toLowerCase();
1170
- const type = ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.webp' ? 'image/webp' : ext === '.md' ? 'text/markdown; charset=utf-8' : 'application/octet-stream';
1171
- return new Response(fs.readFileSync(abs), { headers: { 'content-type': type, 'cache-control': 'no-store' } });
1211
+ // 证据只从输出目录读取;按 realpath 判断,阻止软链接逃逸到账号/文档等配置。
1212
+ let root = path.resolve(config.paths.outputDir);
1213
+ let real = abs;
1214
+ try {
1215
+ root = fs.realpathSync(root);
1216
+ real = fs.realpathSync(abs);
1217
+ } catch {
1218
+ throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
1219
+ }
1220
+ if (real !== root && !real.startsWith(root + path.sep)) {
1221
+ throw hostError(403, 'FILE_FORBIDDEN', '只能读取输出目录内的证据图片');
1222
+ }
1223
+ const ext = path.extname(real).toLowerCase();
1224
+ const types = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
1225
+ if (!types[ext]) throw hostError(403, 'FILE_FORBIDDEN', '只能读取证据图片');
1226
+ return new Response(fs.readFileSync(real), { headers: { 'content-type': types[ext], 'cache-control': 'no-store' } });
1172
1227
  }
1173
1228
 
1174
1229
  async function handleFeedback(ctx, request) {
@@ -1326,6 +1381,55 @@ async function handleDocsReRead(ctx, request) {
1326
1381
  });
1327
1382
  }
1328
1383
 
1384
+ async function handleDocsArchive(ctx, request) {
1385
+ const body = await readBody(request);
1386
+ const { config } = projectFor(ctx, body.project || '');
1387
+ const docId = String(body.docId || '');
1388
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1389
+ const doc = await setDocumentArchived(config, docId, body.archived !== false);
1390
+ return ok({ doc, docs: [doc], snapshot: buildStudioSnapshot(config) });
1391
+ }
1392
+
1393
+ async function handleDocsDelete(ctx, request) {
1394
+ const body = await readBody(request);
1395
+ const { config } = projectFor(ctx, body.project || '');
1396
+ const busy = activeBatchResponse(config);
1397
+ if (busy) return busy;
1398
+ const docId = String(body.docId || '');
1399
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1400
+ const lock = acquireLock(config, 'writeback');
1401
+ try {
1402
+ const doc = await deleteDocumentRecord(config, docId);
1403
+ return ok({
1404
+ doc,
1405
+ deleted: true,
1406
+ docId: doc.id,
1407
+ name: doc.name,
1408
+ caseCount: Array.isArray(doc.caseIds) ? doc.caseIds.length : 0,
1409
+ snapshot: buildStudioSnapshot(config),
1410
+ });
1411
+ } finally {
1412
+ lock.release();
1413
+ }
1414
+ }
1415
+
1416
+ async function handleDocsWriteback(ctx, request) {
1417
+ const body = await readBody(request);
1418
+ const { config } = projectFor(ctx, body.project || '');
1419
+ const busy = activeBatchResponse(config);
1420
+ if (busy) return busy;
1421
+ const docId = String(body.docId || '');
1422
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1423
+ const options = {
1424
+ batchId: String(body.batchId || ''),
1425
+ caseIds: Array.isArray(body.caseIds) ? body.caseIds.map(String) : [],
1426
+ };
1427
+ const result = body.dryRun === true
1428
+ ? await previewDocumentWriteback(config, docId, options)
1429
+ : await applyDocumentWriteback(config, docId, options);
1430
+ return ok({ ...result, snapshot: buildStudioSnapshot(config) });
1431
+ }
1432
+
1329
1433
  export function registerStudioRoutes({ ctx, panel }) {
1330
1434
  if (!ctx?.connection?.fetch || typeof ctx.connection.fetch.register !== 'function') {
1331
1435
  throw new Error('uitest studio routes require the connection service');
@@ -1349,10 +1453,12 @@ export function registerStudioRoutes({ ctx, panel }) {
1349
1453
  ['/plan', ['POST'], (request) => handlePlan(ctx, request)],
1350
1454
  ['/batch', ['GET', 'POST'], (request) => (request.method === 'GET' ? handleBatchGet(ctx, request) : handleCreateBatch(ctx, panel, request))],
1351
1455
  ['/batch/stop', ['POST'], (request) => handleStop(ctx, panel, request)],
1456
+ ['/batch/resume', ['POST'], (request) => handleBatchResume(ctx, panel, request)],
1352
1457
  ['/batch/case/stop', ['POST'], (request) => handleCaseStop(ctx, panel, request)],
1353
1458
  ['/batch/case/prioritize', ['POST'], (request) => handleCasePrioritize(ctx, request)],
1354
1459
  ['/batch/delete', ['POST'], (request) => handleBatchDelete(ctx, request)],
1355
1460
  ['/batch/distill', ['POST'], (request) => handleBatchDistill(ctx, request)],
1461
+ ['/batch/distill/status', ['GET'], (request) => handleBatchDistillStatus(ctx, request)],
1356
1462
  ['/batch/backfill', ['POST'], (request) => handleBackfill(ctx, request)],
1357
1463
  ['/accounts', ['GET'], (request) => handleAccounts(ctx, request)],
1358
1464
  ['/accounts/save', ['POST'], (request) => handleAccountSave(ctx, request)],
@@ -1384,6 +1490,9 @@ export function registerStudioRoutes({ ctx, panel }) {
1384
1490
  ['/shot', ['GET', 'HEAD'], (request) => handleShot(ctx, request)],
1385
1491
  ['/docs', ['GET'], (request) => handleDocs(ctx, request)],
1386
1492
  ['/docs/re-read', ['POST'], (request) => handleDocsReRead(ctx, request)],
1493
+ ['/docs/archive', ['POST'], (request) => handleDocsArchive(ctx, request)],
1494
+ ['/docs/delete', ['POST'], (request) => handleDocsDelete(ctx, request)],
1495
+ ['/docs/writeback', ['POST'], (request) => handleDocsWriteback(ctx, request)],
1387
1496
  ];
1388
1497
  const disposers = [];
1389
1498
  for (const [suffix, methods, handler] of routes) {
package/studio/import.mjs CHANGED
@@ -18,14 +18,16 @@ import {
18
18
  removeDocumentCases,
19
19
  removeDocumentOverrides,
20
20
  } from '../lib/cases-import.mjs';
21
+ import { isMarkdownCaseId } from '../lib/cases-md.mjs';
21
22
  import { UitestError, ensureDir, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
22
- import { findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
23
+ import { assertDocumentSourceAvailable, findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
23
24
  import { dataNeedsFromText, normalizeStudioCase, splitNatural } from './model.mjs';
24
25
  import { readDocs } from './store.mjs';
25
26
  import { acquireWritebackLock, writeDocumentResults } from './writeback.mjs';
26
27
 
27
28
  const TEXT_EXT = new Set(['.md', '.markdown', '.txt']);
28
- const XLSX_EXT = new Set(['.xlsx']);
29
+ const CSV_EXT = new Set(['.csv']);
30
+ const TABLE_EXT = new Set(['.xlsx', '.csv']);
29
31
  const JSON_EXT = new Set(['.json']);
30
32
  const MAX_FILES = 200;
31
33
  const MAX_BYTES = 20 * 1024 * 1024;
@@ -160,6 +162,32 @@ function guessIdFromHeading(heading) {
160
162
  return '';
161
163
  }
162
164
 
165
+ /**
166
+ * 把作者写的编号整理成 cases-md 能读回的形态。
167
+ * 统一大写、下划线转连字符、末段数字补足两位;无法安全修正时返回空串,由调用方生成编号。
168
+ */
169
+ function normalizeCaseId(value) {
170
+ const raw = String(value || '').trim();
171
+ if (!raw) return '';
172
+ if (isMarkdownCaseId(raw)) return raw;
173
+ let token = raw.toUpperCase().replace(/[^A-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');
174
+ if (!token) return '';
175
+ if (/^[0-9]/.test(token)) token = 'CASE-' + token;
176
+ if (isMarkdownCaseId(token)) return token;
177
+ const parts = token.split('-');
178
+ const last = parts[parts.length - 1];
179
+ if (/^\d$/.test(last)) {
180
+ parts[parts.length - 1] = '0' + last;
181
+ const padded = parts.join('-');
182
+ if (isMarkdownCaseId(padded)) return padded;
183
+ }
184
+ return '';
185
+ }
186
+
187
+ function idRenameWarning(from, to) {
188
+ return '用例编号 ' + from + ' 不能被用例库读取,已改为 ' + to;
189
+ }
190
+
163
191
  function titleFromHeading(heading, id) {
164
192
  let title = String(heading || '').trim();
165
193
  if (id && title.startsWith(id)) title = title.slice(id.length).trim();
@@ -187,8 +215,10 @@ function docPrefix(name) {
187
215
  const raw = String(name || 'CASE').toUpperCase();
188
216
  const module = raw.match(/M\d+[A-Z]?/);
189
217
  if (module) return module[0];
190
- const token = raw.replace(/[^A-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').split('-').slice(0, 2).join('-');
191
- return token.slice(0, 12) || 'CASE';
218
+ let token = raw.replace(/[^A-Z0-9]+/g, '-').replace(/^-+|-+$/g, '').split('-').slice(0, 2).join('-');
219
+ token = token.slice(0, 12).replace(/-+$/g, '');
220
+ if (!token) return 'CASE';
221
+ return /^[A-Z]/.test(token) ? token : 'CASE-' + token;
192
222
  }
193
223
 
194
224
  function ensureUniqueId(base, used) {
@@ -255,9 +285,11 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
255
285
  seq += 1;
256
286
  const fields = extractFields(lines, section.heading.index + 1, section.end);
257
287
  const body = section.body;
258
- const explicitId = guessIdFromHeading(section.heading.text);
288
+ const rawExplicitId = guessIdFromHeading(section.heading.text);
289
+ const explicitId = normalizeCaseId(rawExplicitId);
259
290
  const baseId = explicitId || (prefix + '-' + String(seq).padStart(3, '0'));
260
291
  const tcId = ensureUniqueId(baseId, usedIds);
292
+ if (rawExplicitId && rawExplicitId !== tcId) warnings.push(idRenameWarning(rawExplicitId, tcId));
261
293
  let steps = fields.steps || [];
262
294
  let expected = fields.expected || [];
263
295
  if (!steps.length) {
@@ -281,7 +313,7 @@ export function parseNaturalDocument(text, { name = 'CASE', sourcePath = '', use
281
313
  warnings.push('跳过无步骤/预期/前置的段落:' + oneLine(section.heading.text, 60));
282
314
  continue;
283
315
  }
284
- const title = titleFromHeading(section.heading.text, explicitId) || oneLine(section.heading.text, 80) || tcId;
316
+ const title = titleFromHeading(section.heading.text, rawExplicitId) || oneLine(section.heading.text, 80) || tcId;
285
317
  const remarkParts = [...(fields.remark || [])].filter((part) => !/^\s*来源[::]/.test(part));
286
318
  if (sourcePath) remarkParts.push('来源:' + path.relative(projectDir || process.cwd(), sourcePath).split(path.sep).join('/'));
287
319
  const caseItem = {
@@ -346,9 +378,14 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
346
378
  const list = Array.isArray(raw) ? raw : Array.isArray(raw?.cases) ? raw.cases : [];
347
379
  const prefix = docPrefix(idPrefix || name);
348
380
  const cases = [];
381
+ const warnings = [];
349
382
  list.forEach((item, index) => {
350
383
  if (!item || typeof item !== 'object' || Array.isArray(item)) return;
351
- const tcId = ensureUniqueId(String(item.tcId || item.id || prefix + '-' + String(index + 1).padStart(3, '0')), usedIds);
384
+ const rawId = String(item.tcId || item.id || '');
385
+ const explicitId = normalizeCaseId(rawId);
386
+ const baseId = explicitId || prefix + '-' + String(index + 1).padStart(3, '0');
387
+ const tcId = ensureUniqueId(baseId, usedIds);
388
+ if (rawId && rawId !== tcId) warnings.push(idRenameWarning(rawId, tcId));
352
389
  cases.push({
353
390
  seq: item.seq || tcId,
354
391
  tcId,
@@ -366,7 +403,7 @@ function jsonCases(raw, { name, sourcePath, usedIds, docKey = '', docName = '',
366
403
  source: { kind: 'studio-import', file: sourcePath, doc: name, ...(docKey ? { docKey, docName: docName || name } : {}) },
367
404
  });
368
405
  });
369
- return cases;
406
+ return { cases, warnings };
370
407
  }
371
408
 
372
409
  function existingCaseIds(config, { excludeDoc = '', excludeFile = '', excludeDocKey = '', excludeDocKeys = [] } = {}) {
@@ -505,16 +542,41 @@ function compactDiff(diff) {
505
542
  };
506
543
  }
507
544
 
545
+ const importQueues = new Map();
546
+
508
547
  /**
509
548
  * 导入一个文件或目录。
549
+ * 身份预检和随后的用例文件/用例库/注册表写入必须在同一临界区:并发导入都能通过预检时,
550
+ * 后失败者会在落库前已经改过文件与用例库。目录导入的递归走内部实现,避免自锁。
551
+ */
552
+ export function importDocument(config, options = {}) {
553
+ const key = path.resolve(config.projectDir);
554
+ const previous = importQueues.get(key) || Promise.resolve();
555
+ const current = previous.then(() => importDocumentInner(config, options));
556
+ const stored = current.catch(() => {});
557
+ importQueues.set(key, stored);
558
+ stored.finally(() => {
559
+ if (importQueues.get(key) === stored) importQueues.delete(key);
560
+ });
561
+ return current;
562
+ }
563
+
564
+ /**
510
565
  * mode=merge 保留文档中已移除的旧用例;mode=overwrite 以当前文档为准删除旧用例。
511
566
  * @returns {Promise<{doc:object, docs:object[], cases:object[], warnings:object[], diff:object}>}
512
567
  */
513
- export async function importDocument(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
568
+ async function importDocumentInner(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
514
569
  const sourcePath = path.resolve(config.projectDir, String(file || ''));
515
570
  if (!fs.existsSync(sourcePath)) throw new UitestError('路径不存在:' + sourcePath, { code: 'IMPORT_PATH_NOT_FOUND' });
516
571
  const stat = fs.statSync(sourcePath);
572
+ const explicitDoc = findTargetDoc(config, docId);
517
573
  if (stat.isDirectory()) {
574
+ if (docId) {
575
+ throw new UitestError('重新关联源文件只接受单个文件:' + sourcePath, {
576
+ code: 'IMPORT_TARGET_MUST_BE_FILE',
577
+ detail: { docId },
578
+ });
579
+ }
518
580
  const files = scanTextFiles(sourcePath);
519
581
  if (!files.length) throw new UitestError('目录内没有 .md/.markdown/.txt 文件', { code: 'IMPORT_EMPTY_DIR' });
520
582
  const docs = [];
@@ -523,7 +585,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
523
585
  const diff = { added: [], updated: [], unchanged: [], removed: [], missing: [], hidden: [] };
524
586
  for (const item of files) {
525
587
  try {
526
- const result = await importDocument(config, {
588
+ const result = await importDocumentInner(config, {
527
589
  file: item,
528
590
  name: name ? name + '-' + path.basename(item, path.extname(item)) : '',
529
591
  mode,
@@ -540,7 +602,6 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
540
602
  }
541
603
  if (stat.size > MAX_BYTES) throw new UitestError('文件超过 20MB 上限:' + sourcePath, { code: 'IMPORT_TOO_LARGE' });
542
604
  const ext = path.extname(sourcePath).toLowerCase();
543
- const explicitDoc = findTargetDoc(config, docId);
544
605
  const docName = name || explicitDoc?.name || path.basename(sourcePath, ext);
545
606
  const docKey = normalizeDocKey(docName) || normalizeDocKey(path.basename(sourcePath, ext)) || 'document';
546
607
  const overwrite = mode === 'overwrite';
@@ -553,13 +614,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
553
614
  const excludeDocKeys = [...new Set([docKey, ...previousDocKeys])];
554
615
  // 改名时沿用旧文档名的编号前缀,避免自动编号随名称变化产生重复用例。
555
616
  const idPrefix = previousDoc?.name || '';
617
+ // 身份冲突在写任何用例文件/用例库之前拦下:拒绝一次重新关联不能留下半次导入。
618
+ assertDocumentSourceAvailable(config, {
619
+ id: previousDoc?.id || docIdForKey(docKey),
620
+ docKey,
621
+ sourcePath,
622
+ });
556
623
 
557
624
  let cases = [];
558
625
  let warnings = [];
559
626
  let generatedPath = '';
560
627
  let importId = '';
561
628
 
562
- if (XLSX_EXT.has(ext)) {
629
+ if (TABLE_EXT.has(ext)) {
563
630
  const result = importCases(config.projectDir, {
564
631
  file: sourcePath,
565
632
  name: docName,
@@ -567,6 +634,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
567
634
  docName,
568
635
  mode: overwrite ? 'overwrite' : 'merge',
569
636
  replacesDocKeys: previousDocKeys,
637
+ requireMarkdownIds: CSV_EXT.has(ext),
570
638
  });
571
639
  importId = result.imports?.find((item) => item.id && item.count > 0)?.id || result.imports?.[0]?.id || '';
572
640
  const loaded = loadProjectCases(config);
@@ -577,6 +645,12 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
577
645
  source: { ...item.source, docKey, docName },
578
646
  }));
579
647
  warnings = result.warnings || [];
648
+ if (CSV_EXT.has(ext)) {
649
+ // CSV 是导入来源,回写仍落在生成的 Markdown 用例文件上。
650
+ generatedPath = generatedFileFor(config, sourcePath, docName);
651
+ ensureDir(path.dirname(generatedPath));
652
+ fs.writeFileSync(generatedPath, renderCaseMarkdown(cases, { title: docName, sourcePath }) + '\n');
653
+ }
580
654
  } else if (JSON_EXT.has(ext)) {
581
655
  let raw;
582
656
  try {
@@ -586,8 +660,10 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
586
660
  }
587
661
  const target = generatedFileFor(config, sourcePath, docName);
588
662
  const used = existingCaseIds(config, { excludeDoc: docName, excludeFile: target, excludeDocKey: docKey, excludeDocKeys });
589
- cases = jsonCases(raw, { name: docName, sourcePath, usedIds: used, docKey, docName, idPrefix });
590
- if (!cases.length) throw new UitestError('JSON 中没有 cases 数组', { code: 'IMPORT_NO_CASES' });
663
+ const parsed = jsonCases(raw, { name: docName, sourcePath, usedIds: used, docKey, docName, idPrefix });
664
+ if (!parsed.cases.length) throw new UitestError('JSON 中没有 cases 数组', { code: 'IMPORT_NO_CASES' });
665
+ warnings = parsed.warnings;
666
+ cases = parsed.cases;
591
667
  ensureDir(path.dirname(target));
592
668
  fs.writeFileSync(target, renderCaseMarkdown(cases, { title: docName, sourcePath }) + '\n');
593
669
  generatedPath = target;
@@ -611,7 +687,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
611
687
  generatedPath = sourcePath;
612
688
  }
613
689
  } else {
614
- throw new UitestError('暂不支持该格式:' + ext + '(支持 .md/.markdown/.txt/.xlsx/.json)', { code: 'IMPORT_UNSUPPORTED' });
690
+ throw new UitestError('暂不支持该格式:' + ext + '(支持 .md/.markdown/.txt/.xlsx/.csv/.json)', { code: 'IMPORT_UNSUPPORTED' });
615
691
  }
616
692
 
617
693
  if (
@@ -626,6 +702,19 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
626
702
  }
627
703
 
628
704
  const newIds = cases.map((item) => String(item.tcId));
705
+ // CSV 的回写目标是生成的 Markdown 镜像,编号必须和 Markdown 用例一样可被回写解析;
706
+ // 只有 xlsx 直接回写工作簿,不受这个限制。
707
+ if (ext !== '.xlsx') {
708
+ const badIds = newIds.filter((id) => !isMarkdownCaseId(id));
709
+ const loadable = new Set(loadProjectCases(config).cases.map((item) => String(item.tcId)));
710
+ const lostIds = newIds.filter((id) => !loadable.has(id));
711
+ if (badIds.length || lostIds.length) {
712
+ throw new UitestError('用例编号无法被用例库读回:' + [...new Set([...badIds, ...lostIds])].join('、'), {
713
+ code: 'IMPORT_BAD_CASE_ID',
714
+ detail: { ids: [...new Set([...badIds, ...lostIds])], badIds, lostIds },
715
+ });
716
+ }
717
+ }
629
718
 
630
719
  clearCaseTombstones(config.projectDir, newIds);
631
720
  // 同编号用例以文档为准:面板修改与合并保留的旧内容都让位给新文档。
@@ -688,7 +777,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
688
777
  sourcePath,
689
778
  originalName: originalName || previousDoc?.originalName || '',
690
779
  generatedPath,
691
- kind: XLSX_EXT.has(ext) ? 'xlsx' : JSON_EXT.has(ext) ? 'json' : 'markdown',
780
+ kind: TABLE_EXT.has(ext) ? (CSV_EXT.has(ext) ? 'csv' : 'xlsx') : JSON_EXT.has(ext) ? 'json' : 'markdown',
692
781
  importedAt: previousDoc?.importedAt || nowIso(),
693
782
  updatedAt: nowIso(),
694
783
  count: ownedIds.length,
@@ -710,6 +799,8 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
710
799
  version: (Number(existing.version) || 0) + 1,
711
800
  lastRead: existing.lastRead ?? input.lastRead,
712
801
  writeback: existing.writeback ?? input.writeback,
802
+ archived: existing.archived === true,
803
+ archivedAt: existing.archivedAt || '',
713
804
  }
714
805
  : input),
715
806
  });
@@ -743,7 +834,10 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
743
834
  try {
744
835
  const doc = findTargetDoc(config, docId);
745
836
  if (!doc) throw new UitestError('缺少文档 id', { code: 'DOC_NOT_FOUND', detail: { docId } });
746
- const sourcePath = String(doc.sourcePath || '');
837
+ const storedSource = String(doc.sourcePath || '');
838
+ const sourcePath = storedSource
839
+ ? (path.isAbsolute(storedSource) ? path.resolve(storedSource) : path.resolve(config.projectDir, storedSource))
840
+ : '';
747
841
  let sourceReady = false;
748
842
  try {
749
843
  sourceReady = Boolean(sourcePath) && fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile();
@@ -777,14 +871,14 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
777
871
  const warnings = [...(imported.warnings || [])];
778
872
  let resultReapplied = false;
779
873
  const recorded = imported.doc.writeback;
780
- if (reapplyResults && recorded?.batchId && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
874
+ // 重新导读会重建用例文件,按每条用例的最新结果重放;只重放最后一次批次会丢掉更早批次的结果块。
875
+ if (reapplyResults && recorded && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
781
876
  const survivingIds = loadProjectCases(config).cases
782
- .filter((item) => item.source?.docId === imported.doc.id)
877
+ .filter((item) => (item.docId || item.source?.docId) === imported.doc.id)
783
878
  .map((item) => String(item.tcId));
784
879
  try {
785
880
  const reapplied = await writeDocumentResults(config, {
786
881
  docId: imported.doc.id,
787
- batchId: recorded.batchId,
788
882
  caseIds: survivingIds,
789
883
  });
790
884
  if (reapplied.writeback) {
@@ -793,7 +887,7 @@ export async function reReadDocument(config, { docId = '', mode = '', reapplyRes
793
887
  } else {
794
888
  warnings.push({
795
889
  code: 'WRITEBACK_REAPPLY_SKIPPED',
796
- message: '最近一次回写的批次结果已不存在,用例文件已重新导读但未带回结果块',
890
+ message: '最近一次回写的结果已不存在,用例文件已重新导读但未带回结果块',
797
891
  });
798
892
  }
799
893
  } catch (error) {