dsh-uitest 2.1.1 → 2.1.3

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.
@@ -1,498 +0,0 @@
1
- import http from 'node:http';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
-
6
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
- const root = path.resolve(__dirname, '../../..');
8
- const sample = JSON.parse(fs.readFileSync(path.join(__dirname, 'sample.json'), 'utf8'));
9
- const port = Number(process.env.PORT || 4173);
10
-
11
- sample.batches = (sample.batches || []).map((batch) => (batch.id === sample.activeBatch?.id ? sample.activeBatch : batch));
12
- // 预览数据里批次与 activeBatch 各存一份汇总;启动时统一按用例状态重算,避免两份数据漂移。
13
- for (const batch of sample.batches) applyQueue(batch);
14
- if (sample.activeBatch) applyQueue(sample.activeBatch);
15
-
16
- function batchById(id) {
17
- return sample.batches.find((item) => item.id === id) || (sample.activeBatch?.id === id ? sample.activeBatch : null) || sample.activeBatch;
18
- }
19
-
20
- function applyQueue(batch) {
21
- const entries = batch.queue?.entries || {};
22
- const queued = Object.values(entries)
23
- .filter((entry) => entry.state === 'queued')
24
- .sort((a, b) => (Number(b.priority) || 0) - (Number(a.priority) || 0) || (Number(a.seq) || 0) - (Number(b.seq) || 0));
25
- const positions = new Map(queued.map((entry, index) => [entry.caseId, { position: index + 1, ahead: index }]));
26
- for (const run of batch.cases || []) {
27
- const entry = entries[run.caseId];
28
- if (!entry) continue;
29
- const position = positions.get(run.caseId) || { position: null, ahead: null };
30
- run.queue = {
31
- state: entry.state,
32
- seq: entry.seq,
33
- attempt: entry.attempt,
34
- priority: entry.priority,
35
- stopRequested: entry.stopRequested === true,
36
- position: position.position,
37
- ahead: position.ahead,
38
- };
39
- }
40
- // 与 model.mjs 的 summarizeCaseRuns 保持一致:done 只算有结论的用例,通过率的分母是 done,不是总数。
41
- const summary = { total: (batch.cases || []).length, passed: 0, partial: 0, failed: 0, blocked: 0, untested: 0, running: 0, queued: 0, stopped: 0, done: 0, percent: 0 };
42
- for (const run of batch.cases || []) {
43
- const key = Object.hasOwn(summary, run.status) && !['total', 'done', 'percent'].includes(run.status) ? run.status : 'untested';
44
- summary[key] += 1;
45
- }
46
- summary.done = summary.passed + summary.partial + summary.failed + summary.blocked;
47
- summary.percent = summary.done ? Math.round(((summary.passed + summary.partial) / summary.done) * 100) : 0;
48
- batch.summary = summary;
49
- }
50
-
51
- function requeueCase(batch, caseId) {
52
- const entries = batch.queue?.entries || {};
53
- const existing = entries[caseId] || null;
54
- if (existing && (existing.state === 'queued' || existing.state === 'running')) return { alreadyActive: true };
55
- const run = (batch.cases || []).find((item) => item.caseId === caseId);
56
- const previous = run && ['passed', 'failed', 'partial', 'blocked', 'stopped'].includes(run.status) ? run.status : run?.previousStatus;
57
- const next = existing || { caseId, attempt: 1, priority: 0 };
58
- const now = new Date().toISOString();
59
- next.state = 'queued';
60
- next.seq = Number(batch.queue.nextSeq) || 1;
61
- batch.queue.nextSeq = next.seq + 1;
62
- next.priority = 0;
63
- next.attempt = existing ? (Number(existing.attempt) || 1) + 1 : 1;
64
- next.enqueuedAt = now;
65
- next.startedAt = null;
66
- next.endedAt = null;
67
- next.stopRequested = false;
68
- entries[caseId] = next;
69
- batch.queue.entries = entries;
70
- if (run) {
71
- run.status = 'queued';
72
- if (previous) {
73
- run.previousStatus = previous;
74
- run.previousNote = run.note;
75
- }
76
- run.note = '已重新排队,等待执行';
77
- }
78
- if (['done', 'stopped', 'failed'].includes(batch.status)) {
79
- batch.status = 'queued';
80
- batch.endedAt = null;
81
- batch.stopRequested = false;
82
- }
83
- applyQueue(batch);
84
- return { requeued: true };
85
- }
86
-
87
- function stopCase(batch, caseId) {
88
- const entry = batch.queue?.entries?.[caseId];
89
- if (!entry) return { code: 400, message: '该用例不在批次队列中' };
90
- if (entry.state === 'queued') {
91
- entry.state = 'stopped';
92
- entry.endedAt = new Date().toISOString();
93
- const run = (batch.cases || []).find((item) => item.caseId === caseId);
94
- if (run && run.status === 'queued' && !run.previousStatus) {
95
- run.status = 'stopped';
96
- run.note = '已手动停止,未执行';
97
- } else if (run && run.previousStatus) {
98
- run.status = run.previousStatus;
99
- if (run.previousNote) run.note = run.previousNote;
100
- }
101
- } else if (entry.state === 'running') {
102
- entry.stopRequested = true;
103
- entry.state = 'stopped';
104
- entry.endedAt = new Date().toISOString();
105
- const run = (batch.cases || []).find((item) => item.caseId === caseId);
106
- if (run) {
107
- run.status = 'stopped';
108
- run.note = '已手动停止';
109
- if (run.agentLive) run.agentLive = { ...run.agentLive, active: false };
110
- }
111
- } else {
112
- return { code: 409, message: '该用例已经结束' };
113
- }
114
- applyQueue(batch);
115
- return {};
116
- }
117
-
118
- function prioritizeCase(batch, caseId) {
119
- const entry = batch.queue?.entries?.[caseId];
120
- if (!entry) return { code: 400, message: '该用例不在批次队列中' };
121
- if (entry.state !== 'queued') return { code: 409, message: '只有排队中的用例可以优先' };
122
- const max = Math.max(0, ...Object.values(batch.queue.entries).map((item) => Number(item.priority) || 0));
123
- entry.priority = max + 1;
124
- applyQueue(batch);
125
- return {};
126
- }
127
-
128
- function escapeXml(value) {
129
- return String(value || '').replace(/[<>&"]/g, (char) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[char]));
130
- }
131
-
132
- function shotSvg(file) {
133
- const label = escapeXml(baseName(file).replace(/\.\w+$/, ''));
134
- const rows = [0, 1, 2, 3].map((index) => {
135
- const y = 116 + index * 38;
136
- return '<rect x="32" y="' + y + '" width="' + (index % 2 ? 330 : 380) + '" height="18" rx="4" fill="#dde5f0"/>'
137
- + '<rect x="258" y="' + y + '" width="170" height="18" rx="4" fill="#e8eef7"/>';
138
- }).join('');
139
- return '<svg xmlns="http://www.w3.org/2000/svg" width="480" height="300" viewBox="0 0 480 300">'
140
- + '<rect width="480" height="300" fill="#f4f7fb"/>'
141
- + '<rect x="16" y="16" width="448" height="52" rx="8" fill="#e2e9f4"/>'
142
- + '<text x="30" y="48" font-family="sans-serif" font-size="17" fill="#33445f">履约单详情 · ' + label + '</text>'
143
- + '<rect x="16" y="84" width="210" height="200" rx="8" fill="#ffffff" stroke="#ccd8e8"/>'
144
- + '<rect x="242" y="84" width="222" height="200" rx="8" fill="#ffffff" stroke="#ccd8e8"/>'
145
- + rows
146
- + '<text x="30" y="272" font-family="sans-serif" font-size="12" fill="#8a97a8">preview placeholder · ' + label + '</text>'
147
- + '</svg>';
148
- }
149
-
150
- function baseName(value) {
151
- const parts = String(value || '').split(/[\\/]/).filter(Boolean);
152
- return parts[parts.length - 1] || String(value || '');
153
- }
154
-
155
- function send(res, status, body, type) {
156
- res.writeHead(status, { 'content-type': type || 'application/json; charset=utf-8', 'cache-control': 'no-store' });
157
- res.end(body);
158
- }
159
-
160
- function sendFile(res, file, type) {
161
- if (!fs.existsSync(file)) return send(res, 404, 'not found', 'text/plain');
162
- send(res, 200, fs.readFileSync(file), type);
163
- }
164
-
165
- function planFrom(body) {
166
- const ids = Array.isArray(body.caseIds) ? body.caseIds : [];
167
- const items = sample.cases.filter((item) => !ids.length || ids.includes(item.tcId)).map((item) => ({
168
- caseId: item.tcId,
169
- title: item.title,
170
- module: item.module,
171
- priority: item.priority,
172
- mode: item.mode,
173
- state: item.mode === 'flow' ? 'ready' : item.mode === 'agent' ? 'agent-ready' : 'manual',
174
- reasons: item.mode === 'manual' ? ['用例标注不可自动化'] : [],
175
- flow: item.flow,
176
- seed: { state: item.dataNeeds && item.dataNeeds.length ? 'ready' : 'not-needed', needs: item.dataNeeds || [], chain: [], missing: [], blocked: [] },
177
- seedWarning: '',
178
- dataNeeds: item.dataNeeds || [],
179
- }));
180
- return {
181
- summary: {
182
- total: items.length,
183
- flow: items.filter((item) => item.mode === 'flow').length,
184
- agent: items.filter((item) => item.mode === 'agent').length,
185
- manual: items.filter((item) => item.mode === 'manual').length,
186
- blocked: 0,
187
- withSeed: items.filter((item) => item.seed.needs.length).length,
188
- },
189
- warnings: [],
190
- items,
191
- };
192
- }
193
-
194
- const readJson = (req) => new Promise((resolve) => {
195
- let body = '';
196
- req.on('data', (chunk) => { body += chunk; });
197
- req.on('end', () => {
198
- try { resolve(body ? JSON.parse(body) : {}); } catch { resolve({}); }
199
- });
200
- });
201
-
202
- const server = http.createServer(async (req, res) => {
203
- const url = new URL(req.url, 'http://localhost');
204
- if (url.pathname === '/api/uitest/studio/bootstrap') {
205
- const flows = (sample.flows || []).map((flow) => ({
206
- ...flow,
207
- kind: flow.kind || ((flow.tags || []).includes('precondition') ? 'precondition' : 'case'),
208
- }));
209
- return send(res, 200, JSON.stringify({
210
- ok: true,
211
- ...sample,
212
- flows,
213
- config: {
214
- ...(sample.config || {}),
215
- knowledgeCentral: { enabled: true, url: 'http://127.0.0.1:8000', groupId: 'oms-v2-test', timeoutMs: 300000, batchSize: 2, searchTimeoutMs: 10000 },
216
- },
217
- central: { enabled: true, ok: true, url: 'http://127.0.0.1:8000', groupId: 'oms-v2-test', nodes: [{ labels: ['Entity'], count: 245 }], edges: [{ type: 'RELATES_TO', count: 381 }] },
218
- }));
219
- }
220
- if (url.pathname === '/api/uitest/studio/batch' && req.method === 'GET') {
221
- const id = url.searchParams.get('id');
222
- return send(res, 200, JSON.stringify({ ok: true, batch: batchById(id) }));
223
- }
224
- if (url.pathname === '/api/uitest/studio/shot' && req.method === 'GET') {
225
- return send(res, 200, shotSvg(url.searchParams.get('file') || 'screenshot.png'), 'image/svg+xml; charset=utf-8');
226
- }
227
- if (url.pathname === '/api/uitest/studio/batch/case/stop' && req.method === 'POST') {
228
- const body = await readJson(req);
229
- const batch = batchById(body.id);
230
- const result = stopCase(batch, String(body.caseId || ''));
231
- if (result.code) {
232
- res.statusCode = result.code;
233
- return send(res, result.code, JSON.stringify({ ok: false, error: { code: result.code === 409 ? 'CASE_NOT_ACTIVE' : 'CASE_NOT_IN_BATCH', message: result.message } }));
234
- }
235
- return send(res, 200, JSON.stringify({ ok: true, batch }));
236
- }
237
- if (url.pathname === '/api/uitest/studio/batch/case/prioritize' && req.method === 'POST') {
238
- const body = await readJson(req);
239
- const batch = batchById(body.id);
240
- const result = prioritizeCase(batch, String(body.caseId || ''));
241
- if (result.code) {
242
- res.statusCode = result.code;
243
- return send(res, result.code, JSON.stringify({ ok: false, error: { code: result.code === 409 ? 'CASE_NOT_QUEUED' : 'CASE_NOT_IN_BATCH', message: result.message } }));
244
- }
245
- return send(res, 200, JSON.stringify({ ok: true, batch }));
246
- }
247
- if (url.pathname === '/api/uitest/studio/plan') {
248
- let body = '';
249
- req.on('data', (chunk) => { body += chunk; });
250
- req.on('end', () => {
251
- const parsed = body ? JSON.parse(body) : {};
252
- send(res, 200, JSON.stringify({ ok: true, plan: planFrom(parsed) }));
253
- });
254
- return;
255
- }
256
- if (url.pathname === '/api/uitest/studio/batch/backfill') {
257
- return send(res, 200, JSON.stringify({ ok: true, preview: { results: 8, markdown: { files: 2, inserted: 8, replaced: 0 }, xlsx: null, files: ['cases/M006/M006履约管理模块-测试用例.xlsx', 'cases/M005-订单核心/销售订单/SO-LIST-列表与筛选.md'] } }));
258
- }
259
- if (url.pathname === '/api/uitest/studio/doctor') {
260
- return send(res, 200, JSON.stringify({ ok: true, passed: true, checks: [
261
- { id: 'config', label: '项目配置', status: 'ok', detail: sample.project + '/uitest.config.json' },
262
- { id: 'agent-browser', label: 'agent-browser', status: 'ok', detail: sample.env.agentBrowser },
263
- { id: 'state', label: '登录态', status: sample.env.stateReady ? 'ok' : 'warn', detail: sample.env.stateFile || '未配置' },
264
- ] }));
265
- }
266
- if (url.pathname === '/api/uitest/studio/accounts/import' || url.pathname === '/api/uitest/studio/accounts/import-upload') {
267
- return send(res, 200, JSON.stringify({ ok: true, added: 16, updated: 0, total: 16, defaultAccountId: 'wangzhengtao', warnings: [{ code: 'PASSWORD_IGNORED', message: '文档包含明文密码列;密码不会被保存,也不会回传。请用密码环境变量配置登录密码。' }], accounts: sample.accounts }));
268
- }
269
- if (url.pathname === '/api/uitest/studio/accounts/save' || url.pathname === '/api/uitest/studio/accounts/default' || url.pathname === '/api/uitest/studio/accounts/delete') {
270
- return send(res, 200, JSON.stringify({ ok: true, accounts: sample.accounts }));
271
- }
272
- if (url.pathname === '/api/uitest/studio/import-upload' || url.pathname === '/api/uitest/studio/import') {
273
- return send(res, 200, JSON.stringify({
274
- ok: true,
275
- caseCount: sample.cases.length,
276
- cases: sample.cases,
277
- doc: { name: 'M006 履约管理', generatedPath: 'cases/studio/M006-履约管理.md', version: 3, count: 242, docKey: 'm006履约管理' },
278
- diffSummary: { added: 2, updated: 8, unchanged: 232, removed: 1, missing: 1 },
279
- docs: sample.docs,
280
- warnings: [],
281
- snapshot: sample,
282
- uploadedFile: '.uitest/uploads/M006履约管理模块-测试用例.xlsx',
283
- }));
284
- }
285
- if (url.pathname === '/api/uitest/studio/case/delete' || url.pathname === '/api/uitest/studio/case/restore') {
286
- const body = await readJson(req);
287
- const ids = Array.isArray(body.ids) ? body.ids : [];
288
- if (url.pathname.endsWith('/delete')) {
289
- const removed = new Set(ids);
290
- sample.cases = sample.cases.filter((item) => !removed.has(item.tcId));
291
- sample.counts.total = sample.cases.length;
292
- }
293
- return send(res, 200, JSON.stringify({
294
- ok: true,
295
- deleted: url.pathname.endsWith('/delete') ? ids.length : 0,
296
- restored: url.pathname.endsWith('/restore') ? ids.length : 0,
297
- failed: 0,
298
- remaining: sample.cases.length,
299
- results: ids.map((tcId) => ({ caseId: tcId, ok: true, action: url.pathname.endsWith('/delete') ? 'deleted' : 'restored' })),
300
- }));
301
- }
302
- if (url.pathname === '/api/uitest/studio/export/cases' || url.pathname === '/api/uitest/studio/export/results') {
303
- const body = await readJson(req);
304
- const count = Array.isArray(body.caseIds) && body.caseIds.length ? body.caseIds.length : sample.cases.length;
305
- const kind = url.pathname.endsWith('/results') ? 'results' : 'cases';
306
- const fileName = (kind === 'results' ? '测试结果' : '测试用例') + '-预览.xlsx';
307
- return send(res, 200, JSON.stringify({
308
- ok: true,
309
- kind,
310
- file: '/tmp/' + fileName,
311
- fileName,
312
- count,
313
- summary: { total: count, passed: 12, partial: 4, failed: 3, blocked: 1, untested: Math.max(0, count - 20), percent: 80 },
314
- downloadUrl: '/api/uitest/studio/export/download?project=preview&file=' + encodeURIComponent(fileName) + '&name=' + encodeURIComponent(fileName),
315
- }));
316
- }
317
- if (url.pathname === '/api/uitest/studio/export/download') {
318
- const name = url.searchParams.get('name') || '预览导出.xlsx';
319
- res.writeHead(200, {
320
- 'content-type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
321
- 'content-disposition': "attachment; filename*=UTF-8''" + encodeURIComponent(name),
322
- 'cache-control': 'no-store',
323
- });
324
- return res.end(Buffer.from('PK\u0003\u0004 preview', 'utf8'));
325
- }
326
- if (url.pathname === '/api/uitest/studio/case/run' && req.method === 'POST') {
327
- const body = await readJson(req);
328
- if (body.batchId) {
329
- const batch = batchById(body.batchId);
330
- const result = requeueCase(batch, String(body.id || ''));
331
- return send(res, 200, JSON.stringify({
332
- ok: true,
333
- requeued: result.requeued === true,
334
- alreadyActive: result.alreadyActive === true,
335
- batch,
336
- }));
337
- }
338
- return send(res, 200, JSON.stringify({ ok: true, batch: { ...sample.activeBatch, id: 'b-preview-' + Date.now(), name: '预览批次' } }));
339
- }
340
- if (url.pathname === '/api/uitest/studio/batch' && req.method === 'POST') {
341
- return send(res, 200, JSON.stringify({ ok: true, batch: { ...sample.activeBatch, id: 'b-preview-' + Date.now(), name: '预览批次' } }));
342
- }
343
- if (url.pathname === '/api/uitest/studio/settings') {
344
- return send(res, 200, JSON.stringify({ ok: true, snapshot: sample }));
345
- }
346
- if (url.pathname === '/api/uitest/studio/project/open') {
347
- const body = await readJson(req);
348
- const initialized = !String(body.path || '').includes('studio-empty');
349
- return send(res, 200, JSON.stringify({ ok: true, project: initialized ? sample.project : body.path, initialized, entries: 0, snapshot: initialized ? sample : null }));
350
- }
351
- if (url.pathname === '/api/uitest/studio/project/init') {
352
- const body = await readJson(req);
353
- return send(res, 200, JSON.stringify({ ok: true, project: body.path || sample.project, initialized: true, entries: 0, snapshot: sample, created: ['uitest.config.json', 'cases/', 'flows/', 'reports/'] }));
354
- }
355
- if (url.pathname === '/api/uitest/studio/pick-path') {
356
- return send(res, 200, JSON.stringify({ ok: true, status: 'selected', path: '/tmp/studio-empty-preview' }));
357
- }
358
- if (url.pathname === '/api/uitest/studio/flows/delete') {
359
- const body = await readJson(req);
360
- const flows = Array.isArray(body.flows) ? body.flows : [];
361
- return send(res, 200, JSON.stringify({ ok: true, deleted: flows.length, failed: 0, results: flows.map((flow) => ({ ok: true, name: flow.name, file: flow.file, cases: ['TC-FP001-01'] })) }));
362
- }
363
- if (url.pathname === '/api/uitest/studio/feedback') {
364
- const body = await readJson(req);
365
- return send(res, 200, JSON.stringify({ ok: true, feedback: { id: 'fb-preview', at: new Date().toISOString(), caseId: body.caseId, note: body.note, runStatus: body.runStatus } }));
366
- }
367
- if (url.pathname === '/api/uitest/studio/knowledge' && req.method === 'GET') {
368
- return send(res, 200, JSON.stringify({
369
- ok: true,
370
- ...sample.knowledge,
371
- central: { enabled: true, ok: true, url: 'http://127.0.0.1:8000', groupId: 'oms-v2-test', nodes: [{ labels: ['Entity'], count: 245 }], edges: [{ type: 'RELATES_TO', count: 381 }], at: new Date().toISOString() },
372
- }));
373
- }
374
- if (url.pathname === '/api/uitest/studio/knowledge/central/browse') {
375
- const kind = url.searchParams.get('kind') || 'episodes';
376
- const q = (url.searchParams.get('q') || '').toLowerCase();
377
- const category = url.searchParams.get('category') || '';
378
- const limit = Math.max(1, Math.min(100, Number(url.searchParams.get('limit')) || 30));
379
- const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
380
- const categoryOf = (item) => {
381
- if (item.category) return item.category;
382
- const name = String(item.name || '');
383
- if (name.startsWith('page:')) return 'page';
384
- if (name.startsWith('process:') || name.startsWith('case:')) return 'operation';
385
- if (/报价单|订单|履约|单据|流转/.test(String(item.content || ''))) return 'document-flow';
386
- if (/限制|缺陷|注意|阻塞/.test(String(item.content || ''))) return 'caution';
387
- return 'business-flow';
388
- };
389
- const all = (sample.centralKnowledge?.[kind] || []).map((item) => (kind === 'episodes' ? { ...item, category: categoryOf(item) } : item));
390
- const matched = all.filter((item) => (!q || JSON.stringify(item).toLowerCase().includes(q)) && (!category || item.category === category));
391
- const items = matched.slice(offset, offset + limit);
392
- return send(res, 200, JSON.stringify({
393
- ok: true,
394
- enabled: true,
395
- kind,
396
- category,
397
- items,
398
- hasMore: offset + limit < matched.length,
399
- offset,
400
- limit,
401
- groupId: 'oms-v2-test',
402
- }));
403
- }
404
- if (url.pathname === '/api/uitest/studio/knowledge/central/semantic-index') {
405
- return send(res, 200, JSON.stringify({ ok: true, scanned: 5, indexed: 5, remaining: 12, errors: [] }));
406
- }
407
- if (url.pathname === '/api/uitest/studio/knowledge/central/extract') {
408
- return send(res, 200, JSON.stringify({ ok: true, engine: 'llm', scanned: 20, remaining: 3, stored: [{ category: 'page', points: 2 }, { category: 'document-flow', points: 2 }] }));
409
- }
410
- if (url.pathname === '/api/uitest/studio/knowledge/central/extractions') {
411
- return send(res, 200, JSON.stringify({
412
- ok: true,
413
- items: [
414
- { uuid: 'ex-1', category: 'page', points: [{ title: '履约单列表', detail: '筛选区包含履约单编号,表头固定。', source: 'page:fulfill-list' }] },
415
- { uuid: 'ex-2', category: 'document-flow', points: [{ title: '报价转订单', detail: '报价单审批生效后可转订单,再受理。', source: 'policy:报价单建单与提交' }] },
416
- ],
417
- }));
418
- }
419
- if (url.pathname === '/api/uitest/studio/knowledge/central/categories') {
420
- return send(res, 200, JSON.stringify({ ok: true, enabled: true, scanned: 3, updated: 0, groupId: 'oms-v2-test' }));
421
- }
422
- if (url.pathname === '/api/uitest/studio/knowledge/central/search') {
423
- const q = url.searchParams.get('q') || '';
424
- return send(res, 200, JSON.stringify({
425
- ok: true,
426
- query: q,
427
- results: (sample.centralKnowledge?.facts || []).slice(0, 5).map((item) => ({ uuid: item.uuid, fact: item.fact, name: item.name })),
428
- }));
429
- }
430
- if (url.pathname === '/api/uitest/studio/knowledge/docs') {
431
- return send(res, 200, JSON.stringify({
432
- ok: true,
433
- documents: [
434
- { id: 'doc-preview-1', name: '报价单建单与提交.md', category: 'document-flow', format: '.md', centralUuid: 'ep-preview-1', updatedAt: new Date().toISOString() },
435
- { id: 'doc-preview-2', name: 'OMS 已知限制.md', category: 'caution', format: '.md', centralUuid: '', updatedAt: new Date().toISOString() },
436
- ],
437
- }));
438
- }
439
- if (url.pathname === '/api/uitest/studio/knowledge/docs/item') {
440
- return send(res, 200, JSON.stringify({
441
- ok: true,
442
- document: { id: url.searchParams.get('id') || '', name: '报价单建单与提交.md', category: 'document-flow', format: '.md', centralUuid: 'ep-preview-1', updatedAt: new Date().toISOString() },
443
- content: '# 报价单建单与提交\n\n1. 复制或新建报价单\n2. 保存草稿\n3. 提交审核\n4. 审批生效后转订单\n5. 订单受理',
444
- }));
445
- }
446
- if (url.pathname === '/api/uitest/studio/knowledge/docs/update') {
447
- const body = await readJson(req);
448
- return send(res, 200, JSON.stringify({
449
- ok: true,
450
- document: { id: body.id, name: body.name, category: body.category, centralUuid: 'ep-preview-1', updatedAt: new Date().toISOString() },
451
- central: { ok: true, error: '' },
452
- }));
453
- }
454
- if (url.pathname === '/api/uitest/studio/knowledge/docs/delete') {
455
- return send(res, 200, JSON.stringify({ ok: true, deleted: true, central: { ok: true } }));
456
- }
457
- if (url.pathname === '/api/uitest/studio/knowledge/central/episode') {
458
- const uuid = url.searchParams.get('uuid') || '';
459
- const item = (sample.centralKnowledge?.episodes || []).find((entry) => entry.uuid === uuid);
460
- if (!item) {
461
- res.statusCode = 404;
462
- return send(res, 404, JSON.stringify({ ok: false, error: { code: 'KNOWLEDGE_EPISODE_NOT_FOUND', message: '中心知识库没有该条目' } }));
463
- }
464
- return send(res, 200, JSON.stringify({ ok: true, enabled: true, item, groupId: 'oms-v2-test' }));
465
- }
466
- if (url.pathname === '/api/uitest/studio/knowledge/central/import' || url.pathname === '/api/uitest/studio/knowledge/central/import-upload') {
467
- const body = await readJson(req);
468
- const name = body.name || (Array.isArray(body.paths) ? baseName(body.paths[0]) : '知识文档.md');
469
- const dryRun = body.dryRun === true;
470
- return send(res, 200, JSON.stringify({
471
- ok: true,
472
- enabled: true,
473
- dryRun,
474
- uploadedFile: url.pathname.endsWith('import-upload') ? '.uitest/uploads/knowledge/' + name : undefined,
475
- documents: [{ path: name, name, format: 'md', size: 1024, status: 'imported' }],
476
- totals: { files: 1, episodes: 1, ingested: dryRun ? 0 : 1, skipped: 0, failed: 0 },
477
- errors: [],
478
- warnings: [],
479
- }));
480
- }
481
- if (url.pathname === '/api/uitest/studio/knowledge/central/test') {
482
- return send(res, 200, JSON.stringify({ ok: true, central: { enabled: true, ok: true, url: 'http://127.0.0.1:8000', groupId: 'oms-v2-test', nodes: [{ labels: ['Entity'], count: 245 }], edges: [{ type: 'RELATES_TO', count: 381 }] } }));
483
- }
484
- if (url.pathname.startsWith('/api/uitest/studio/')) {
485
- return send(res, 200, JSON.stringify({ ok: true }));
486
- }
487
- if (url.pathname === '/') return sendFile(res, path.join(__dirname, 'index.html'), 'text/html; charset=utf-8');
488
- if (url.pathname === '/client.js') return sendFile(res, path.join(root, 'uitest/client.js'), 'application/javascript; charset=utf-8');
489
- if (url.pathname.startsWith('/node_modules/')) {
490
- const file = path.resolve(root, url.pathname.replace(/^\/+/, ''));
491
- return sendFile(res, file, 'application/javascript; charset=utf-8');
492
- }
493
- send(res, 404, 'not found', 'text/plain');
494
- });
495
-
496
- server.listen(port, () => {
497
- console.log('studio preview: http://127.0.0.1:' + port);
498
- });
@@ -1,90 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import fs from 'node:fs';
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import test from 'node:test';
6
-
7
- import { loadConfig } from '../../lib/config.mjs';
8
- import {
9
- accountConfigFor,
10
- accountsPayload,
11
- deleteAccount,
12
- importAccountsText,
13
- parseAccountsDocument,
14
- readAccountsStore,
15
- saveAccount,
16
- setDefaultAccount,
17
- } from '../accounts.mjs';
18
-
19
- const DOC = path.resolve('../docs/角色权限/OMS测试账号.md');
20
-
21
- function makeProject() {
22
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-accounts-'));
23
- fs.writeFileSync(path.join(dir, 'uitest.config.json'), JSON.stringify({
24
- baseUrl: 'http://example.test',
25
- auth: { username: 'tester', passwordEnv: 'UITEST_PASSWORD', storageState: '.auth/oms.json' },
26
- cases: { markdown: 'cases' },
27
- output: { dir: 'reports' },
28
- }, null, 2));
29
- return loadConfig(dir);
30
- }
31
-
32
- test('accounts: 解析 OMS测试账号.md,合并同账号多角色并保存密码到本地配置', () => {
33
- const text = fs.readFileSync(DOC, 'utf8');
34
- const parsed = parseAccountsDocument(text, { sourcePath: DOC });
35
- assert.equal(parsed.accounts.length, 16);
36
- assert.equal(parsed.rows, 19);
37
- assert.equal(parsed.passwordSeen, true);
38
- const wang = parsed.accounts.find((item) => item.username === 'wangzhengtao');
39
- assert.deepEqual(wang.roles, ['OMS销售', 'OMS采购']);
40
- assert.equal(wang.department, '营口办');
41
- assert.equal(wang.area, '东北片区');
42
- assert.ok(wang.password);
43
- assert.match(parsed.warnings[0].message, /已保存到本地账号配置/);
44
- });
45
-
46
- test('accounts: 导入合并、幂等、保留本地编辑、默认账号与删除', () => {
47
- const config = makeProject();
48
- const text = fs.readFileSync(DOC, 'utf8');
49
- const first = importAccountsText(config, { text, file: DOC });
50
- assert.equal(first.added, 16);
51
- assert.equal(first.total, 16);
52
- assert.equal(first.passwordSaved, true);
53
- assert.equal(accountsPayload(config).accounts.length, 16);
54
- const raw = fs.readFileSync(path.join(config.paths.uitestDir, 'studio', 'accounts.json'), 'utf8');
55
- const stored = JSON.parse(raw);
56
- assert.ok(stored.accounts.find((item) => item.username === 'wangzhengtao').password);
57
- const apiPayload = accountsPayload(config);
58
- assert.equal(Object.prototype.hasOwnProperty.call(apiPayload.accounts[0], 'password'), false);
59
- assert.equal(apiPayload.accounts.find((item) => item.username === 'wangzhengtao').passwordSet, true);
60
- const storedAccount = stored.accounts.find((item) => item.username === 'wangzhengtao');
61
- assert.equal(accountConfigFor(config, storedAccount).auth.password, storedAccount.password);
62
-
63
- const current = accountsPayload(config).accounts.find((item) => item.username === 'wangzhengtao');
64
- saveAccount(config, { id: current.id, patch: { notes: '建单主力', passwordEnv: 'OMS_WANG_PASSWORD', password: 'new-secret' } });
65
- const second = importAccountsText(config, { text, file: DOC });
66
- assert.equal(second.updated, 16);
67
- assert.equal(second.total, 16);
68
- const after = accountsPayload(config).accounts.find((item) => item.username === 'wangzhengtao');
69
- assert.equal(after.notes, '建单主力');
70
- assert.equal(after.passwordEnv, 'OMS_WANG_PASSWORD');
71
- assert.equal(after.passwordSet, true);
72
- assert.deepEqual(after.roles, ['OMS销售', 'OMS采购']);
73
-
74
- setDefaultAccount(config, 'weizheyu');
75
- assert.equal(accountsPayload(config).defaultAccountId, 'weizheyu');
76
- const removed = deleteAccount(config, 'liuzhan');
77
- assert.equal(removed.count, 15);
78
- assert.equal(removed.defaultAccountId, 'weizheyu');
79
- });
80
-
81
- test('accounts: 新账号默认密码环境变量与会话文件', () => {
82
- const config = makeProject();
83
- saveAccount(config, { id: '', patch: { username: 'newuser', name: '新用户', roles: ['OMS销售'], department: '测试部', area: '测试片区' } });
84
- const account = accountsPayload(config).accounts.find((item) => item.username === 'newuser');
85
- assert.equal(account.passwordEnv, 'UITEST_PASSWORD');
86
- assert.equal(account.storageState, '.auth/oms-newuser.json');
87
- assert.equal(account.sessionReady, false);
88
- const store = readAccountsStore(config);
89
- assert.equal(store.accounts.length, 1);
90
- });
@@ -1,53 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import fs from 'node:fs';
3
- import os from 'node:os';
4
- import path from 'node:path';
5
- import test from 'node:test';
6
-
7
- import { loadConfig } from '../../lib/config.mjs';
8
- import { readAgentLive, startAgentLive, stopAgentLive } from '../agent-live.mjs';
9
-
10
- function makeProject() {
11
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'studio-agent-live-'));
12
- fs.writeFileSync(path.join(dir, 'uitest.config.json'), JSON.stringify({
13
- baseUrl: 'http://example.test',
14
- cases: { markdown: 'cases' },
15
- output: { dir: 'reports' },
16
- }, null, 2));
17
- return loadConfig(dir);
18
- }
19
-
20
- test('agent-live: 读取 Agent 思考 comment、动作、账号', async () => {
21
- const config = makeProject();
22
- const sessionId = 'ags-test';
23
- const runDir = path.join(config.paths.runsDir, 'agent-test');
24
- fs.mkdirSync(runDir, { recursive: true });
25
- fs.writeFileSync(path.join(runDir, 'run.json'), JSON.stringify({
26
- steps: [
27
- { index: 1, id: 's1', action: 'comment', desc: '先确认前置数据', detail: { comment: '先确认前置数据' }, status: 'passed', account: 'wangzhengtao', role: 'OMS销售' },
28
- { index: 2, id: 's2', action: 'click', desc: '打开订单', status: 'passed', account: 'wangzhengtao', screenshot: 'screenshots/s2.png' },
29
- ],
30
- }));
31
- fs.mkdirSync(path.join(config.paths.uitestDir, 'agent-sessions'), { recursive: true });
32
- fs.writeFileSync(path.join(config.paths.uitestDir, 'agent-sessions', sessionId + '.json'), JSON.stringify({
33
- id: sessionId,
34
- sessionName: 'uitest-agent-ags-test-wangzhengtao',
35
- accountId: 'wangzhengtao',
36
- runJsonPath: path.join(runDir, 'run.json'),
37
- status: 'running',
38
- recovery: { required: true, lastFailure: { stepId: 's2', action: 'click', error: 'selector 无效' } },
39
- }));
40
- startAgentLive(config, { batchId: 'b-20261117-120000-abcd', caseId: 'TC-1', jobId: 'job-1', sessionId, sessionName: 'uitest-agent-ags-test-wangzhengtao' });
41
- const live = readAgentLive(config, 'b-20261117-120000-abcd', 'TC-1');
42
- assert.equal(live.active, true);
43
- assert.equal(live.steps.length, 2);
44
- assert.equal(live.steps[0].comment, '先确认前置数据');
45
- assert.equal(live.steps[0].account, 'wangzhengtao');
46
- assert.equal(live.steps[1].action, 'click');
47
- assert.equal(live.recovery.required, true);
48
- assert.equal(live.recovery.lastFailure.action, 'click');
49
- stopAgentLive(config, 'b-20261117-120000-abcd', 'TC-1', { note: '完成' });
50
- const stopped = readAgentLive(config, 'b-20261117-120000-abcd', 'TC-1');
51
- assert.equal(stopped.active, false);
52
- assert.equal(stopped.note, '完成');
53
- });