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/lib/ab.mjs CHANGED
@@ -160,12 +160,13 @@ function parseJson(text) {
160
160
  }
161
161
 
162
162
  export class Ab {
163
- constructor(session, { headed = false, state = null, profile = null } = {}) {
163
+ constructor(session, { headed = false, state = null, profile = null, viewport = null } = {}) {
164
164
  if (!/^[\p{L}\p{N}_-]+$/u.test(session)) throw new Error('非法 session 名:' + session);
165
165
  this.session = session;
166
166
  this.headed = headed;
167
167
  this.state = state;
168
168
  this.profile = profile;
169
+ this.viewport = viewport;
169
170
  this._launched = false;
170
171
  this.closed = true;
171
172
  }
@@ -187,17 +188,29 @@ export class Ab {
187
188
  return g;
188
189
  }
189
190
 
191
+ /** 会话内设置视口;CLI 不支持时静默保留默认视口。 */
192
+ async applyViewport() {
193
+ const width = Number(this.viewport?.width);
194
+ const height = Number(this.viewport?.height);
195
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return;
196
+ try {
197
+ await this.cmd(['set', 'viewport', String(width), String(height)], { timeout: 30000 });
198
+ } catch { /* 旧版 CLI 没有 set viewport */ }
199
+ }
200
+
190
201
  async open(url) {
191
202
  const args = this.launchArgs();
192
203
  this._launched = true;
193
204
  this.closed = false;
205
+ let result = null;
194
206
  try {
195
- return await this.cmd([...args, 'open', url], { timeout: 120000 });
207
+ result = await this.cmd([...args, 'open', url], { timeout: 120000 });
196
208
  } catch (e) {
197
209
  // 泛微首屏常超过 open 的 25s load 等待;导航已发出,交给调用方轮询 DOM
198
- if (/waiting for load state|Timed out/i.test(e.message)) return null;
199
- throw e;
210
+ if (!/waiting for load state|Timed out/i.test(e.message)) throw e;
200
211
  }
212
+ await this.applyViewport();
213
+ return result;
201
214
  }
202
215
 
203
216
  async close() {
package/lib/backfill.mjs CHANGED
@@ -230,9 +230,9 @@ function compactDate(value) {
230
230
  return String(value || '').replace(/-/g, '');
231
231
  }
232
232
 
233
- function outputXlsxPath({ config, date, outputPath }) {
233
+ function outputXlsxPath({ config, date, outputPath, sourceFile }) {
234
234
  if (outputPath) return path.isAbsolute(outputPath) ? outputPath : path.resolve(config.projectDir, outputPath);
235
- const source = config.casesFile;
235
+ const source = sourceFile || config.casesFile;
236
236
  const suffix = config.backfill?.xlsxSuffix || '-执行结果';
237
237
  const ext = path.extname(source) || '.xlsx';
238
238
  const base = path.basename(source, ext);
@@ -286,43 +286,19 @@ async function prepareWorkbookSource(source) {
286
286
  return { file, cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };
287
287
  }
288
288
 
289
- /** 生成回填后的 xlsx(默认写到源文件旁的副本,不覆盖原文档)。 */
290
- export async function applyXlsxResults({
291
- config,
292
- cases = [],
293
- resultsByCase,
294
- date = formatDate(new Date()),
295
- outputPath = '',
296
- dryRun = false,
297
- embedShots = true,
298
- maxShotsPerCase = 4,
299
- } = {}) {
300
- const xlsxCases = cases.filter((item) => item.source?.kind === 'xlsx' && item.source.file && path.resolve(item.source.file) === path.resolve(config.casesFile));
301
- if (!xlsxCases.length) return { path: null, written: false, reason: '没有来自 xlsx 的用例' };
302
- const target = outputXlsxPath({ config, date, outputPath });
303
- if (dryRun) {
304
- const count = xlsxCases.filter((item) => resultForCase(resultsByCase, item)).length;
305
- return { path: target, written: false, dryRun: true, cases: count, shots: 0 };
289
+ /** 面板编辑把来源包成 manual + original 链;xlsx 归属要沿链找到最初的工作簿。 */
290
+ function xlsxOriginOf(caseItem) {
291
+ let current = caseItem?.source || null;
292
+ for (let depth = 0; depth < 4 && current; depth += 1) {
293
+ if (['xlsx', 'import'].includes(current.kind) && current.file) return current;
294
+ current = current.original || null;
306
295
  }
296
+ return null;
297
+ }
307
298
 
308
- const mod = await import('exceljs');
309
- const ExcelJS = mod.default || mod;
310
- const workbook = new ExcelJS.Workbook();
311
- const prepared = await prepareWorkbookSource(config.casesFile);
312
- try {
313
- await workbook.xlsx.readFile(prepared.file);
314
- } finally {
315
- prepared.cleanup();
316
- }
317
- const sheetName = config.cases?.sheet || '';
318
- const worksheet =
319
- (sheetName && workbook.getWorksheet(sheetName)) ||
320
- workbook.worksheets.find((item) => item.name.includes('履约')) ||
321
- workbook.worksheets[0];
322
- if (!worksheet) throw new ConfigError(`xlsx 中没有可回填的工作表:${config.casesFile}`);
299
+ function applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase = 4 } = {}) {
323
300
  const header = findHeaderRow(worksheet);
324
- if (!header) throw new ConfigError(`xlsx 表头缺失(前 10 行未找到「测试功能点」):${config.casesFile}`);
325
-
301
+ if (!header) return { changed: 0, evidenceByName: new Map(), sheet: worksheet.name, headers: null };
326
302
  const resultCol = columnOf(header.texts, [/^测试结果$/, /^执行结果$/, /^结果$/]) || header.texts.length + 1;
327
303
  const timeCol = columnOf(header.texts, [/^执行时间$/]) || Math.max(resultCol, header.texts.length) + 1;
328
304
  const noteCol = columnOf(header.texts, [/^执行备注$/, /^实测观察$/]) || Math.max(timeCol, header.texts.length) + 1;
@@ -349,15 +325,13 @@ export async function applyXlsxResults({
349
325
  const seqCol = columnOf(header.texts, [/^序号$/]);
350
326
  const tcCol = columnOf(header.texts, [/^用例编号$/, /^TC编号$/]);
351
327
  const remarkCol = columnOf(header.texts, [/^备注$/]);
352
- const functionCol = columnOf(header.texts, [/测试功能点|用例名称|测试点/]);
353
- const priorityCol = columnOf(header.texts, [/^优先级$/]);
354
328
  const rowCache = new Map();
355
329
  const maxRow = worksheet.rowCount;
356
330
  for (let rowNumber = header.rowNumber + 1; rowNumber <= maxRow; rowNumber += 1) {
357
331
  const seq = seqCol ? String(worksheet.getCell(rowNumber, seqCol).value ?? '').trim() : '';
358
332
  const tc = tcCol ? String(worksheet.getCell(rowNumber, tcCol).value ?? '').trim() : '';
359
333
  const remark = remarkCol ? String(worksheet.getCell(rowNumber, remarkCol).value ?? '').trim() : '';
360
- for (const caseItem of xlsxCases) {
334
+ for (const caseItem of sheetCases) {
361
335
  const id = String(caseItem.tcId);
362
336
  if (!resultForCase(resultsByCase, caseItem)) continue;
363
337
  if ((tc && tc === id) || (remark && remark.includes(id)) || (seq && seq === String(caseItem.seq))) {
@@ -365,13 +339,16 @@ export async function applyXlsxResults({
365
339
  }
366
340
  }
367
341
  }
368
- for (const caseItem of xlsxCases) {
369
- if (caseItem.source?.rowNumber && !rowCache.has(String(caseItem.tcId))) rowCache.set(String(caseItem.tcId), caseItem.source.rowNumber);
342
+ for (const caseItem of sheetCases) {
343
+ const origin = xlsxOriginOf(caseItem);
344
+ const rowNumber = origin?.rowNumber || caseItem.source?.rowNumber;
345
+ if (rowNumber && !rowCache.has(String(caseItem.tcId))) rowCache.set(String(caseItem.tcId), rowNumber);
370
346
  }
371
347
 
372
348
  const evidenceByName = new Map();
349
+ const writtenIds = [];
373
350
  let changed = 0;
374
- for (const caseItem of xlsxCases) {
351
+ for (const caseItem of sheetCases) {
375
352
  const id = String(caseItem.tcId);
376
353
  const result = resultForCase(resultsByCase, caseItem);
377
354
  if (!result) continue;
@@ -386,8 +363,87 @@ export async function applyXlsxResults({
386
363
  setCell(worksheet, rowNumber, batchCol, result.batchId || '');
387
364
  setCell(worksheet, rowNumber, keyShotCol, evidence.key.map((item) => path.basename(item.absolute)).join('; '));
388
365
  setCell(worksheet, rowNumber, errorShotCol, evidence.error.map((item) => path.basename(item.absolute)).join('; '));
366
+ writtenIds.push(id);
389
367
  changed += 1;
390
368
  }
369
+ return {
370
+ changed,
371
+ writtenIds,
372
+ evidenceByName,
373
+ sheet: worksheet.name,
374
+ headers: { resultCol, timeCol, noteCol, batchCol, keyShotCol, errorShotCol },
375
+ };
376
+ }
377
+
378
+ /**
379
+ * 生成回填后的 xlsx(默认写到源文件旁的副本,不覆盖原文档)。
380
+ * sourceFile/outputPath 让导入文档从自己的源工作簿生成独立执行副本;cases 按 source.sheet 分表写回。
381
+ */
382
+ export async function applyXlsxResults({
383
+ config,
384
+ cases = [],
385
+ resultsByCase,
386
+ sourceFile = '',
387
+ date = formatDate(new Date()),
388
+ outputPath = '',
389
+ dryRun = false,
390
+ embedShots = true,
391
+ maxShotsPerCase = 4,
392
+ } = {}) {
393
+ const source = sourceFile
394
+ ? (path.isAbsolute(sourceFile) ? sourceFile : path.resolve(config.projectDir, String(sourceFile)))
395
+ : config.casesFile;
396
+ const xlsxCases = [];
397
+ for (const item of cases) {
398
+ const origin = xlsxOriginOf(item);
399
+ if (!origin) continue;
400
+ if (path.resolve(origin.file) !== path.resolve(source)) continue;
401
+ xlsxCases.push(item);
402
+ }
403
+ if (!xlsxCases.length) return { path: null, written: false, reason: '没有来自 xlsx 的用例' };
404
+ const target = outputXlsxPath({ config, date, outputPath, sourceFile: source });
405
+ if (dryRun) {
406
+ const count = xlsxCases.filter((item) => resultForCase(resultsByCase, item)).length;
407
+ return { path: target, written: false, dryRun: true, cases: count, shots: 0, sourceFile: source };
408
+ }
409
+
410
+ const mod = await import('exceljs');
411
+ const ExcelJS = mod.default || mod;
412
+ const workbook = new ExcelJS.Workbook();
413
+ const prepared = await prepareWorkbookSource(source);
414
+ try {
415
+ await workbook.xlsx.readFile(prepared.file);
416
+ } finally {
417
+ prepared.cleanup();
418
+ }
419
+ const fallbackSheet = () => (config.cases?.sheet && workbook.getWorksheet(config.cases.sheet))
420
+ || workbook.worksheets.find((item) => item.name.includes('履约'))
421
+ || workbook.worksheets[0];
422
+ const bySheet = new Map();
423
+ for (const caseItem of xlsxCases) {
424
+ const sheetName = String(xlsxOriginOf(caseItem)?.sheet || '');
425
+ if (!bySheet.has(sheetName)) bySheet.set(sheetName, []);
426
+ bySheet.get(sheetName).push(caseItem);
427
+ }
428
+ const sheets = [];
429
+ const written = new Set();
430
+ const evidenceByName = new Map();
431
+ let changed = 0;
432
+ let firstHeaders = null;
433
+ for (const [sheetName, sheetCases] of bySheet) {
434
+ const worksheet = sheetName ? workbook.getWorksheet(sheetName) : fallbackSheet();
435
+ if (!worksheet) continue;
436
+ const applied = applySheetCases(config, worksheet, sheetCases, resultsByCase, { maxShotsPerCase });
437
+ if (!applied.headers) continue;
438
+ firstHeaders = firstHeaders || applied.headers;
439
+ changed += applied.changed;
440
+ for (const id of applied.writtenIds) written.add(String(id));
441
+ for (const [id, evidence] of applied.evidenceByName) evidenceByName.set(id, evidence);
442
+ sheets.push({ sheet: applied.sheet, cases: applied.changed });
443
+ }
444
+ if (!sheets.length) throw new ConfigError(`xlsx 中没有可回填的工作表:${source}`);
445
+ // 摘要和截图只列真正写进用例表的行;找不到工作表或表头的用例不能出现在执行副本里。
446
+ const summaryCases = xlsxCases.filter((item) => written.has(String(item.tcId)));
391
447
 
392
448
  // 摘要表
393
449
  const oldSummary = workbook.getWorksheet('执行摘要');
@@ -407,7 +463,7 @@ export async function applyXlsxResults({
407
463
  ];
408
464
  summary.getRow(1).font = { bold: true };
409
465
  summary.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFE7E6E6' } };
410
- const summaryRows = xlsxCases
466
+ const summaryRows = summaryCases
411
467
  .map((caseItem) => ({ caseItem, result: resultForCase(resultsByCase, caseItem) }))
412
468
  .filter((item) => item.result)
413
469
  .map(({ caseItem, result }) => {
@@ -438,7 +494,7 @@ export async function applyXlsxResults({
438
494
  { width: 70 },
439
495
  ];
440
496
  let cursor = 1;
441
- for (const caseItem of xlsxCases) {
497
+ for (const caseItem of summaryCases) {
442
498
  const id = String(caseItem.tcId);
443
499
  const result = resultForCase(resultsByCase, caseItem);
444
500
  if (!result) continue;
@@ -478,8 +534,10 @@ export async function applyXlsxResults({
478
534
  written: true,
479
535
  cases: changed,
480
536
  shots: shotsAdded,
481
- sheet: worksheet.name,
482
- headers: { resultCol, timeCol, noteCol, batchCol, keyShotCol, errorShotCol },
537
+ sheet: sheets[0].sheet,
538
+ sheets,
539
+ sourceFile: source,
540
+ headers: firstHeaders,
483
541
  };
484
542
  }
485
543
 
@@ -181,7 +181,7 @@ export async function launchSession(config, { headless, logger, storageState = t
181
181
  if (profileDir) ensureDir(profileDir);
182
182
  const { needsSeed, useState } = profileSeedPlan({ storageState, stateFile, profileDir });
183
183
  const name = sessionName || `uitest-${timeStamp()}-${Math.random().toString(36).slice(2, 6)}`;
184
- const abFactory = () => new Ab(name, { state: useState ? stateFile : null, headed: !headless, profile: profileDir || null });
184
+ const abFactory = () => new Ab(name, { state: useState ? stateFile : null, headed: !headless, profile: profileDir || null, viewport: config.browser?.viewport });
185
185
  await prepareProfile(profileDir, name, logger);
186
186
  const base = config.baseUrl ? String(config.baseUrl).replace(/\/+$/, '') + '/' : 'about:blank';
187
187
  const ab = await startAb({ ab: abFactory(), abFactory, name, profileDir, logger, url: base });
@@ -211,7 +211,7 @@ export async function attachSession(config, { session = 'uitest-do', headless, l
211
211
  const profileDir = profileOf(config, profile);
212
212
  if (profileDir) ensureDir(profileDir);
213
213
  const { needsSeed, useState } = profileSeedPlan({ storageState, stateFile, profileDir });
214
- const abFactory = () => new Ab(session, { state: useState ? stateFile : null, headed: !headless, profile: profileDir || null });
214
+ const abFactory = () => new Ab(session, { state: useState ? stateFile : null, headed: !headless, profile: profileDir || null, viewport: config.browser?.viewport });
215
215
  let ab = abFactory();
216
216
  let url = null;
217
217
  try { url = await ab.url(); } catch { url = null; }
@@ -224,6 +224,7 @@ export async function attachSession(config, { session = 'uitest-do', headless, l
224
224
  } else {
225
225
  // Ab 构造时默认 closed=true;url() 能返回有效地址才说明复用的会话还活着,页面观察靠这个标记判断是否继续。
226
226
  ab.closed = false;
227
+ await ab.applyViewport();
227
228
  }
228
229
  const s = { ab, config, pageErrors: [], _url: url, sessionName: session };
229
230
  s.page = pageShim(s);
package/lib/browser.mjs CHANGED
@@ -57,7 +57,7 @@ export async function launchSession(config, { headless, logger, storageState = t
57
57
  const statePath = config.paths.stateFile;
58
58
  const stateUsed = Boolean(storageState && statePath && fs.existsSync(statePath));
59
59
  const contextOptions = {
60
- viewport: config.browser.viewport || { width: 1600, height: 1000 },
60
+ viewport: config.browser.viewport || { width: 1920, height: 1280 },
61
61
  locale: config.browser.locale || 'zh-CN',
62
62
  timezoneId: config.browser.timezoneId || 'Asia/Shanghai',
63
63
  ignoreHTTPSErrors: true,
@@ -1,5 +1,6 @@
1
1
  // 导入 xlsx 用例到项目 .uitest/cases/imported.json:多 sheet 自动解析、按 tcId 合并、目录批量、原子写。
2
2
  // 不修改 config.cases.xlsx;Host 读取时再把 imported 用例合并到 config 用例之上。
3
+ import crypto from 'node:crypto';
3
4
  import fs from 'node:fs';
4
5
  import path from 'node:path';
5
6
 
@@ -150,13 +151,15 @@ export function loadProjectCases(config) {
150
151
  deletedCaseIds: importedStore.deletedCaseIds || [],
151
152
  });
152
153
  const docs = readDocsIndex(config?.projectDir || process.cwd());
154
+ const linkIndex = documentLinkIndex(docs, config?.projectDir || process.cwd());
153
155
  return {
154
- cases: merged.cases.map((item) => enrichDocKey(item, docs, config?.projectDir || process.cwd())),
156
+ cases: merged.cases.map((item) => linkCaseToDocument(item, linkIndex)),
155
157
  configCount: configCases.length,
156
158
  markdownCount: markdown.cases.length,
157
159
  markdownFiles: markdown.files.length,
158
160
  importedCount: merged.importedCount,
159
161
  deletedCount: merged.deletedCount,
162
+ deletedCaseIds: importedStore.deletedCaseIds || [],
160
163
  file,
161
164
  warnings,
162
165
  };
@@ -173,52 +176,133 @@ function readDocsIndex(projectDir) {
173
176
  }
174
177
  }
175
178
 
176
- /** 旧 imported 条目可能没有 docKey;用 docs.json 的 importId/文件路径补出归属。 */
177
- function docOwnerIndex(projectDir) {
178
- const byImportId = new Map();
179
- const byFile = new Map();
180
- for (const doc of readDocsIndex(projectDir)) {
181
- const key = doc.docKey || normalizeDocKey(doc.name);
182
- if (!key) continue;
183
- for (const importId of doc.importIds || []) if (importId) byImportId.set(importId, key);
184
- for (const value of [doc.sourcePath, doc.generatedPath]) {
179
+ /** 文档 identity 只由首次导入的 docKey 决定,改名不重算。 */
180
+ export function docIdForKey(docKey) {
181
+ return 'doc-' + crypto.createHash('sha1').update(String(docKey || '')).digest('hex').slice(0, 10);
182
+ }
183
+
184
+ function uniqueStrings(values) {
185
+ return [...new Set((Array.isArray(values) ? values : []).map((item) => String(item || '').trim()).filter(Boolean))];
186
+ }
187
+
188
+ /** 旧记录缺少 id/caseIds 等字段时在内存补齐,旧文件不需要迁移。 */
189
+ export function normalizeDocumentRecord(raw = {}) {
190
+ const docKey = raw.docKey || normalizeDocKey(raw.name || '');
191
+ const caseIds = uniqueStrings(raw.caseIds);
192
+ return {
193
+ ...raw,
194
+ id: raw.id || docIdForKey(docKey || raw.sourcePath || raw.name || 'document'),
195
+ docKey,
196
+ name: raw.name || docKey,
197
+ kind: raw.kind || '',
198
+ sourcePath: raw.sourcePath || '',
199
+ originalName: raw.originalName || '',
200
+ generatedPath: raw.generatedPath || '',
201
+ caseIds,
202
+ importIds: uniqueStrings(raw.importIds),
203
+ count: caseIds.length || Number(raw.count) || 0,
204
+ lastCount: Number.isFinite(Number(raw.lastCount)) ? Number(raw.lastCount) : caseIds.length,
205
+ mode: raw.mode === 'overwrite' ? 'overwrite' : 'merge',
206
+ version: Number(raw.version) || 1,
207
+ diff: raw.diff || null,
208
+ digests: raw.digests && typeof raw.digests === 'object' ? raw.digests : {},
209
+ importedAt: raw.importedAt || '',
210
+ updatedAt: raw.updatedAt || raw.importedAt || '',
211
+ warnings: Array.isArray(raw.warnings) ? raw.warnings : [],
212
+ lastRead: raw.lastRead || null,
213
+ writeback: raw.writeback || null,
214
+ };
215
+ }
216
+
217
+ function pushIndex(map, key, doc) {
218
+ if (!key) return;
219
+ const list = map.get(key) || [];
220
+ if (!list.includes(doc)) list.push(doc);
221
+ map.set(key, list);
222
+ }
223
+
224
+ /** 一次导入/加载共用的文档解析索引;一个 key 命中多个文档时视为歧义。 */
225
+ export function documentLinkIndex(docs = [], projectDir = process.cwd()) {
226
+ const index = {
227
+ docs: [],
228
+ byId: new Map(),
229
+ byKey: new Map(),
230
+ byImportId: new Map(),
231
+ byFile: new Map(),
232
+ projectDir,
233
+ };
234
+ for (const raw of Array.isArray(docs) ? docs : []) {
235
+ const doc = normalizeDocumentRecord(raw);
236
+ index.docs.push(doc);
237
+ if (doc.id) index.byId.set(doc.id, doc);
238
+ pushIndex(index.byKey, doc.docKey, doc);
239
+ pushIndex(index.byKey, normalizeDocKey(doc.name), doc);
240
+ for (const importId of doc.importIds) pushIndex(index.byImportId, importId, doc);
241
+ for (const value of [doc.generatedPath, doc.sourcePath]) {
185
242
  if (!value) continue;
186
- byFile.set(path.isAbsolute(value) ? path.resolve(value) : path.resolve(projectDir, value), key);
243
+ pushIndex(index.byFile, path.isAbsolute(value) ? path.resolve(value) : path.resolve(projectDir, value), doc);
187
244
  }
188
245
  }
189
- return { byImportId, byFile, projectDir };
190
- }
191
-
192
- function docKeyForSource(source, index) {
193
- if (!source || !index) return '';
194
- const importId = source.importId || source.original?.importId;
195
- if (importId && index.byImportId.has(importId)) return index.byImportId.get(importId);
196
- const raw = source.file || source.original?.file;
197
- if (!raw) return '';
198
- const file = path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(index.projectDir, raw);
199
- return index.byFile.get(file) || '';
200
- }
201
-
202
- /** Markdown/json 生成的用例来源只带文件路径;按 docs.json 补回 docKey,保证手工修改可追溯。 */
203
- function enrichDocKey(item, docs, projectDir) {
204
- const source = item?.source;
205
- if (!source?.file || source.docKey || !docs.length) return item;
206
- const file = path.resolve(source.file);
207
- const resolvePath = (value) => (path.isAbsolute(value) ? value : path.resolve(projectDir, value));
208
- const doc = docs.find((entry) => {
209
- const generated = entry.generatedPath ? resolvePath(entry.generatedPath) : '';
210
- const original = entry.sourcePath ? resolvePath(entry.sourcePath) : '';
211
- return (generated && path.resolve(generated) === file) || (original && path.resolve(original) === file);
212
- });
213
- if (!doc) return item;
214
- return {
215
- ...item,
216
- source: {
217
- ...source,
218
- docKey: doc.docKey || normalizeDocKey(doc.name),
219
- docName: doc.name || doc.docName || '',
246
+ return index;
247
+ }
248
+
249
+ function sourceChain(source) {
250
+ const chain = [];
251
+ let current = source || null;
252
+ for (let depth = 0; depth < 3 && current; depth += 1) {
253
+ chain.push(current);
254
+ current = current.original || null;
255
+ }
256
+ return chain;
257
+ }
258
+
259
+ function resolveIndexLevel(chain, resolve) {
260
+ const found = [];
261
+ for (const source of chain) {
262
+ for (const doc of resolve(source) || []) if (!found.includes(doc)) found.push(doc);
263
+ }
264
+ if (found.length > 1) return { doc: null, ambiguous: true };
265
+ return { doc: found[0] || null, ambiguous: false };
266
+ }
267
+
268
+ /**
269
+ * 按持久 id → importId → 文件路径 → docKey 的顺序解析归属。
270
+ * 任一层命中多个文档都判为未归属,绝不猜一个文档。
271
+ */
272
+ export function linkCaseToDocument(caseItem, index) {
273
+ const source = caseItem?.source;
274
+ if (!source || !index) return caseItem;
275
+ const chain = sourceChain(source);
276
+ const levels = [
277
+ (item) => (item.docId ? [index.byId.get(String(item.docId))].filter(Boolean) : []),
278
+ (item) => index.byImportId.get(String(item.importId || '')) || [],
279
+ (item) => {
280
+ if (!item.file) return [];
281
+ const file = path.isAbsolute(item.file) ? path.resolve(item.file) : path.resolve(index.projectDir, item.file);
282
+ return index.byFile.get(file) || [];
220
283
  },
221
- };
284
+ (item) => {
285
+ const key = normalizeDocKey(item.docKey || item.docName);
286
+ return key ? index.byKey.get(key) || [] : [];
287
+ },
288
+ ];
289
+ for (const resolve of levels) {
290
+ const hit = resolveIndexLevel(chain, resolve);
291
+ if (hit.ambiguous) return caseItem;
292
+ if (!hit.doc) continue;
293
+ const doc = hit.doc;
294
+ return {
295
+ ...caseItem,
296
+ source: {
297
+ ...source,
298
+ docId: doc.id,
299
+ docKey: doc.docKey || normalizeDocKey(doc.name),
300
+ docName: doc.name || '',
301
+ docKind: doc.kind || '',
302
+ },
303
+ };
304
+ }
305
+ return caseItem;
222
306
  }
223
307
 
224
308
  export function importedCasesFile(project) {
@@ -727,7 +811,7 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
727
811
  }
728
812
 
729
813
  const store = loadImportedCases(project);
730
- const ownerIndex = docOwnerIndex(projectDir);
814
+ const linkIndex = documentLinkIndex(readDocsIndex(projectDir), projectDir);
731
815
  const casesById = new Map(store.cases.map((item) => [String(item.tcId), item]));
732
816
  const seenBatch = new Set();
733
817
  const imports = [];
@@ -808,10 +892,11 @@ export function importCases(project, { file, files, dir, sheet, name, docKey = '
808
892
  seenBatch.add(tcId);
809
893
  if (casesById.has(tcId)) {
810
894
  const existing = casesById.get(tcId);
811
- const existingDocKey = existing?.source?.docKey
895
+ const linkedExisting = linkCaseToDocument(existing, linkIndex);
896
+ const existingDocKey = linkedExisting?.source?.docKey
897
+ || existing?.source?.docKey
812
898
  || existing?.source?.original?.docKey
813
899
  || existing?.source?.original?.original?.docKey
814
- || docKeyForSource(existing?.source, ownerIndex)
815
900
  || '';
816
901
  if (docKey && existingDocKey && existingDocKey !== docKey && !replaceKeys.has(existingDocKey)) {
817
902
  importRecord.conflicts += 1;
package/lib/config.mjs CHANGED
@@ -13,7 +13,7 @@ export const DEFAULT_CONFIG = {
13
13
  browser: {
14
14
  executablePath: '',
15
15
  headless: true,
16
- viewport: { width: 1600, height: 1000 },
16
+ viewport: { width: 1920, height: 1280 },
17
17
  args: ['--no-sandbox', '--disable-dev-shm-usage'],
18
18
  locale: 'zh-CN',
19
19
  timezoneId: 'Asia/Shanghai',
@@ -58,7 +58,7 @@ export function configTemplate(overrides = {}) {
58
58
  browser: {
59
59
  executablePath: '/usr/bin/chromium',
60
60
  headless: true,
61
- viewport: { width: 1600, height: 1000 },
61
+ viewport: { width: 1920, height: 1280 },
62
62
  args: ['--no-sandbox', '--disable-dev-shm-usage'],
63
63
  locale: 'zh-CN',
64
64
  timezoneId: 'Asia/Shanghai',
@@ -299,6 +299,22 @@ export async function centralIngestFast(config, { episodes = [], groupId = '' }
299
299
  };
300
300
  }
301
301
 
302
+ /** 自动管线状态;轮询用短超时,失败返回 ok:false 不抛出。 */
303
+ export async function centralPipelineStatus(config, { groupId = '' } = {}) {
304
+ const central = centralConfig(config);
305
+ const group = String(groupId || central.groupId);
306
+ const base = { enabled: central.enabled, groupId: group };
307
+ if (!central.enabled) return { ok: false, ...base, error: '中心知识库未启用' };
308
+ try {
309
+ const payload = await requestJson(config, '/pipeline/status?group_id=' + encodeURIComponent(group), {
310
+ timeoutMs: Math.min(central.searchTimeoutMs, 15000),
311
+ });
312
+ return { ...base, ...payload, ok: payload?.ok !== false };
313
+ } catch (error) {
314
+ return { ok: false, ...base, error: String(error.message || error), code: error.code || '' };
315
+ }
316
+ }
317
+
302
318
  /** 把提取结果送入 Graphiti 做实体/关系抽取,补齐语义检索。 */
303
319
  export async function centralSemanticIndex(config, { limit = 5, groupId = '' } = {}) {
304
320
  const central = centralConfig(config);
package/lib/xlsx.mjs CHANGED
@@ -595,14 +595,14 @@ export const HEADER_ALIASES = {
595
595
  module: ['模块', '所属模块', '业务模块'],
596
596
  l1: ['一级功能', '场景', '一级模块', '功能模块'],
597
597
  l2: ['二级功能', '子功能', '功能点分组'],
598
- functionPoint: ['测试功能点', '用例名称', '测试点', '用例标题', '标题', '测试功能'],
598
+ functionPoint: ['测试功能点', '用例名称', '测试点', '用例标题', '标题', '测试功能', '测试内容', '用例描述', '测试描述'],
599
599
  precondition: ['前提条件', '前置条件', '预置条件'],
600
- steps: ['操作步骤', '执行步骤', '步骤'],
600
+ steps: ['操作步骤', '执行步骤', '步骤', '测试步骤'],
601
601
  expected: ['预期结果', '期望结果', '预期'],
602
- testResult: ['测试结果', '执行结果', '结果'],
602
+ testResult: ['测试结果', '执行结果', '结果', '实际结果'],
603
603
  remark: ['备注', '说明', '备注说明'],
604
604
  automationClass: ['可自动化', '是否可自动化', '自动化分类', '自动化等级', '自动化'],
605
- type: ['用例类型', '类型'],
605
+ type: ['用例类型', '类型', '测试类型'],
606
606
  page: ['页面', '关联页面', '所在页面'],
607
607
  };
608
608
 
@@ -710,13 +710,15 @@ export function buildCases({
710
710
  { sheet, file },
711
711
  );
712
712
  }
713
- if (header.mapping.functionPoint === undefined) {
713
+ if (header.mapping.functionPoint === undefined
714
+ && header.mapping.l1 === undefined
715
+ && header.mapping.l2 === undefined) {
714
716
  const actual = [...(rows.get(header.rowNumber)?.keys() || [])]
715
717
  .sort((a, b) => a - b)
716
718
  .map((col) => `${indexToCol(col)}=${cellPlainText(rows.get(header.rowNumber)?.get(col))}`)
717
719
  .join(' | ');
718
720
  throw new XlsxError(
719
- `表头缺失:工作表「${sheet}」第 ${header.rowNumber} 行未找到「测试功能点」列;实际表头:${actual || '(空行)'}`,
721
+ `表头缺失:工作表「${sheet}」第 ${header.rowNumber} 行未找到「测试功能点」列(也没有一级/二级功能列);实际表头:${actual || '(空行)'}`,
720
722
  { sheet, headerRow: header.rowNumber },
721
723
  );
722
724
  }
@@ -736,12 +738,14 @@ export function buildCases({
736
738
  const l1Order = new Map();
737
739
  const cases = [];
738
740
  for (const rowNumber of dataRowNumbers) {
739
- const functionPoint = readCell(rowNumber, 'functionPoint');
740
741
  const caseIdRaw = readCell(rowNumber, 'caseId');
741
742
  const tcIdRaw = readCell(rowNumber, 'tcId');
743
+ const l1 = readCell(rowNumber, 'l1');
744
+ const l2 = readCell(rowNumber, 'l2');
745
+ // 「测试内容」等描述列已并入 functionPoint;都没有时退回一级/二级功能
746
+ const functionPoint = readCell(rowNumber, 'functionPoint') || [l1, l2].filter(Boolean).join('/');
742
747
  if (!functionPoint && !caseIdRaw && !tcIdRaw) continue;
743
748
 
744
- const l1 = readCell(rowNumber, 'l1');
745
749
  if (l1 && !l1Order.has(l1)) l1Order.set(l1, l1Order.size);
746
750
  const seq = /^\d+$/.test(caseIdRaw) ? Number(caseIdRaw) : cases.length + 1;
747
751
  const remark = readCell(rowNumber, 'remark');
@@ -757,8 +761,9 @@ export function buildCases({
757
761
  priority: readCell(rowNumber, 'priority'),
758
762
  module: readCell(rowNumber, 'module'),
759
763
  l1,
760
- l2: readCell(rowNumber, 'l2'),
764
+ l2,
761
765
  functionPoint,
766
+ type: readCell(rowNumber, 'type'),
762
767
  precondition: readCell(rowNumber, 'precondition'),
763
768
  steps: readCell(rowNumber, 'steps'),
764
769
  expected: readCell(rowNumber, 'expected'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-uitest",
3
- "version": "2.1.3",
3
+ "version": "2.2.0",
4
4
  "type": "module",
5
5
  "description": "Test Studio for DSH: import cases into natural-language tests, seed preconditions, run flow and Agent cases concurrently with agent-browser, archive evidence, write back by batch, and accumulate reusable flows and page knowledge.",
6
6
  "icon": "./icon.svg",