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/lib/csv.mjs
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// CSV 用例解析:把逗号/制表符分隔的行映射成与 xlsx 相同的 rows 结构,
|
|
2
|
+
// 表头识别、列别名与字段归一化全部复用 xlsx.mjs 的 buildCases。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { UitestError } from './util.mjs';
|
|
7
|
+
import { buildCases, indexToCol } from './xlsx.mjs';
|
|
8
|
+
|
|
9
|
+
export class CsvError extends UitestError {
|
|
10
|
+
constructor(message, detail = {}) {
|
|
11
|
+
super(message, { code: 'CSV_ERROR', detail });
|
|
12
|
+
this.name = 'CsvError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Excel 在中文 Windows 上导出的 CSV 常见 GB18030;UTF-8 严格解码失败才回退。 */
|
|
17
|
+
function stripBom(text) {
|
|
18
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function decodeText(buffer) {
|
|
22
|
+
try {
|
|
23
|
+
return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(buffer));
|
|
24
|
+
} catch {
|
|
25
|
+
try {
|
|
26
|
+
return stripBom(new TextDecoder('gb18030').decode(buffer));
|
|
27
|
+
} catch {
|
|
28
|
+
return stripBom(new TextDecoder('utf-8').decode(buffer));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function countOutsideQuotes(line, delimiter) {
|
|
34
|
+
let quoted = false;
|
|
35
|
+
let count = 0;
|
|
36
|
+
for (let i = 0; i < line.length; i += 1) {
|
|
37
|
+
const ch = line[i];
|
|
38
|
+
if (ch === '"') {
|
|
39
|
+
if (quoted && line[i + 1] === '"') {
|
|
40
|
+
i += 1;
|
|
41
|
+
} else {
|
|
42
|
+
quoted = !quoted;
|
|
43
|
+
}
|
|
44
|
+
} else if (ch === delimiter && !quoted) {
|
|
45
|
+
count += 1;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return count;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 取前若干条顶层记录,跳过引号内换行,避免前言行或字段内容干扰分隔符判断。 */
|
|
52
|
+
function topLevelLines(text, limit = 20) {
|
|
53
|
+
const lines = [];
|
|
54
|
+
let current = '';
|
|
55
|
+
let quoted = false;
|
|
56
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
57
|
+
const ch = text[i];
|
|
58
|
+
if (ch === '"') {
|
|
59
|
+
if (quoted && text[i + 1] === '"') {
|
|
60
|
+
current += '""';
|
|
61
|
+
i += 1;
|
|
62
|
+
} else {
|
|
63
|
+
quoted = !quoted;
|
|
64
|
+
current += ch;
|
|
65
|
+
}
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!quoted && (ch === '\n' || ch === '\r')) {
|
|
69
|
+
if (ch === '\r' && text[i + 1] === '\n') i += 1;
|
|
70
|
+
if (current.trim()) lines.push(current);
|
|
71
|
+
current = '';
|
|
72
|
+
if (lines.length >= limit) return lines;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
current += ch;
|
|
76
|
+
}
|
|
77
|
+
if (current.trim() && lines.length < limit) lines.push(current);
|
|
78
|
+
return lines;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function detectDelimiter(text) {
|
|
82
|
+
const lines = topLevelLines(text);
|
|
83
|
+
let best = ',';
|
|
84
|
+
let bestLines = 0;
|
|
85
|
+
let bestCount = 0;
|
|
86
|
+
for (const candidate of [',', '\t', ';']) {
|
|
87
|
+
let lineCount = 0;
|
|
88
|
+
let total = 0;
|
|
89
|
+
for (const line of lines) {
|
|
90
|
+
const count = countOutsideQuotes(line, candidate);
|
|
91
|
+
if (count > 0) lineCount += 1;
|
|
92
|
+
total += count;
|
|
93
|
+
}
|
|
94
|
+
if (lineCount > bestLines || (lineCount === bestLines && total > bestCount)) {
|
|
95
|
+
best = candidate;
|
|
96
|
+
bestLines = lineCount;
|
|
97
|
+
bestCount = total;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return best;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* RFC 4180 风格解析:双引号包裹字段,字段内允许分隔符与换行,"" 表示一个引号。
|
|
105
|
+
* 返回二维字符串数组,行内保留空字段。
|
|
106
|
+
*/
|
|
107
|
+
export function parseCsv(text, { delimiter } = {}) {
|
|
108
|
+
const split = delimiter || detectDelimiter(text);
|
|
109
|
+
const rows = [];
|
|
110
|
+
let row = [];
|
|
111
|
+
let field = '';
|
|
112
|
+
let quoted = false;
|
|
113
|
+
const endField = () => {
|
|
114
|
+
row.push(field);
|
|
115
|
+
field = '';
|
|
116
|
+
};
|
|
117
|
+
const endRow = () => {
|
|
118
|
+
endField();
|
|
119
|
+
rows.push(row);
|
|
120
|
+
row = [];
|
|
121
|
+
};
|
|
122
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
123
|
+
const ch = text[i];
|
|
124
|
+
if (quoted) {
|
|
125
|
+
if (ch === '"') {
|
|
126
|
+
if (text[i + 1] === '"') {
|
|
127
|
+
field += '"';
|
|
128
|
+
i += 1;
|
|
129
|
+
} else {
|
|
130
|
+
quoted = false;
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
field += ch;
|
|
134
|
+
}
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (ch === '"' && field === '') {
|
|
138
|
+
quoted = true;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (ch === split) {
|
|
142
|
+
endField();
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (ch === '\n') {
|
|
146
|
+
endRow();
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (ch === '\r') {
|
|
150
|
+
if (text[i + 1] === '\n') i += 1;
|
|
151
|
+
endRow();
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
field += ch;
|
|
155
|
+
}
|
|
156
|
+
if (field !== '' || row.length) endRow();
|
|
157
|
+
return rows;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** CSV 只有一张表;sheet 名用文件名,与 xlsx 的表头/列映射保持一致。 */
|
|
161
|
+
export function loadCsvCases({ file, headerRow, fill = true, maxScan = 10 } = {}) {
|
|
162
|
+
if (!file) throw new CsvError('未指定 CSV 用例文件');
|
|
163
|
+
const resolved = path.resolve(String(file));
|
|
164
|
+
let buffer;
|
|
165
|
+
try {
|
|
166
|
+
buffer = fs.readFileSync(resolved);
|
|
167
|
+
} catch (err) {
|
|
168
|
+
if (err.code === 'ENOENT') throw new CsvError(`CSV 文件不存在:${resolved}`, { file: resolved });
|
|
169
|
+
throw new CsvError(`读取 CSV 文件失败:${resolved}:${err.message}`, { file: resolved, cause: err });
|
|
170
|
+
}
|
|
171
|
+
const text = decodeText(buffer);
|
|
172
|
+
const table = parseCsv(text);
|
|
173
|
+
const rows = new Map();
|
|
174
|
+
let lastCol = 0;
|
|
175
|
+
table.forEach((values, index) => {
|
|
176
|
+
const rowNumber = index + 1;
|
|
177
|
+
const cells = new Map();
|
|
178
|
+
values.forEach((value, col) => {
|
|
179
|
+
if (value === '') return;
|
|
180
|
+
cells.set(col, { ref: indexToCol(col) + rowNumber, type: 's', value });
|
|
181
|
+
if (col + 1 > lastCol) lastCol = col + 1;
|
|
182
|
+
});
|
|
183
|
+
if (cells.size) rows.set(rowNumber, cells);
|
|
184
|
+
});
|
|
185
|
+
if (!rows.size) throw new CsvError(`CSV 文件是空的:${resolved}`, { file: resolved });
|
|
186
|
+
const sheet = path.basename(resolved);
|
|
187
|
+
// 大文件行数可以到十万级,不能把全部键展开成 Math.max 参数(会触发调用栈上限)。
|
|
188
|
+
let lastRow = 0;
|
|
189
|
+
for (const rowNumber of rows.keys()) if (rowNumber > lastRow) lastRow = rowNumber;
|
|
190
|
+
const built = buildCases({
|
|
191
|
+
rows,
|
|
192
|
+
merges: [],
|
|
193
|
+
sheet,
|
|
194
|
+
file: resolved,
|
|
195
|
+
headerRow,
|
|
196
|
+
fill,
|
|
197
|
+
maxScan,
|
|
198
|
+
kind: 'csv',
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
file: resolved,
|
|
202
|
+
sheet,
|
|
203
|
+
sheets: [sheet],
|
|
204
|
+
dimension: `A1:${indexToCol(Math.max(0, lastCol - 1))}${lastRow}`,
|
|
205
|
+
...built,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
@@ -47,6 +47,23 @@ export function stableHash(value) {
|
|
|
47
47
|
return crypto.createHash('sha1').update(text).digest('hex');
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
const fastUpsertCache = new Map();
|
|
51
|
+
|
|
52
|
+
async function centralSupportsFastUpsert(config) {
|
|
53
|
+
const central = centralConfig(config);
|
|
54
|
+
const cached = fastUpsertCache.get(central.url);
|
|
55
|
+
if (cached && Date.now() - cached.at < 60000) return cached.value;
|
|
56
|
+
let value = false;
|
|
57
|
+
try {
|
|
58
|
+
const payload = await requestJson(config, '/health', { timeoutMs: 5000 });
|
|
59
|
+
value = payload?.fast_upsert === true;
|
|
60
|
+
} catch {
|
|
61
|
+
value = false;
|
|
62
|
+
}
|
|
63
|
+
fastUpsertCache.set(central.url, { at: Date.now(), value });
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
|
|
50
67
|
async function requestJson(config, pathname, { method = 'GET', body, timeoutMs } = {}) {
|
|
51
68
|
const central = centralConfig(config);
|
|
52
69
|
if (!central.enabled) throw new CentralKnowledgeError('中心知识库未启用', { code: 'CENTRAL_DISABLED' });
|
|
@@ -358,13 +375,14 @@ export function saveCentralSyncState(config, state) {
|
|
|
358
375
|
|
|
359
376
|
/**
|
|
360
377
|
* 增量写入中心库。相同 key + 相同内容的 Episode 默认跳过,避免重复导入。
|
|
361
|
-
* @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[]}>}
|
|
378
|
+
* @returns {Promise<{enabled:boolean, total:number, ingested:number, skipped:number, failed:number, results:object[], errors:object[], mode:string}>}
|
|
362
379
|
*/
|
|
363
|
-
export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true } = {}) {
|
|
380
|
+
export async function centralIngest(config, { episodes = [], groupId = '', dedupe = true, fast = false, onProgress = null } = {}) {
|
|
364
381
|
const central = centralConfig(config);
|
|
365
382
|
if (!central.enabled) {
|
|
366
|
-
return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [] };
|
|
383
|
+
return { enabled: false, total: episodes.length, ingested: 0, skipped: 0, failed: 0, results: [], errors: [], mode: 'classic' };
|
|
367
384
|
}
|
|
385
|
+
const mode = fast && (await centralSupportsFastUpsert(config)) ? 'fast' : 'classic';
|
|
368
386
|
const state = dedupe ? readCentralSyncState(config) : { version: 1, entries: {} };
|
|
369
387
|
const entries = state.entries && typeof state.entries === 'object' ? state.entries : {};
|
|
370
388
|
const pending = [];
|
|
@@ -381,11 +399,14 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
381
399
|
const results = [];
|
|
382
400
|
const errors = [];
|
|
383
401
|
let ingested = 0;
|
|
384
|
-
const batchSize =
|
|
402
|
+
const batchSize = mode === 'fast'
|
|
403
|
+
? Math.max(10, Number(central.batchSize || 2) * 5)
|
|
404
|
+
: Math.max(1, Number(central.batchSize) || 5);
|
|
405
|
+
if (onProgress) await onProgress({ done: 0, total: pending.length, mode });
|
|
385
406
|
for (let offset = 0; offset < pending.length; offset += batchSize) {
|
|
386
407
|
const chunk = pending.slice(offset, offset + batchSize);
|
|
387
408
|
try {
|
|
388
|
-
const payload = await requestJson(config, '/ingest', {
|
|
409
|
+
const payload = await requestJson(config, mode === 'fast' ? '/ingest-fast' : '/ingest', {
|
|
389
410
|
method: 'POST',
|
|
390
411
|
body: {
|
|
391
412
|
group_id: groupId || central.groupId,
|
|
@@ -397,6 +418,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
397
418
|
source: episode.source || 'json',
|
|
398
419
|
group_id: episode.group_id || groupId || central.groupId,
|
|
399
420
|
replace_prefix: episode.replace_prefix || null,
|
|
421
|
+
...(mode === 'fast' ? { upsert: true } : {}),
|
|
400
422
|
})),
|
|
401
423
|
},
|
|
402
424
|
timeoutMs: central.timeoutMs,
|
|
@@ -415,6 +437,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
415
437
|
} catch (error) {
|
|
416
438
|
errors.push({ ok: false, error: String(error.message || error), count: chunk.length, names: chunk.map((entry) => entry.name) });
|
|
417
439
|
}
|
|
440
|
+
if (onProgress) await onProgress({ done: offset + chunk.length, total: pending.length, mode });
|
|
418
441
|
}
|
|
419
442
|
if (dedupe) saveCentralSyncState(config, { version: 1, updatedAt: nowIso(), entries });
|
|
420
443
|
const failed = errors.reduce((sum, item) => sum + (Number(item.count) || 1), 0);
|
|
@@ -426,6 +449,7 @@ export async function centralIngest(config, { episodes = [], groupId = '', dedup
|
|
|
426
449
|
failed,
|
|
427
450
|
results,
|
|
428
451
|
errors,
|
|
452
|
+
mode,
|
|
429
453
|
groupId: groupId || central.groupId,
|
|
430
454
|
url: central.url,
|
|
431
455
|
};
|
package/lib/xlsx.mjs
CHANGED
|
@@ -688,6 +688,7 @@ export function buildCases({
|
|
|
688
688
|
headerRow,
|
|
689
689
|
fill = true,
|
|
690
690
|
maxScan = 10,
|
|
691
|
+
kind = 'xlsx',
|
|
691
692
|
} = {}) {
|
|
692
693
|
let header;
|
|
693
694
|
if (headerRow !== undefined && headerRow !== null) {
|
|
@@ -755,7 +756,7 @@ export function buildCases({
|
|
|
755
756
|
cases.push({
|
|
756
757
|
sheet: sheet || null,
|
|
757
758
|
rowNumber,
|
|
758
|
-
source: { kind
|
|
759
|
+
source: { kind, file: file || '', sheet: sheet || null, rowNumber },
|
|
759
760
|
seq,
|
|
760
761
|
tcId,
|
|
761
762
|
priority: readCell(rowNumber, 'priority'),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-uitest",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.1",
|
|
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",
|
package/skills/uitest/SKILL.md
CHANGED
|
@@ -7,14 +7,14 @@ description: Test Studio for a running web system: import test-case documents in
|
|
|
7
7
|
|
|
8
8
|
## 何时使用
|
|
9
9
|
|
|
10
|
-
- 有一份测试用例文档(Markdown、文本、xlsx),需要在真实 Web 系统上做回归或验收。
|
|
10
|
+
- 有一份测试用例文档(Markdown、文本、xlsx、CSV),需要在真实 Web 系统上做回归或验收。
|
|
11
11
|
- 用例还没有 flow,需要 Agent 按自然语言执行;或者已有 flow,需要批量并发回归。
|
|
12
12
|
- 需要前置造数、截图证据、把结果写回用例文档,并把通过轨迹沉淀成可复跑 flow。
|
|
13
13
|
- 需要把执行中看到的页面结构、动作和坑点持续积累为知识。
|
|
14
14
|
|
|
15
15
|
## 一条主线
|
|
16
16
|
|
|
17
|
-
1. **导入文档**:uitest_import 把 .md/.txt/.xlsx/.json 或目录整理成自然语言用例。源文档不改;Markdown/文本会生成到 cases/studio/
|
|
17
|
+
1. **导入文档**:uitest_import 把 .md/.txt/.xlsx/.csv/.json 或目录整理成自然语言用例。源文档不改;Markdown/文本会生成到 cases/studio/ 下,CSV 会生成 Markdown 回写镜像。
|
|
18
18
|
2. **检查用例**:uitest_cases 读前置条件、测试过程、预期结果、执行方式(flow / agent / manual)和最近结果。
|
|
19
19
|
3. **规划**:uitest_batch action=start 会先做计划:有 flow 的走 flow 泳道,没有 flow 的走 Agent 泳道,缺前置数据时按 fixtures/recipes 造数,人工用例标记阻塞。
|
|
20
20
|
4. **执行**:flow 与 Agent 两条泳道并发;Agent 用 agent-browser 逐步操作,每步自动截图并写 run.json。
|
|
@@ -26,7 +26,8 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
|
|
|
26
26
|
|
|
27
27
|
## 工具
|
|
28
28
|
|
|
29
|
-
- uitest_import:导入文档或目录;返回 doc、case ids、warning
|
|
29
|
+
- uitest_import:导入文档或目录;返回 doc、case ids、warning。传 docId 可重新关联已有文档,mode=overwrite 删除源文档已移除的用例。
|
|
30
|
+
- uitest_docs:文档层:list 查文档与归属;writeback 单文档回写(默认预览);re-read 重新导读;archive/restore;delete 需 confirm=true。
|
|
30
31
|
- uitest_accounts:读取/导入/编辑测试账号;导入「OMS测试账号」表格,密码会保存到本地账号配置。
|
|
31
32
|
- uitest_cases:按 id/query/mode/status 查用例;mode 取 flow、agent、manual、blocked。
|
|
32
33
|
- uitest_batch:action=start 创建批次;action=status 查实时进度与每例证据;action=stop 请求停止;action=writeback 预览或执行回写。
|
|
@@ -42,6 +43,9 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
|
|
|
42
43
|
|
|
43
44
|
node bin/studio.mjs import cases/新用例.md --project .
|
|
44
45
|
node bin/studio.mjs cases --project . --mode agent
|
|
46
|
+
node bin/studio.mjs docs --project .
|
|
47
|
+
node bin/studio.mjs docs writeback <docId> --dry-run --project .
|
|
48
|
+
node bin/studio.mjs docs re-read <docId> --project .
|
|
45
49
|
node bin/studio.mjs plan --project . --case TC-FP001-01
|
|
46
50
|
node bin/studio.mjs batch create --project . --case TC-FP001-01 --workers 3
|
|
47
51
|
node bin/studio.mjs batch run --project . --id <batchId>
|
|
@@ -57,6 +61,7 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
|
|
|
57
61
|
## 数据模型
|
|
58
62
|
|
|
59
63
|
- Case:tcId、title、module、priority、precondition、steps、expected、remark、mode、flow、status、lastRun。
|
|
64
|
+
- Document:id、docKey、name、kind、sourcePath、generatedPath、caseIds、version、diff、lastRead、writeback、archived;用例归属以文档账本为准,用例是否存在仍看用例库。
|
|
60
65
|
- Batch:id、name、status、stage、options、plan、summary、stages、resultDoc、writeback、knowledge。
|
|
61
66
|
- CaseRun:caseId、mode、status、startedAt、endedAt、durationMs、seed、flow、agent、steps、evidence、runDir、note。
|
|
62
67
|
- Flow:name、title、file、cases、requires、seedRecipes、steps、generated。
|
|
@@ -71,7 +76,7 @@ flow 不是执行的前提。自然语言用例才是事实来源;flow 是执
|
|
|
71
76
|
- 每个 worker 只写自己的 case-run 文件;批次汇总、归档、回写、知识合并由协调器串行完成。
|
|
72
77
|
- 结果文档只在批次结束后写一次。不要在每个用例结束时单独回写同一份文档。
|
|
73
78
|
- 回写使用单写者锁;并发回写返回 WRITEBACK_BUSY。等当前批次完成再试。
|
|
74
|
-
- Markdown 回写插入带标记的结果块,重复回写会替换而不是追加;xlsx
|
|
79
|
+
- Markdown 回写插入带标记的结果块,重复回写会替换而不是追加;xlsx 生成执行结果副本,不覆盖原文档;CSV 写入生成的 Markdown 镜像,CSV 用例编号必须能被 Markdown 回写解析(如 TC-XXX-01)。
|
|
75
80
|
- 写业务数据的配方默认不执行;只有 allowWrites=true 才放行。造数前先确认源单库存与资源锁。
|
|
76
81
|
|
|
77
82
|
## Agent 执行规则
|
package/studio/documents.mjs
CHANGED
|
@@ -23,11 +23,20 @@ function caseKey(value) {
|
|
|
23
23
|
return String(value || '').toLowerCase();
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
+
function resolveProjectPath(config, value) {
|
|
27
|
+
const text = String(value || '');
|
|
28
|
+
if (!text) return '';
|
|
29
|
+
return path.isAbsolute(text) ? path.resolve(text) : path.resolve(config.projectDir, text);
|
|
30
|
+
}
|
|
31
|
+
|
|
26
32
|
export function documentRegistry(config) {
|
|
27
33
|
const store = readDocs(config);
|
|
28
34
|
return {
|
|
29
35
|
version: Number(store.version) || 1,
|
|
30
36
|
updatedAt: store.updatedAt || '',
|
|
37
|
+
invalid: store.invalid === true,
|
|
38
|
+
error: store.error || '',
|
|
39
|
+
file: store.file || '',
|
|
31
40
|
docs: asArray(store.docs).map(normalizeDocumentRecord),
|
|
32
41
|
};
|
|
33
42
|
}
|
|
@@ -49,6 +58,41 @@ export function findDocument(config, { docId = '', docKey = '', sourcePath = ''
|
|
|
49
58
|
return null;
|
|
50
59
|
}
|
|
51
60
|
|
|
61
|
+
function matchDocumentRecord(config, docs, input) {
|
|
62
|
+
const byId = docs.find((doc) => doc.id === input.id) || null;
|
|
63
|
+
const byKey = input.docKey ? docs.find((doc) => doc.docKey === input.docKey) || null : null;
|
|
64
|
+
const byPath = input.sourcePath
|
|
65
|
+
? docs.find((doc) => doc.sourcePath && resolveProjectPath(config, doc.sourcePath) === resolveProjectPath(config, input.sourcePath)) || null
|
|
66
|
+
: null;
|
|
67
|
+
const existing = byId || byKey || byPath;
|
|
68
|
+
// 重新关联到另一份文档的源文件时不能静默删掉那份文档:身份冲突必须显式报错。
|
|
69
|
+
const conflict = [byKey, byPath].find((doc) => doc && existing && doc.id !== existing.id) || null;
|
|
70
|
+
return { existing, conflict };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function sourceInUseError(conflict, existing, input) {
|
|
74
|
+
return new UitestError('该源文件已属于文档:' + (conflict.name || conflict.id), {
|
|
75
|
+
code: 'DOC_SOURCE_IN_USE',
|
|
76
|
+
detail: {
|
|
77
|
+
docId: existing.id,
|
|
78
|
+
otherDocId: conflict.id,
|
|
79
|
+
sourcePath: input.sourcePath || '',
|
|
80
|
+
otherSourcePath: conflict.sourcePath || '',
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 导入写文件前预检身份冲突:命中时整次导入不产生任何副作用。
|
|
87
|
+
* 锁内 saveDocumentRecord 仍会复查,防止预检与落库之间注册表被并发修改。
|
|
88
|
+
*/
|
|
89
|
+
export function assertDocumentSourceAvailable(config, record) {
|
|
90
|
+
const input = normalizeDocumentRecord(record);
|
|
91
|
+
const { docs } = documentRegistry(config);
|
|
92
|
+
const { existing, conflict } = matchDocumentRecord(config, docs, input);
|
|
93
|
+
if (conflict) throw sourceInUseError(conflict, existing, input);
|
|
94
|
+
}
|
|
95
|
+
|
|
52
96
|
/**
|
|
53
97
|
* 按 id → docKey → sourcePath 的顺序 upsert 一条文档记录,并去重。
|
|
54
98
|
* 命中旧记录时保留它的 id,改名不会换身份。
|
|
@@ -58,12 +102,8 @@ export function saveDocumentRecord(config, record, { reconcile = null } = {}) {
|
|
|
58
102
|
const input = normalizeDocumentRecord(record);
|
|
59
103
|
return updateDocs(config, (store) => {
|
|
60
104
|
const docs = asArray(store.docs).map(normalizeDocumentRecord);
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
const byPath = input.sourcePath
|
|
64
|
-
? docs.find((doc) => doc.sourcePath && path.resolve(doc.sourcePath) === path.resolve(input.sourcePath)) || null
|
|
65
|
-
: null;
|
|
66
|
-
const existing = byId || byKey || byPath;
|
|
105
|
+
const { existing, conflict } = matchDocumentRecord(config, docs, input);
|
|
106
|
+
if (conflict) throw sourceInUseError(conflict, existing, input);
|
|
67
107
|
const base = reconcile ? reconcile(existing, input) : { ...(existing || {}), ...input };
|
|
68
108
|
const saved = normalizeDocumentRecord({
|
|
69
109
|
...base,
|
|
@@ -74,18 +114,19 @@ export function saveDocumentRecord(config, record, { reconcile = null } = {}) {
|
|
|
74
114
|
store.docs = [saved, ...docs.filter((doc) => {
|
|
75
115
|
if (doc.id === saved.id) return false;
|
|
76
116
|
if (saved.docKey && doc.docKey === saved.docKey) return false;
|
|
77
|
-
if (saved.sourcePath && doc.sourcePath &&
|
|
117
|
+
if (saved.sourcePath && doc.sourcePath && resolveProjectPath(config, doc.sourcePath) === resolveProjectPath(config, saved.sourcePath)) return false;
|
|
78
118
|
return true;
|
|
79
119
|
})];
|
|
80
120
|
return saved;
|
|
81
121
|
});
|
|
82
122
|
}
|
|
83
123
|
|
|
84
|
-
export function documentSourceState(doc) {
|
|
124
|
+
export function documentSourceState(config, doc) {
|
|
85
125
|
const sourcePath = String(doc?.sourcePath || '');
|
|
86
126
|
if (!sourcePath) return 'missing';
|
|
127
|
+
const abs = resolveProjectPath(config, sourcePath);
|
|
87
128
|
try {
|
|
88
|
-
return fs.existsSync(
|
|
129
|
+
return fs.existsSync(abs) && fs.statSync(abs).isFile() ? 'ready' : 'missing';
|
|
89
130
|
} catch {
|
|
90
131
|
return 'missing';
|
|
91
132
|
}
|
|
@@ -109,11 +150,11 @@ export function documentCaseFileState(config, doc) {
|
|
|
109
150
|
if (!doc) return 'missing';
|
|
110
151
|
if (doc.kind === 'xlsx') {
|
|
111
152
|
if (!doc.writeback?.targetPath) return 'pending';
|
|
112
|
-
return fs.existsSync(doc.writeback.targetPath) ? 'ready' : 'missing';
|
|
153
|
+
return fs.existsSync(resolveProjectPath(config, doc.writeback.targetPath)) ? 'ready' : 'missing';
|
|
113
154
|
}
|
|
114
155
|
const file = documentCaseFile(config, doc);
|
|
115
156
|
if (!file) return 'missing';
|
|
116
|
-
const abs =
|
|
157
|
+
const abs = resolveProjectPath(config, file);
|
|
117
158
|
try {
|
|
118
159
|
return fs.existsSync(abs) && fs.statSync(abs).isFile() ? 'ready' : 'missing';
|
|
119
160
|
} catch {
|
|
@@ -143,7 +184,7 @@ export function documentCounts(doc, cases, { deletedCaseIds = [] } = {}) {
|
|
|
143
184
|
}
|
|
144
185
|
|
|
145
186
|
function statusCountsOf(cases) {
|
|
146
|
-
const counts = { total: cases.length, passed: 0, partial: 0, failed: 0, blocked: 0,
|
|
187
|
+
const counts = { total: cases.length, passed: 0, partial: 0, failed: 0, blocked: 0, queued: 0, running: 0, stopped: 0, untested: 0 };
|
|
147
188
|
for (const item of cases) {
|
|
148
189
|
const key = Object.hasOwn(counts, item?.status) && item.status !== 'total' ? item.status : 'untested';
|
|
149
190
|
counts[key] += 1;
|
|
@@ -176,10 +217,12 @@ export function documentView(config, doc, cases, { deletedCaseIds = [] } = {}) {
|
|
|
176
217
|
docKey: record.docKey,
|
|
177
218
|
name: record.name,
|
|
178
219
|
kind: record.kind,
|
|
220
|
+
archived: record.archived === true,
|
|
221
|
+
archivedAt: record.archivedAt || '',
|
|
179
222
|
sourcePath: record.sourcePath,
|
|
180
223
|
generatedPath: record.generatedPath,
|
|
181
224
|
caseFile: documentCaseFile(config, record),
|
|
182
|
-
sourceState: documentSourceState(record),
|
|
225
|
+
sourceState: documentSourceState(config, record),
|
|
183
226
|
caseFileState: documentCaseFileState(config, record),
|
|
184
227
|
visibleCount: counts.visibleCount,
|
|
185
228
|
ownedCount: counts.ownedCount,
|
|
@@ -214,14 +257,15 @@ export function groupCasesByDocument(docs, cases) {
|
|
|
214
257
|
|
|
215
258
|
export function documentWriteTarget(config, doc, date = formatDate(new Date())) {
|
|
216
259
|
if (!doc) return { kind: 'none', reason: 'DOC_NOT_FOUND' };
|
|
217
|
-
if (doc.kind === 'markdown' || doc.kind === 'json') {
|
|
260
|
+
if (doc.kind === 'markdown' || doc.kind === 'json' || doc.kind === 'csv') {
|
|
218
261
|
const file = doc.generatedPath || '';
|
|
219
262
|
if (!file) return { kind: 'none', path: '', reason: 'DOC_CASE_FILE_MISSING' };
|
|
220
|
-
|
|
263
|
+
// CSV 的回写目标是导入时生成的 Markdown 镜像,下游统一按 Markdown 处理。
|
|
264
|
+
return { kind: 'markdown', path: file, sourcePath: doc.sourcePath || '', sourceState: documentSourceState(config, doc) };
|
|
221
265
|
}
|
|
222
266
|
if (doc.kind === 'xlsx') {
|
|
223
267
|
const target = documentWritebackPath(config, doc, date);
|
|
224
|
-
const sourceState = documentSourceState(doc);
|
|
268
|
+
const sourceState = documentSourceState(config, doc);
|
|
225
269
|
return {
|
|
226
270
|
kind: 'xlsx',
|
|
227
271
|
path: target,
|
|
@@ -249,6 +293,32 @@ export function updateDocumentRecord(config, docId, mutate) {
|
|
|
249
293
|
});
|
|
250
294
|
}
|
|
251
295
|
|
|
296
|
+
/** 归档只改注册表,不碰用例、源文件或已生成的用例文件。 */
|
|
297
|
+
export function setDocumentArchived(config, docId, archived = true) {
|
|
298
|
+
const flag = archived === true;
|
|
299
|
+
return updateDocumentRecord(config, docId, (current) => ({
|
|
300
|
+
...current,
|
|
301
|
+
archived: flag,
|
|
302
|
+
archivedAt: flag ? (current.archivedAt || nowIso()) : '',
|
|
303
|
+
}));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* 删除文档记录。用例仍在用例库中,只是失去文档归属;源文件与用例文件都不删。
|
|
308
|
+
* 同一 docKey 再次导入会得到确定性 id,旧用例可以重新关联回来。
|
|
309
|
+
*/
|
|
310
|
+
export function deleteDocumentRecord(config, docId) {
|
|
311
|
+
const id = String(docId || '');
|
|
312
|
+
return updateDocs(config, (store) => {
|
|
313
|
+
const docs = asArray(store.docs).map(normalizeDocumentRecord);
|
|
314
|
+
const index = docs.findIndex((doc) => doc.id === id);
|
|
315
|
+
if (index < 0) throw new UitestError('文档不存在:' + id, { code: 'DOC_NOT_FOUND', detail: { docId: id } });
|
|
316
|
+
const removed = docs[index];
|
|
317
|
+
store.docs = docs.filter((doc) => doc.id !== id);
|
|
318
|
+
return removed;
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
252
322
|
/**
|
|
253
323
|
* 回写只能做锁内读改写。调用方手里的文档快照可能已经落后于并发的
|
|
254
324
|
* 重新导读/导入,整条覆盖会回滚 version、lastRead 与 caseIds。
|