@clipy/cli 0.17.0 → 0.18.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.
@@ -0,0 +1,934 @@
1
+ /**
2
+ * `clipy recheck <id> --url <start-url>`: replays a recorded workflow against
3
+ * today's UI and reports, step by step, where it still works and where it
4
+ * diverges.
5
+ *
6
+ * The original run comes from the existing API: the interaction timeline
7
+ * (clicks with element labels, navigations, scrolls, typing bursts), key
8
+ * moments (frames) and the transcript. The replay drives Chrome for Clipy
9
+ * through a small RecheckDriver interface, so everything here except
10
+ * `createPageDriver` is plain data in, plain data out and testable without a
11
+ * browser.
12
+ *
13
+ * Honesty rules, which are the point of the command:
14
+ * - A click is replayed only by its recorded element label. A raw position is
15
+ * never clicked on its own; an unlabelled click is reported as "could not
16
+ * map step" instead of a guess.
17
+ * - Typed values are never captured, so typing is never replayed.
18
+ * - A step whose page does not match the recorded route is "different
19
+ * screen" and is not clicked: clicking a same-named control on another
20
+ * screen is exactly the silent failure this command exists to catch.
21
+ *
22
+ * Safety rules, because the replay runs on a real, signed-in site:
23
+ * - A control whose name reads as irreversible (delete, pay, send, submit and
24
+ * similar) is not clicked unless the caller passes allowIrreversible.
25
+ * - A recorded page is opened directly only on the recording's own host
26
+ * (moved onto the re-check's host), never on a host the timeline names.
27
+ */
28
+ import { mkdirSync, writeFileSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ export const RECHECK_REPORT_VERSION = 1;
31
+ /** clipy proof accepts 1-50 frames, and one frame is captured per step. */
32
+ export const RECHECK_MAX_STEPS = 50;
33
+ const MOMENT_MATCH_MS = 2_500;
34
+ /** Words on a control that usually change or spend something on a real
35
+ * account and cannot be taken back. A heuristic: it errs toward not clicking,
36
+ * and --allow-destructive turns it off. */
37
+ const IRREVERSIBLE_LABEL = /\b(?:delete|remove|destroy|erase|purge|wipe|discard|pay|purchase|buy|checkout|check out|place order|order now|subscribe|unsubscribe|upgrade|downgrade|cancel (?:subscription|plan|account|order|membership|trial)|transfer|send|submit|publish|deploy|merge|archive|revoke|deactivate|reset|refund|charge|donate|invite|confirm|approve|reject|sign out|log out|logout|leave)\b/i;
38
+ export function looksIrreversible(label) {
39
+ return Boolean(label && IRREVERSIBLE_LABEL.test(label.replace(/\s+/g, " ")));
40
+ }
41
+ function irreversibleReason(name) {
42
+ return `"${name}" looks like it changes or spends something that cannot be undone (delete, pay, send, submit and similar), so it is not clicked without --allow-destructive`;
43
+ }
44
+ function nearestMoment(tMs, moments) {
45
+ let best = null;
46
+ for (const m of moments) {
47
+ if (!best || Math.abs(m.tMs - tMs) < Math.abs(best.tMs - tMs))
48
+ best = m;
49
+ }
50
+ return best && Math.abs(best.tMs - tMs) <= MOMENT_MATCH_MS ? best : null;
51
+ }
52
+ /** What was said while the step happened: the segment covering it, else the
53
+ * last one that ended within two seconds before it. */
54
+ export function saidAt(tMs, segments) {
55
+ const t = tMs / 1000;
56
+ const covering = segments.find((s) => s.start <= t && t <= s.end);
57
+ if (covering)
58
+ return covering.text.trim() || null;
59
+ let previous = null;
60
+ for (const s of segments)
61
+ if (s.end <= t && t - s.end <= 2 && (!previous || s.end > previous.end))
62
+ previous = s;
63
+ return previous?.text.trim() || null;
64
+ }
65
+ /** Turns the recorded timeline into replayable steps. Pointer moves, dwells
66
+ * and highlights are evidence, not actions, and are skipped. Repeated
67
+ * navigations to one route (SPA re-renders) and consecutive scrolls in one
68
+ * direction collapse into one step. */
69
+ export function buildRecheckPlan(run, maxSteps = RECHECK_MAX_STEPS, planOpts = {}) {
70
+ const events = [...run.events].sort((a, b) => a.tMs - b.tMs);
71
+ const steps = [];
72
+ let lastRoute = null;
73
+ for (const event of events) {
74
+ const evidence = event.evidence ?? null;
75
+ const moment = evidence ? null : nearestMoment(event.tMs, run.moments);
76
+ const original = {
77
+ caption: evidence?.caption ?? moment?.caption ?? null,
78
+ frameUrl: evidence?.frameUrl ?? moment?.frameUrl ?? null,
79
+ cropUrl: evidence?.cropUrl ?? moment?.cropUrl ?? null,
80
+ said: saidAt(event.tMs, run.segments),
81
+ };
82
+ const base = {
83
+ tMs: Math.max(0, Math.round(event.tMs)),
84
+ label: null,
85
+ role: null,
86
+ position: null,
87
+ route: event.pageUrl ?? lastRoute,
88
+ direction: null,
89
+ button: null,
90
+ unmappable: null,
91
+ original,
92
+ };
93
+ switch (event.kind) {
94
+ case "navigation": {
95
+ const route = event.pageUrl ?? null;
96
+ if (!route || route === lastRoute)
97
+ break;
98
+ steps.push({ ...base, kind: steps.length === 0 ? "start" : "navigate", route });
99
+ lastRoute = route;
100
+ break;
101
+ }
102
+ case "click": {
103
+ const label = event.target?.label?.trim() || null;
104
+ const button = event.button ?? "primary";
105
+ let unmappable = null;
106
+ if (button !== "primary") {
107
+ unmappable = `a ${button}-button click is not replayed`;
108
+ }
109
+ else if (!label) {
110
+ unmappable = "no element label was recorded for this click, and a raw screen position is not clicked on its own";
111
+ }
112
+ else if (!planOpts.allowIrreversible && looksIrreversible(label)) {
113
+ unmappable = irreversibleReason(label);
114
+ }
115
+ steps.push({
116
+ ...base,
117
+ kind: "click",
118
+ label,
119
+ role: event.target?.role ?? null,
120
+ position: event.position ?? null,
121
+ button,
122
+ unmappable,
123
+ });
124
+ break;
125
+ }
126
+ case "scroll": {
127
+ const direction = event.direction ?? "mixed";
128
+ const prev = steps[steps.length - 1];
129
+ if (prev?.kind === "scroll" && prev.direction === direction)
130
+ break;
131
+ steps.push({
132
+ ...base,
133
+ kind: "scroll",
134
+ direction,
135
+ unmappable: direction === "mixed" ? "the recorded scroll has no single direction" : null,
136
+ });
137
+ break;
138
+ }
139
+ case "typing":
140
+ steps.push({
141
+ ...base,
142
+ kind: "type",
143
+ unmappable: "typed values are never captured in a recording, so typing is not replayed",
144
+ });
145
+ break;
146
+ case "drag":
147
+ steps.push({
148
+ ...base,
149
+ kind: "drag",
150
+ position: event.position ?? null,
151
+ unmappable: "drags are not replayed yet",
152
+ });
153
+ break;
154
+ default:
155
+ break;
156
+ }
157
+ if (event.pageUrl)
158
+ lastRoute = event.pageUrl;
159
+ }
160
+ const kept = steps.slice(0, maxSteps).map((s, i) => ({ ...s, index: i + 1 }));
161
+ return { steps: kept, truncatedSteps: Math.max(0, steps.length - kept.length) };
162
+ }
163
+ // ---------------------------------------------------------------------------
164
+ // Routes
165
+ // ---------------------------------------------------------------------------
166
+ // Mirrors SENSITIVE_PATH_SEGMENT_PATTERN in lib/browserDiagnostics.ts, which is
167
+ // how recorded routes were redacted: long numbers, UUIDs, long tokens and
168
+ // mixed letter-digit ids become `:id`.
169
+ const SENSITIVE_PATH_SEGMENT = /^(?:[0-9]{4,}|[A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}|[A-Za-z0-9_-]{16,}|(?=[A-Za-z0-9_-]{10,}$)(?=[A-Za-z0-9_-]*[0-9])[A-Za-z0-9_-]+)$/;
170
+ function segmentsOf(pathname) {
171
+ return pathname.split("/").filter(Boolean);
172
+ }
173
+ /** A live URL reduced to the same shape recordings store: origin and path,
174
+ * with id-like segments as `:id` and no query or hash. Used in reports, so a
175
+ * token in the live URL never lands in one. */
176
+ export function routeOf(url) {
177
+ try {
178
+ const u = new URL(url);
179
+ if (u.protocol !== "http:" && u.protocol !== "https:")
180
+ return null;
181
+ const path = segmentsOf(u.pathname)
182
+ .map((s) => (SENSITIVE_PATH_SEGMENT.test(s) ? ":id" : s))
183
+ .join("/");
184
+ return `${u.origin}/${path}`;
185
+ }
186
+ catch {
187
+ return null;
188
+ }
189
+ }
190
+ export function originOf(url) {
191
+ if (!url)
192
+ return null;
193
+ try {
194
+ return new URL(url).origin;
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ }
200
+ /** Whether a live URL is on the recorded route. `:id` and redacted segments
201
+ * match anything; query strings are ignored (recordings keep key names only).
202
+ * With `ignoreOrigin` (the re-check runs on another host, e.g. staging) only
203
+ * the path is compared. */
204
+ export function routeMatches(expected, liveUrl, ignoreOrigin, originOnly = false) {
205
+ let exp;
206
+ let live;
207
+ try {
208
+ exp = new URL(expected);
209
+ live = new URL(liveUrl);
210
+ }
211
+ catch {
212
+ return false;
213
+ }
214
+ if (!ignoreOrigin && exp.origin !== live.origin)
215
+ return false;
216
+ // The recording kept origins only: there is no path to compare.
217
+ if (originOnly)
218
+ return true;
219
+ const a = segmentsOf(exp.pathname);
220
+ const b = segmentsOf(live.pathname);
221
+ if (a.length !== b.length)
222
+ return false;
223
+ return a.every((seg, i) => {
224
+ if (seg === ":id" || seg.includes("[redacted"))
225
+ return true;
226
+ let liveSeg = b[i];
227
+ try {
228
+ liveSeg = decodeURIComponent(liveSeg);
229
+ }
230
+ catch {
231
+ // keep it encoded
232
+ }
233
+ let expSeg = seg;
234
+ try {
235
+ expSeg = decodeURIComponent(seg);
236
+ }
237
+ catch {
238
+ // keep it encoded
239
+ }
240
+ return expSeg === liveSeg;
241
+ });
242
+ }
243
+ /** A recorded route we can open directly: no redacted parts and no query
244
+ * (only key names were kept, so the values are gone). */
245
+ export function concreteRoute(route) {
246
+ return !route.includes(":id") && !route.includes("[redacted") && !route.includes("?");
247
+ }
248
+ /** Moves a recorded route onto the re-check's origin. */
249
+ export function mapOrigin(route, toOrigin) {
250
+ try {
251
+ const u = new URL(route);
252
+ return `${toOrigin}${u.pathname}`;
253
+ }
254
+ catch {
255
+ return route;
256
+ }
257
+ }
258
+ /**
259
+ * Runs in the page. Collects the visible controls (interactive elements, and
260
+ * pointer-cursor elements that hold no interactive element), computes each
261
+ * control's OWN accessible name, roughly per accname (aria-labelledby,
262
+ * aria-label, a form control's value or label, alt, then the text of its
263
+ * rendered subtree with hidden parts skipped, then title), and matches the
264
+ * recorded label against that name only. Descendant text never names an
265
+ * ancestor on its own: `<button aria-label="Preview"><span>Save</span>` is
266
+ * "Preview". A name equal to the label (case and whitespace folded) is exact;
267
+ * the label plus digits or punctuation only (an unread count, "Inbox 3") is
268
+ * partial; a name that adds words ("Cancel plan" for "Cancel") is another
269
+ * control. Several matches are told apart by the recorded role, then by
270
+ * distance to the recorded position; with no way to choose, it reports
271
+ * "ambiguous" rather than picking one.
272
+ *
273
+ * Everything works on the composed (flat) tree: open shadow roots are walked,
274
+ * names cross into shadow content and slots, containment and the coverage
275
+ * hit test descend through shadow hosts. Iframes are not searched.
276
+ */
277
+ const LOCATE_SCRIPT = `(hint) => {
278
+ const norm = (s) => String(s || "").replace(/\\s+/g, " ").trim().toLowerCase();
279
+ const clean = (s, n) => String(s || "").replace(/\\s+/g, " ").trim().slice(0, n);
280
+ const want = norm(hint.label);
281
+ const roleWant = norm(hint.role).replace(/^ax/, "");
282
+ // Interactive roles only: [role] alone would make a dialog, list or landmark
283
+ // around the text the "control", and a dialog's tabindex="-1" likewise.
284
+ const ROLES = ["button", "link", "menuitem", "menuitemcheckbox", "menuitemradio", "tab", "checkbox", "radio", "switch", "option", "combobox", "treeitem", "textbox", "searchbox", "slider", "spinbutton"];
285
+ const CLICKABLE = 'a[href],button,input,select,textarea,summary,label,option,[onclick],[tabindex]:not([tabindex^="-"]),[contenteditable="true"],' + ROLES.map((r) => '[role="' + r + '"]').join(",");
286
+
287
+ // Composed-tree helpers: a shadow root's parent is its host.
288
+ const parentOf = (el) => el.parentElement || (el.parentNode && el.parentNode.host) || null;
289
+ const composedContains = (outer, inner) => {
290
+ for (let n = inner; n; n = parentOf(n)) if (n === outer) return true;
291
+ return false;
292
+ };
293
+ const composedClosest = (el, selector) => {
294
+ for (let n = el; n; n = parentOf(n)) if (n.matches && n.matches(selector)) return n;
295
+ return null;
296
+ };
297
+ const childrenOf = (node) => {
298
+ if (node.shadowRoot) return Array.from(node.shadowRoot.childNodes);
299
+ if (node.tagName === "SLOT") {
300
+ const assigned = node.assignedNodes({ flatten: true });
301
+ return assigned.length ? assigned : Array.from(node.childNodes);
302
+ }
303
+ return Array.from(node.childNodes);
304
+ };
305
+ const hiddenForName = (el) => {
306
+ if (el.getAttribute("aria-hidden") === "true" || el.hidden) return true;
307
+ const s = getComputedStyle(el);
308
+ return s.display === "none" || s.visibility === "hidden";
309
+ };
310
+
311
+ /** The text an element contributes to its ancestor's name: its own
312
+ * aria-label or alt when it has one, else its rendered subtree. */
313
+ const subtreeText = (node) => {
314
+ if (node.nodeType === 3) return node.data;
315
+ if (node.nodeType !== 1 || hiddenForName(node)) return "";
316
+ const aria = node.getAttribute("aria-label");
317
+ if (aria && aria.trim()) return " " + aria + " ";
318
+ const tag = node.tagName.toLowerCase();
319
+ if (tag === "img") return " " + (node.getAttribute("alt") || "") + " ";
320
+ if (tag === "input" && ["button", "submit", "reset"].includes((node.getAttribute("type") || "").toLowerCase())) return " " + node.value + " ";
321
+ const inner = childrenOf(node).map(subtreeText).join("");
322
+ const display = getComputedStyle(node).display;
323
+ return display === "inline" ? inner : " " + inner + " ";
324
+ };
325
+ const byId = (el, id) => {
326
+ const root = el.getRootNode();
327
+ return (root.getElementById && root.getElementById(id)) || document.getElementById(id);
328
+ };
329
+ const nameOf = (el) => {
330
+ const by = el.getAttribute("aria-labelledby");
331
+ if (by) {
332
+ const t = by.split(/\\s+/).map((id) => { const n = byId(el, id); return n ? childrenOf(n).map(subtreeText).join("") : ""; }).join(" ");
333
+ if (norm(t)) return t;
334
+ }
335
+ const aria = el.getAttribute("aria-label");
336
+ if (aria && aria.trim()) return aria;
337
+ const tag = el.tagName.toLowerCase();
338
+ if (tag === "input") {
339
+ const type = (el.getAttribute("type") || "text").toLowerCase();
340
+ if (["button", "submit", "reset"].includes(type)) return el.value || type;
341
+ if (type === "image") return el.getAttribute("alt") || el.getAttribute("title") || "";
342
+ }
343
+ if (tag === "input" || tag === "select" || tag === "textarea") {
344
+ if (el.labels && el.labels.length) return Array.from(el.labels).map((l) => childrenOf(l).map(subtreeText).join("")).join(" ");
345
+ return el.getAttribute("placeholder") || el.getAttribute("title") || "";
346
+ }
347
+ if (tag === "img") return el.getAttribute("alt") || el.getAttribute("title") || "";
348
+ const text = childrenOf(el).map(subtreeText).join("");
349
+ if (norm(text)) return text;
350
+ return el.getAttribute("title") || "";
351
+ };
352
+ const roleOf = (el) => norm(el.getAttribute("role") || ({ a: "link", button: "button", input: "textbox", select: "combobox", textarea: "textbox", summary: "button" })[el.tagName.toLowerCase()] || el.tagName);
353
+ const visible = (el) => {
354
+ const r = el.getBoundingClientRect();
355
+ if (r.width < 1 || r.height < 1) return false;
356
+ const s = getComputedStyle(el);
357
+ return s.visibility !== "hidden" && s.display !== "none" && Number(s.opacity) > 0;
358
+ };
359
+ const pointer = (el) => el && el.nodeType === 1 && getComputedStyle(el).cursor === "pointer";
360
+ /** A control: an interactive element, or the outermost pointer-cursor
361
+ * element (cursor inherits) that is not inside or around an interactive one. */
362
+ const isControl = (el) => {
363
+ if (el.matches(CLICKABLE)) return true;
364
+ if (!pointer(el) || pointer(parentOf(el))) return false;
365
+ if (composedClosest(el, CLICKABLE)) return false;
366
+ return !el.querySelector(CLICKABLE);
367
+ };
368
+
369
+ const exact = new Set(), partial = new Set(), all = new Set();
370
+ const visit = (root) => {
371
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
372
+ for (let el = walker.nextNode(); el; el = walker.nextNode()) {
373
+ if (el.shadowRoot) visit(el.shadowRoot);
374
+ if (!isControl(el) || !visible(el)) continue;
375
+ all.add(el);
376
+ const name = norm(nameOf(el));
377
+ if (!name) continue;
378
+ if (name === want) exact.add(el);
379
+ else if (want.length >= 3 && name.includes(want) && !/\\p{L}/u.test(name.replace(want, ""))) partial.add(el);
380
+ }
381
+ };
382
+ visit(document);
383
+ // A control nested in another with the same name (a button inside a link):
384
+ // keep the outermost one.
385
+ const prune = (set) => Array.from(set).filter((el) => !Array.from(set).some((o) => o !== el && composedContains(o, el)));
386
+ let quality = "exact";
387
+ let pool = prune(exact);
388
+ if (!pool.length) { pool = prune(partial); quality = "partial"; }
389
+ const vw = innerWidth, vh = innerHeight;
390
+ const center = (el) => { const r = el.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; };
391
+ if (!pool.length) {
392
+ const px = hint.x == null ? vw / 2 : hint.x * vw, py = hint.y == null ? vh / 2 : hint.y * vh;
393
+ const nearby = Array.from(all)
394
+ .map((el) => ({ el, d: Math.hypot(center(el).x - px, center(el).y - py), n: clean(nameOf(el), 60) }))
395
+ .filter((c) => c.n)
396
+ .sort((a, b) => a.d - b.d)
397
+ .slice(0, 6)
398
+ .map((c) => c.n);
399
+ return { status: "none", nearby: Array.from(new Set(nearby)) };
400
+ }
401
+ // A disabled control ignores the click, so it is never "matched": prefer an
402
+ // enabled one with the same name, and report it when every one is disabled.
403
+ const disabled = (el) => el.matches(":disabled") || Boolean(composedClosest(el, '[aria-disabled="true"]'));
404
+ const enabled = pool.filter((el) => !disabled(el));
405
+ const allDisabled = enabled.length === 0;
406
+ if (!allDisabled) pool = enabled;
407
+ if (pool.length > 1 && roleWant) {
408
+ const byRole = pool.filter((el) => roleOf(el) === roleWant || roleOf(el).includes(roleWant) || roleWant.includes(roleOf(el)));
409
+ if (byRole.length) pool = byRole;
410
+ }
411
+ let chosen = pool[0];
412
+ if (pool.length > 1) {
413
+ if (hint.x == null || hint.y == null) return { status: "ambiguous", candidates: pool.length };
414
+ const px = hint.x * vw, py = hint.y * vh;
415
+ pool.sort((a, b) => Math.hypot(center(a).x - px, center(a).y - py) - Math.hypot(center(b).x - px, center(b).y - py));
416
+ chosen = pool[0];
417
+ }
418
+ const r0 = chosen.getBoundingClientRect();
419
+ // "instant": a page with scroll-behavior: smooth would otherwise still be
420
+ // scrolling when the centre is measured, and the click would land elsewhere.
421
+ if (r0.top < 0 || r0.left < 0 || r0.bottom > vh || r0.right > vw) chosen.scrollIntoView({ block: "center", inline: "center", behavior: "instant" });
422
+ const c = center(chosen);
423
+ const control = { name: clean(nameOf(chosen), 120), role: roleOf(chosen), quality, x: Math.round(c.x), y: Math.round(c.y), candidates: pool.length };
424
+ if (allDisabled) return { status: "disabled", control };
425
+ if (c.x < 0 || c.y < 0 || c.x >= vw || c.y >= vh) return { status: "covered", control, coveredBy: "the edge of the window (it could not be scrolled into view)" };
426
+ // Hit test on the composed tree: document.elementFromPoint stops at a
427
+ // shadow host, so descend through open shadow roots to the real element.
428
+ let top = document.elementFromPoint(c.x, c.y);
429
+ while (top && top.shadowRoot) {
430
+ const inner = top.shadowRoot.elementFromPoint(c.x, c.y);
431
+ if (!inner || inner === top) break;
432
+ top = inner;
433
+ }
434
+ if (!top) return { status: "covered", control, coveredBy: "nothing the page reports at that point" };
435
+ if (!composedContains(chosen, top) && !composedContains(top, chosen)) {
436
+ const name = clean(nameOf(top), 60);
437
+ return { status: "covered", control, coveredBy: top.tagName.toLowerCase() + (name ? ' "' + name + '"' : "") };
438
+ }
439
+ return { status: "found", control };
440
+ }`;
441
+ export function createPageDriver(page, opts) {
442
+ const settle = async () => {
443
+ try {
444
+ await page.waitForLoadState?.("domcontentloaded", { timeout: 10_000 });
445
+ }
446
+ catch {
447
+ // a slow page is still checked in whatever state it reached
448
+ }
449
+ await new Promise((r) => setTimeout(r, opts.settleMs));
450
+ };
451
+ return {
452
+ async open(url) {
453
+ try {
454
+ await page.goto(url, { waitUntil: "load", timeout: 30_000 });
455
+ }
456
+ catch (error) {
457
+ // A load that times out still leaves a page to check; an unreachable
458
+ // URL does not.
459
+ if (!/timeout/i.test(String(error?.message ?? error)))
460
+ throw error;
461
+ }
462
+ await settle();
463
+ },
464
+ async url() {
465
+ return page.url();
466
+ },
467
+ async locate(hint) {
468
+ return page.evaluate(`(${LOCATE_SCRIPT})(${JSON.stringify(hint)})`);
469
+ },
470
+ async click(x, y) {
471
+ await page.mouse.click(x, y);
472
+ },
473
+ async scroll(direction) {
474
+ const viewport = await page.evaluate("({ w: innerWidth, h: innerHeight })");
475
+ const dy = Math.round(viewport.h * 0.8);
476
+ const dx = Math.round(viewport.w * 0.8);
477
+ const delta = { down: [0, dy], up: [0, -dy], right: [dx, 0], left: [-dx, 0] };
478
+ const [x, y] = delta[direction] ?? [0, 0];
479
+ await page.mouse.wheel(x, y);
480
+ },
481
+ settle,
482
+ async screenshot(path) {
483
+ await page.screenshot({ path, type: "png" });
484
+ },
485
+ };
486
+ }
487
+ export function fmtClock(ms) {
488
+ const total = Math.max(0, Math.floor(ms / 1000));
489
+ const h = Math.floor(total / 3600);
490
+ const m = Math.floor((total % 3600) / 60);
491
+ const s = total % 60;
492
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
493
+ }
494
+ function errorText(error) {
495
+ return (error instanceof Error ? error.message : String(error)).split("\n")[0].slice(0, 300);
496
+ }
497
+ export async function runRecheck(plan, driver, opts) {
498
+ const now = opts.now ?? Date.now;
499
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
500
+ const log = opts.log ?? (() => { });
501
+ mkdirSync(opts.framesDir, { recursive: true });
502
+ const startedAt = new Date(now()).toISOString();
503
+ const t0 = now();
504
+ const recordedOrigin = originOf(plan.steps.find((s) => s.route)?.route ?? null);
505
+ const liveOrigin = originOf(opts.startUrl);
506
+ const originMapping = recordedOrigin && liveOrigin && recordedOrigin !== liveOrigin ? { from: recordedOrigin, to: liveOrigin } : null;
507
+ const ignoreOrigin = originMapping !== null;
508
+ const originOnly = opts.urlPrivacy === "origin_only";
509
+ try {
510
+ await driver.open(opts.startUrl);
511
+ }
512
+ catch (error) {
513
+ throw new RecheckInputError("start_url_unreachable", `the start URL could not be opened in Chrome for Clipy: ${errorText(error)}`, "Check that --url loads (is the server running, is it the right host?), then re-run.");
514
+ }
515
+ const liveRoute = async () => {
516
+ const url = await driver.url();
517
+ return { url, route: routeOf(url) };
518
+ };
519
+ /** A recorded route on the recording's host, moved onto the replay host.
520
+ * Routes are then compared with their origin, so a replay site that
521
+ * redirects back to the recorded (production) host at the same path is a
522
+ * different screen, never a match. */
523
+ const onReplayHost = (route) => ignoreOrigin && liveOrigin && originOf(route) === recordedOrigin ? mapOrigin(route, liveOrigin) : route;
524
+ const waitForRoute = async (route, timeoutMs) => {
525
+ const deadline = now() + timeoutMs;
526
+ for (;;) {
527
+ if (routeMatches(onReplayHost(route), (await liveRoute()).url, false, originOnly))
528
+ return true;
529
+ if (now() >= deadline)
530
+ return false;
531
+ await sleep(250);
532
+ }
533
+ };
534
+ /** Only the recording's own (http) host is ever opened directly; a route on
535
+ * another host comes from the timeline and could point anywhere. */
536
+ const sameHostAsRecording = (route) => /^https?:\/\//i.test(route) && recordedOrigin !== null && originOf(route) === recordedOrigin;
537
+ /** Clicks happen only on the replay host (--url's origin). Without an origin
538
+ * mapping, a host the recording itself clicked on (an SSO page) is allowed
539
+ * once its route matched; with one, nothing but the replay host is, so a
540
+ * redirect to production never gets a click. */
541
+ const clickHostAllowed = async (route) => {
542
+ const live = originOf(await driver.url());
543
+ if (live && live === liveOrigin)
544
+ return null;
545
+ if (!ignoreOrigin && route && live && live === originOf(route))
546
+ return null;
547
+ return live ?? "an unreadable URL";
548
+ };
549
+ const results = [];
550
+ let previousKind = null;
551
+ for (const step of plan.steps) {
552
+ if (opts.signal?.aborted)
553
+ break;
554
+ let status = "error";
555
+ let reason = "";
556
+ let control = null;
557
+ let nearby = [];
558
+ try {
559
+ if (step.unmappable) {
560
+ status = "unmapped";
561
+ reason = `could not map step: ${step.unmappable}`;
562
+ }
563
+ else if (step.kind === "start" || step.kind === "navigate") {
564
+ const route = step.route;
565
+ const timeout = step.kind === "start" ? 0 : opts.navigationTimeoutMs;
566
+ if (await waitForRoute(route, timeout)) {
567
+ status = "matched";
568
+ reason = step.kind === "start" ? "the start page is on the recorded route" : "the page reached the recorded route";
569
+ }
570
+ else if (step.kind === "navigate" &&
571
+ previousKind !== "click" &&
572
+ !originOnly &&
573
+ concreteRoute(route) &&
574
+ !sameHostAsRecording(route)) {
575
+ status = "different_screen";
576
+ reason = `expected ${route}, the page is on ${(await liveRoute()).route ?? "an unreadable URL"}; the recording went to another host here, and a re-check never opens a host the recording names`;
577
+ }
578
+ else if (step.kind === "navigate" && previousKind !== "click" && !originOnly && concreteRoute(route)) {
579
+ // Nothing clicked led here in the original (a typed URL, a link from
580
+ // outside), so open it the way the user did, on the re-check's host.
581
+ await driver.open(onReplayHost(route));
582
+ if (await waitForRoute(route, 0)) {
583
+ status = "matched";
584
+ reason = "opened the recorded route directly (no click led here in the original)";
585
+ }
586
+ else {
587
+ status = "different_screen";
588
+ reason = `opening the recorded route landed on ${(await liveRoute()).route ?? "an unreadable URL"}`;
589
+ }
590
+ }
591
+ else {
592
+ status = "different_screen";
593
+ reason = `expected ${route}, the page is on ${(await liveRoute()).route ?? "an unreadable URL"}`;
594
+ }
595
+ }
596
+ else if (step.kind === "click") {
597
+ // A click that follows another action may still be navigating: give
598
+ // the page a moment to arrive before calling it a different screen.
599
+ if (step.route && !(await waitForRoute(step.route, previousKind === "click" ? opts.navigationTimeoutMs : 0))) {
600
+ status = "different_screen";
601
+ reason = `the click happened on ${step.route}; the page is on ${(await liveRoute()).route ?? "an unreadable URL"}, so it was not clicked`;
602
+ }
603
+ else if (await clickHostAllowed(step.route)) {
604
+ status = "different_screen";
605
+ reason = `the page is on ${await clickHostAllowed(step.route)}, not the re-check's host ${liveOrigin ?? "(unknown)"}, so it was not clicked`;
606
+ }
607
+ else {
608
+ const located = await driver.locate({
609
+ label: step.label,
610
+ role: step.role,
611
+ x: step.position?.x ?? null,
612
+ y: step.position?.y ?? null,
613
+ });
614
+ if (located.status === "none") {
615
+ status = "control_not_found";
616
+ nearby = located.nearby;
617
+ reason = `no visible control named "${step.label}"`;
618
+ }
619
+ else if (located.status === "ambiguous") {
620
+ status = "unmapped";
621
+ reason = `could not map step: ${located.candidates} controls are named "${step.label}" and the recording has no position to choose between them`;
622
+ }
623
+ else if (located.status === "covered") {
624
+ status = "different_screen";
625
+ control = located.control;
626
+ reason = `"${step.label}" is on the page but covered by ${located.coveredBy}, so it was not clicked`;
627
+ }
628
+ else if (located.status === "disabled") {
629
+ status = "different_screen";
630
+ control = located.control;
631
+ reason = `"${step.label}" is on the page but disabled, so it was not clicked`;
632
+ }
633
+ else if (!opts.allowIrreversible && looksIrreversible(located.control.name)) {
634
+ status = "unmapped";
635
+ control = located.control;
636
+ reason = `could not map step: ${irreversibleReason(located.control.name)}`;
637
+ }
638
+ else if (opts.signal?.aborted) {
639
+ status = "error";
640
+ reason = "the re-check was interrupted before this click";
641
+ }
642
+ else if (await clickHostAllowed(step.route)) {
643
+ status = "different_screen";
644
+ control = located.control;
645
+ reason = `the page moved to ${await clickHostAllowed(step.route)} before the click, so it was not clicked`;
646
+ }
647
+ else {
648
+ control = located.control;
649
+ await driver.click(control.x, control.y);
650
+ await driver.settle();
651
+ status = "matched";
652
+ reason =
653
+ control.quality === "exact"
654
+ ? `clicked ${control.role} "${control.name}"`
655
+ : `clicked ${control.role} "${control.name}" (its name contains the recorded label "${step.label}")`;
656
+ }
657
+ }
658
+ }
659
+ else if (step.kind === "scroll") {
660
+ await driver.scroll(step.direction ?? "down");
661
+ await driver.settle();
662
+ status = "replayed";
663
+ reason = `scrolled ${step.direction} (the recording keeps the direction, not the distance)`;
664
+ }
665
+ }
666
+ catch (error) {
667
+ status = "error";
668
+ reason = `unexpected error: ${errorText(error)}`;
669
+ }
670
+ let frame = join(opts.framesDir, `step-${String(step.index).padStart(2, "0")}.png`);
671
+ try {
672
+ await driver.screenshot(frame);
673
+ }
674
+ catch (error) {
675
+ log(`step ${step.index}: frame capture failed (${errorText(error)})`);
676
+ frame = null;
677
+ }
678
+ let observedRoute = null;
679
+ try {
680
+ observedRoute = (await liveRoute()).route;
681
+ }
682
+ catch {
683
+ // reported as null
684
+ }
685
+ results.push({
686
+ index: step.index,
687
+ kind: step.kind,
688
+ tMs: step.tMs,
689
+ timeLabel: fmtClock(step.tMs),
690
+ status,
691
+ reason,
692
+ expected: {
693
+ label: step.label,
694
+ role: step.role,
695
+ position: step.position,
696
+ route: step.route,
697
+ direction: step.direction,
698
+ caption: step.original.caption,
699
+ said: step.original.said,
700
+ frameUrl: step.original.frameUrl,
701
+ cropUrl: step.original.cropUrl,
702
+ },
703
+ observed: { route: observedRoute, control, nearbyControls: nearby, frame, atMs: Math.max(0, now() - t0) },
704
+ });
705
+ log(`step ${step.index}/${plan.steps.length} ${status}: ${reason}`);
706
+ // An unmapped click still led to whatever came next in the original, so
707
+ // the next navigation is not opened directly as if typed.
708
+ if (!step.unmappable || step.kind === "click")
709
+ previousKind = step.kind;
710
+ }
711
+ return { steps: results, originMapping, startedAt, finishedAt: new Date(now()).toISOString() };
712
+ }
713
+ export function summarize(steps) {
714
+ const count = (s) => steps.filter((r) => r.status === s).length;
715
+ const diverging = steps.find((r) => r.status === "control_not_found" || r.status === "different_screen" || r.status === "error");
716
+ const matched = count("matched");
717
+ const checked = matched + count("control_not_found") + count("different_screen");
718
+ const summary = {
719
+ total: steps.length,
720
+ matched,
721
+ replayed: count("replayed"),
722
+ controlNotFound: count("control_not_found"),
723
+ differentScreen: count("different_screen"),
724
+ error: count("error"),
725
+ unmapped: count("unmapped"),
726
+ firstDivergence: diverging?.index ?? null,
727
+ verdict: "incomplete",
728
+ };
729
+ if (summary.controlNotFound > 0 || summary.differentScreen > 0)
730
+ summary.verdict = "diverged";
731
+ else if (summary.error === 0 && checked > 0)
732
+ summary.verdict = "matches";
733
+ return summary;
734
+ }
735
+ export function limitationsFor(run, opts = {}) {
736
+ const notes = [
737
+ "Clicks are replayed by their recorded element label only; an unlabelled click is reported as unmapped, never clicked by position.",
738
+ ...(opts.allowIrreversible
739
+ ? []
740
+ : ["Controls whose names read as irreversible (delete, pay, send, submit and similar) are not clicked; those steps are unmapped. --allow-destructive replays them, on a site where that is safe."]),
741
+ "Typed values are never captured, so typing steps are not replayed; a later step that depends on that input may diverge for that reason.",
742
+ "Frames are compared by people or agents reading them: the report pairs each original key-moment frame with the new screenshot but does not diff pixels.",
743
+ "Controls inside iframes are not searched.",
744
+ ];
745
+ if (run.urlPrivacy === "origin_only")
746
+ notes.push("The original recording kept page origins only, so route checks compare the host, not the path.");
747
+ if (run.urlPrivacy === "not_captured" || run.urlPrivacy === null) {
748
+ notes.push("The original recording has no page URLs, so no step can be flagged as a different screen by route; only missing or covered controls are detected.");
749
+ }
750
+ if (run.sourcePlatform === "mac" || run.sourcePlatform === "windows") {
751
+ notes.push("Click positions from a desktop recording are relative to the captured window, not the page, so they only break ties between same-named controls.");
752
+ }
753
+ return notes;
754
+ }
755
+ const STATUS_LABEL = {
756
+ matched: "matched",
757
+ replayed: "replayed",
758
+ control_not_found: "control not found",
759
+ different_screen: "different screen",
760
+ error: "error",
761
+ unmapped: "could not map step",
762
+ };
763
+ function cell(text) {
764
+ return text.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim();
765
+ }
766
+ /** Desktop recordings carry macOS roles ("AXButton"); show them as the page would. */
767
+ function displayRole(role) {
768
+ if (!role)
769
+ return "control";
770
+ return role.replace(/^AX/, "").replace(/^[A-Z]/, (c) => c.toLowerCase());
771
+ }
772
+ function describeExpected(step) {
773
+ switch (step.kind) {
774
+ case "start":
775
+ return `start on ${step.expected.route ?? "the start URL"}`;
776
+ case "navigate":
777
+ return `go to ${step.expected.route}`;
778
+ case "click":
779
+ return step.expected.label ? `click ${displayRole(step.expected.role)} "${step.expected.label}"` : "click (no label recorded)";
780
+ case "scroll":
781
+ return `scroll ${step.expected.direction ?? ""}`.trim();
782
+ case "type":
783
+ return "type (value not captured)";
784
+ case "drag":
785
+ return "drag";
786
+ }
787
+ }
788
+ export function renderMarkdown(report) {
789
+ const s = report.summary;
790
+ const lines = [];
791
+ lines.push(`# Re-check: ${report.original.name || report.original.id}`);
792
+ lines.push("");
793
+ const verdict = s.verdict === "matches"
794
+ ? "The recorded workflow still works on today's UI."
795
+ : s.verdict === "diverged"
796
+ ? `Today's UI diverges from the recording, first at step ${s.firstDivergence}.`
797
+ : "Not enough of the recording could be replayed to say whether it still works.";
798
+ lines.push(verdict);
799
+ lines.push("");
800
+ lines.push(`${s.total} steps: ${s.matched} matched, ${s.replayed} replayed, ${s.controlNotFound} control not found, ` +
801
+ `${s.differentScreen} different screen, ${s.error} error, ${s.unmapped} could not map.`);
802
+ lines.push("");
803
+ if (report.original.webUrl)
804
+ lines.push(`- Original recording: ${report.original.webUrl}`);
805
+ if (report.recording) {
806
+ lines.push(`- Re-check recording: ${report.recording.shareUrl}`);
807
+ lines.push(`- Re-check agent context: ${report.recording.contextUrl}`);
808
+ }
809
+ if (report.start.originMapping) {
810
+ lines.push(`- Recorded on ${report.start.originMapping.from}, re-checked on ${report.start.originMapping.to} (recorded paths checked on the re-check host; nothing is clicked on any other host)`);
811
+ }
812
+ lines.push(`- Frames: ${report.run.framesDir}`);
813
+ if (report.original.expectedResult) {
814
+ lines.push("");
815
+ lines.push(`**Expected result (from the original recording):** ${report.original.expectedResult}`);
816
+ lines.push("Compare it with the last frame; the re-check does not judge it automatically.");
817
+ }
818
+ lines.push("");
819
+ lines.push("| # | At | Step | Result | Detail |");
820
+ lines.push("|---|----|------|--------|--------|");
821
+ for (const step of report.steps) {
822
+ // The Result column already says "could not map step".
823
+ let detail = step.reason.replace(/^could not map step: /, "");
824
+ if (step.observed.nearbyControls.length)
825
+ detail += `. Nearby: ${step.observed.nearbyControls.map((n) => `"${n}"`).join(", ")}`;
826
+ lines.push(`| ${step.index} | ${step.timeLabel} | ${cell(describeExpected(step))} | ${STATUS_LABEL[step.status]} | ${cell(detail)} |`);
827
+ }
828
+ if (report.run.truncatedSteps > 0) {
829
+ lines.push("");
830
+ lines.push(`${report.run.truncatedSteps} later steps were not checked (a re-check covers at most ${RECHECK_MAX_STEPS} steps).`);
831
+ }
832
+ if (report.warnings.length) {
833
+ lines.push("");
834
+ for (const w of report.warnings)
835
+ lines.push(`Warning: ${w.error} ${w.remediation}`);
836
+ }
837
+ lines.push("");
838
+ return lines.join("\n");
839
+ }
840
+ /** One caption per frame for the uploaded proof. */
841
+ export function frameCaption(step, total) {
842
+ const reason = step.reason.replace(/^could not map step: /, "");
843
+ const sentence = reason.charAt(0).toUpperCase() + reason.slice(1);
844
+ return `Step ${step.index}/${total} ${STATUS_LABEL[step.status]}: ${describeExpected(step)}. ${sentence}`.slice(0, 400);
845
+ }
846
+ const MAX_TIMELINE_PAGES = 20;
847
+ export class RecheckInputError extends Error {
848
+ code;
849
+ remediation;
850
+ constructor(code, message, remediation) {
851
+ super(message);
852
+ this.code = code;
853
+ this.remediation = remediation;
854
+ }
855
+ }
856
+ function str(value) {
857
+ return typeof value === "string" && value.trim() ? value : null;
858
+ }
859
+ /** Reads the recording, its interaction timeline (every page), key moments and
860
+ * transcript. Moments and the transcript are optional evidence: when they are
861
+ * not ready the steps simply carry less of it. */
862
+ export async function readOriginalRun(getJson, publicId) {
863
+ const base = `/api/v1/recordings/${encodeURIComponent(publicId)}`;
864
+ const recording = ((await getJson(base)).recording ?? {});
865
+ const types = "navigation,click,scroll,typing,drag";
866
+ const events = [];
867
+ let cursor = null;
868
+ let status = "absent";
869
+ let urlPrivacy = null;
870
+ let pages = 0;
871
+ let truncated = false;
872
+ do {
873
+ const query = new URLSearchParams({ types, limit: "250" });
874
+ if (cursor)
875
+ query.set("cursor", cursor);
876
+ const page = await getJson(`${base}/interactions?${query}`);
877
+ status = String(page.status ?? "absent");
878
+ urlPrivacy = str(page.privacy?.urls) ?? urlPrivacy;
879
+ if (Array.isArray(page.events))
880
+ events.push(...page.events);
881
+ cursor = str(page.pagination?.nextCursor);
882
+ pages += 1;
883
+ if (cursor && pages >= MAX_TIMELINE_PAGES) {
884
+ truncated = true;
885
+ cursor = null;
886
+ }
887
+ } while (cursor);
888
+ if (status === "preparing") {
889
+ throw new RecheckInputError("timeline_not_ready", "the recording's interaction timeline is still being prepared", "Wait a minute and re-run the same command.");
890
+ }
891
+ if (events.filter((e) => e.kind === "click" || e.kind === "navigation").length === 0) {
892
+ throw new RecheckInputError("no_interactions", `the recording has no clicks or page navigations to replay (timeline ${status})`, "Only recordings with click or browser-navigation data can be re-checked: Chrome extension, Chrome for Clipy, Mac and Windows app takes. A plain web-recorder take has none.");
893
+ }
894
+ let moments = [];
895
+ try {
896
+ const body = await getJson(`${base}/key-moments`);
897
+ if (Array.isArray(body.moments))
898
+ moments = body.moments;
899
+ }
900
+ catch {
901
+ // evidence only
902
+ }
903
+ let segments = [];
904
+ try {
905
+ const body = await getJson(`${base}/transcript`);
906
+ const t = body.transcript;
907
+ if (t && Array.isArray(t.segments))
908
+ segments = t.segments;
909
+ }
910
+ catch {
911
+ // evidence only
912
+ }
913
+ return {
914
+ id: str(recording.id) ?? publicId,
915
+ name: str(recording.name) ?? "",
916
+ webUrl: str(recording.webUrl),
917
+ sourcePlatform: str(recording.sourcePlatform),
918
+ expectedResult: str(recording.expectedResult),
919
+ timelineStatus: status,
920
+ urlPrivacy,
921
+ events,
922
+ eventsTruncated: truncated,
923
+ moments,
924
+ segments,
925
+ };
926
+ }
927
+ export function writeReportFiles(dir, report) {
928
+ mkdirSync(dir, { recursive: true });
929
+ const json = join(dir, "report.json");
930
+ const markdown = join(dir, "report.md");
931
+ writeFileSync(json, `${JSON.stringify(report, null, 2)}\n`);
932
+ writeFileSync(markdown, renderMarkdown(report));
933
+ return { json, markdown };
934
+ }