@jeffawe/understudy 0.2.3 → 0.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 +69 -19
- package/REASONER.md +31 -4
- package/dist/adapters/recorder/script.js +206 -4
- package/dist/core/distill.d.ts +12 -0
- package/dist/core/distill.js +25 -32
- package/dist/core/recording.d.ts +49 -1
- package/dist/core/recording.js +60 -0
- package/dist/core/replay.d.ts +70 -1
- package/dist/core/replay.js +251 -12
- package/dist/entry/cli.js +187 -11
- package/dist/entry/mcp.d.ts +2 -1
- package/dist/entry/mcp.js +187 -33
- package/dist/flows/destructive.d.ts +17 -1
- package/dist/flows/destructive.js +23 -5
- package/dist/flows/distill.js +2 -0
- package/dist/flows/emit.js +88 -5
- package/dist/flows/execute.d.ts +22 -2
- package/dist/flows/execute.js +19 -3
- package/dist/flows/findings.d.ts +4 -1
- package/dist/flows/findings.js +15 -3
- package/dist/flows/runs.d.ts +13 -0
- package/dist/flows/runs.js +43 -7
- package/dist/flows/save.d.ts +42 -1
- package/dist/flows/save.js +214 -14
- package/dist/memory/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +258 -0
- package/dist/memory/recall.d.ts +42 -25
- package/dist/memory/recall.js +61 -21
- package/dist/memory/vocabulary.js +9 -3
- package/dist/plan/planner.d.ts +8 -4
- package/dist/plan/planner.js +77 -4
- package/dist/store/reembed.js +18 -7
- package/dist/store/types.d.ts +78 -2
- package/package.json +1 -1
package/dist/core/recording.d.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* in a string of JavaScript.
|
|
14
14
|
*/
|
|
15
15
|
/** Actions the IR can express. Mirrors the `steps.action` CHECK constraint. */
|
|
16
|
-
export type RecordedAction = 'goto' | 'click' | 'fill' | 'press' | 'select' | 'check' | 'uncheck' | 'upload' | 'wait_url' | 'wait_text' | 'dispatch_click' | 'scroll_container' | 'snapshot' | 'assert';
|
|
16
|
+
export type RecordedAction = 'goto' | 'click' | 'fill' | 'press' | 'select' | 'check' | 'uncheck' | 'upload' | 'wait_url' | 'wait_text' | 'dispatch_click' | 'scroll_container' | 'snapshot' | 'assert' | 'human' | 'wait_response';
|
|
17
17
|
/**
|
|
18
18
|
* How we came to believe an event's role and name — the honesty field.
|
|
19
19
|
*
|
|
@@ -183,3 +183,51 @@ export declare function redactValue(fieldHint: string, value: string, inputType?
|
|
|
183
183
|
value?: string;
|
|
184
184
|
valueRef?: string;
|
|
185
185
|
};
|
|
186
|
+
/**
|
|
187
|
+
* The value references a recording really needs filled in — the login values
|
|
188
|
+
* a run asks for before it opens a browser.
|
|
189
|
+
*
|
|
190
|
+
* Only steps that take a value count. Script import used to store
|
|
191
|
+
* `click({ force: true })` as `valueRef: '{ force: true }'`, and every caller
|
|
192
|
+
* then demanded a login value by that name, stopping the run before it began.
|
|
193
|
+
*/
|
|
194
|
+
export declare function valueRefsOf(events: ReadonlyArray<Pick<RawEvent, 'action' | 'valueRef'>>): string[];
|
|
195
|
+
/**
|
|
196
|
+
* Should this step skip Playwright's actionability checks — `click({ force: true })`?
|
|
197
|
+
*
|
|
198
|
+
* Needed for controls the app hides behind a styled overlay, like custom
|
|
199
|
+
* checkboxes under their label. Kept as `hints.force`; flows saved before that
|
|
200
|
+
* carry it as the stringified options in `valueRef`, and are read the same way
|
|
201
|
+
* so they need no re-saving.
|
|
202
|
+
*/
|
|
203
|
+
export declare function forced(event: Pick<RawEvent, 'action' | 'valueRef' | 'hints'>): boolean;
|
|
204
|
+
/**
|
|
205
|
+
* A response to wait for: `POST /api/visits` answered 201, and its JSON says
|
|
206
|
+
* `commission.amount` is above 0.
|
|
207
|
+
*/
|
|
208
|
+
export interface ResponseCheck {
|
|
209
|
+
/** Address: a substring, or a glob (`**\/api/visits`). */
|
|
210
|
+
url: string;
|
|
211
|
+
method?: string;
|
|
212
|
+
status?: number;
|
|
213
|
+
/** A dot path into the JSON body, e.g. "commission.amount" or "items.0.id". */
|
|
214
|
+
field?: string;
|
|
215
|
+
/** The field equals this. */
|
|
216
|
+
equals?: string | number | boolean;
|
|
217
|
+
/** The field is a number above this. */
|
|
218
|
+
above?: number;
|
|
219
|
+
}
|
|
220
|
+
/** Read a response check from a step's value + hints, or from a hints object of its own. */
|
|
221
|
+
export declare function responseCheckOf(url: unknown, hints: Record<string, unknown> | undefined): ResponseCheck | undefined;
|
|
222
|
+
/** `POST /api/visits → 201, commission.amount > 0` */
|
|
223
|
+
export declare function describeResponse(c: ResponseCheck): string;
|
|
224
|
+
/** How a human step shows it's done, if it says. */
|
|
225
|
+
export interface HumanUntil {
|
|
226
|
+
/** The address contains this (or matches it as a glob, as in wait_url). */
|
|
227
|
+
url?: string;
|
|
228
|
+
/** This text appears on the page. */
|
|
229
|
+
text?: string;
|
|
230
|
+
/** The server answers like this — for a step done somewhere the page can't see. */
|
|
231
|
+
response?: ResponseCheck;
|
|
232
|
+
}
|
|
233
|
+
export declare const humanUntil: (event: Pick<RawEvent, "hints">) => HumanUntil | undefined;
|
package/dist/core/recording.js
CHANGED
|
@@ -98,3 +98,63 @@ export function redactValue(fieldHint, value, inputType, secretSignal = fieldHin
|
|
|
98
98
|
}
|
|
99
99
|
return { value };
|
|
100
100
|
}
|
|
101
|
+
/**
|
|
102
|
+
* Actions that never take a value: their first argument in Playwright is an
|
|
103
|
+
* options object (`click({ force: true })`), not something typed or chosen.
|
|
104
|
+
*/
|
|
105
|
+
const VALUELESS_ACTIONS = new Set(['click', 'dispatch_click', 'check', 'uncheck']);
|
|
106
|
+
/**
|
|
107
|
+
* The value references a recording really needs filled in — the login values
|
|
108
|
+
* a run asks for before it opens a browser.
|
|
109
|
+
*
|
|
110
|
+
* Only steps that take a value count. Script import used to store
|
|
111
|
+
* `click({ force: true })` as `valueRef: '{ force: true }'`, and every caller
|
|
112
|
+
* then demanded a login value by that name, stopping the run before it began.
|
|
113
|
+
*/
|
|
114
|
+
export function valueRefsOf(events) {
|
|
115
|
+
const refs = events.filter((e) => e.valueRef && !VALUELESS_ACTIONS.has(e.action)).map((e) => e.valueRef);
|
|
116
|
+
return [...new Set(refs)];
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Should this step skip Playwright's actionability checks — `click({ force: true })`?
|
|
120
|
+
*
|
|
121
|
+
* Needed for controls the app hides behind a styled overlay, like custom
|
|
122
|
+
* checkboxes under their label. Kept as `hints.force`; flows saved before that
|
|
123
|
+
* carry it as the stringified options in `valueRef`, and are read the same way
|
|
124
|
+
* so they need no re-saving.
|
|
125
|
+
*/
|
|
126
|
+
export function forced(event) {
|
|
127
|
+
if (event.hints?.force === true)
|
|
128
|
+
return true;
|
|
129
|
+
return VALUELESS_ACTIONS.has(event.action) && /\bforce\s*:\s*true\b/.test(event.valueRef ?? '');
|
|
130
|
+
}
|
|
131
|
+
/** Read a response check from a step's value + hints, or from a hints object of its own. */
|
|
132
|
+
export function responseCheckOf(url, hints) {
|
|
133
|
+
if (typeof url !== 'string' || !url)
|
|
134
|
+
return undefined;
|
|
135
|
+
const h = hints ?? {};
|
|
136
|
+
const eq = h.equals;
|
|
137
|
+
return {
|
|
138
|
+
url,
|
|
139
|
+
...(typeof h.method === 'string' ? { method: h.method.toUpperCase() } : {}),
|
|
140
|
+
...(typeof h.status === 'number' ? { status: h.status } : {}),
|
|
141
|
+
...(typeof h.field === 'string' ? { field: h.field } : {}),
|
|
142
|
+
...(typeof eq === 'string' || typeof eq === 'number' || typeof eq === 'boolean' ? { equals: eq } : {}),
|
|
143
|
+
...(typeof h.above === 'number' ? { above: h.above } : {}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** `POST /api/visits → 201, commission.amount > 0` */
|
|
147
|
+
export function describeResponse(c) {
|
|
148
|
+
const field = c.field ? `, ${c.field}${c.equals !== undefined ? ` = ${JSON.stringify(c.equals)}` : c.above !== undefined ? ` > ${c.above}` : ' present'}` : '';
|
|
149
|
+
return `${c.method ? `${c.method} ` : ''}${c.url}${c.status !== undefined ? ` → ${c.status}` : ''}${field}`;
|
|
150
|
+
}
|
|
151
|
+
export const humanUntil = (event) => {
|
|
152
|
+
const url = typeof event.hints?.untilUrl === 'string' ? event.hints.untilUrl : undefined;
|
|
153
|
+
const text = typeof event.hints?.untilText === 'string' ? event.hints.untilText : undefined;
|
|
154
|
+
// `untilResponse: '/api/visits'`, or `{ url, method, status, field, equals | above }`.
|
|
155
|
+
const raw = event.hints?.untilResponse;
|
|
156
|
+
const response = typeof raw === 'string'
|
|
157
|
+
? responseCheckOf(raw, undefined)
|
|
158
|
+
: raw && typeof raw === 'object' ? responseCheckOf(raw.url, raw) : undefined;
|
|
159
|
+
return url || text || response ? { ...(url ? { url } : {}), ...(text ? { text } : {}), ...(response ? { response } : {}) } : undefined;
|
|
160
|
+
};
|
package/dist/core/replay.d.ts
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { type BrowserLease } from './browser.js';
|
|
25
25
|
import { type VisualCheck } from './visual.js';
|
|
26
|
-
import type
|
|
26
|
+
import { type HumanUntil, type RawEvent, type RawRecording } from './recording.js';
|
|
27
27
|
import type { StorageState } from './auth-cache.js';
|
|
28
28
|
import type { PendingDecision } from './types.js';
|
|
29
29
|
export interface StepOutcome {
|
|
@@ -66,6 +66,8 @@ export interface StepOutcome {
|
|
|
66
66
|
attempts?: number;
|
|
67
67
|
/** Set when a human took this step over rather than the executor running it. */
|
|
68
68
|
viaHandoff?: boolean;
|
|
69
|
+
/** A `human` step: how it was finished — a person said so, or the page showed it. */
|
|
70
|
+
viaHuman?: 'answered' | 'page';
|
|
69
71
|
/**
|
|
70
72
|
* Set when role+name matched several elements and something more specific
|
|
71
73
|
* had to disambiguate. Feeds `selectors.fragility` — a name that is not
|
|
@@ -87,6 +89,16 @@ export interface StepOutcome {
|
|
|
87
89
|
};
|
|
88
90
|
/** A failed assertion: what it actually found, e.g. the visible text near where the expected text should be. */
|
|
89
91
|
saw?: string;
|
|
92
|
+
/**
|
|
93
|
+
* The page this step ran on (its address just before acting). What a step's
|
|
94
|
+
* `url` should have been all along — a script read statically can only guess.
|
|
95
|
+
*/
|
|
96
|
+
at?: string;
|
|
97
|
+
/**
|
|
98
|
+
* Found but deliberately NOT done: the step a `stopBefore` replay stopped at.
|
|
99
|
+
* Its control was there, visible and enabled; it was never clicked.
|
|
100
|
+
*/
|
|
101
|
+
held?: true;
|
|
90
102
|
}
|
|
91
103
|
/**
|
|
92
104
|
* The part of a page's text worth showing next to an expected string that
|
|
@@ -146,6 +158,18 @@ export interface ReplayResult {
|
|
|
146
158
|
* elsewhere. Callers surface this alongside the verdict.
|
|
147
159
|
*/
|
|
148
160
|
handoffs: HandoffRecord[];
|
|
161
|
+
/** Set when the replay stopped, as asked, before this step (see `stopBefore`). */
|
|
162
|
+
stoppedBefore?: number;
|
|
163
|
+
/** With `endChecks`: what the last page showed, as steps that would check it. */
|
|
164
|
+
endChecks?: EndCheck[];
|
|
165
|
+
}
|
|
166
|
+
/** A check of how the flow ended, offered for someone to approve — never added by itself. */
|
|
167
|
+
export interface EndCheck {
|
|
168
|
+
action: 'assert' | 'wait_text';
|
|
169
|
+
role?: string;
|
|
170
|
+
name?: string;
|
|
171
|
+
value?: string;
|
|
172
|
+
hints?: Record<string, unknown>;
|
|
149
173
|
}
|
|
150
174
|
export interface ReplayOptions {
|
|
151
175
|
/**
|
|
@@ -228,6 +252,28 @@ export interface ReplayOptions {
|
|
|
228
252
|
* which is right for a verification replay and wrong for a real test.
|
|
229
253
|
*/
|
|
230
254
|
onDecision?: (decision: PendingDecision) => Promise<Record<string, unknown>>;
|
|
255
|
+
/**
|
|
256
|
+
* Stop before this step (by `seq`): find its control and check it is visible
|
|
257
|
+
* and enabled, then end the replay without doing it.
|
|
258
|
+
*
|
|
259
|
+
* This is how a flow that ends in a real purchase gets proven. Everything up
|
|
260
|
+
* to the commit is replayed for real; the commit itself is only looked at.
|
|
261
|
+
* A run that stops here is `ok` when every step before it passed and the
|
|
262
|
+
* control was ready — and says so in `stoppedBefore`.
|
|
263
|
+
*/
|
|
264
|
+
stopBefore?: number;
|
|
265
|
+
/**
|
|
266
|
+
* Ask a person to do a `human` step, and wait for them.
|
|
267
|
+
*
|
|
268
|
+
* Aborted (`signal`) when the page shows the step is done before anyone
|
|
269
|
+
* answers — the run then carries on without them, and whoever asked should
|
|
270
|
+
* stop waiting. Omitted means a human step fails: nobody is there to ask.
|
|
271
|
+
*/
|
|
272
|
+
onHuman?: (request: HumanRequest, signal: AbortSignal) => Promise<HumanAnswer>;
|
|
273
|
+
/** How long a human step waits, in ms. Default 15 minutes. */
|
|
274
|
+
humanTimeoutMs?: number;
|
|
275
|
+
/** After a full pass, read the last page into `endChecks` — what "ended right" could mean. */
|
|
276
|
+
endChecks?: boolean;
|
|
231
277
|
/**
|
|
232
278
|
* Turn visual checkpoints on. Opt-in because it only means something when
|
|
233
279
|
* the reasoner can actually look at an image — Bedrock's adapter answers
|
|
@@ -256,6 +302,22 @@ export interface ReplayOptions {
|
|
|
256
302
|
body: string;
|
|
257
303
|
}>>;
|
|
258
304
|
}
|
|
305
|
+
/** What a person is asked to do at a `human` step. */
|
|
306
|
+
export interface HumanRequest {
|
|
307
|
+
seq: number;
|
|
308
|
+
/** What to do, in words to read to them. */
|
|
309
|
+
instruction: string;
|
|
310
|
+
/** The page the run is on. */
|
|
311
|
+
url: string;
|
|
312
|
+
until?: HumanUntil;
|
|
313
|
+
}
|
|
314
|
+
/** done: they did it (the page is still checked, if the step says how). */
|
|
315
|
+
export type HumanAnswer = {
|
|
316
|
+
action: 'done';
|
|
317
|
+
} | {
|
|
318
|
+
action: 'abort';
|
|
319
|
+
reason?: string;
|
|
320
|
+
};
|
|
259
321
|
/** What a decision may tell the executor to do. */
|
|
260
322
|
export type DecisionAction = 'continue' | 'abort' | 'retry';
|
|
261
323
|
/** Why the executor gave up on doing this itself. */
|
|
@@ -301,6 +363,13 @@ export type HandoffOutcome = {
|
|
|
301
363
|
sig?: string;
|
|
302
364
|
storageState?: StorageState;
|
|
303
365
|
recordingHash?: string;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* A person did the step in THIS run's own browser (it was headed), so there
|
|
369
|
+
* is nothing to adopt or reload: carry on from the page they left it on.
|
|
370
|
+
*/
|
|
371
|
+
| {
|
|
372
|
+
action: 'continue';
|
|
304
373
|
} | {
|
|
305
374
|
action: 'skip';
|
|
306
375
|
} | {
|
package/dist/core/replay.js
CHANGED
|
@@ -25,6 +25,7 @@ import {} from 'playwright';
|
|
|
25
25
|
import { openLease } from './browser.js';
|
|
26
26
|
import { computeSig, urlPattern, waitForAriaStable } from './sig.js';
|
|
27
27
|
import { acceptBaseline, captureCheckpoint, worthJudging, VISUAL_SEVERE } from './visual.js';
|
|
28
|
+
import { describeResponse, forced, humanUntil, responseCheckOf } from './recording.js';
|
|
28
29
|
/** An assertion that failed, carrying what it actually saw. */
|
|
29
30
|
class AssertionFailed extends Error {
|
|
30
31
|
saw;
|
|
@@ -221,6 +222,90 @@ export function urlGlob(glob) {
|
|
|
221
222
|
}
|
|
222
223
|
return new RegExp(`${/^[a-z]+:/i.test(glob) || glob.startsWith('*') ? '^' : ''}${re}$`);
|
|
223
224
|
}
|
|
225
|
+
/** Steps that only look, so a response wait still counts what came before them. */
|
|
226
|
+
const WAITS = new Set(['wait_url', 'wait_text', 'wait_response', 'assert', 'snapshot']);
|
|
227
|
+
/** A substring of the address, or a glob over it. */
|
|
228
|
+
function urlMatches(pattern, href) {
|
|
229
|
+
return pattern.includes('*') ? urlGlob(pattern).test(href) : href.includes(pattern);
|
|
230
|
+
}
|
|
231
|
+
/** `items.0.id` of a parsed JSON body. */
|
|
232
|
+
function fieldAt(body, path) {
|
|
233
|
+
let at = body;
|
|
234
|
+
for (const key of path.split('.')) {
|
|
235
|
+
if (at === null || typeof at !== 'object')
|
|
236
|
+
return undefined;
|
|
237
|
+
at = at[key];
|
|
238
|
+
}
|
|
239
|
+
return at;
|
|
240
|
+
}
|
|
241
|
+
/** Every response the page got, by step, for `wait_response` and human steps to look through. */
|
|
242
|
+
class ResponseLog {
|
|
243
|
+
keepBody;
|
|
244
|
+
seen = [];
|
|
245
|
+
constructor(keepBody) {
|
|
246
|
+
this.keepBody = keepBody;
|
|
247
|
+
}
|
|
248
|
+
add(step, res) {
|
|
249
|
+
const url = res.url();
|
|
250
|
+
if (this.seen.length >= 1000)
|
|
251
|
+
this.seen.shift();
|
|
252
|
+
// Read now, while it exists: after the page moves on the body may be gone.
|
|
253
|
+
const body = this.keepBody(url) ? res.json().catch(() => undefined) : undefined;
|
|
254
|
+
this.seen.push({ step, method: res.request().method(), url, status: res.status(), ...(body ? { body } : {}) });
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* The first unused answer since `since` that matches, waiting up to
|
|
258
|
+
* `timeoutMs` for one. A wait step uses it up, so two waits for the same
|
|
259
|
+
* address need two answers; a human step only looks — it checks the same
|
|
260
|
+
* answer twice (while waiting, and after they say done).
|
|
261
|
+
*/
|
|
262
|
+
async wait(check, since, timeoutMs, consume = true) {
|
|
263
|
+
const deadline = Date.now() + timeoutMs;
|
|
264
|
+
const near = new Set();
|
|
265
|
+
for (;;) {
|
|
266
|
+
for (const r of this.seen) {
|
|
267
|
+
if (r.used || r.step < since || !urlMatches(check.url, r.url))
|
|
268
|
+
continue;
|
|
269
|
+
const said = `${r.method} ${new URL(r.url).pathname} → ${r.status}`;
|
|
270
|
+
if ((check.method && r.method !== check.method) || (check.status !== undefined && r.status !== check.status)) {
|
|
271
|
+
near.add(said);
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (check.field) {
|
|
275
|
+
const value = fieldAt(await r.body, check.field);
|
|
276
|
+
const fits = check.equals !== undefined ? value === check.equals
|
|
277
|
+
: check.above !== undefined ? typeof value === 'number' && value > check.above
|
|
278
|
+
: value !== undefined;
|
|
279
|
+
if (!fits) {
|
|
280
|
+
near.add(`${said} with ${check.field} = ${JSON.stringify(value) ?? 'missing'}`);
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (consume)
|
|
285
|
+
r.used = true;
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
if (Date.now() >= deadline) {
|
|
289
|
+
throw new Error(`no response matched ${describeResponse(check)}${near.size ? ` — saw ${[...near].slice(-3).join('; ')}` : ''}`);
|
|
290
|
+
}
|
|
291
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** Wait until the page — or the server — shows a human step is done. */
|
|
296
|
+
async function pageShows(page, until, timeoutMs, responses, since) {
|
|
297
|
+
const deadline = Date.now() + timeoutMs;
|
|
298
|
+
if (until.response)
|
|
299
|
+
await responses.wait(until.response, since, timeoutMs, false);
|
|
300
|
+
if (until.url) {
|
|
301
|
+
const glob = until.url.includes('*') ? urlGlob(until.url) : undefined;
|
|
302
|
+
await page.waitForURL((u) => (glob ? glob.test(u.href) : u.href.includes(until.url)), { timeout: timeoutMs });
|
|
303
|
+
}
|
|
304
|
+
if (until.text) {
|
|
305
|
+
await page.getByText(until.text).first().waitFor({ state: 'visible', timeout: Math.max(1, deadline - Date.now()) });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const describeUntil = (u) => [u.url && `an address with "${u.url}"`, u.text && `the text "${u.text}"`, u.response && `a response ${describeResponse(u.response)}`].filter(Boolean).join(' and ');
|
|
224
309
|
/** Whitespace-normalised, as Playwright's text assertions compare. */
|
|
225
310
|
const squash = (s) => s.replace(/\s+/g, ' ').trim();
|
|
226
311
|
/**
|
|
@@ -344,7 +429,8 @@ function valueFor(event, values) {
|
|
|
344
429
|
return values[event.valueRef];
|
|
345
430
|
}
|
|
346
431
|
export async function replay(recording, opts = {}) {
|
|
347
|
-
const { values = {}, headless = true, timeoutMs = 10_000, captureBodies = true, visualCheck, onDecision, lessonsFor, storageState, prelude, onHandoff, budget, } = opts;
|
|
432
|
+
const { values = {}, headless = true, timeoutMs = 10_000, captureBodies = true, visualCheck, onDecision, lessonsFor, storageState, prelude, onHandoff, budget, stopBefore, onHuman, } = opts;
|
|
433
|
+
let stoppedBefore;
|
|
348
434
|
const maxAttempts = Math.max(1, budget?.stepAttempts ?? 1);
|
|
349
435
|
const handoffs = [];
|
|
350
436
|
const escalations = [];
|
|
@@ -364,6 +450,17 @@ export async function replay(recording, opts = {}) {
|
|
|
364
450
|
// the correlation between a signal and the intent that was executing when it
|
|
365
451
|
// fired. A 500 is interesting; a 500 *during checkout* is a finding.
|
|
366
452
|
let currentStep = -1;
|
|
453
|
+
/** The last step that did something, so a wait only counts what came after it. */
|
|
454
|
+
let lastActionSeq = -1;
|
|
455
|
+
// EVERY RESPONSE IS LOGGED, not just the ones a wait is waiting on now. The
|
|
456
|
+
// click that triggers `POST /api/visits` usually gets its answer before the
|
|
457
|
+
// wait step after it even starts; a wait that only listened from then on
|
|
458
|
+
// would miss it every time.
|
|
459
|
+
const checks = [
|
|
460
|
+
...recording.events.filter((e) => e.action === 'wait_response').map((e) => responseCheckOf(e.value, e.hints)),
|
|
461
|
+
...recording.events.filter((e) => e.action === 'human').map((e) => humanUntil(e)?.response),
|
|
462
|
+
].filter((c) => Boolean(c?.field));
|
|
463
|
+
const responses = new ResponseLog((url) => checks.some((c) => urlMatches(c.url, url)));
|
|
367
464
|
/** Route of the page we are on, so a lesson can be scoped to one page. */
|
|
368
465
|
let lastPattern;
|
|
369
466
|
page.on('console', (msg) => {
|
|
@@ -383,6 +480,7 @@ export async function replay(recording, opts = {}) {
|
|
|
383
480
|
});
|
|
384
481
|
});
|
|
385
482
|
page.on('response', async (res) => {
|
|
483
|
+
responses.add(currentStep, res);
|
|
386
484
|
const status = res.status();
|
|
387
485
|
const contentType = res.headers()['content-type'] ?? '';
|
|
388
486
|
const interesting = status >= 400 || contentType.includes('application/json');
|
|
@@ -421,7 +519,23 @@ export async function replay(recording, opts = {}) {
|
|
|
421
519
|
/** Set the instant an action goes out, so a retry cannot double-submit. */
|
|
422
520
|
let dispatched = false;
|
|
423
521
|
const stepStart = Date.now();
|
|
424
|
-
|
|
522
|
+
if (!WAITS.has(event.action))
|
|
523
|
+
lastActionSeq = event.seq;
|
|
524
|
+
const here = page.url();
|
|
525
|
+
const outcome = {
|
|
526
|
+
seq: event.seq, action: event.action, ok: false, durationMs: 0,
|
|
527
|
+
...(/^https?:\/\//.test(here) ? { at: here } : {}),
|
|
528
|
+
};
|
|
529
|
+
// THE COMMIT STEP OF A stopBefore REPLAY. A control is looked at below,
|
|
530
|
+
// just before it would be dispatched; a step with no control (a goto to the
|
|
531
|
+
// payment site, a wait) is simply not done.
|
|
532
|
+
const holding = !isPrelude && stopBefore === event.seq;
|
|
533
|
+
const holdsWithoutLooking = holding && ['goto', 'wait_url', 'wait_text', 'assert', 'snapshot', 'human'].includes(event.action);
|
|
534
|
+
if (holdsWithoutLooking) {
|
|
535
|
+
outcome.ok = true;
|
|
536
|
+
outcome.held = true;
|
|
537
|
+
}
|
|
538
|
+
const attemptsHere = holdsWithoutLooking ? 0 : maxAttempts;
|
|
425
539
|
// WHAT HAVE WE LEARNED ABOUT THIS STEP? Consulted BEFORE acting, because a
|
|
426
540
|
// lesson's whole purpose is "do Y first".
|
|
427
541
|
let applied = [];
|
|
@@ -457,7 +571,7 @@ export async function replay(recording, opts = {}) {
|
|
|
457
571
|
// THE ATTEMPT LOOP IS PURE CONTROL FLOW, not a reasoner round trip.
|
|
458
572
|
// Retrying by asking would make every retry human-speed, which is the
|
|
459
573
|
// opposite of the point — the budget exists to REDUCE escalations.
|
|
460
|
-
for (let attempt = 1; attempt <=
|
|
574
|
+
for (let attempt = 1; attempt <= attemptsHere; attempt++) {
|
|
461
575
|
outcome.ok = false;
|
|
462
576
|
delete outcome.error;
|
|
463
577
|
try {
|
|
@@ -503,6 +617,54 @@ export async function replay(recording, opts = {}) {
|
|
|
503
617
|
}
|
|
504
618
|
outcome.ok = true;
|
|
505
619
|
}
|
|
620
|
+
else if (event.action === 'wait_response') {
|
|
621
|
+
// A check, not an action: it looks at answers already logged since
|
|
622
|
+
// the last step that did something, then waits for more.
|
|
623
|
+
const check = responseCheckOf(event.value, event.hints);
|
|
624
|
+
if (!check)
|
|
625
|
+
throw new Error('wait_response has no address to wait for');
|
|
626
|
+
await responses.wait(check, lastActionSeq, timeoutMs);
|
|
627
|
+
outcome.ok = true;
|
|
628
|
+
}
|
|
629
|
+
else if (event.action === 'human') {
|
|
630
|
+
// A PERSON'S STEP. Nothing here may try it: it exists because the run
|
|
631
|
+
// can't. Marked dispatched first, so a failure is never "retried" by
|
|
632
|
+
// asking the person twice.
|
|
633
|
+
dispatched = true;
|
|
634
|
+
const instruction = event.value ?? 'a step only a person can do';
|
|
635
|
+
if (!onHuman)
|
|
636
|
+
throw new Error(`needs a person: ${instruction} — nobody is here to ask`);
|
|
637
|
+
const until = humanUntil(event);
|
|
638
|
+
const waitMs = opts.humanTimeoutMs ?? 15 * 60_000;
|
|
639
|
+
const stop = new AbortController();
|
|
640
|
+
const shown = until ? pageShows(page, until, waitMs, responses, event.seq).then(() => 'page') : new Promise(() => { });
|
|
641
|
+
shown.catch(() => { });
|
|
642
|
+
const asked = onHuman({ seq: event.seq, instruction, url: page.url(), ...(until ? { until } : {}) }, stop.signal);
|
|
643
|
+
let timer;
|
|
644
|
+
const timedOut = new Promise((r) => { timer = setTimeout(() => r('timeout'), waitMs); });
|
|
645
|
+
const first = await Promise.race([asked, shown, timedOut]).finally(() => clearTimeout(timer));
|
|
646
|
+
if (first === 'timeout') {
|
|
647
|
+
stop.abort();
|
|
648
|
+
throw new Error(`waited ${Math.round(waitMs / 60_000)} min for a person to: ${instruction}`);
|
|
649
|
+
}
|
|
650
|
+
if (first === 'page') {
|
|
651
|
+
stop.abort();
|
|
652
|
+
outcome.viaHuman = 'page';
|
|
653
|
+
}
|
|
654
|
+
else if (first.action === 'abort') {
|
|
655
|
+
throw new Error(`stopped at a person's step: ${first.reason ?? 'they declined'}`);
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
// They say it's done; when the step says how to tell, check.
|
|
659
|
+
if (until) {
|
|
660
|
+
await pageShows(page, until, timeoutMs, responses, event.seq).catch(() => {
|
|
661
|
+
throw new Error(`a person said "${instruction}" was done, but the page never showed it (${describeUntil(until)})`);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
outcome.viaHuman = 'answered';
|
|
665
|
+
}
|
|
666
|
+
outcome.ok = true;
|
|
667
|
+
}
|
|
506
668
|
else if (event.action === 'assert') {
|
|
507
669
|
// A check, not an action: nothing is dispatched, so a retry is safe.
|
|
508
670
|
await checkAssert(page, event, values, timeoutMs);
|
|
@@ -648,12 +810,27 @@ export async function replay(recording, opts = {}) {
|
|
|
648
810
|
if (outcome.matched === 0)
|
|
649
811
|
throw new Error(`locator ${describeLocator(event)} matched no elements`);
|
|
650
812
|
const target = outcome.matched > 1 ? locator.first() : locator;
|
|
813
|
+
// LOOK, DON'T TOUCH. The control exists — is it one a person could
|
|
814
|
+
// press right now? Then stop: nothing below this line runs for it.
|
|
815
|
+
if (holding) {
|
|
816
|
+
if (!forced(event)) {
|
|
817
|
+
await target.waitFor({ state: 'visible', timeout: timeoutMs }).catch(() => {
|
|
818
|
+
throw new Error(`the step it stops before, ${describeLocator(event)}, is there but not visible`);
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
if (!(await target.isEnabled({ timeout: timeoutMs }).catch(() => false))) {
|
|
822
|
+
throw new Error(`the step it stops before, ${describeLocator(event)}, is there but not enabled`);
|
|
823
|
+
}
|
|
824
|
+
outcome.ok = true;
|
|
825
|
+
outcome.held = true;
|
|
826
|
+
break;
|
|
827
|
+
}
|
|
651
828
|
// Past this line the app may have been changed. Everything above is
|
|
652
829
|
// addressing, which is safe to try again; nothing below is.
|
|
653
830
|
dispatched = true;
|
|
654
831
|
switch (event.action) {
|
|
655
832
|
case 'click':
|
|
656
|
-
await target.click({ timeout: timeoutMs });
|
|
833
|
+
await target.click({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
657
834
|
break;
|
|
658
835
|
case 'fill': {
|
|
659
836
|
const value = valueFor(event, values);
|
|
@@ -675,10 +852,10 @@ export async function replay(recording, opts = {}) {
|
|
|
675
852
|
await target.press(valueFor(event, values) ?? 'Enter', { timeout: timeoutMs });
|
|
676
853
|
break;
|
|
677
854
|
case 'check':
|
|
678
|
-
await target.check({ timeout: timeoutMs });
|
|
855
|
+
await target.check({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
679
856
|
break;
|
|
680
857
|
case 'uncheck':
|
|
681
|
-
await target.uncheck({ timeout: timeoutMs });
|
|
858
|
+
await target.uncheck({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
682
859
|
break;
|
|
683
860
|
case 'select': {
|
|
684
861
|
const value = valueFor(event, values);
|
|
@@ -814,7 +991,7 @@ export async function replay(recording, opts = {}) {
|
|
|
814
991
|
if (err instanceof AssertionFailed && err.saw)
|
|
815
992
|
outcome.saw = err.saw;
|
|
816
993
|
}
|
|
817
|
-
if (outcome.ok || attempt ===
|
|
994
|
+
if (outcome.ok || attempt === attemptsHere)
|
|
818
995
|
break;
|
|
819
996
|
// A RETRY IS ONLY SAFE BEFORE THE ACTION WENT OUT. Re-clicking a button
|
|
820
997
|
// that navigated and then failed its fingerprint check submits twice.
|
|
@@ -852,7 +1029,7 @@ export async function replay(recording, opts = {}) {
|
|
|
852
1029
|
// asks a human to do the piece it cannot and carries on from wherever they
|
|
853
1030
|
// got to. A prelude step is excluded: the prelude is how we reached the
|
|
854
1031
|
// starting line, and a human patching it would be patching the wrong thing.
|
|
855
|
-
if (!outcome.ok && onHandoff && !isPrelude) {
|
|
1032
|
+
if (!outcome.ok && onHandoff && !isPrelude && event.action !== 'human') {
|
|
856
1033
|
const trigger = outcome.error?.includes('does not implement action')
|
|
857
1034
|
? 'unimplemented_action'
|
|
858
1035
|
: event.hints?.seamGapBefore
|
|
@@ -879,7 +1056,26 @@ export async function replay(recording, opts = {}) {
|
|
|
879
1056
|
},
|
|
880
1057
|
};
|
|
881
1058
|
const handed = await onHandoff(request);
|
|
882
|
-
if (handed.action === '
|
|
1059
|
+
if (handed.action === 'continue') {
|
|
1060
|
+
// Done by hand in this very browser: the page they left is the state.
|
|
1061
|
+
await waitForUrlSettled(page, { mayNavigate: true });
|
|
1062
|
+
await waitForAriaStable(page, 1500);
|
|
1063
|
+
const landed = await computeSig(page);
|
|
1064
|
+
outcome.ok = true;
|
|
1065
|
+
outcome.viaHandoff = true;
|
|
1066
|
+
delete outcome.error;
|
|
1067
|
+
if (sigSequence[sigSequence.length - 1] !== landed.sig)
|
|
1068
|
+
sigSequence.push(landed.sig);
|
|
1069
|
+
outcome.sig = landed.sig;
|
|
1070
|
+
lastPattern = landed.urlPattern;
|
|
1071
|
+
handoffs.push({ seq: event.seq, trigger, reason: request.reason, steps: 0, url: page.url() });
|
|
1072
|
+
if (trigger === 'unresolved_seam') {
|
|
1073
|
+
delete event.hints.seamGapBefore;
|
|
1074
|
+
i--;
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
else if (handed.action === 'adopt') {
|
|
883
1079
|
// ADOPT, DO NOT RE-DRIVE. The handoff window shared this run's
|
|
884
1080
|
// server-side session, so the work is already done over there. Replaying
|
|
885
1081
|
// the captured steps here would walk a flow that has already moved on —
|
|
@@ -941,6 +1137,10 @@ export async function replay(recording, opts = {}) {
|
|
|
941
1137
|
preludeFailed = isPrelude;
|
|
942
1138
|
break;
|
|
943
1139
|
}
|
|
1140
|
+
if (outcome.held) {
|
|
1141
|
+
stoppedBefore = event.seq;
|
|
1142
|
+
break;
|
|
1143
|
+
}
|
|
944
1144
|
}
|
|
945
1145
|
// THE VISUAL VERDICT, ONCE, AT THE END.
|
|
946
1146
|
//
|
|
@@ -989,20 +1189,28 @@ export async function replay(recording, opts = {}) {
|
|
|
989
1189
|
await acceptBaseline(check).catch(() => { });
|
|
990
1190
|
}
|
|
991
1191
|
}
|
|
1192
|
+
const failed = steps.filter((s) => !s.ok);
|
|
1193
|
+
const endChecks = opts.endChecks && !failed.length && stoppedBefore === undefined && steps.length === recording.events.length
|
|
1194
|
+
? await endChecksOf(page).catch(() => [])
|
|
1195
|
+
: undefined;
|
|
992
1196
|
if (ownsLease)
|
|
993
1197
|
await lease.close();
|
|
994
|
-
const failed = steps.filter((s) => !s.ok);
|
|
995
1198
|
// A prelude that did not replay means the recording's own steps NEVER RAN.
|
|
996
1199
|
// Calling that `needsReview` would quarantine a recording nothing was learned
|
|
997
1200
|
// about, so it is reported as its own condition and `ok` is simply false.
|
|
998
1201
|
const preludeOk = !preludeFailed;
|
|
1202
|
+
// Every step should have run — or, when it stopped as asked, every step up to
|
|
1203
|
+
// and including the one it stopped at.
|
|
1204
|
+
const expected = stoppedBefore === undefined
|
|
1205
|
+
? recording.events.length
|
|
1206
|
+
: recording.events.findIndex((e) => e.seq === stoppedBefore) + 1;
|
|
999
1207
|
return {
|
|
1000
1208
|
hash: recording.hash,
|
|
1001
1209
|
...(prelude?.length ? { preludeSteps, preludeOk } : {}),
|
|
1002
|
-
ok: preludeOk && failed.length === 0 && steps.length ===
|
|
1210
|
+
ok: preludeOk && failed.length === 0 && steps.length === expected,
|
|
1003
1211
|
// The gate. Anything that did not fully reproduce is quarantined from
|
|
1004
1212
|
// memory rather than partially ingested.
|
|
1005
|
-
needsReview: preludeOk && (failed.length > 0 || steps.length !==
|
|
1213
|
+
needsReview: preludeOk && (failed.length > 0 || steps.length !== expected),
|
|
1006
1214
|
steps,
|
|
1007
1215
|
sigSequence,
|
|
1008
1216
|
signals,
|
|
@@ -1010,5 +1218,36 @@ export async function replay(recording, opts = {}) {
|
|
|
1010
1218
|
escalations,
|
|
1011
1219
|
visualChecks,
|
|
1012
1220
|
handoffs,
|
|
1221
|
+
...(stoppedBefore !== undefined ? { stoppedBefore } : {}),
|
|
1222
|
+
...(endChecks?.length ? { endChecks } : {}),
|
|
1013
1223
|
};
|
|
1014
1224
|
}
|
|
1225
|
+
/**
|
|
1226
|
+
* What the last page says about how the flow ended: its headings, the state of
|
|
1227
|
+
* every named checkbox, radio and switch ("Extended care" ticked), and any
|
|
1228
|
+
* status or alert message. Read from the accessibility tree, so it is what a
|
|
1229
|
+
* person would read, not markup. Offered, never assumed: which of these mean
|
|
1230
|
+
* "it ended right" is a person's call.
|
|
1231
|
+
*/
|
|
1232
|
+
async function endChecksOf(page) {
|
|
1233
|
+
const tree = await page.locator('body').ariaSnapshot({ timeout: 2000 });
|
|
1234
|
+
const headings = [];
|
|
1235
|
+
const states = [];
|
|
1236
|
+
const messages = [];
|
|
1237
|
+
for (const line of tree.split('\n')) {
|
|
1238
|
+
const m = line.match(/^\s*- (heading|checkbox|radio|switch|status|alert)(?: "((?:[^"\\]|\\.)*)")?([^:]*)(?::\s*(.+))?$/);
|
|
1239
|
+
if (!m)
|
|
1240
|
+
continue;
|
|
1241
|
+
const [, role, rawName, flags = '', text] = m;
|
|
1242
|
+
const name = rawName?.replace(/\\(.)/g, '$1');
|
|
1243
|
+
if (role === 'heading' && name)
|
|
1244
|
+
headings.push({ action: 'assert', role, name, hints: { assert: 'visible' } });
|
|
1245
|
+
else if ((role === 'checkbox' || role === 'radio' || role === 'switch') && name) {
|
|
1246
|
+
states.push({ action: 'assert', role, name, hints: { assert: /\[checked(=true)?\]/.test(flags) ? 'checked' : 'unchecked' } });
|
|
1247
|
+
}
|
|
1248
|
+
else if ((role === 'status' || role === 'alert') && (text ?? name)) {
|
|
1249
|
+
messages.push({ action: 'wait_text', value: (text ?? name).trim() });
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
return [...headings.slice(0, 3), ...states.slice(0, 6), ...messages.slice(0, 2)];
|
|
1253
|
+
}
|