dsh-uitest 2.2.0 → 2.3.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/README.md +30 -9
- package/bin/studio.mjs +117 -17
- package/bin/uitest.mjs +3 -3
- package/client.js +888 -177
- 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/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 +103 -14
- package/studio/import.mjs +115 -21
- 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
|
+
}
|
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.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",
|
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。
|
package/studio/host.mjs
CHANGED
|
@@ -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;
|
|
@@ -326,6 +328,8 @@ function handleCase(ctx, request) {
|
|
|
326
328
|
}
|
|
327
329
|
return ok({
|
|
328
330
|
case: found.case,
|
|
331
|
+
// 执行抽屉按需取用例定义;归一化后前端不必再理解原始表格字段。
|
|
332
|
+
studio: normalizeStudioCase(found.case, { flow, preconditionFlows }),
|
|
329
333
|
flow: flow ? { name: flow.name, title: flow.title, file: flow.file, tags: flow.tags || [], steps } : null,
|
|
330
334
|
preconditionFlows: preconditionFlows.map((item) => ({ name: item.name, title: item.title, file: item.file, provides: item.provides || [], cases: item.cases || [] })),
|
|
331
335
|
});
|
|
@@ -438,6 +442,7 @@ async function handleImport(ctx, request) {
|
|
|
438
442
|
file: body.file,
|
|
439
443
|
name: body.name || '',
|
|
440
444
|
mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
|
|
445
|
+
docId: String(body.docId || ''),
|
|
441
446
|
});
|
|
442
447
|
return ok({
|
|
443
448
|
doc: result.doc,
|
|
@@ -456,7 +461,7 @@ async function handleImportUpload(ctx, request) {
|
|
|
456
461
|
const { config } = projectFor(ctx, body.project || '');
|
|
457
462
|
const name = path.basename(String(body.name || 'upload.xlsx'));
|
|
458
463
|
const ext = path.extname(name).toLowerCase();
|
|
459
|
-
if (!['.md', '.markdown', '.txt', '.xlsx', '.json'].includes(ext)) {
|
|
464
|
+
if (!['.md', '.markdown', '.txt', '.xlsx', '.csv', '.json'].includes(ext)) {
|
|
460
465
|
throw hostError(400, 'IMPORT_UNSUPPORTED', '暂不支持该文件类型:' + ext);
|
|
461
466
|
}
|
|
462
467
|
const encoded = String(body.dataBase64 || '');
|
|
@@ -473,12 +478,13 @@ async function handleImportUpload(ctx, request) {
|
|
|
473
478
|
const safeName = name.replace(/[^\p{L}\p{N}._-]+/gu, '_');
|
|
474
479
|
const uploadFile = path.join(uploadDir, Date.now() + '-' + safeName);
|
|
475
480
|
fs.writeFileSync(uploadFile, buffer);
|
|
476
|
-
const docName = String(body.docName || path.basename(name, ext));
|
|
481
|
+
const docName = String(body.docName || (body.docId ? '' : path.basename(name, ext)));
|
|
477
482
|
const result = await importDocument(config, {
|
|
478
483
|
file: uploadFile,
|
|
479
484
|
name: docName,
|
|
480
485
|
originalName: name,
|
|
481
486
|
mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
|
|
487
|
+
docId: String(body.docId || ''),
|
|
482
488
|
});
|
|
483
489
|
return ok({
|
|
484
490
|
doc: result.doc,
|
|
@@ -631,6 +637,27 @@ async function handleStop(ctx, panel, request) {
|
|
|
631
637
|
return ok({ stopped: requested, batch: batchDetail(config, id) });
|
|
632
638
|
}
|
|
633
639
|
|
|
640
|
+
async function handleBatchResume(ctx, panel, request) {
|
|
641
|
+
const body = await readBody(request);
|
|
642
|
+
const { config } = projectFor(ctx, body.project || '');
|
|
643
|
+
const id = String(body.id || '');
|
|
644
|
+
if (!id) throw hostError(400, 'BATCH_REQUIRED', '缺少批次 id');
|
|
645
|
+
const busy = activeBatchResponse(config);
|
|
646
|
+
if (busy) return busy;
|
|
647
|
+
const result = await resumeBatch({ config, batchId: id, panel });
|
|
648
|
+
const logger = ctx?.logger || null;
|
|
649
|
+
Promise.resolve()
|
|
650
|
+
.then(() => runBatch({ config, batchId: id, panel, logger }))
|
|
651
|
+
.catch((error) => {
|
|
652
|
+
try {
|
|
653
|
+
patchBatch(config, id, { status: 'failed', error: String(error.message || error) });
|
|
654
|
+
} catch {
|
|
655
|
+
/* 状态更新失败不阻断响应 */
|
|
656
|
+
}
|
|
657
|
+
});
|
|
658
|
+
return ok({ resumed: result.resumed, batch: batchDetail(config, id) });
|
|
659
|
+
}
|
|
660
|
+
|
|
634
661
|
async function handleBatchDelete(ctx, request) {
|
|
635
662
|
const body = await readBody(request);
|
|
636
663
|
const { config } = projectFor(ctx, body.project || '');
|
|
@@ -1161,14 +1188,23 @@ function handleShot(ctx, request) {
|
|
|
1161
1188
|
const file = url.searchParams.get('file') || '';
|
|
1162
1189
|
if (!file) throw hostError(400, 'FILE_REQUIRED', '缺少 file');
|
|
1163
1190
|
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
1191
|
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1192
|
+
// 证据只从输出目录读取;按 realpath 判断,阻止软链接逃逸到账号/文档等配置。
|
|
1193
|
+
let root = path.resolve(config.paths.outputDir);
|
|
1194
|
+
let real = abs;
|
|
1195
|
+
try {
|
|
1196
|
+
root = fs.realpathSync(root);
|
|
1197
|
+
real = fs.realpathSync(abs);
|
|
1198
|
+
} catch {
|
|
1199
|
+
throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
|
|
1200
|
+
}
|
|
1201
|
+
if (real !== root && !real.startsWith(root + path.sep)) {
|
|
1202
|
+
throw hostError(403, 'FILE_FORBIDDEN', '只能读取输出目录内的证据图片');
|
|
1203
|
+
}
|
|
1204
|
+
const ext = path.extname(real).toLowerCase();
|
|
1205
|
+
const types = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
|
|
1206
|
+
if (!types[ext]) throw hostError(403, 'FILE_FORBIDDEN', '只能读取证据图片');
|
|
1207
|
+
return new Response(fs.readFileSync(real), { headers: { 'content-type': types[ext], 'cache-control': 'no-store' } });
|
|
1172
1208
|
}
|
|
1173
1209
|
|
|
1174
1210
|
async function handleFeedback(ctx, request) {
|
|
@@ -1326,6 +1362,55 @@ async function handleDocsReRead(ctx, request) {
|
|
|
1326
1362
|
});
|
|
1327
1363
|
}
|
|
1328
1364
|
|
|
1365
|
+
async function handleDocsArchive(ctx, request) {
|
|
1366
|
+
const body = await readBody(request);
|
|
1367
|
+
const { config } = projectFor(ctx, body.project || '');
|
|
1368
|
+
const docId = String(body.docId || '');
|
|
1369
|
+
if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
|
|
1370
|
+
const doc = await setDocumentArchived(config, docId, body.archived !== false);
|
|
1371
|
+
return ok({ doc, docs: [doc], snapshot: buildStudioSnapshot(config) });
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
async function handleDocsDelete(ctx, request) {
|
|
1375
|
+
const body = await readBody(request);
|
|
1376
|
+
const { config } = projectFor(ctx, body.project || '');
|
|
1377
|
+
const busy = activeBatchResponse(config);
|
|
1378
|
+
if (busy) return busy;
|
|
1379
|
+
const docId = String(body.docId || '');
|
|
1380
|
+
if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
|
|
1381
|
+
const lock = acquireLock(config, 'writeback');
|
|
1382
|
+
try {
|
|
1383
|
+
const doc = await deleteDocumentRecord(config, docId);
|
|
1384
|
+
return ok({
|
|
1385
|
+
doc,
|
|
1386
|
+
deleted: true,
|
|
1387
|
+
docId: doc.id,
|
|
1388
|
+
name: doc.name,
|
|
1389
|
+
caseCount: Array.isArray(doc.caseIds) ? doc.caseIds.length : 0,
|
|
1390
|
+
snapshot: buildStudioSnapshot(config),
|
|
1391
|
+
});
|
|
1392
|
+
} finally {
|
|
1393
|
+
lock.release();
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
|
|
1397
|
+
async function handleDocsWriteback(ctx, request) {
|
|
1398
|
+
const body = await readBody(request);
|
|
1399
|
+
const { config } = projectFor(ctx, body.project || '');
|
|
1400
|
+
const busy = activeBatchResponse(config);
|
|
1401
|
+
if (busy) return busy;
|
|
1402
|
+
const docId = String(body.docId || '');
|
|
1403
|
+
if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
|
|
1404
|
+
const options = {
|
|
1405
|
+
batchId: String(body.batchId || ''),
|
|
1406
|
+
caseIds: Array.isArray(body.caseIds) ? body.caseIds.map(String) : [],
|
|
1407
|
+
};
|
|
1408
|
+
const result = body.dryRun === true
|
|
1409
|
+
? await previewDocumentWriteback(config, docId, options)
|
|
1410
|
+
: await applyDocumentWriteback(config, docId, options);
|
|
1411
|
+
return ok({ ...result, snapshot: buildStudioSnapshot(config) });
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1329
1414
|
export function registerStudioRoutes({ ctx, panel }) {
|
|
1330
1415
|
if (!ctx?.connection?.fetch || typeof ctx.connection.fetch.register !== 'function') {
|
|
1331
1416
|
throw new Error('uitest studio routes require the connection service');
|
|
@@ -1349,6 +1434,7 @@ export function registerStudioRoutes({ ctx, panel }) {
|
|
|
1349
1434
|
['/plan', ['POST'], (request) => handlePlan(ctx, request)],
|
|
1350
1435
|
['/batch', ['GET', 'POST'], (request) => (request.method === 'GET' ? handleBatchGet(ctx, request) : handleCreateBatch(ctx, panel, request))],
|
|
1351
1436
|
['/batch/stop', ['POST'], (request) => handleStop(ctx, panel, request)],
|
|
1437
|
+
['/batch/resume', ['POST'], (request) => handleBatchResume(ctx, panel, request)],
|
|
1352
1438
|
['/batch/case/stop', ['POST'], (request) => handleCaseStop(ctx, panel, request)],
|
|
1353
1439
|
['/batch/case/prioritize', ['POST'], (request) => handleCasePrioritize(ctx, request)],
|
|
1354
1440
|
['/batch/delete', ['POST'], (request) => handleBatchDelete(ctx, request)],
|
|
@@ -1384,6 +1470,9 @@ export function registerStudioRoutes({ ctx, panel }) {
|
|
|
1384
1470
|
['/shot', ['GET', 'HEAD'], (request) => handleShot(ctx, request)],
|
|
1385
1471
|
['/docs', ['GET'], (request) => handleDocs(ctx, request)],
|
|
1386
1472
|
['/docs/re-read', ['POST'], (request) => handleDocsReRead(ctx, request)],
|
|
1473
|
+
['/docs/archive', ['POST'], (request) => handleDocsArchive(ctx, request)],
|
|
1474
|
+
['/docs/delete', ['POST'], (request) => handleDocsDelete(ctx, request)],
|
|
1475
|
+
['/docs/writeback', ['POST'], (request) => handleDocsWriteback(ctx, request)],
|
|
1387
1476
|
];
|
|
1388
1477
|
const disposers = [];
|
|
1389
1478
|
for (const [suffix, methods, handler] of routes) {
|