dsh-uitest 2.3.1 → 2.4.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 +72 -11
- package/bin/uitest.mjs +189 -11
- package/client.js +81 -11
- package/host/agent-bridge.mjs +9 -2
- package/host/agent-test.mjs +1 -1
- package/host/context-budget.mjs +1 -1
- package/index.js +14 -2
- package/lib/agent-session.mjs +81 -3
- package/lib/agent-tasks.mjs +212 -0
- package/lib/batch.mjs +204 -13
- package/lib/browser-ab.mjs +21 -6
- package/lib/browser.mjs +5 -5
- package/lib/config.mjs +1 -0
- package/lib/convert.mjs +178 -40
- package/lib/doc-structure.mjs +316 -0
- package/lib/flow.mjs +49 -14
- package/lib/knowledge-central-episodes.mjs +120 -0
- package/lib/knowledge-central-import.mjs +16 -1
- package/lib/knowledge-central.mjs +149 -22
- package/lib/knowledge-clean.mjs +749 -0
- package/lib/knowledge-consolidate.mjs +1271 -0
- package/lib/knowledge-coverage.mjs +150 -0
- package/lib/knowledge-docs.mjs +3 -3
- package/lib/knowledge-effect.mjs +148 -0
- package/lib/knowledge-facts.mjs +1008 -0
- package/lib/knowledge-maintain.mjs +185 -0
- package/lib/knowledge-permission.mjs +447 -0
- package/lib/knowledge-query.mjs +304 -26
- package/lib/knowledge-store.mjs +169 -14
- package/lib/knowledge-summarize.mjs +332 -0
- package/lib/knowledge.mjs +944 -47
- package/lib/learn-run.mjs +157 -51
- package/lib/run-learn.mjs +34 -0
- package/lib/run-observe.mjs +95 -27
- package/lib/run-stats.mjs +71 -0
- package/package.json +12 -2
- package/scripts/knowledge-central-purge.mjs +248 -0
- package/scripts/knowledge-central-sync.mjs +102 -20
- package/scripts/knowledge-consolidate.mjs +158 -0
- package/scripts/knowledge-coverage.mjs +94 -0
- package/scripts/knowledge-effect.mjs +82 -0
- package/scripts/knowledge-permission-probe.mjs +196 -0
- package/scripts/knowledge-permission-report.mjs +140 -0
- package/scripts/knowledge-report.mjs +492 -0
- package/scripts/knowledge-summarize.mjs +200 -0
- package/skills/uitest/SKILL.md +4 -2
- package/skills/uitest/references/convert-knowledge.md +66 -13
- package/studio/host.mjs +120 -3
- package/studio/knowledge.mjs +195 -45
- package/studio/snapshot.mjs +6 -1
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Agent 交接清单:批次把没有 flow 的用例写成结构化作业,宿主执行完后按会话对账。
|
|
2
|
+
// 清单是协议,不是执行器;这里不启动浏览器,也不写结果库。
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { listAgentSessions } from './agent-session.mjs';
|
|
7
|
+
import { loadProjectCases } from './cases-import.mjs';
|
|
8
|
+
import { validateFlow } from './flow.mjs';
|
|
9
|
+
import { findCase } from './xlsx.mjs';
|
|
10
|
+
import { ensureDir, nowIso, slug, writeFileAtomic } from './util.mjs';
|
|
11
|
+
import { readCaseRuns } from '../studio/store.mjs';
|
|
12
|
+
|
|
13
|
+
export const AGENT_TASK_STATES = ['pending', 'done', 'partial', 'failed', 'blocked'];
|
|
14
|
+
|
|
15
|
+
const VERDICT_STATE = { 通过: 'done', 部分通过: 'partial', 失败: 'failed', 阻塞: 'blocked' };
|
|
16
|
+
// 工作室批次用例状态用的是英文,流水线批次历史记录里是中文,两套都要认。
|
|
17
|
+
const RUN_STATE = { passed: 'done', 通过: 'done', partial: 'partial', 部分通过: 'partial', failed: 'failed', 失败: 'failed', blocked: 'blocked', stopped: 'blocked' };
|
|
18
|
+
|
|
19
|
+
export function agentTasksFile(config, batchId) {
|
|
20
|
+
return path.join(config.paths.outputDir, 'batches', batchId, 'agent-tasks.json');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 从批次计划生成清单;只收 agent-ready。任务 id 只由批次和用例决定,可重复生成。 */
|
|
24
|
+
export function planAgentTasks({ config, plan, cases = [], batchId, createdAt = nowIso() }) {
|
|
25
|
+
const list = cases.length ? cases : loadProjectCases(config).cases;
|
|
26
|
+
const tasks = [];
|
|
27
|
+
for (const item of plan?.items || []) {
|
|
28
|
+
if (item.state !== 'agent-ready') continue;
|
|
29
|
+
const caseItem = findCase(list, item.caseId)?.case || {};
|
|
30
|
+
tasks.push({
|
|
31
|
+
id: `agent-task-${batchId}-${slug(item.caseId)}`,
|
|
32
|
+
batchId,
|
|
33
|
+
caseId: item.caseId,
|
|
34
|
+
title: item.title || caseItem.functionPoint || '',
|
|
35
|
+
precondition: item.precondition || caseItem.precondition || '',
|
|
36
|
+
steps: caseItem.steps || '',
|
|
37
|
+
expected: caseItem.expected || '',
|
|
38
|
+
advisoryNeeds: item.advisoryNeeds || [],
|
|
39
|
+
draftFlow: item.draftFlow
|
|
40
|
+
? { name: item.draftFlow.name, file: item.draftFlow.file, generated: item.draftFlow.generated || null }
|
|
41
|
+
: null,
|
|
42
|
+
knowledge: {
|
|
43
|
+
library: config?.knowledge?.library || null,
|
|
44
|
+
hint: `uitest agent-session knowledge --case ${item.caseId}`,
|
|
45
|
+
},
|
|
46
|
+
acceptance: {
|
|
47
|
+
verdict: '通过',
|
|
48
|
+
distill: true,
|
|
49
|
+
note: item.draftFlow
|
|
50
|
+
? '草稿 flow 缺可执行入口或断言;以它为参考修正,跑通后 finish 通过沉淀新 flow'
|
|
51
|
+
: '跑通后用 agent-session finish --verdict 通过 沉淀 flow;失败也要 finish 记录结论',
|
|
52
|
+
},
|
|
53
|
+
status: 'pending',
|
|
54
|
+
createdAt,
|
|
55
|
+
result: null,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return tasks;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function persistAgentTasks(config, payload) {
|
|
62
|
+
const file = agentTasksFile(config, payload.batchId);
|
|
63
|
+
ensureDir(path.dirname(file));
|
|
64
|
+
const next = { ...payload, total: payload.tasks.length, updatedAt: nowIso(), file };
|
|
65
|
+
writeFileAtomic(file, `${JSON.stringify(next, null, 2)}\n`);
|
|
66
|
+
return {
|
|
67
|
+
file,
|
|
68
|
+
batchId: payload.batchId,
|
|
69
|
+
total: next.total,
|
|
70
|
+
pending: next.tasks.filter((task) => task.status === 'pending').length,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function saveAgentTasks(config, batchId, tasks, createdAt = nowIso()) {
|
|
75
|
+
if (!tasks.length) return null;
|
|
76
|
+
return persistAgentTasks(config, {
|
|
77
|
+
version: 1,
|
|
78
|
+
batchId,
|
|
79
|
+
createdAt,
|
|
80
|
+
tasks,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function readAgentTasks(config, batchId) {
|
|
85
|
+
const file = agentTasksFile(config, batchId);
|
|
86
|
+
if (!fs.existsSync(file)) return null;
|
|
87
|
+
const payload = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
88
|
+
return { ...payload, file };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 最近一个带清单的批次,供 CLI 省略 --batch。 */
|
|
92
|
+
export function latestAgentTasksBatch(config) {
|
|
93
|
+
const dir = path.join(config.paths.outputDir, 'batches');
|
|
94
|
+
if (!fs.existsSync(dir)) return null;
|
|
95
|
+
const names = fs
|
|
96
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
97
|
+
.filter((entry) => entry.isDirectory() && fs.existsSync(path.join(dir, entry.name, 'agent-tasks.json')))
|
|
98
|
+
.map((entry) => entry.name)
|
|
99
|
+
.sort();
|
|
100
|
+
return names.at(-1) || null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function summarizeAgentTasks(payload) {
|
|
104
|
+
const counts = {};
|
|
105
|
+
for (const task of payload?.tasks || []) counts[task.status] = (counts[task.status] || 0) + 1;
|
|
106
|
+
return {
|
|
107
|
+
batchId: payload?.batchId || '',
|
|
108
|
+
file: payload?.file || '',
|
|
109
|
+
total: (payload?.tasks || []).length,
|
|
110
|
+
pending: counts.pending || 0,
|
|
111
|
+
counts,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 供宿主快照与入口读取最近一份清单;没有清单时返回 null。 */
|
|
116
|
+
export function latestAgentTasksSummary(config) {
|
|
117
|
+
const batchId = latestAgentTasksBatch(config);
|
|
118
|
+
if (!batchId) return null;
|
|
119
|
+
const payload = readAgentTasks(config, batchId);
|
|
120
|
+
return payload ? summarizeAgentTasks(payload) : null;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 通过结论必须落下一个能回放的 flow;文件缺失或结构不合法都要在对账时暴露。 */
|
|
124
|
+
function inspectFlowArtifact(config, ref) {
|
|
125
|
+
if (!ref) return { flowValid: false, flowError: '结论为通过,但没有沉淀 flow 文件' };
|
|
126
|
+
const file = path.isAbsolute(ref) ? ref : path.join(config.paths.flowsDir, ref);
|
|
127
|
+
if (!fs.existsSync(file)) return { flowValid: false, flowError: `flow 文件不存在:${file}` };
|
|
128
|
+
try {
|
|
129
|
+
validateFlow(JSON.parse(fs.readFileSync(file, 'utf8')), file);
|
|
130
|
+
return { flowValid: true, flowError: null };
|
|
131
|
+
} catch (error) {
|
|
132
|
+
return { flowValid: false, flowError: error.message };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 宿主认领清单时登记批次,对账才知道哪些用例记录属于本轮认领。 */
|
|
137
|
+
export function recordAgentTasksAdoption(config, batchId, adoptedBatchId, at = nowIso()) {
|
|
138
|
+
const payload = readAgentTasks(config, batchId);
|
|
139
|
+
if (!payload) return null;
|
|
140
|
+
const adoptions = (payload.adoptions || []).filter((item) => item.batchId !== adoptedBatchId);
|
|
141
|
+
adoptions.push({ batchId: adoptedBatchId, at });
|
|
142
|
+
return persistAgentTasks(config, { ...payload, adoptions });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 对账:按 caseId 找任务创建后开始的已结束会话,写回结论,并校验通过的 flow 能否回放。
|
|
147
|
+
* 会话没有结论时回落到认领批次自己的用例记录,宿主执行失败也要落结论而不是永远 pending。
|
|
148
|
+
*/
|
|
149
|
+
export function reconcileAgentTasks(config, payload) {
|
|
150
|
+
const sessions = listAgentSessions(config)
|
|
151
|
+
.filter((session) => session.status === 'finished' && session.verdict && session.finishedAt)
|
|
152
|
+
.sort((a, b) => String(b.finishedAt).localeCompare(String(a.finishedAt)));
|
|
153
|
+
const runs = reconcileAdoptedRuns(config, payload);
|
|
154
|
+
const tasks = (payload.tasks || []).map((task) => {
|
|
155
|
+
const match = sessions.find(
|
|
156
|
+
(session) => session.caseId === task.caseId && String(session.createdAt || '') >= String(task.createdAt || ''),
|
|
157
|
+
);
|
|
158
|
+
if (match) {
|
|
159
|
+
const artifact = match.verdict === '通过' ? inspectFlowArtifact(config, match.flow) : { flowValid: null, flowError: null };
|
|
160
|
+
return {
|
|
161
|
+
...task,
|
|
162
|
+
status: VERDICT_STATE[match.verdict] || 'done',
|
|
163
|
+
reconciledAt: nowIso(),
|
|
164
|
+
result: {
|
|
165
|
+
sessionId: match.sessionId,
|
|
166
|
+
verdict: match.verdict,
|
|
167
|
+
runDir: match.runDir || null,
|
|
168
|
+
flow: match.flow || null,
|
|
169
|
+
...artifact,
|
|
170
|
+
note: match.note || '',
|
|
171
|
+
finishedAt: match.finishedAt,
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const run = runs.find((item) => item.caseId === task.caseId);
|
|
176
|
+
const state = run ? RUN_STATE[run.status] : null;
|
|
177
|
+
if (!state) return task;
|
|
178
|
+
const artifact = state === 'done' ? inspectFlowArtifact(config, run.flow) : { flowValid: null, flowError: null };
|
|
179
|
+
return {
|
|
180
|
+
...task,
|
|
181
|
+
status: state,
|
|
182
|
+
reconciledAt: nowIso(),
|
|
183
|
+
result: {
|
|
184
|
+
source: 'batch',
|
|
185
|
+
batchId: run.batchId || null,
|
|
186
|
+
verdict: run.status,
|
|
187
|
+
runDir: run.runDir || null,
|
|
188
|
+
flow: run.flow || null,
|
|
189
|
+
...artifact,
|
|
190
|
+
note: run.note || '',
|
|
191
|
+
finishedAt: run.endedAt || null,
|
|
192
|
+
},
|
|
193
|
+
};
|
|
194
|
+
});
|
|
195
|
+
return { ...payload, tasks };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function reconcileAdoptedRuns(config, payload) {
|
|
199
|
+
const out = [];
|
|
200
|
+
for (const adoption of payload.adoptions || []) {
|
|
201
|
+
let runs = [];
|
|
202
|
+
try {
|
|
203
|
+
runs = readCaseRuns(config, adoption.batchId);
|
|
204
|
+
} catch {
|
|
205
|
+
runs = [];
|
|
206
|
+
}
|
|
207
|
+
for (const run of runs) {
|
|
208
|
+
if (RUN_STATE[run.status]) out.push({ ...run, adoptedAt: adoption.at });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return out.sort((a, b) => String(b.endedAt || '').localeCompare(String(a.endedAt || '')));
|
|
212
|
+
}
|
package/lib/batch.mjs
CHANGED
|
@@ -17,6 +17,11 @@ import {
|
|
|
17
17
|
describeRecipeLibrary,
|
|
18
18
|
} from './seed.mjs';
|
|
19
19
|
import { addResult, collectRunEvidence } from './results.mjs';
|
|
20
|
+
import { planAgentTasks, saveAgentTasks } from './agent-tasks.mjs';
|
|
21
|
+
import { learnRun } from './run-learn.mjs';
|
|
22
|
+
import { loadFlowRunStats } from './run-stats.mjs';
|
|
23
|
+
import { convertCase } from './convert.mjs';
|
|
24
|
+
import { loadKnowledge, resolveRunDir } from './knowledge.mjs';
|
|
20
25
|
import * as abDriver from './browser-ab.mjs';
|
|
21
26
|
|
|
22
27
|
// 批量测试固定走 agent-browser;Playwright 只保留给登录/审批兼容层和手工对照。
|
|
@@ -92,18 +97,62 @@ export function indexFlowsByCase(flows = []) {
|
|
|
92
97
|
return map;
|
|
93
98
|
}
|
|
94
99
|
|
|
95
|
-
function
|
|
96
|
-
|
|
97
|
-
if (
|
|
98
|
-
return 0;
|
|
100
|
+
function flowOutcomeRank(flow, runStats) {
|
|
101
|
+
const stat = runStats?.[flow.name];
|
|
102
|
+
if (!stat || stat.lastStatus === null) return 1;
|
|
103
|
+
return stat.lastStatus === 'passed' ? 0 : stat.lastStatus === 'failed' ? 2 : 1;
|
|
99
104
|
}
|
|
100
105
|
|
|
101
|
-
/**
|
|
102
|
-
|
|
103
|
-
|
|
106
|
+
/**
|
|
107
|
+
* 来源排序:人工 flow 最先;真实跑通的 Agent 轨迹其次;规则生成的 needsReview 草稿最后。
|
|
108
|
+
* Agent 轨迹里含判断步骤时仍排在草稿前面,CLI 回放会把这些步骤标成未验证。
|
|
109
|
+
*/
|
|
110
|
+
function flowSourceRank(flow) {
|
|
111
|
+
const tags = asArray(flow.tags);
|
|
112
|
+
const generatedBy = flow.generated?.by;
|
|
113
|
+
if (!generatedBy) return 0;
|
|
114
|
+
const agentVerified = tags.includes('agent-verified') || generatedBy === 'uitest-agent-execute';
|
|
115
|
+
if (agentVerified) return (flow.steps || []).some((step) => step.action === 'agent') ? 3 : 1;
|
|
116
|
+
if (flow.generated?.needsReview === true) return 4;
|
|
117
|
+
return 2;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** 一个用例只选一条执行 flow:最近成功优先,其次人工 flow,再次 Agent 真实轨迹,最后是规则草稿。 */
|
|
121
|
+
function pickCaseFlow(matched, runStats = {}) {
|
|
122
|
+
const sorted = [...matched].sort((a, b) =>
|
|
123
|
+
flowOutcomeRank(a, runStats) - flowOutcomeRank(b, runStats)
|
|
124
|
+
|| flowSourceRank(a) - flowSourceRank(b)
|
|
125
|
+
|| String(a.name).localeCompare(String(b.name)));
|
|
104
126
|
return { chosen: sorted[0] || null, alternatives: sorted.slice(1) };
|
|
105
127
|
}
|
|
106
128
|
|
|
129
|
+
function flowHealth(flow, runStats) {
|
|
130
|
+
const stat = runStats?.[flow.name];
|
|
131
|
+
if (!stat) return null;
|
|
132
|
+
return {
|
|
133
|
+
lastStatus: stat.lastStatus,
|
|
134
|
+
lastStartedAt: stat.lastStartedAt,
|
|
135
|
+
lastDurationMs: stat.lastDurationMs,
|
|
136
|
+
successRate: stat.successRate,
|
|
137
|
+
runs: stat.runs,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 规则草稿至少要能到达页面并核对一个断言,才算可执行。
|
|
143
|
+
* 人工 flow 和 Agent 真实轨迹不受此限;Agent 判断步骤本身就是验证。
|
|
144
|
+
*/
|
|
145
|
+
export function flowExecutable(flow) {
|
|
146
|
+
if (!flow) return false;
|
|
147
|
+
const tags = Array.isArray(flow.tags) ? flow.tags : [];
|
|
148
|
+
const agentVerified = tags.includes('agent-verified') || flow.generated?.by === 'uitest-agent-execute';
|
|
149
|
+
if (!flow.generated?.by || agentVerified) return true;
|
|
150
|
+
const steps = Array.isArray(flow.steps) ? flow.steps : [];
|
|
151
|
+
const hasNavigation = steps.some((step) => step.action === 'goto' || step.action === 'subflow');
|
|
152
|
+
const hasAssertion = steps.some((step) => step.action === 'expect' || step.action === 'assert');
|
|
153
|
+
return hasNavigation && hasAssertion;
|
|
154
|
+
}
|
|
155
|
+
|
|
107
156
|
/* ------------------------------------------------------------------ */
|
|
108
157
|
/* 计划 */
|
|
109
158
|
/* ------------------------------------------------------------------ */
|
|
@@ -148,6 +197,7 @@ export function buildBatchPlan({
|
|
|
148
197
|
classFilter,
|
|
149
198
|
limit,
|
|
150
199
|
scope = 'flows',
|
|
200
|
+
runStats = {},
|
|
151
201
|
} = {}) {
|
|
152
202
|
const selected = selectCases({ cases, flows, tag, caseRefs, classFilter, limit, scope });
|
|
153
203
|
const byCase = indexFlowsByCase(flows);
|
|
@@ -156,8 +206,12 @@ export function buildBatchPlan({
|
|
|
156
206
|
const caseId = String(caseItem.tcId);
|
|
157
207
|
let candidates = byCase.get(caseId) || [];
|
|
158
208
|
if (tagSet) candidates = candidates.filter((flow) => flow.tags.includes(tag));
|
|
159
|
-
const
|
|
209
|
+
const executable = candidates.filter((flow) => flowExecutable(flow));
|
|
210
|
+
const unusable = candidates.filter((flow) => !flowExecutable(flow));
|
|
211
|
+
const { chosen, alternatives } = pickCaseFlow(executable, runStats);
|
|
212
|
+
const draft = chosen ? null : pickCaseFlow(unusable, runStats).chosen;
|
|
160
213
|
const matched = chosen ? [chosen] : [];
|
|
214
|
+
const chosenHealth = chosen ? flowHealth(chosen, runStats) : null;
|
|
161
215
|
const requires = uniq(matched.flatMap((flow) => flow.requires));
|
|
162
216
|
const preferredRecipes = uniq(matched.flatMap((flow) => flow.seedRecipes || []));
|
|
163
217
|
const seed = planSeeds({ needs: requires, recipes, allowWrites, preferRecipeIds: preferredRecipes });
|
|
@@ -170,7 +224,11 @@ export function buildBatchPlan({
|
|
|
170
224
|
reasons.push('用例标注不可自动化/已知缺陷,需人工执行');
|
|
171
225
|
} else {
|
|
172
226
|
state = 'agent-ready';
|
|
173
|
-
reasons.push(
|
|
227
|
+
reasons.push(
|
|
228
|
+
draft
|
|
229
|
+
? `flow ${draft.name} 没有可执行入口或断言,交给 Agent 修正后再回放`
|
|
230
|
+
: '没有 flow;可由 DSH Agent 按自然语言直接执行,通过后沉淀 flow',
|
|
231
|
+
);
|
|
174
232
|
}
|
|
175
233
|
} else if (seed.state === 'missing') {
|
|
176
234
|
state = 'needs-data';
|
|
@@ -181,6 +239,9 @@ export function buildBatchPlan({
|
|
|
181
239
|
} else {
|
|
182
240
|
state = 'ready';
|
|
183
241
|
}
|
|
242
|
+
if (chosen && chosenHealth?.lastStatus === 'failed') {
|
|
243
|
+
reasons.push('该 flow 上次执行失败;批次前会按最近运行与人工反馈尝试刷新');
|
|
244
|
+
}
|
|
184
245
|
return {
|
|
185
246
|
caseId,
|
|
186
247
|
seq: caseItem.seq,
|
|
@@ -202,8 +263,12 @@ export function buildBatchPlan({
|
|
|
202
263
|
requires: flow.requires,
|
|
203
264
|
seedRecipes: flow.seedRecipes || [],
|
|
204
265
|
generated: flow.generated || null,
|
|
266
|
+
health: flowHealth(flow, runStats),
|
|
205
267
|
})),
|
|
206
|
-
alternativeFlows: alternatives.map((flow) => ({ name: flow.name, file: flow.file, tags: flow.tags })),
|
|
268
|
+
alternativeFlows: [...alternatives, ...unusable].map((flow) => ({ name: flow.name, file: flow.file, tags: flow.tags, health: flowHealth(flow, runStats) })),
|
|
269
|
+
draftFlow: draft
|
|
270
|
+
? { name: draft.name, title: draft.title, file: draft.file, generated: draft.generated || null, health: flowHealth(draft, runStats) }
|
|
271
|
+
: null,
|
|
207
272
|
seed,
|
|
208
273
|
state,
|
|
209
274
|
reasons,
|
|
@@ -230,6 +295,7 @@ export function buildBatchPlan({
|
|
|
230
295
|
manual: byState.manual || 0,
|
|
231
296
|
blocked: byState.blocked || 0,
|
|
232
297
|
withSeed: items.filter((item) => item.seed.needs.length).length,
|
|
298
|
+
withDraft: items.filter((item) => item.draftFlow).length,
|
|
233
299
|
},
|
|
234
300
|
};
|
|
235
301
|
}
|
|
@@ -240,6 +306,7 @@ export function planBatch(config, options = {}) {
|
|
|
240
306
|
const { flows, warnings: flowWarnings } = readFlows(config, { dir: options.dir });
|
|
241
307
|
const loadedRecipes = loadSeedRecipes(config);
|
|
242
308
|
const allowWrites = options.allowWrites === true || config.seed?.allowWrites === true;
|
|
309
|
+
const runStats = options.runStats || loadFlowRunStats(config);
|
|
243
310
|
const plan = buildBatchPlan({
|
|
244
311
|
cases: loadedCases.cases,
|
|
245
312
|
flows,
|
|
@@ -250,6 +317,7 @@ export function planBatch(config, options = {}) {
|
|
|
250
317
|
classFilter: options.classFilter,
|
|
251
318
|
limit: options.limit,
|
|
252
319
|
scope: options.scope,
|
|
320
|
+
runStats,
|
|
253
321
|
});
|
|
254
322
|
plan.recipeLibrary = describeRecipeLibrary(config);
|
|
255
323
|
plan.caseLibrary = {
|
|
@@ -269,6 +337,7 @@ export function planBatch(config, options = {}) {
|
|
|
269
337
|
requires: flow.requires,
|
|
270
338
|
seedRecipes: flow.seedRecipes || [],
|
|
271
339
|
generated: flow.generated || null,
|
|
340
|
+
health: flowHealth(flow, runStats),
|
|
272
341
|
}));
|
|
273
342
|
return plan;
|
|
274
343
|
}
|
|
@@ -293,11 +362,16 @@ export async function runPool(items, size, fn) {
|
|
|
293
362
|
return results;
|
|
294
363
|
}
|
|
295
364
|
|
|
296
|
-
function flowRunNote({ flow, result, seed, index }) {
|
|
365
|
+
export function flowRunNote({ flow, result, seed, index }) {
|
|
297
366
|
const parts = [];
|
|
298
367
|
parts.push(`flow ${flow.name} ${result.status === 'passed' ? '通过' : '失败'}`);
|
|
299
368
|
if (result.durationMs !== undefined) parts.push(`${(result.durationMs / 1000).toFixed(1)}s`);
|
|
300
|
-
|
|
369
|
+
const hard = (result.failedSteps || []).filter((step) => !step.soft);
|
|
370
|
+
const soft = (result.failedSteps || []).filter((step) => step.soft);
|
|
371
|
+
if (hard.length) parts.push(`失败步骤 ${hard.map((step) => step.id).join('、')}`);
|
|
372
|
+
if (soft.length) parts.push(`未验证断言 ${soft.map((step) => step.id).join('、')}`);
|
|
373
|
+
if (result.skipped > 0) parts.push(`未验证判断 ${result.skipped} 步`);
|
|
374
|
+
if (result.assertions === 0) parts.push('无可执行断言(预期结果仅剩 comment)');
|
|
301
375
|
if (seed?.state === 'passed' && seed.runs?.length) {
|
|
302
376
|
parts.push(`前置造数 ${seed.runs.map((run) => `${run.recipeId}(${Object.keys(run.vars || {}).join('/')})`).join(' → ')}`);
|
|
303
377
|
}
|
|
@@ -367,6 +441,7 @@ export function renderBatchSummary(summary) {
|
|
|
367
441
|
`| 并发 | ${summary.workers} |`,
|
|
368
442
|
`| 用例 | ${summary.total}(通过 ${summary.passed} / 失败 ${summary.failed} / 阻塞 ${summary.blocked} / 未执行 ${summary.notExecuted}) |`,
|
|
369
443
|
`| 造数 | ${JSON.stringify(summary.seed)} |`,
|
|
444
|
+
...(summary.agentTasks ? [`| Agent 交接 | ${summary.agentTasks.total} 条 pending,见 agent-tasks.json |`] : []),
|
|
370
445
|
'',
|
|
371
446
|
'| 用例 | 结果 | 用时 | flow | 关键/错误截图 | 备注 |',
|
|
372
447
|
'| --- | --- | --- | --- | --- | --- |',
|
|
@@ -376,6 +451,73 @@ export function renderBatchSummary(summary) {
|
|
|
376
451
|
return lines.join('\n');
|
|
377
452
|
}
|
|
378
453
|
|
|
454
|
+
function markRunLearned(config, runDir, result) {
|
|
455
|
+
try {
|
|
456
|
+
const dir = resolveRunDir(config, runDir);
|
|
457
|
+
const file = path.join(dir, 'run.json');
|
|
458
|
+
const run = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
459
|
+
run.learn = {
|
|
460
|
+
at: nowIso(),
|
|
461
|
+
pagesAdded: result.observations?.pagesAdded || 0,
|
|
462
|
+
actionsAdded: result.observations?.actionsAdded || 0,
|
|
463
|
+
waitsUpdated: result.timing?.updatedPages?.length || 0,
|
|
464
|
+
suggestions: result.timing?.suggestions?.length || 0,
|
|
465
|
+
learnings: result.timing?.learnings?.length || 0,
|
|
466
|
+
errors: result.errors,
|
|
467
|
+
};
|
|
468
|
+
run.updatedAt = run.learn.at;
|
|
469
|
+
writeFileAtomic(file, `${JSON.stringify(run, null, 2)}\n`);
|
|
470
|
+
} catch {
|
|
471
|
+
/* 标记失败不影响沉淀本身 */
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* 批次前刷新上次失败的 generated flow:只处理非 agent flow,知识库为空时跳过。
|
|
477
|
+
* convert 可注入,便于单测;默认使用 convertCase。
|
|
478
|
+
*/
|
|
479
|
+
export function refreshFailedFlows({
|
|
480
|
+
config,
|
|
481
|
+
plan,
|
|
482
|
+
allCases = [],
|
|
483
|
+
convert = convertCase,
|
|
484
|
+
knowledge = null,
|
|
485
|
+
log = null,
|
|
486
|
+
} = {}) {
|
|
487
|
+
const result = { enabled: true, refreshed: [], errors: [] };
|
|
488
|
+
let loaded = knowledge;
|
|
489
|
+
for (const item of plan?.items || []) {
|
|
490
|
+
if (item.state !== 'ready') continue;
|
|
491
|
+
const flow = item.flows?.[0];
|
|
492
|
+
if (!flow || flow.health?.lastStatus !== 'failed' || !flow.generated) continue;
|
|
493
|
+
if (asArray(flow.tags).includes('agent')) continue;
|
|
494
|
+
const caseItem = findCase(allCases, item.caseId)?.case;
|
|
495
|
+
if (!caseItem) continue;
|
|
496
|
+
try {
|
|
497
|
+
loaded = loaded || loadKnowledge(config);
|
|
498
|
+
if (loaded?.missing || !(loaded?.pages?.pages || []).length) {
|
|
499
|
+
result.errors.push({ caseId: item.caseId, flow: flow.name, error: '知识库没有页面,跳过刷新' });
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const converted = convert({
|
|
503
|
+
knowledge: loaded,
|
|
504
|
+
caseItem,
|
|
505
|
+
config,
|
|
506
|
+
options: { save: true, force: true, regen: true },
|
|
507
|
+
});
|
|
508
|
+
if (converted.savedPath) {
|
|
509
|
+
result.refreshed.push({ caseId: item.caseId, flow: flow.name, file: converted.savedPath, diagnostics: converted.diagnostics?.length || 0 });
|
|
510
|
+
} else {
|
|
511
|
+
result.errors.push({ caseId: item.caseId, flow: flow.name, error: converted.diagnostics?.map((entry) => entry.message).join(';') || '未保存' });
|
|
512
|
+
}
|
|
513
|
+
} catch (error) {
|
|
514
|
+
result.errors.push({ caseId: item.caseId, flow: flow.name, error: String(error?.message || error) });
|
|
515
|
+
if (log) log.warn(`刷新失败 flow 跳过 ${item.caseId}/${flow.name}:${error.message}`);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return result;
|
|
519
|
+
}
|
|
520
|
+
|
|
379
521
|
/**
|
|
380
522
|
* 执行批次。
|
|
381
523
|
* @param {object} options
|
|
@@ -402,18 +544,31 @@ export async function runBatch({
|
|
|
402
544
|
logger = null,
|
|
403
545
|
runFlowImpl = runFlow,
|
|
404
546
|
recordImpl = addResult,
|
|
547
|
+
learn = config?.learn?.autoAfterRun !== false,
|
|
548
|
+
refresh = config?.learn?.refreshFailedFlows !== false,
|
|
405
549
|
sessionFactory,
|
|
406
550
|
} = {}) {
|
|
407
551
|
if (!config) throw new ConfigError('runBatch 缺少 config');
|
|
408
552
|
if (!plan) throw new ConfigError('runBatch 缺少 plan');
|
|
553
|
+
const learnEnabled = learn === false ? false : learn === true ? true : config.learn?.autoAfterRun !== false;
|
|
409
554
|
const log = logger || createLogger({ quiet: true });
|
|
410
555
|
const workerCount = Math.max(1, Number(workers) || Number(config.batch?.workers) || 3);
|
|
411
556
|
const loadedRecipes = loadSeedRecipes(config);
|
|
412
557
|
const allCases = loadProjectCases(config).cases;
|
|
413
558
|
const batchDir = ensureDir(path.join(config.paths.outputDir, 'batches', runId));
|
|
414
559
|
const startedAt = nowIso();
|
|
560
|
+
let agentTasks = null;
|
|
561
|
+
try {
|
|
562
|
+
agentTasks = saveAgentTasks(config, runId, planAgentTasks({ config, plan, cases: allCases, batchId: runId, createdAt: startedAt }), startedAt);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
log.warn(`Agent 交接清单写入失败:${error.message}`);
|
|
565
|
+
}
|
|
415
566
|
const sharedSeeds = new SharedSeedStore();
|
|
416
567
|
const headless = config.browser?.headless !== false;
|
|
568
|
+
const refreshEnabled = refresh !== false;
|
|
569
|
+
const refreshResult = refreshEnabled
|
|
570
|
+
? refreshFailedFlows({ config, plan, allCases, log })
|
|
571
|
+
: { enabled: false, refreshed: [], errors: [] };
|
|
417
572
|
|
|
418
573
|
const runnable = plan.items.filter((item) => item.state === 'ready');
|
|
419
574
|
const notRunnable = plan.items.filter((item) => item.state !== 'ready');
|
|
@@ -502,7 +657,7 @@ export async function runBatch({
|
|
|
502
657
|
vars: seed.vars || {},
|
|
503
658
|
session,
|
|
504
659
|
shotEveryStep,
|
|
505
|
-
observePages:
|
|
660
|
+
observePages: learnEnabled,
|
|
506
661
|
learnAfterRun: false,
|
|
507
662
|
logger: log,
|
|
508
663
|
liveEnabled: false,
|
|
@@ -516,6 +671,8 @@ export async function runBatch({
|
|
|
516
671
|
failed: result.failed,
|
|
517
672
|
total: result.total,
|
|
518
673
|
durationMs: new Date(result.endedAt).getTime() - new Date(result.startedAt).getTime(),
|
|
674
|
+
assertions: result.assertions,
|
|
675
|
+
skipped: result.skipped,
|
|
519
676
|
runDir: result.runDir,
|
|
520
677
|
runLabel: result.label,
|
|
521
678
|
failedSteps: result.failedSteps,
|
|
@@ -612,6 +769,37 @@ export async function runBatch({
|
|
|
612
769
|
});
|
|
613
770
|
});
|
|
614
771
|
|
|
772
|
+
// 批次结束后串行沉淀,避免并发 worker 同时改写 pages.json / learnings.jsonl。
|
|
773
|
+
const learning = { enabled: learnEnabled, learned: [], errors: [] };
|
|
774
|
+
if (learnEnabled) {
|
|
775
|
+
const learnedDirs = new Set();
|
|
776
|
+
for (const run of caseRuns) {
|
|
777
|
+
for (const dir of asArray(run.runDirs)) {
|
|
778
|
+
if (dir) learnedDirs.add(String(dir));
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
for (const dir of learnedDirs) {
|
|
782
|
+
try {
|
|
783
|
+
const result = learnRun(config, { runDir: dir, logger: log });
|
|
784
|
+
markRunLearned(config, dir, result);
|
|
785
|
+
learning.learned.push({
|
|
786
|
+
runDir: dir,
|
|
787
|
+
pagesAdded: result.observations?.pagesAdded || 0,
|
|
788
|
+
actionsAdded: result.observations?.actionsAdded || 0,
|
|
789
|
+
waitsUpdated: result.timing?.updatedPages?.length || 0,
|
|
790
|
+
suggestions: result.timing?.suggestions?.length || 0,
|
|
791
|
+
errors: result.errors,
|
|
792
|
+
});
|
|
793
|
+
if (result.errors.length) {
|
|
794
|
+
learning.errors.push({ runDir: dir, errors: result.errors });
|
|
795
|
+
}
|
|
796
|
+
} catch (error) {
|
|
797
|
+
learning.errors.push({ runDir: dir, errors: [{ stage: 'learn', message: String(error?.message || error) }] });
|
|
798
|
+
log.warn(`批次沉淀跳过 ${dir}:${error.message}`);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
615
803
|
const allRuns = [...caseRuns, ...skippedRuns];
|
|
616
804
|
const recorded = [];
|
|
617
805
|
const skippedRecords = [];
|
|
@@ -663,6 +851,9 @@ export async function runBatch({
|
|
|
663
851
|
seed: summarizeSeedRuns(allRuns.map((run) => ({ seed: run.seed }))),
|
|
664
852
|
recorded: recorded.length,
|
|
665
853
|
recordedSkipped: skippedRecords,
|
|
854
|
+
learning,
|
|
855
|
+
refresh: refreshResult,
|
|
856
|
+
agentTasks,
|
|
666
857
|
cases: allRuns.map((run) => ({
|
|
667
858
|
caseId: run.caseId,
|
|
668
859
|
title: caseById.get(run.caseId)?.title || '',
|
package/lib/browser-ab.mjs
CHANGED
|
@@ -317,14 +317,29 @@ export async function login(session, { logger = null, screenshotPath = null, for
|
|
|
317
317
|
if (!user || !password) {
|
|
318
318
|
throw new StepError('会话已过期,且未设置登录密码(' + pwEnv + ' / OMS_PASSWORD / 账号配置)');
|
|
319
319
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
320
|
+
// 登录页是 SPA,表单在脚本执行后才挂载;按钮晚到不能直接判缺失。
|
|
321
|
+
const formReady = await pollExpr(
|
|
322
|
+
ab,
|
|
323
|
+
null,
|
|
324
|
+
"(() => { const vis=e=>e&&e.getBoundingClientRect().width>0; return Boolean([...document.querySelectorAll('input[type=password]')].find(vis) && [...document.querySelectorAll('button')].find(b=>/^\\s*登录\\s*$/.test((b.innerText||'').trim())&&vis(b))); })()",
|
|
325
|
+
{ timeout: 20000, interval: 500 },
|
|
326
|
+
);
|
|
327
|
+
if (!formReady) throw new StepError('登录页找不到「登录」按钮');
|
|
328
|
+
const mark = (sel, tag) => ab.eval(
|
|
329
|
+
"(() => { const e=[...document.querySelectorAll(" + json(sel) + ")].find(x => { const r=x.getBoundingClientRect(); return r.width>0 && r.height>0; }); if(!e) return null; document.querySelectorAll('[data-ab-target]').forEach(x=>x.removeAttribute('data-ab-target')); e.setAttribute('data-ab-target','" + tag + "'); return '[data-ab-target=\"" + tag + "\"]'; })()",
|
|
330
|
+
);
|
|
331
|
+
// React 受控输入只认真实按键;直接改 value 再点登录会被当成空表单。
|
|
332
|
+
const typeInto = async (sel, value) => {
|
|
333
|
+
try {
|
|
334
|
+
await ab.type(sel, value, { clear: true, delay: 40 });
|
|
335
|
+
} catch {
|
|
336
|
+
await ab.fill(sel, value);
|
|
337
|
+
}
|
|
338
|
+
};
|
|
324
339
|
const userSel = await mark('input[type=text]', 'login-user');
|
|
325
|
-
if (userSel) await
|
|
340
|
+
if (userSel) await typeInto(userSel, user);
|
|
326
341
|
const pwSel = await mark('input[type=password]', 'login-pwd');
|
|
327
|
-
if (pwSel) await
|
|
342
|
+
if (pwSel) await typeInto(pwSel, password);
|
|
328
343
|
const btnSel = await mark('button', 'login-btn-all').catch(() => null);
|
|
329
344
|
const loginBtn = await ab.eval(() => {
|
|
330
345
|
const b = [...document.querySelectorAll('button')].find(x => /^\s*登录\s*$/.test((x.innerText || '').trim()) && x.getBoundingClientRect().width > 0);
|
package/lib/browser.mjs
CHANGED
|
@@ -518,14 +518,14 @@ export async function locateClickableByText(page, text, { exact = false, index =
|
|
|
518
518
|
for (const factory of strategies) {
|
|
519
519
|
const locator = factory();
|
|
520
520
|
const count = await locator.count().catch(() => 0);
|
|
521
|
-
|
|
521
|
+
const visible = [];
|
|
522
522
|
for (let i = 0; i < Math.min(count, 60); i += 1) {
|
|
523
523
|
const item = locator.nth(i);
|
|
524
|
-
if (await item.isVisible().catch(() => false))
|
|
525
|
-
if (visible === index) return item;
|
|
526
|
-
visible += 1;
|
|
527
|
-
}
|
|
524
|
+
if (await item.isVisible().catch(() => false)) visible.push(item);
|
|
528
525
|
}
|
|
526
|
+
// 负索引从可见匹配的末尾取(-1 即最后一个),用于同文案多个入口时点最后一行。
|
|
527
|
+
if (index < 0 && visible.length >= Math.abs(index)) return visible[visible.length + index];
|
|
528
|
+
if (index >= 0 && visible.length > index) return visible[index];
|
|
529
529
|
}
|
|
530
530
|
if (Date.now() >= deadline) break;
|
|
531
531
|
await sleep(250);
|
package/lib/config.mjs
CHANGED
|
@@ -164,6 +164,7 @@ export function loadConfig(projectDir = process.cwd()) {
|
|
|
164
164
|
library: config.knowledge.library ?? null,
|
|
165
165
|
dir: config.knowledge.dir ?? null,
|
|
166
166
|
central: isPlainObject(config.knowledge.central) ? config.knowledge.central : null,
|
|
167
|
+
maintenance: isPlainObject(config.knowledge.maintenance) ? config.knowledge.maintenance : null,
|
|
167
168
|
};
|
|
168
169
|
return resolveConfig(config, dir, configPath);
|
|
169
170
|
}
|