@jeffawe/understudy 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -12
- 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 +81 -1
- package/dist/core/replay.js +319 -19
- package/dist/entry/cli.js +112 -10
- package/dist/entry/mcp.d.ts +1 -1
- package/dist/entry/mcp.js +175 -35
- 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 +25 -7
- 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/recall.d.ts +10 -1
- package/dist/memory/recall.js +12 -5
- 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/types.d.ts +46 -2
- package/package.json +1 -1
package/dist/core/replay.js
CHANGED
|
@@ -25,6 +25,41 @@ 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';
|
|
29
|
+
/** An assertion that failed, carrying what it actually saw. */
|
|
30
|
+
class AssertionFailed extends Error {
|
|
31
|
+
saw;
|
|
32
|
+
constructor(message, saw) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.saw = saw;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The part of a page's text worth showing next to an expected string that
|
|
39
|
+
* wasn't there: a window around the longest run of the expected words that IS
|
|
40
|
+
* there ("Total Transactions 9" for an expected "Total Transactions 10"), or
|
|
41
|
+
* the start of the text if none is. Pure; exported for tests.
|
|
42
|
+
*/
|
|
43
|
+
export function excerpt(actual, expected, width = 160) {
|
|
44
|
+
const text = actual.replace(/\s+/g, ' ').trim();
|
|
45
|
+
if (text.length <= width)
|
|
46
|
+
return text;
|
|
47
|
+
const words = (expected ?? '').replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
|
|
48
|
+
const lower = text.toLowerCase();
|
|
49
|
+
for (let k = words.length; k >= 1; k--) {
|
|
50
|
+
for (let start = 0; start + k <= words.length; start++) {
|
|
51
|
+
const phrase = words.slice(start, start + k).join(' ').toLowerCase();
|
|
52
|
+
if (phrase.length < 3)
|
|
53
|
+
continue;
|
|
54
|
+
const at = lower.indexOf(phrase);
|
|
55
|
+
if (at < 0)
|
|
56
|
+
continue;
|
|
57
|
+
const from = Math.max(0, Math.min(at - Math.floor(width / 3), text.length - width));
|
|
58
|
+
return `${from > 0 ? '…' : ''}${text.slice(from, from + width)}${from + width < text.length ? '…' : ''}`;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return `${text.slice(0, width)}…`;
|
|
62
|
+
}
|
|
28
63
|
/** Lesson kinds that mean "this page resolves late" — settle before acting. */
|
|
29
64
|
const SETTLE_KINDS = new Set(['wait', 'timing']);
|
|
30
65
|
/** Bodies above this are truncated — a findings fingerprint needs the shape, not the payload. */
|
|
@@ -187,6 +222,90 @@ export function urlGlob(glob) {
|
|
|
187
222
|
}
|
|
188
223
|
return new RegExp(`${/^[a-z]+:/i.test(glob) || glob.startsWith('*') ? '^' : ''}${re}$`);
|
|
189
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 ');
|
|
190
309
|
/** Whitespace-normalised, as Playwright's text assertions compare. */
|
|
191
310
|
const squash = (s) => s.replace(/\s+/g, ' ').trim();
|
|
192
311
|
/**
|
|
@@ -207,7 +326,9 @@ async function checkAssert(page, event, values, timeoutMs) {
|
|
|
207
326
|
: squash(actual) === squash(expected);
|
|
208
327
|
const shown = regex ? `/${expected}/` : `"${expected}"`;
|
|
209
328
|
/** Poll `read` until `ok`, like expect's retrying; report the last value seen. */
|
|
210
|
-
const until = async (read, ok, what
|
|
329
|
+
const until = async (read, ok, what,
|
|
330
|
+
/** What to show as "saw" — e.g. the visible text, not textContent's scripts. */
|
|
331
|
+
shownAs) => {
|
|
211
332
|
const deadline = Date.now() + timeoutMs;
|
|
212
333
|
let last = null;
|
|
213
334
|
for (;;) {
|
|
@@ -215,7 +336,10 @@ async function checkAssert(page, event, values, timeoutMs) {
|
|
|
215
336
|
if (ok(last))
|
|
216
337
|
return;
|
|
217
338
|
if (Date.now() >= deadline) {
|
|
218
|
-
|
|
339
|
+
const visible = shownAs ? await shownAs().catch(() => null) : null;
|
|
340
|
+
const raw = visible ?? (typeof last === 'string' ? last : null);
|
|
341
|
+
const saw = raw !== null ? `"${excerpt(raw, expected)}"` : last === null ? 'nothing it could read' : String(last);
|
|
342
|
+
throw new AssertionFailed(`${what} — saw ${saw}`, saw);
|
|
219
343
|
}
|
|
220
344
|
await page.waitForTimeout(100);
|
|
221
345
|
}
|
|
@@ -236,12 +360,18 @@ async function checkAssert(page, event, values, timeoutMs) {
|
|
|
236
360
|
case 'hidden':
|
|
237
361
|
await target.waitFor({ state: kind, timeout: timeoutMs }).catch(async () => {
|
|
238
362
|
const count = await locator.count().catch(() => 0);
|
|
239
|
-
|
|
363
|
+
const saw = kind === 'visible'
|
|
364
|
+
? (count === 0 ? 'it matched no elements' : `it matched ${count} element(s), none visible`)
|
|
365
|
+
: `it is still visible${count > 1 ? ` (${count} match)` : ''}`;
|
|
366
|
+
throw new AssertionFailed(`expected ${desc} to be ${kind} — ${saw}`, saw);
|
|
240
367
|
});
|
|
241
368
|
return;
|
|
242
369
|
case 'text':
|
|
243
370
|
case 'contains':
|
|
244
|
-
return until(() => target.textContent({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to ${kind === 'text' ? 'have text' : 'contain text'} ${shown}
|
|
371
|
+
return until(() => target.textContent({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to ${kind === 'text' ? 'have text' : 'contain text'} ${shown}`,
|
|
372
|
+
// textContent includes <script> and hidden text (a JSON-LD blob on <body>);
|
|
373
|
+
// show what a person would see.
|
|
374
|
+
() => target.innerText({ timeout: 1000 }));
|
|
245
375
|
case 'value':
|
|
246
376
|
return until(() => target.inputValue({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to have value ${event.valueRef ? `of ${event.valueRef}` : shown}`);
|
|
247
377
|
case 'checked':
|
|
@@ -299,7 +429,8 @@ function valueFor(event, values) {
|
|
|
299
429
|
return values[event.valueRef];
|
|
300
430
|
}
|
|
301
431
|
export async function replay(recording, opts = {}) {
|
|
302
|
-
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;
|
|
303
434
|
const maxAttempts = Math.max(1, budget?.stepAttempts ?? 1);
|
|
304
435
|
const handoffs = [];
|
|
305
436
|
const escalations = [];
|
|
@@ -319,12 +450,23 @@ export async function replay(recording, opts = {}) {
|
|
|
319
450
|
// the correlation between a signal and the intent that was executing when it
|
|
320
451
|
// fired. A 500 is interesting; a 500 *during checkout* is a finding.
|
|
321
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)));
|
|
322
464
|
/** Route of the page we are on, so a lesson can be scoped to one page. */
|
|
323
465
|
let lastPattern;
|
|
324
466
|
page.on('console', (msg) => {
|
|
325
467
|
if (msg.type() !== 'error' && msg.type() !== 'warning')
|
|
326
468
|
return;
|
|
327
|
-
signals.push({ kind: 'console', duringStep: currentStep, text: msg.text().slice(0, 500) });
|
|
469
|
+
signals.push({ kind: 'console', level: msg.type() === 'error' ? 'error' : 'warning', duringStep: currentStep, text: msg.text().slice(0, 500) });
|
|
328
470
|
});
|
|
329
471
|
page.on('pageerror', (err) => {
|
|
330
472
|
signals.push({ kind: 'pageerror', duringStep: currentStep, text: String(err).slice(0, 500) });
|
|
@@ -338,6 +480,7 @@ export async function replay(recording, opts = {}) {
|
|
|
338
480
|
});
|
|
339
481
|
});
|
|
340
482
|
page.on('response', async (res) => {
|
|
483
|
+
responses.add(currentStep, res);
|
|
341
484
|
const status = res.status();
|
|
342
485
|
const contentType = res.headers()['content-type'] ?? '';
|
|
343
486
|
const interesting = status >= 400 || contentType.includes('application/json');
|
|
@@ -376,7 +519,23 @@ export async function replay(recording, opts = {}) {
|
|
|
376
519
|
/** Set the instant an action goes out, so a retry cannot double-submit. */
|
|
377
520
|
let dispatched = false;
|
|
378
521
|
const stepStart = Date.now();
|
|
379
|
-
|
|
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;
|
|
380
539
|
// WHAT HAVE WE LEARNED ABOUT THIS STEP? Consulted BEFORE acting, because a
|
|
381
540
|
// lesson's whole purpose is "do Y first".
|
|
382
541
|
let applied = [];
|
|
@@ -412,7 +571,7 @@ export async function replay(recording, opts = {}) {
|
|
|
412
571
|
// THE ATTEMPT LOOP IS PURE CONTROL FLOW, not a reasoner round trip.
|
|
413
572
|
// Retrying by asking would make every retry human-speed, which is the
|
|
414
573
|
// opposite of the point — the budget exists to REDUCE escalations.
|
|
415
|
-
for (let attempt = 1; attempt <=
|
|
574
|
+
for (let attempt = 1; attempt <= attemptsHere; attempt++) {
|
|
416
575
|
outcome.ok = false;
|
|
417
576
|
delete outcome.error;
|
|
418
577
|
try {
|
|
@@ -458,6 +617,54 @@ export async function replay(recording, opts = {}) {
|
|
|
458
617
|
}
|
|
459
618
|
outcome.ok = true;
|
|
460
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
|
+
}
|
|
461
668
|
else if (event.action === 'assert') {
|
|
462
669
|
// A check, not an action: nothing is dispatched, so a retry is safe.
|
|
463
670
|
await checkAssert(page, event, values, timeoutMs);
|
|
@@ -603,12 +810,27 @@ export async function replay(recording, opts = {}) {
|
|
|
603
810
|
if (outcome.matched === 0)
|
|
604
811
|
throw new Error(`locator ${describeLocator(event)} matched no elements`);
|
|
605
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
|
+
}
|
|
606
828
|
// Past this line the app may have been changed. Everything above is
|
|
607
829
|
// addressing, which is safe to try again; nothing below is.
|
|
608
830
|
dispatched = true;
|
|
609
831
|
switch (event.action) {
|
|
610
832
|
case 'click':
|
|
611
|
-
await target.click({ timeout: timeoutMs });
|
|
833
|
+
await target.click({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
612
834
|
break;
|
|
613
835
|
case 'fill': {
|
|
614
836
|
const value = valueFor(event, values);
|
|
@@ -630,10 +852,10 @@ export async function replay(recording, opts = {}) {
|
|
|
630
852
|
await target.press(valueFor(event, values) ?? 'Enter', { timeout: timeoutMs });
|
|
631
853
|
break;
|
|
632
854
|
case 'check':
|
|
633
|
-
await target.check({ timeout: timeoutMs });
|
|
855
|
+
await target.check({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
634
856
|
break;
|
|
635
857
|
case 'uncheck':
|
|
636
|
-
await target.uncheck({ timeout: timeoutMs });
|
|
858
|
+
await target.uncheck({ timeout: timeoutMs, ...(forced(event) ? { force: true } : {}) });
|
|
637
859
|
break;
|
|
638
860
|
case 'select': {
|
|
639
861
|
const value = valueFor(event, values);
|
|
@@ -726,7 +948,15 @@ export async function replay(recording, opts = {}) {
|
|
|
726
948
|
// every step regardless. Not comparing them meant execution could walk
|
|
727
949
|
// into a page the plan had never seen and notice nothing until a locator
|
|
728
950
|
// happened to miss.
|
|
729
|
-
|
|
951
|
+
// A REDIRECT THAT LANDS A BEAT EARLY OR LATE IS NOT AN UNEXPECTED PAGE.
|
|
952
|
+
// Signing in submits, then the app routes to /auth/otp once its API
|
|
953
|
+
// answers — sometimes before this fingerprint, sometimes after. Seeing
|
|
954
|
+
// the page the previous step expected (not there yet) or the one the
|
|
955
|
+
// next step expects (there already) is the same path, a step out of
|
|
956
|
+
// phase. Never for the first step: that one detects a stale session.
|
|
957
|
+
const neighbours = i > 0 ? [walk[i - 1]?.event.expectedSig, walk[i + 1]?.event.expectedSig] : [];
|
|
958
|
+
const inPhase = neighbours.includes(sig.sig);
|
|
959
|
+
if (event.expectedSig && event.expectedSig !== sig.sig && !inPhase) {
|
|
730
960
|
outcome.unexpectedPage = { expected: event.expectedSig, observed: sig.sig };
|
|
731
961
|
// THE ESCALATION. An unexpected page is not automatically wrong — an
|
|
732
962
|
// app may have gained a banner — but continuing blindly is how a run
|
|
@@ -751,9 +981,17 @@ export async function replay(recording, opts = {}) {
|
|
|
751
981
|
}
|
|
752
982
|
}
|
|
753
983
|
catch (err) {
|
|
754
|
-
|
|
984
|
+
let message = (err instanceof Error ? err.message : String(err)).split('\n')[0];
|
|
985
|
+
// Playwright's first line ("locator.click: Timeout 5000ms exceeded.") leaves
|
|
986
|
+
// the locator to later lines; say which one, so the step can be found.
|
|
987
|
+
const desc = describeLocator(event);
|
|
988
|
+
if (desc !== '(no locator)' && !message.includes(desc))
|
|
989
|
+
message = `${desc}: ${message}`;
|
|
990
|
+
outcome.error = message.slice(0, 500);
|
|
991
|
+
if (err instanceof AssertionFailed && err.saw)
|
|
992
|
+
outcome.saw = err.saw;
|
|
755
993
|
}
|
|
756
|
-
if (outcome.ok || attempt ===
|
|
994
|
+
if (outcome.ok || attempt === attemptsHere)
|
|
757
995
|
break;
|
|
758
996
|
// A RETRY IS ONLY SAFE BEFORE THE ACTION WENT OUT. Re-clicking a button
|
|
759
997
|
// that navigated and then failed its fingerprint check submits twice.
|
|
@@ -791,7 +1029,7 @@ export async function replay(recording, opts = {}) {
|
|
|
791
1029
|
// asks a human to do the piece it cannot and carries on from wherever they
|
|
792
1030
|
// got to. A prelude step is excluded: the prelude is how we reached the
|
|
793
1031
|
// starting line, and a human patching it would be patching the wrong thing.
|
|
794
|
-
if (!outcome.ok && onHandoff && !isPrelude) {
|
|
1032
|
+
if (!outcome.ok && onHandoff && !isPrelude && event.action !== 'human') {
|
|
795
1033
|
const trigger = outcome.error?.includes('does not implement action')
|
|
796
1034
|
? 'unimplemented_action'
|
|
797
1035
|
: event.hints?.seamGapBefore
|
|
@@ -818,7 +1056,26 @@ export async function replay(recording, opts = {}) {
|
|
|
818
1056
|
},
|
|
819
1057
|
};
|
|
820
1058
|
const handed = await onHandoff(request);
|
|
821
|
-
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') {
|
|
822
1079
|
// ADOPT, DO NOT RE-DRIVE. The handoff window shared this run's
|
|
823
1080
|
// server-side session, so the work is already done over there. Replaying
|
|
824
1081
|
// the captured steps here would walk a flow that has already moved on —
|
|
@@ -880,6 +1137,10 @@ export async function replay(recording, opts = {}) {
|
|
|
880
1137
|
preludeFailed = isPrelude;
|
|
881
1138
|
break;
|
|
882
1139
|
}
|
|
1140
|
+
if (outcome.held) {
|
|
1141
|
+
stoppedBefore = event.seq;
|
|
1142
|
+
break;
|
|
1143
|
+
}
|
|
883
1144
|
}
|
|
884
1145
|
// THE VISUAL VERDICT, ONCE, AT THE END.
|
|
885
1146
|
//
|
|
@@ -928,20 +1189,28 @@ export async function replay(recording, opts = {}) {
|
|
|
928
1189
|
await acceptBaseline(check).catch(() => { });
|
|
929
1190
|
}
|
|
930
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;
|
|
931
1196
|
if (ownsLease)
|
|
932
1197
|
await lease.close();
|
|
933
|
-
const failed = steps.filter((s) => !s.ok);
|
|
934
1198
|
// A prelude that did not replay means the recording's own steps NEVER RAN.
|
|
935
1199
|
// Calling that `needsReview` would quarantine a recording nothing was learned
|
|
936
1200
|
// about, so it is reported as its own condition and `ok` is simply false.
|
|
937
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;
|
|
938
1207
|
return {
|
|
939
1208
|
hash: recording.hash,
|
|
940
1209
|
...(prelude?.length ? { preludeSteps, preludeOk } : {}),
|
|
941
|
-
ok: preludeOk && failed.length === 0 && steps.length ===
|
|
1210
|
+
ok: preludeOk && failed.length === 0 && steps.length === expected,
|
|
942
1211
|
// The gate. Anything that did not fully reproduce is quarantined from
|
|
943
1212
|
// memory rather than partially ingested.
|
|
944
|
-
needsReview: preludeOk && (failed.length > 0 || steps.length !==
|
|
1213
|
+
needsReview: preludeOk && (failed.length > 0 || steps.length !== expected),
|
|
945
1214
|
steps,
|
|
946
1215
|
sigSequence,
|
|
947
1216
|
signals,
|
|
@@ -949,5 +1218,36 @@ export async function replay(recording, opts = {}) {
|
|
|
949
1218
|
escalations,
|
|
950
1219
|
visualChecks,
|
|
951
1220
|
handoffs,
|
|
1221
|
+
...(stoppedBefore !== undefined ? { stoppedBefore } : {}),
|
|
1222
|
+
...(endChecks?.length ? { endChecks } : {}),
|
|
952
1223
|
};
|
|
953
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
|
+
}
|