-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathreport-cases.mjs
More file actions
253 lines (239 loc) · 7.93 KB
/
Copy pathreport-cases.mjs
File metadata and controls
253 lines (239 loc) · 7.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
import {
loadReportImages,
normalizeJsonControlCharacters,
} from './omarchy-shell-evidence.mjs';
function allAttemptSteps(attempt) {
return [
...(attempt?.beforeEach ?? []),
...(attempt?.steps ?? []),
...(attempt?.afterEach ?? []),
];
}
function hasScreenshotEvidence(step) {
return Array.isArray(step?.agentDetails) && step.agentDetails.length > 0;
}
function projectSlug(projectName) {
const slug = projectName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
if (!slug) {
throw new Error(
`Cannot build a preview filename for project ${projectName}`,
);
}
return slug;
}
export function casePreviewFileName(projectName, caseId, extension = 'jpg') {
if (!/^[a-zA-Z0-9-]+$/.test(caseId)) {
throw new Error(`Invalid Midscene case ID: ${caseId}`);
}
if (!['jpg', 'png', 'webp'].includes(extension)) {
throw new Error(`Unsupported Midscene screenshot format: ${extension}`);
}
return `case-preview-${projectSlug(projectName)}-${caseId}.${extension}`;
}
function scriptAttributes(source) {
const attributes = new Map();
for (const match of source.matchAll(/([\w-]+)=["']([^"']*)["']/g)) {
attributes.set(match[1], match[2]);
}
return attributes;
}
async function embeddedReportData(reportHtml, reportFile) {
const dumps = [];
for (const match of reportHtml.matchAll(
/<script\s+([^>]*\btype=["']midscene_web_dump["'][^>]*)>\s*(\{[\s\S]*?)<\/script>/g,
)) {
const attributes = scriptAttributes(match[1]);
dumps.push({
reportId:
attributes.get('data-report-id') ??
attributes.get('data-group-id') ??
null,
dump: JSON.parse(normalizeJsonControlCharacters(match[2].trim())),
});
}
const images = await loadReportImages(reportHtml, reportFile);
return { dumps, images };
}
function normalizedText(value) {
if (typeof value !== 'string') return null;
const text = value
.replaceAll('__midscene_lt__', '<')
.replaceAll('__midscene_gt__', '>')
.replace(/\s+/g, ' ')
.trim();
return text || null;
}
function taggedModelText(rawResponse) {
const response = normalizedText(rawResponse);
if (!response) return null;
const tagged = response.match(
/<(?:observation|planning)>([\s\S]*?)<\/(?:observation|planning)>/,
);
return normalizedText(tagged?.[1]);
}
function modelTaskText(task) {
return (
normalizedText(task?.thought) ??
normalizedText(task?.log?.taskInfo?.formatResponse?.thought) ??
normalizedText(task?.output?.thought) ??
taggedModelText(task?.log?.rawResponse) ??
taggedModelText(task?.log?.taskInfo?.rawResponse) ??
normalizedText(task?.output?.output)
);
}
function isModelTask(task) {
return (
task?.type === 'Insight' ||
(task?.type === 'Planning' && task?.subType === 'Plan')
);
}
function executionForDetail(dumps, detail) {
const preferred = dumps.filter(
(entry) => !detail.reportId || entry.reportId === detail.reportId,
);
for (const entry of preferred.length ? preferred : dumps) {
const execution = entry.dump?.executions?.find(
(item) => item.id === detail.executionId,
);
if (execution) return execution;
}
return null;
}
function evidenceForStep(step, embedded, allowUntimedEvidence = false) {
const candidates = [];
function collect(execution, destination) {
for (const task of execution?.tasks ?? []) {
const screenshotId = task?.uiContext?.screenshot?.id;
const explanation = modelTaskText(task);
if (
isModelTask(task) &&
screenshotId &&
embedded.images.has(screenshotId)
) {
destination.push({ screenshotId, explanation });
}
}
}
for (const detail of step.agentDetails ?? []) {
collect(executionForDetail(embedded.dumps, detail), candidates);
}
// Custom Nodes can call an Agent without forwarding agentDetails to the
// runner step. Match by execution time when available; for older reports
// without timestamps, only a one-step, one-attempt case is unambiguous.
if (!candidates.length && !hasScreenshotEvidence(step)) {
const startedAt = Date.parse(step.startedAt ?? '');
const endedAt = Date.parse(step.endedAt ?? '');
const hasWindow = Number.isFinite(startedAt) && Number.isFinite(endedAt);
const unlinked = [];
for (const entry of embedded.dumps) {
for (const execution of entry.dump?.executions ?? []) {
const executionTime = Number(
execution.logTime ?? execution.tasks?.[0]?.timing?.start,
);
const inStep = hasWindow && Number.isFinite(executionTime) &&
executionTime >= startedAt - 1000 &&
executionTime <= endedAt + 1000;
if (!inStep && !(allowUntimedEvidence && !hasWindow)) continue;
collect(execution, unlinked);
}
}
if (unlinked.length === 1) candidates.push(unlinked[0]);
}
const selected = candidates.at(-1);
const error = normalizedText(step.error?.message);
const result = normalizedText(step.output?.summary);
const description = error ?? selected?.explanation ?? result ??
(step.status === 'success'
? 'Step passed; no per-step AI response was recorded.'
: 'Step failed without a recorded error message.');
return {
...(selected
? { screenshot: embedded.images.get(selected.screenshotId) }
: {}),
description,
descriptionKind: error ? 'error' : selected?.explanation ? 'ai' : 'result',
};
}
export async function reportCases(
run,
projectName,
{ reportHtml, reportFile } = {},
) {
const project = run?.projects?.find((item) => item.name === projectName);
if (!project) {
throw new Error(`Project ${projectName} is absent from the runner dump`);
}
const embedded = reportHtml
? await embeddedReportData(reportHtml, reportFile)
: null;
const cases = (project.documents ?? []).flatMap((document) =>
document.cases ?? [],
);
return cases.flatMap((testCase) => {
const attempt = testCase.attempts?.at(-1);
if (!attempt) {
if (testCase.status === 'not-run') return [];
throw new Error(
`Case ${testCase.name ?? testCase.caseId} has no attempt`,
);
}
const steps = allAttemptSteps(attempt);
const passed = (testCase.status ?? attempt.status) === 'success';
const step = passed
? steps.findLast(hasScreenshotEvidence) ?? steps.at(-1)
: steps.find(
(item) => item.status === 'failed' && hasScreenshotEvidence(item),
) ??
steps.find((item) => item.status === 'failed');
if (!step?.id) {
throw new Error(
`Case ${testCase.name ?? testCase.caseId} has no report step to preview`,
);
}
if (!testCase.caseId || !testCase.name) {
throw new Error('Midscene case metadata is incomplete');
}
const soleUntimedStep = cases.length === 1 &&
testCase.attempts?.length === 1 && steps.length === 1;
const evidence = embedded
? evidenceForStep(step, embedded, soleUntimedStep)
: null;
if (
passed && embedded && !evidence?.screenshot &&
(hasScreenshotEvidence(step) || step.node?.startsWith('ai'))
) {
throw new Error(`Step ${step.id} has no embedded node screenshot`);
}
const selection = passed
? embedded && !evidence?.screenshot
? 'last-no-screenshot'
: 'last-screenshot'
: evidence && !evidence.screenshot
? 'first-failing-no-screenshot'
: 'first-failing-screenshot';
return [{
caseId: testCase.caseId,
name: testCase.name,
status: passed ? 'success' : 'failed',
durationMs: attempt.durationMs,
stepId: step.id,
stepTitle: step.title ?? step.node,
selection,
...(evidence?.screenshot
? {
previewFile: casePreviewFileName(
projectName,
testCase.caseId,
evidence.screenshot.extension,
),
}
: embedded
? {}
: { previewFile: casePreviewFileName(projectName, testCase.caseId) }),
...(evidence ?? {}),
}];
});
}