clearcote 0.51.1 → 0.52.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.
Files changed (61) hide show
  1. package/dist/attention.d.ts +26 -0
  2. package/dist/attention.d.ts.map +1 -0
  3. package/dist/attention.js +82 -0
  4. package/dist/attention.js.map +1 -0
  5. package/dist/cloud.d.ts +10 -3
  6. package/dist/cloud.d.ts.map +1 -1
  7. package/dist/cloud.js +9 -1
  8. package/dist/cloud.js.map +1 -1
  9. package/dist/forms.d.ts +8 -0
  10. package/dist/forms.d.ts.map +1 -1
  11. package/dist/forms.js +56 -0
  12. package/dist/forms.js.map +1 -1
  13. package/dist/frames.d.ts +33 -0
  14. package/dist/frames.d.ts.map +1 -0
  15. package/dist/frames.js +415 -0
  16. package/dist/frames.js.map +1 -0
  17. package/dist/hold.d.ts +14 -7
  18. package/dist/hold.d.ts.map +1 -1
  19. package/dist/hold.js +33 -6
  20. package/dist/hold.js.map +1 -1
  21. package/dist/humanize.d.ts +49 -20
  22. package/dist/humanize.d.ts.map +1 -1
  23. package/dist/humanize.js +2024 -261
  24. package/dist/humanize.js.map +1 -1
  25. package/dist/hzoptions.d.ts +78 -0
  26. package/dist/hzoptions.d.ts.map +1 -0
  27. package/dist/hzoptions.js +171 -0
  28. package/dist/hzoptions.js.map +1 -0
  29. package/dist/index.d.ts +9 -4
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +6 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/isolated.d.ts +6 -0
  34. package/dist/isolated.d.ts.map +1 -1
  35. package/dist/isolated.js +57 -1
  36. package/dist/isolated.js.map +1 -1
  37. package/dist/keys.d.ts +69 -0
  38. package/dist/keys.d.ts.map +1 -0
  39. package/dist/keys.js +201 -0
  40. package/dist/keys.js.map +1 -0
  41. package/dist/motion.d.ts +130 -12
  42. package/dist/motion.d.ts.map +1 -1
  43. package/dist/motion.js +258 -19
  44. package/dist/motion.js.map +1 -1
  45. package/dist/motionscore.d.ts +81 -0
  46. package/dist/motionscore.d.ts.map +1 -1
  47. package/dist/motionscore.js +279 -2
  48. package/dist/motionscore.js.map +1 -1
  49. package/dist/pacing.d.ts +5 -0
  50. package/dist/pacing.d.ts.map +1 -1
  51. package/dist/pacing.js +10 -0
  52. package/dist/pacing.js.map +1 -1
  53. package/dist/scroll.d.ts +143 -0
  54. package/dist/scroll.d.ts.map +1 -0
  55. package/dist/scroll.js +426 -0
  56. package/dist/scroll.js.map +1 -0
  57. package/dist/trace.d.ts +12 -0
  58. package/dist/trace.d.ts.map +1 -0
  59. package/dist/trace.js +60 -0
  60. package/dist/trace.js.map +1 -0
  61. package/package.json +1 -1
package/dist/humanize.js CHANGED
@@ -27,11 +27,39 @@
27
27
  // goes through the isolated world (./isolated.ts) or Playwright's utility-world queries, never
28
28
  // page.evaluate / locator.evaluate.
29
29
  import { errors as pwErrors } from "playwright-core";
30
- import { makePersona, planMove, dragDwell, clickHold, keyDwell, clickPoint, planAmbient, gaussFrom, rolloverRate, wheelNotches, platformFromNavigator, WHEEL_NOTCH_PX, } from "./motion.js";
30
+ import { makePersona, planMove, aimTraits, dragDwell, dragHesitation, hesitateThenDrag, clickHold, keyDwell, clickPoint, planAmbient, gaussFrom, rolloverRate, dblclickGap, pauseMs, timingTraits, wheelNotches, platformFromNavigator, WHEEL_NOTCH_PX, } from "./motion.js";
31
+ import { ANCHOR_TARGET_W, ISO_SCROLLER, ISO_SCROLL_RANGE, anchorNeeded, anchorPoint, bringIntoView, inView as boxIn, inputDevice, pacedWheel, planTrackpad, trackpadTraits, wheelDrift, } from "./scroll.js";
32
+ import { dwellMs, moveOffDelayMs, moveOffRoll, planDwell, planMoveOff, } from "./motion.js";
33
+ import { ambientMode, exploreNotches, idleDrifts, readPauseMs, IDLE_DRIFT_MAX_MS, TEXT_LENGTH as ISO_TEXT_LENGTH } from "./attention.js";
31
34
  import { keepInView, trimTo, walk } from "./pacing.js";
35
+ import { record as traceRecord, traceEnabled } from "./trace.js";
32
36
  import { pressAndHold } from "./hold.js";
33
- import { COVER_CHECK_MS, COVER_RETRY_MS, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_FRAMES, ISO_HIT_IN_BOX, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, roundHalfEven, worldFor, } from "./isolated.js";
34
- import { DEFAULT_TYPO_RATE, NEARBY_LETTERS, classifyField, datetimeEqual, enginePathOk, fitMaxlength, formattedEqual, maskKept, matchOption, normalizeClickOptions, numericEqual, planDatetime, planSelect, planTypo, prePressMs, pyFloat, rangeAttrs, rangeFraction, rangeNudge, rangePoint, rangeSanitize, rangeValueOk, segmentNodesFromTree, typoEligible, typosAllowed, } from "./forms.js";
37
+ import { BLANK_POINT, FOCUSABLE, SEARCH_SLIP_RATE, SELECTION_STATE, TAB_DISTANCE, WORD_FIX_RATE, flightMs, modifierLagMs, modifierLeadMs, planGap, planRepeat, splitChord, submitPauseMs, tabPauseMs, typingTraits, } from "./keys.js";
38
+ import { COVER_CHECK_MS, COVER_RETRY_MS, ISO_ACTIVE_FIELD, ISO_ACTIVE_VALUE, ISO_CSS_BOX, ISO_DESCRIBE, ISO_FORM_CONTROL, ISO_FRAMES, ISO_HIT_IN_BOX, ISO_LABEL_BY_SEL, ISO_LABEL_OF, ISO_LISTBOX_ROW, ISO_PLATFORM, ISO_SCROLL_BY, ISO_VIEWPORT, roundHalfEven, worldFor, } from "./isolated.js";
39
+ import { NATIVE, frameLocatorOf, frameRoute, humanized as frameHumanized } from "./frames.js";
40
+ export { reportFallback, strictMode } from "./frames.js";
41
+ /** The error a strict-mode tap raises on a touch context (lane F, SC 232). */
42
+ export const TAP_NOT_HUMANIZED = "tap is not humanized for touch contexts yet";
43
+ // Checkbox clicks on the <label> (setChecked). The persona fixes the TRAIT -- how often this identity clicks a
44
+ // visible checkbox's label rather than its box (persona.labelShare when the persona carries one, else 0.4) --;
45
+ // each click's choice is an UNSEEDED Math.random draw, like planMove's: a seeded per-identity stream would make
46
+ // every session of an identity choose the same way in the same order (a cross-session fingerprint).
47
+ export const LABEL_SHARE = 0.4;
48
+ /** The persona's trait: the share of visible-checkbox clicks that land on the label text. */
49
+ export function labelShare(persona) {
50
+ const v = persona?.labelShare; // an explicit override (tests)
51
+ if (typeof v === "number" && v >= 0 && v <= 1)
52
+ return v;
53
+ // lane B's aim traits (salted stream of the seed, 0.25-0.55); LABEL_SHARE without a persona
54
+ return persona && typeof persona.seed === "number" ? aimTraits(persona).labelShare : LABEL_SHARE;
55
+ }
56
+ /** This click: on the label? An unseeded draw against the persona's trait (`rng`: a test's own). */
57
+ export function labelDraw(persona, rng = Math.random) {
58
+ return rng() < labelShare(persona);
59
+ }
60
+ import { DEFAULT_TYPO_RATE, NEARBY_LETTERS, classifyField, datetimeEqual, enginePathOk, fitMaxlength, formattedEqual, maskKept, matchOption, normalizeClickOptions, numericEqual, planDatetime, planSelect, planTypo, prePressMs, pyFloat, rangeAttrs, rangeFraction, rangeNudge, rangePoint, rangeSanitize, rangeValueOk, segmentNodesFromTree, typoEligible, typosAllowed, ENGINE_KEY_SEQUENCE, engineClickParams, engineHeldBits, engineKeyPlan, } from "./forms.js";
61
+ import { applyToPersona, engineModeFor, optionsOf, reportFallback, resolveHumanize, typoRateFor, withCallerApi, } from "./hzoptions.js";
62
+ export { ClearcoteStrictError } from "./hzoptions.js";
35
63
  /** Overlay: a red dot that follows real mousemove events. Idempotent IIFE so it works both as
36
64
  * an addInitScript source string AND when passed to page.evaluate. */
37
65
  export const CURSOR_OVERLAY = `(() => {
@@ -111,6 +139,31 @@ export async function sendEngineCommand(session, cacheKey, method, legacy, param
111
139
  // The longest an engine walk waits for the page to draw (ISO_FRAMES): measured 111-812 ms on a fresh
112
140
  // headless browser's first page (r40, SC 216). A page that never draws (a hidden tab) walks after it.
113
141
  const FRAMES_WAIT_MS = 1500;
142
+ /** CLEARCOTE_HUMANIZE_ENGINE_EXT=off (also 0/false/no) keeps the r43 engine extensions unused (r42 behaviour). */
143
+ export function engineExtMode() {
144
+ const v = (process.env.CLEARCOTE_HUMANIZE_ENGINE_EXT || "").trim().toLowerCase();
145
+ return !["0", "off", "false", "no", "none"].includes(v);
146
+ }
147
+ // CDP's "invalid params" (-32602) and nothing else: what an r43 engine answers to an EMPTY dispatchKeySequence --
148
+ // the code when the error carries one, else the exact -32602 wording ("Invalid parameters", crdtp's, after
149
+ // Playwright's "Protocol error (method): " prefix; Playwright strips the code). Any other failure of the probe (a
150
+ // proxy's "Invalid target", "Invalid session id") is NOT an r43 engine: a browser memoised as r43 by mistake would
151
+ // get fromX/fromY on an out-of-sync plain click, which a pre-r43 engine ignores while walking from its own stale
152
+ // point -- the teleport the re-sync exists to remove (verifier A's R4, SC 232: any "invalid" counted).
153
+ const CDP_INVALID_PARAMS = /(?:^|: )Invalid parameters(?![A-Za-z])/;
154
+ const isInvalidParams = (e) => {
155
+ if (isMethodNotFound(e))
156
+ return false;
157
+ if (typeof e?.code === "number")
158
+ return e.code === -32602;
159
+ const m = String(e?.message ?? e);
160
+ return m.includes("-32602") || CDP_INVALID_PARAMS.test(m);
161
+ };
162
+ // Which browsers' engines take the r43 extensions (asked once per browser, like the command name), and which
163
+ // browsers lane A's onFallback has already heard about.
164
+ const engineExt = new WeakMap();
165
+ const engineExtReported = new WeakSet();
166
+ export const ENGINE_EXT_MISSING = "the engine has no r43 extensions (Browser.dispatchKeySequence): the SDK planner walks and types";
114
167
  /** @internal exported for tests. Did this browser's engine already say it has no pointer-path command? */
115
168
  export function engineHasNoPointerPath(cacheKey) {
116
169
  return !!cacheKey && engineMethodNames.get(cacheKey)?.get(POINTER_PATH) === NO_ENGINE_PATH;
@@ -140,6 +193,9 @@ export function trialTimeoutError(selector, ms, why) {
140
193
  const SHIFTED_SYMBOLS = new Set('~!@#$%^&*()_+{}|:"<>?');
141
194
  /** @internal exported for tests */
142
195
  export const needsShift = (ch) => (ch >= "A" && ch <= "Z" && ch.length === 1) || SHIFTED_SYMBOLS.has(ch);
196
+ // Does box a ([x, y, w, h]) cover any of box b beyond a hairline? A label aim still over the input's own box is an
197
+ // input click, not a label click (SC 239).
198
+ const boxesOverlap = (a, b) => !!b && b.length >= 4 && a[0] < b[0] + b[2] - 0.5 && a[0] + a[2] > b[0] + 0.5 && a[1] < b[1] + b[3] - 0.5 && a[1] + a[3] > b[1] + 0.5;
143
199
  const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
144
200
  // Same unseeded live source as rand() — the seeded persona rng stays inside motion.ts, this is only
145
201
  // for placing a point in a plausible spread instead of on an exact landmark.
@@ -149,13 +205,14 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
149
205
  // name for anything that imported it from here.
150
206
  /** @internal */
151
207
  export const NEARBY = NEARBY_LETTERS;
152
- /** @internal exported for tests. Per-character fat-finger rate. CLEARCOTE_HUMANIZE_TYPO_RATE
153
- * overrides it (0 disables typos; the test suites raise it to exercise the correction paths). Read at
154
- * call time, like Python's typo_rate(). */
155
- export function typoRate() {
208
+ /** @internal exported for tests. Per-character fat-finger rate: the persona's own (timingTraits, 0.5–4 %
209
+ * per identity; the global 2 % without a persona). CLEARCOTE_HUMANIZE_TYPO_RATE overrides it when set (0
210
+ * disables typos; the test suites raise it to exercise the correction paths). Read at call time, like
211
+ * Python's typo_rate(). */
212
+ export function typoRate(persona) {
156
213
  const v = process.env.CLEARCOTE_HUMANIZE_TYPO_RATE;
157
214
  if (v === undefined || v === "")
158
- return DEFAULT_TYPO_RATE;
215
+ return persona ? timingTraits(persona).typoRate : DEFAULT_TYPO_RATE;
159
216
  const f = pyFloat(v);
160
217
  if (f === null || Number.isNaN(f))
161
218
  return DEFAULT_TYPO_RATE;
@@ -200,14 +257,14 @@ export function asApiError(err, api) {
200
257
  }
201
258
  /** @internal `fn`, with every Playwright error it rejects with worded as `api`'s (asApiError). */
202
259
  export function apiErrors(api, fn) {
203
- return async (...a) => {
260
+ return async (...a) => withCallerApi(api, async () => {
204
261
  try {
205
262
  return await fn(...a);
206
263
  }
207
264
  catch (e) {
208
265
  throw asApiError(e, api);
209
266
  }
210
- };
267
+ });
211
268
  }
212
269
  /** @internal An Error the SDK raises where Playwright would, worded by the caller's API (apiErrors). */
213
270
  export function sdkPlaywrightError(message) {
@@ -215,7 +272,11 @@ export function sdkPlaywrightError(message) {
215
272
  }
216
273
  /** Internal: the humane route cannot apply here; run the native Playwright call instead. */
217
274
  class NativeSignal extends Error {
218
- constructor() { super("clearcote humanize: native route"); this.name = "NativeSignal"; }
275
+ constructor(why = "the humane route cannot apply") { super(why); this.name = "NativeSignal"; }
276
+ }
277
+ /** Why a humanized route handed over: a NativeSignal's reason, else the error it met. */
278
+ function whyOf(e) {
279
+ return e instanceof NativeSignal ? e.message : "error: " + String(e?.message ?? e);
219
280
  }
220
281
  /** @internal exported for tests. A per-page lock: each wrapped public entry point (page.click / fill
221
282
  * / type / press / selectOption / check / uncheck / setChecked / dblclick / hover, mouse.click /
@@ -240,6 +301,8 @@ export function createInputLock() {
240
301
  * Targeted clicks stay on the SDK planner by default (SC 210 lane S, measured on r38): the engine
241
302
  * presses 9 ms after its last move (the planner's press waits 40-130 ms), and it walks from its own last
242
303
  * position, which an SDK glide does not update. Same values as Python `_engine_clicks_mode`. */
304
+ /** Lane A's ClearcoteStrictError (strict mode): never swallowed by a best-effort path. */
305
+ const isStrict = (e) => !!e && (e.name === "ClearcoteStrictError" || e.constructor?.name === "ClearcoteStrictError");
243
306
  export function engineClicksMode() {
244
307
  const v = (process.env.CLEARCOTE_HUMANIZE_ENGINE_CLICKS || "").trim().toLowerCase();
245
308
  if (["0", "off", "false", "no", "none"].includes(v))
@@ -272,22 +335,68 @@ export async function attachHumanize(browser, page, opts) {
272
335
  page.on("framenavigated", (f) => { if (f === page.mainFrame())
273
336
  inject(); });
274
337
  }
275
- if (!opts.humanize)
338
+ // humanize: true | "strict" | HumanizeOptions (hzoptions.ts). true is {}: every default reproduces 0.51.0,
339
+ // and no option draws from the persona RNG (same seed, same persona).
340
+ const hz = resolveHumanize(opts.humanize);
341
+ if (!hz)
276
342
  return;
343
+ page._clearcoteHz = hz;
344
+ const tempo = hz.tempo; // preset: every planned duration x1.4 / x1.0 / x0.7
345
+ // The stock methods, for per-call { humanize: false } (wired at the end of attach).
346
+ const stockPage = {}, stockMouse = {}, stockKb = {};
347
+ for (const n of PAGE_METHODS)
348
+ if (typeof page[n] === "function")
349
+ stockPage[n] = page[n].bind(page);
350
+ for (const n of MOUSE_METHODS)
351
+ if (typeof page.mouse[n] === "function")
352
+ stockMouse[n] = page.mouse[n].bind(page.mouse);
353
+ for (const n of KB_METHODS)
354
+ if (typeof page.keyboard[n] === "function")
355
+ stockKb[n] = page.keyboard[n].bind(page.keyboard);
277
356
  // Per-identity motor persona (cadence, tremor, overshoot, handedness) — stable across the session,
278
357
  // seeded from the fingerprint so behavior is consistent within an identity and unlinkable across
279
358
  // seeds. Stored on the page so the module-level Locator.dragTo patch can reach it too.
280
- const persona = makePersona(opts.seed);
359
+ const persona = applyToPersona(makePersona(opts.seed), hz);
281
360
  page._clearcotePersona = persona;
282
- // One input action at a time on this page (see createInputLock).
283
- const locked = createInputLock();
361
+ // The typing identity (WPM, bigram factors, Tab preference, pauses) from a salted side stream
362
+ // of the persona seed (keys.typingTraits): the persona's own draws are unchanged.
363
+ const traits = typingTraits(persona.seed);
364
+ // The trackpad identity (report rate, inertia decay): another salted side stream of the seed (R2).
365
+ const tpTraits = trackpadTraits(persona.seed);
366
+ // Keys the CALLER holds through keyboard.down: key -> [when it went down, the hold it is owed].
367
+ const heldKeys = new Map();
368
+ // A keydown->keyup hold: lane B's keyDwell (log-normal around the persona's median, preset-scaled).
369
+ const kdwell = () => keyDwell(persona);
370
+ const tabPref = () => (typeof persona.tabPref === "number" ? persona.tabPref : traits.tabPref);
371
+ // The slip rate: lane A's typoRate option, else lane B's typoRate(persona) (CLEARCOTE_HUMANIZE_TYPO_RATE when
372
+ // set, else the persona's 0.5-4 %).
373
+ const personaTypoRate = () => typoRateFor(page, () => typoRate(persona));
374
+ // One input action at a time on this page (see createInputLock). Inside the lock the outermost action
375
+ // first runs the lazy after-action step (SC 232 lane C: afterRun). `nextCall` carries what the public
376
+ // wrapper knew about THIS call to the locked() it reaches synchronously: a trial performs no action (so
377
+ // nothing after-action either); a coordinate action names a viewport point (no exploratory scroll).
378
+ const lockRaw = createInputLock();
379
+ let nextCall = null;
380
+ const locked = (fn) => {
381
+ const o = nextCall ?? { coords: false, after: true };
382
+ nextCall = null;
383
+ return lockRaw(() => afterRun(fn, o));
384
+ };
284
385
  // Tracked cursor position so each move continues from where the last one ended.
285
386
  // `held` tracks whether a mouse button is currently down — see mouse.move below.
286
387
  // `placed` records whether the engine's cursor has actually been moved yet. A page starts with the
287
388
  // pointer at the default origin, so anything that delivers input WITHOUT a target to move to —
288
389
  // a wheel, a mouse.down that opens a drag, a bare keyboard.type — otherwise happens from a cursor
289
390
  // that has never been anywhere. The guarantees below key off this flag.
290
- const st = { x: rand(140, 380), y: rand(90, 240), held: false, placed: false };
391
+ // `typed`: when the last typed run ended (the submit / Tab pause owed by afterTyping), null after a glide.
392
+ const st = { x: rand(140, 380), y: rand(90, 240), held: false, placed: false, typed: null,
393
+ heldButton: "left" };
394
+ // After-action state (SC 232 lane C; see the block at the end of attachHumanize).
395
+ const af = {
396
+ // per-action draws are unseeded, as in planMove: the seed fixes the persona's traits only
397
+ rng: Math.random, depth: 0, lastEnd: null, loadAt: null,
398
+ mo: null, moHits: 0, moN: 0, trace: [],
399
+ };
291
400
  const mouse = page.mouse;
292
401
  const nativeMove = mouse.move.bind(mouse);
293
402
  const nativeClick = mouse.click.bind(mouse);
@@ -303,9 +412,12 @@ export async function attachHumanize(browser, page, opts) {
303
412
  // dispatched for 40 ms: MAX_JUMP_PX / IDLE_HOP_PX). "Move, then sleep the planned gap" added the
304
413
  // ~27 ms mouse.move round trip to every 6-8 ms sample: a 1.05 s planned glide took 3.5-5.4 s on
305
414
  // PRO r38 (SC 209), ambient motion 5.7x as long.
306
- const dispatch = async (steps) => {
415
+ // `kind` / `buttons` name the walk for the score hook (trace.ts, lane G): glide | drag (buttons 1) | ambient | hover.
416
+ const dispatch = async (steps, kind = "glide", buttons = 0) => {
307
417
  const vp = await viewBounds();
308
- await walk(vp ? keepInView(steps, vp.width, vp.height) : steps, async (x, y) => { await nativeMove(x, y); st.placed = true; });
418
+ if (tempo !== 1)
419
+ steps = steps.map((s) => ({ ...s, sleepMs: s.sleepMs * tempo }));
420
+ await walk(vp ? keepInView(steps, vp.width, vp.height) : steps, async (x, y) => { await nativeMove(x, y); st.placed = true; }, { kind, buttons });
309
421
  };
310
422
  // The viewport a planned path is kept inside (keepInView: the planner's overshoot arcs left the window
311
423
  // near its edges, verifier B), read in the isolated world at most every 2 s; null when it cannot be read.
@@ -327,9 +439,10 @@ export async function attachHumanize(browser, page, opts) {
327
439
  // Move to (x, y) as a minimum-jerk sum-of-submovements path (primary ballistic + corrective homing)
328
440
  // with colored sub-pixel noise and Fitts-scaled duration. `settle` adds a seating jiggle (drag).
329
441
  const glide = async (x, y, o = {}) => {
330
- await dispatch(planMove(st, { x, y }, persona, { settle: o.settle, targetW: o.targetW, held: o.held }));
442
+ await dispatch(planMove(st, { x, y }, persona, { settle: o.settle, targetW: o.targetW, held: o.held }), o.held ? "drag" : "glide", o.held ? 1 : 0);
331
443
  st.x = x;
332
444
  st.y = y;
445
+ st.typed = null; // the hand left the keyboard: no submit / Tab pause owed
333
446
  };
334
447
  // Engine real-trajectory routing (PRO): send point-to-point moves/clicks through
335
448
  // Browser.dispatchPointerPath (Browser.humanizedClick before r34, see sendEngineCommand; real
@@ -343,8 +456,67 @@ export async function attachHumanize(browser, page, opts) {
343
456
  // from where the pointer was. So the engine walks only while nothing else has moved the pointer
344
457
  // since its own last walk (before its first walk: while nothing has moved it at all).
345
458
  const engineInSync = () => (eng.at === null ? !st.placed : st.x === eng.at.x && st.y === eng.at.y);
346
- const engineGlide = async (x, y, noClick) => {
347
- if (!eng.ok || !engineInSync())
459
+ const engineSession = async () => {
460
+ if (eng.session === null) {
461
+ const ctx = page.context();
462
+ const tsession = await ctx.newCDPSession(page);
463
+ const info = await tsession.send("Target.getTargetInfo");
464
+ eng.tid = info.targetInfo.targetId;
465
+ const br = ctx.browser ? ctx.browser() : null;
466
+ eng.key = br ?? ctx; // the command name is a property of the engine: learn it once per browser
467
+ eng.session = br ? await br.newBrowserCDPSession() : tsession;
468
+ }
469
+ };
470
+ // Lane A's onFallback hears ONCE per browser that a PRO engine (it has the pointer path) lacks the r43
471
+ // extensions. The hook only: the SDK planner does the work, so this is not a native fallback and strict mode
472
+ // does not throw.
473
+ const maybeReportExt = () => {
474
+ if (!eng.key || engineExt.get(eng.key) !== false || engineExtReported.has(eng.key))
475
+ return;
476
+ const names = engineMethodNames.get(eng.key);
477
+ const known = names?.get(POINTER_PATH);
478
+ if (!known || known === NO_ENGINE_PATH)
479
+ return;
480
+ engineExtReported.add(eng.key);
481
+ optionsOf(page)?.onFallback?.({ api: "engine_ext", reason: ENGINE_EXT_MISSING });
482
+ };
483
+ // r43 engine (SC 232 lane H): dispatchPointerPath takes fromX/fromY, button, clickCount, modifiers, buttons,
484
+ // settle and answers after its last event; dispatchKeySequence exists. Asked once per browser, only when needed:
485
+ // an empty dispatchKeySequence answers -32602 (invalid params) on r43 and -32601 (not found) before; anything
486
+ // else counts as no (an engine that accepts no keys is not r43).
487
+ const engineExtOk = async () => {
488
+ if (!eng.ok || !engineExtMode())
489
+ return false;
490
+ try {
491
+ await engineSession();
492
+ }
493
+ catch {
494
+ return false;
495
+ }
496
+ const known = engineExt.get(eng.key);
497
+ if (known !== undefined)
498
+ return known;
499
+ let ok;
500
+ try {
501
+ await eng.session.send(ENGINE_KEY_SEQUENCE, { targetId: eng.tid, keys: [] });
502
+ ok = false;
503
+ }
504
+ catch (e) {
505
+ ok = isInvalidParams(e);
506
+ }
507
+ engineExt.set(eng.key, ok);
508
+ maybeReportExt();
509
+ return ok;
510
+ };
511
+ // One engine pointer path to (x, y). `ext`: r43 parameters (button, clickCount, modifiers, buttons, settle),
512
+ // only sent to an engine that takes them; on such an engine the path also starts where THIS SDK left the
513
+ // pointer (fromX/fromY) instead of requiring the engine to be in sync, and no sleep follows (it answers after
514
+ // its last event). A plain in-sync left click never probes: the r42 route is unchanged.
515
+ const engineGlide = async (x, y, noClick, ext) => {
516
+ if (!eng.ok)
517
+ return false;
518
+ const useExt = !!(ext || !engineInSync()) && await engineExtOk();
519
+ if (!useExt && (ext || !engineInSync()))
348
520
  return false;
349
521
  try {
350
522
  // This browser's engine already said it has neither command: no sessions, no probe.
@@ -353,23 +525,25 @@ export async function attachHumanize(browser, page, opts) {
353
525
  eng.ok = false;
354
526
  return false;
355
527
  }
356
- if (eng.session === null) {
357
- const ctx = page.context();
358
- const tsession = await ctx.newCDPSession(page);
359
- const info = await tsession.send("Target.getTargetInfo");
360
- eng.tid = info.targetInfo.targetId;
361
- const br = ctx.browser ? ctx.browser() : null;
362
- eng.key = br ?? ctx; // the command name is a property of the engine: learn it once per browser
363
- eng.session = br ? await br.newBrowserCDPSession() : tsession;
364
- }
528
+ await engineSession();
365
529
  // The engine does not wait for the page: what it walks into a page that has not drawn yet is lost
366
530
  // (a fresh headless browser's first page, SC 216). Wait for two frames first; free once drawn.
367
531
  await worldFor(page).evaluate(ISO_FRAMES, FRAMES_WAIT_MS, true);
368
532
  const dx = x - st.x, dy = y - st.y;
369
533
  const dist = Math.sqrt(dx * dx + dy * dy);
370
- const dur = Math.min(1.10, Math.max(0.28, 0.30 + dist / 1700)) * (0.85 + 0.30 * Math.random());
534
+ const dur = Math.min(1.10, Math.max(0.28, 0.30 + dist / 1700)) * (0.85 + 0.30 * Math.random()) * tempo;
371
535
  const tSend = Date.now();
372
- await sendEngineCommand(eng.session, eng.key, POINTER_PATH, POINTER_PATH_LEGACY, { targetId: eng.tid, x, y, duration: dur, noClick });
536
+ const params = { targetId: eng.tid, x, y, duration: dur, noClick };
537
+ if (useExt) {
538
+ // r43: start where this SDK left the pointer; before any move the engine enters over the top edge itself.
539
+ if (st.placed && !engineInSync()) {
540
+ params.fromX = st.x;
541
+ params.fromY = st.y;
542
+ }
543
+ Object.assign(params, ext || {});
544
+ }
545
+ await sendEngineCommand(eng.session, eng.key, POINTER_PATH, POINTER_PATH_LEGACY, params);
546
+ maybeReportExt();
373
547
  // The engine walks the trajectory in the BROWSER process and answers this command before it
374
548
  // has finished. Without waiting, a following mouse.down() fires at the cursor's STALE
375
549
  // position — measured: a move to (110,58) then a press landed at (981,629), on <body>
@@ -378,7 +552,8 @@ export async function attachHumanize(browser, page, opts) {
378
552
  // r38 answers only after the walk AND the click (send returned 772 ms after a 600 ms walk, 2 ms
379
553
  // after the release, SC 210): wait only for what is left of `dur`, so an engine that answers
380
554
  // late does not add a second, idle `dur` after every click.
381
- await sleep(Math.max(0, dur * 1000 - (Date.now() - tSend)));
555
+ if (!useExt)
556
+ await sleep(Math.max(0, dur * 1000 - (Date.now() - tSend))); // r43 answers after its last event
382
557
  try {
383
558
  await nativeMove(x, y);
384
559
  }
@@ -425,7 +600,7 @@ export async function attachHumanize(browser, page, opts) {
425
600
  // planAmbient overruns its budget (whole excursions, rests drawn at 0.9-1.4x a frame): cut the
426
601
  // plan at a slow sample near ms so ambientMotion(ms) lasts about ms.
427
602
  const steps = trimTo(planAmbient(st, await viewport(), persona, ms), ms);
428
- await dispatch(steps);
603
+ await dispatch(steps, "ambient");
429
604
  if (steps.length) {
430
605
  st.x = steps[steps.length - 1].x;
431
606
  st.y = steps[steps.length - 1].y;
@@ -471,6 +646,11 @@ export async function attachHumanize(browser, page, opts) {
471
646
  mouse.move = async (x, y) => {
472
647
  // A move while the button is held is a DRAG leg: planDrag keeps it on the line between grab and
473
648
  // drop (an aimed reach's arc took a slider handle 47 px off a 40 px track, SC 209).
649
+ // r43 engine (SC 232 lane H): held legs take the engine route (buttons carried on every sample, answered after
650
+ // the walk).
651
+ if (st.held && engineModeFor(page, engineClicksMode) !== "off" && await engineExtOk()
652
+ && await engineGlide(x, y, true, { buttons: engineHeldBits(st.heldButton) }))
653
+ return;
474
654
  await glide(x, y, { held: st.held });
475
655
  };
476
656
  // down/up are wrapped to TRACK the held state mouse.move needs, and — critically — to make the
@@ -482,7 +662,7 @@ export async function attachHumanize(browser, page, opts) {
482
662
  // The pause between the pointer coming to rest and the button going down (forms.prePressMs: 40-250
483
663
  // ms, right-skewed, centred per identity). Measured on r38 before it: the focus click before typing
484
664
  // pressed ~4 ms after the last pointermove, a drag grab ~21 ms.
485
- const prePress = async () => { await sleep(prePressMs(persona.seed)); };
665
+ const prePress = async () => { await sleep(prePressMs(persona.seed) * tempo); };
486
666
  // What is left of a button hold once mouse.down() has returned: the hold runs from when the press was
487
667
  // SENT. mouse.down() returns only after the page handled the press, and a <select> opens its popup
488
668
  // inside that, so a hold slept afterwards reached the page ~30-80 ms longer than planned.
@@ -525,6 +705,7 @@ export async function attachHumanize(browser, page, opts) {
525
705
  await prePress();
526
706
  }
527
707
  st.held = true;
708
+ st.heldButton = (a[0] && a[0].button) || "left";
528
709
  try {
529
710
  return await nativeDown(...a);
530
711
  }
@@ -539,24 +720,60 @@ export async function attachHumanize(browser, page, opts) {
539
720
  finally {
540
721
  st.held = false;
541
722
  } };
723
+ // r43 engine (SC 232 lane H): a right/middle, double/triple or modified click walked AND pressed engine-side
724
+ // (dispatchPointerPath button / clickCount / modifiers); the modifier KEYS are pressed here around it (lead
725
+ // before, lag after), as pressAt does. False when the engine cannot take it (a caller-chosen hold, no r43
726
+ // extensions, modifiers without keyboard.down): the planner presses then. Shared by mouse.click and the targeted
727
+ // click (verifier A's R5: selector clicks never took it).
728
+ const engineExtClick = async (x, y, o) => {
729
+ const ext = engineClickParams(o);
730
+ if (!ext || engineModeFor(page, engineClicksMode) === "off" || !(await engineExtOk()))
731
+ return false;
732
+ if (o.modifiers.length && !(nativeKbDown && nativeKbUp))
733
+ return false;
734
+ const held = [];
735
+ try {
736
+ for (const m of o.modifiers) {
737
+ await nativeKbDown(m);
738
+ held.push(m);
739
+ await sleep(rand(40, 110));
740
+ }
741
+ return await engineGlide(x, y, false, ext);
742
+ }
743
+ finally {
744
+ for (const m of held.reverse()) {
745
+ await sleep(rand(20, 80));
746
+ try {
747
+ await nativeKbUp(m);
748
+ }
749
+ catch { /* best effort */ }
750
+ }
751
+ }
752
+ };
542
753
  // The engine path performs ONE plain left click. Anything else -- right/middle button, a double
543
754
  // click, a caller-chosen hold -- glides SDK-side and presses as asked (pressAt); the old wrapper
544
755
  // dropped those options and always left-clicked once.
545
756
  const hclick = async (x, y, options = {}) => {
546
757
  const o = normalizeClickOptions(options);
547
- if (enginePathOk(o) && engineClicksMode() !== "off" && await engineGlide(x, y, false))
758
+ if (enginePathOk(o) && engineModeFor(page, engineClicksMode) !== "off" && await engineGlide(x, y, false))
759
+ return;
760
+ // r43 engine (SC 232 lane H): right/middle, double/triple and modified clicks too (engineExtClick).
761
+ if (await engineExtClick(x, y, o))
548
762
  return;
549
763
  await glide(x, y);
550
- try {
551
- if (o.modifiers.length && !(nativeKbDown && nativeKbUp)) {
552
- await prePress(); // the hand confirms the target before it presses
553
- // delay = the mousedown→mouseup HOLD (human ~60–150 ms); without it Playwright releases in ~2 ms.
554
- await nativeClick(x, y, { delay: o.delay ?? clickHold(persona), button: o.button, clickCount: o.clickCount });
555
- return;
556
- }
764
+ // A press that rejects REJECTS (it was swallowed here: a click whose press failed reported success).
765
+ // Only the pin before a press (mouse.down) stays best-effort.
766
+ if (o.modifiers.length && !(nativeKbDown && nativeKbUp)) {
767
+ await prePress(); // the hand confirms the target before it presses
768
+ // delay = the mousedown→mouseup HOLD (the persona's); without it Playwright releases in ~2 ms.
769
+ await nativeClick(x, y, { delay: o.delay ?? clickHold(persona), button: o.button, clickCount: o.clickCount });
770
+ }
771
+ else {
557
772
  await pressAt(o);
558
773
  }
559
- catch { /* best-effort */ }
774
+ // Not after an engine click (returned above): a glide the engine does not see would take the next
775
+ // coordinate click off the engine path (engineInSync).
776
+ scheduleMoveOff();
560
777
  };
561
778
  mouse.click = (x, y, options = {}) => locked(() => hclick(x, y, options));
562
779
  // Stock dblclick teleported and pressed for ~0 ms: route it through the humanized click.
@@ -572,16 +789,26 @@ export async function attachHumanize(browser, page, opts) {
572
789
  page.ambientMotion = async (ms = 1200) => { await ambient(ms); };
573
790
  // Held-button drag leg with the seating jiggle (settle), reachable from the module-level
574
791
  // Locator.dragTo patch (which can't see this closure) via the page object.
575
- page._clearcoteHeldGlide = async (x, y) => { await glide(x, y, { settle: true }); };
792
+ page._clearcoteHeldGlide = async (x, y) => {
793
+ // r43 engine (SC 232 lane H): the held leg + seating jiggle (settle) walked engine-side, buttons carried.
794
+ if (st.held && engineModeFor(page, engineClicksMode) !== "off" && await engineExtOk()
795
+ && await engineGlide(x, y, true, { buttons: engineHeldBits(st.heldButton), settle: true }))
796
+ return;
797
+ await glide(x, y, { settle: true });
798
+ };
576
799
  // OPT-IN: no ambient burst on load by default (it interleaves with caller-driven input,
577
800
  // e.g. a slider drag). Call page.ambientMotion(ms) explicitly, or set
578
801
  // page._clearcoteAutoAmbient = true to restore the per-load burst.
579
- page._clearcoteAutoAmbient = false;
802
+ page._clearcoteAutoAmbient = hz.ambient === "load";
803
+ page._clearcoteAmbient = hz.ambient ?? "off"; // read by the attention/idle code (lane C)
580
804
  page.on("load", () => {
581
- if (page._clearcoteAutoAmbient) {
805
+ // ambient: "load" (lane A's option, read defensively) is the same per-load burst as the flag.
806
+ if (page._clearcoteAutoAmbient === true || ambientMode(page) === "load") {
582
807
  Promise.resolve(page.ambientMotion(rand(450, 950))).catch(() => { });
583
808
  }
584
809
  });
810
+ // The attention model's read pause counts from the last load (read lazily by the next action).
811
+ page.on("load", () => { af.loadAt = Date.now(); });
585
812
  // A wheel event carries the pointer position, and until something moves the cursor that position
586
813
  // is the default origin — so a scroll right after a page load reported the mouse parked in the
587
814
  // corner, over nothing it was scrolling, while the deltas rolled down the middle of the document.
@@ -593,13 +820,13 @@ export async function attachHumanize(browser, page, opts) {
593
820
  const scrollAnchor = async () => {
594
821
  try {
595
822
  const vp = await viewport();
596
- if (st.placed && st.x > 6 && st.y > 6 && st.x < vp.width - 6 && st.y < vp.height - 6)
823
+ if (!anchorNeeded([st.x, st.y], vp.width, vp.height, st.placed, st.held))
597
824
  return;
598
- // Upper-middle of the reading column, gaussian-jittered: an exact viewport centre is as
825
+ // Upper-middle of the reading column, gaussian-jittered (scroll.ts anchorPoint: the numbers Python
826
+ // and .NET use too -- before 0.52 the three SDKs each had their own): an exact viewport centre is as
599
827
  // machine-made as the origin is, so the anchor has to be a distribution, not a landmark.
600
- const x = clamp(vp.width * 0.48 + gauss() * vp.width * 0.10, vp.width * 0.18, vp.width * 0.82);
601
- const y = clamp(vp.height * 0.36 + gauss() * vp.height * 0.09, vp.height * 0.14, vp.height * 0.62);
602
- await glide(x, y);
828
+ const [x, y] = anchorPoint(vp.width, vp.height);
829
+ await glide(x, y, { targetW: ANCHOR_TARGET_W });
603
830
  await sleep(rand(60, 180)); // eyes land before the finger rolls the wheel
604
831
  }
605
832
  catch { /* best-effort: scroll from wherever the cursor is */ }
@@ -609,6 +836,7 @@ export async function attachHumanize(browser, page, opts) {
609
836
  // cannot say (closed, mid-navigation, no CDP) gets the host's platform. Kept for the life of the
610
837
  // page either way: a mouse does not change its notch between two scrolls.
611
838
  let notchPx = null;
839
+ let wheelPlat = null;
612
840
  const wheelNotchPx = async () => {
613
841
  if (notchPx === null) {
614
842
  let plat = null;
@@ -616,10 +844,43 @@ export async function attachHumanize(browser, page, opts) {
616
844
  plat = platformFromNavigator(await worldFor(page).evaluate(ISO_PLATFORM));
617
845
  }
618
846
  catch { /* host below */ }
619
- notchPx = WHEEL_NOTCH_PX[plat ?? hostWheelPlatform()];
847
+ wheelPlat = plat ?? hostWheelPlatform();
848
+ notchPx = WHEEL_NOTCH_PX[wheelPlat];
620
849
  }
621
850
  return notchPx;
622
851
  };
852
+ // "trackpad" or "mouse" for this page: the caller's `inputDevice` option when the options object carries
853
+ // one (read defensively: the options plumbing is lane A's), else a trackpad for a macOS persona.
854
+ let device = null;
855
+ const inputDev = async () => {
856
+ if (device === null) {
857
+ await wheelNotchPx();
858
+ const o = opts;
859
+ const pg = page;
860
+ // lane A's resolved options (optionsOf) first, then the stand-in seams
861
+ const cand = [optionsOf(page)?.inputDevice, o?.inputDevice, o?.input_device, pg._clearcoteOptions?.inputDevice,
862
+ pg._clearcoteInputDevice]
863
+ .find((v) => typeof v === "string");
864
+ device = inputDevice(wheelPlat, cand);
865
+ }
866
+ return device;
867
+ };
868
+ const scrollIO = {
869
+ viewport: () => viewport(),
870
+ pointer: () => [st.x, st.y],
871
+ placed: () => st.placed,
872
+ held: () => st.held,
873
+ glide: (x, y, w) => glide(x, y, { targetW: w }),
874
+ wheel: async (dx, dy) => { await nativeWheel(dx, dy); },
875
+ sleep: async (ms) => { await sleep(ms * tempo); }, // the preset scales the scroll-into-view pauses
876
+ notchPx: () => wheelNotchPx(),
877
+ device: () => inputDev(),
878
+ trackpad: () => tpTraits,
879
+ scrollRange: async () => {
880
+ const r = await worldFor(page).evaluate(ISO_SCROLL_RANGE);
881
+ return Array.isArray(r) && r.length === 4 ? r.map(Number) : null;
882
+ },
883
+ };
623
884
  /** Scroll in WHOLE NOTCHES, the only thing a wheel emits. Humanize scrolls whole notches: the
624
885
  * delivered total is the requested distance rounded to the nearest notch (at least one), not the
625
886
  * exact pixel count.
@@ -630,6 +891,30 @@ export async function attachHumanize(browser, page, opts) {
630
891
  * macOS. One axis per event, like a real wheel or tilt, and the notches come in finger-flick bursts. */
631
892
  mouse.wheel = async (dx, dy) => {
632
893
  await scrollAnchor();
894
+ // Score hook (trace.ts, lane G): every wheel event this call sends, with its send time, scored as "wheel".
895
+ const wrec = traceEnabled() ? [] : null;
896
+ const wt0 = performance.now();
897
+ const sendWheel = async (a, b) => {
898
+ await nativeWheel(a, b);
899
+ wrec?.push({ t: performance.now() - wt0, dx: a, dy: b, mode: 0 });
900
+ };
901
+ const device = await inputDev();
902
+ try {
903
+ await wheelRun(device, dx, dy, sendWheel);
904
+ }
905
+ finally {
906
+ if (wrec?.length)
907
+ traceRecord("wheel", wrec, { device, dx, dy });
908
+ }
909
+ };
910
+ const wheelRun = async (device, dx, dy, sendWheel) => {
911
+ if (device === "trackpad") {
912
+ // A trackpad persona swipes the exact distance: 2-40 px events at the persona's 60-120/s on a min-jerk
913
+ // bell, then an inertia tail (scroll.ts planTrackpad / trackpadTraits). Playwright sends pixel deltas
914
+ // either way (deltaMode 0); a notch persona's deltas are whole multiples of its notch.
915
+ await pacedWheel(planTrackpad(dx, dy, tpTraits), sendWheel, async (ms) => { await sleep(ms); });
916
+ return;
917
+ }
633
918
  const notch = await wheelNotchPx();
634
919
  const plan = [];
635
920
  for (let k = wheelNotches(dy, notch); k > 0; k--)
@@ -638,27 +923,32 @@ export async function attachHumanize(browser, page, opts) {
638
923
  plan.push([Math.sign(dx) * notch, 0]);
639
924
  let burst = randInt(2, 5);
640
925
  for (let i = 0; i < plan.length; i++) {
641
- await nativeWheel(plan[i][0], plan[i][1]);
926
+ await sendWheel(plan[i][0], plan[i][1]);
642
927
  if (i === plan.length - 1)
643
928
  break;
644
929
  // local sleep, NOT page.waitForTimeout: the latter is a CDP round-trip per call, so it
645
930
  // emits protocol traffic bot-detectors (e.g. reCAPTCHA) can score — a self-inflicted tell
646
931
  // inside the humanize path. setTimeout is off-protocol.
647
932
  if (--burst === 0) {
648
- await sleep(rand(110, 320)); // the finger resets for the next flick
933
+ await sleep(rand(110, 320) * tempo); // the finger resets for the next flick
649
934
  burst = randInt(2, 5);
650
935
  }
651
936
  else {
652
937
  await sleep(rand(18, 55));
653
938
  }
654
939
  if (Math.random() < 0.07)
655
- await sleep(rand(150, 450)); // occasional mid-scroll pause (reading)
940
+ await sleep(rand(150, 450) * tempo); // occasional mid-scroll pause (reading)
656
941
  // A hand resting on the mouse does not hold it perfectly still through a long scroll. Without
657
942
  // this a wheel burst is the one input where the pointer coordinate never changes at all. Never
658
943
  // while a button is down, where a move is a drag leg.
659
944
  if (plan.length >= 6 && !st.held && Math.random() < 0.06) {
945
+ // ONE native move of N(0,1.5) x N(0,1.2) px (scroll.ts wheelDrift; it used to be a planned glide of
946
+ // 3.5/2.5 px sd, unlike Python and .NET)
660
947
  try {
661
- await glide(st.x + gauss() * 3.5, st.y + gauss() * 2.5);
948
+ const [ddx, ddy] = wheelDrift();
949
+ await nativeMove(st.x + ddx, st.y + ddy);
950
+ st.x += ddx;
951
+ st.y += ddy;
662
952
  }
663
953
  catch { /* drift is cosmetic */ }
664
954
  }
@@ -667,33 +957,68 @@ export async function attachHumanize(browser, page, opts) {
667
957
  // ----------------------------------------------------------------- keyboard
668
958
  const keyboard = page.keyboard;
669
959
  const nativeKbType = keyboard.type.bind(keyboard);
670
- const nativeKbPress = keyboard.press.bind(keyboard);
960
+ const nativeKbPress0 = keyboard.press.bind(keyboard);
671
961
  // A bulk fill's paste (Input.insertText).
672
962
  const nativeKbInsert = typeof keyboard.insertText === "function" ? keyboard.insertText.bind(keyboard) : undefined;
673
963
  // A page-like keyboard without down/up still gets every other humanization; it just types
674
964
  // capitals without the Shift key, as before.
675
- const nativeKbDown = typeof keyboard.down === "function" ? keyboard.down.bind(keyboard) : undefined;
676
- const nativeKbUp = typeof keyboard.up === "function" ? keyboard.up.bind(keyboard) : undefined;
965
+ const nativeKbDown0 = typeof keyboard.down === "function" ? keyboard.down.bind(keyboard) : undefined;
966
+ const nativeKbUp0 = typeof keyboard.up === "function" ? keyboard.up.bind(keyboard) : undefined;
967
+ // Score hook (trace.ts, lane G): while a typed run is being traced (keyRec is a list), every key the natives
968
+ // send is recorded as {key, down, up} (ms; modifiers left out), and humanTypeText scores the run as "typed".
969
+ // Off (keyRec null, the default) the wrappers only forward.
970
+ let keyRec = null;
971
+ const keyPend = new Map();
972
+ const MOD_KEYS = new Set(["Shift", "Control", "Alt", "Meta", "ControlOrMeta"]);
973
+ const kbNow = () => performance.now();
974
+ const kbRec = (key, down, up) => {
975
+ if (keyRec !== null && !MOD_KEYS.has(key))
976
+ keyRec.push({ key, down, up });
977
+ };
978
+ const nativeKbPress = async (key, o) => {
979
+ const t0 = kbNow();
980
+ const r = await nativeKbPress0(key, o);
981
+ kbRec(key, t0, kbNow());
982
+ return r;
983
+ };
984
+ const nativeKbDown = nativeKbDown0 === undefined ? undefined : async (key, o) => {
985
+ const t0 = kbNow();
986
+ const r = await nativeKbDown0(key, o);
987
+ if (keyRec !== null)
988
+ keyPend.set(key, t0);
989
+ return r;
990
+ };
991
+ const nativeKbUp = nativeKbUp0 === undefined ? undefined : async (key, o) => {
992
+ const r = await nativeKbUp0(key, o);
993
+ const t0 = keyPend.get(key);
994
+ if (t0 !== undefined) {
995
+ keyPend.delete(key);
996
+ kbRec(key, t0, kbNow());
997
+ }
998
+ return r;
999
+ };
677
1000
  // Emit one character with a human keydown→keyup DWELL. keyboard.press's `delay` IS the hold
678
1001
  // (keyboard.type's delay is only inter-key flight), so per-char press gives the missing dwell.
679
1002
  // Fall back to type() for anything press can't map (some symbols / composed chars).
680
1003
  const emitKey = async (ch) => {
681
1004
  try {
682
- await nativeKbPress(ch, { delay: keyDwell(persona) });
1005
+ await nativeKbPress(ch, { delay: kdwell() });
1006
+ return;
683
1007
  }
684
- catch {
685
- try {
686
- await nativeKbType(ch);
687
- }
688
- catch { /* best-effort */ }
1008
+ catch { /* below */ }
1009
+ // Outside the catch: in strict mode lane A's report throws, and that must reach the caller.
1010
+ fallback("keyboard.press", "insertText: a character keyboard.press cannot map");
1011
+ try {
1012
+ await nativeKbType(ch);
689
1013
  }
1014
+ catch { /* best-effort */ }
690
1015
  };
691
1016
  // Press `k` (n times) with the persona's hold on every press and a human gap between repeats.
692
1017
  const key = async (k, n = 1, gap = [60, 150]) => {
693
1018
  for (let j = 0; j < n; j++) {
694
- await nativeKbPress(k, { delay: keyDwell(persona) });
1019
+ await nativeKbPress(k, { delay: kdwell() });
695
1020
  if (j < n - 1)
696
- await sleep(rand(gap[0], gap[1]));
1021
+ await sleep(pauseMs(persona, gap[0], gap[1]));
697
1022
  }
698
1023
  };
699
1024
  // Press at the point the last glide ended, the way the options ask: the button, the click count (a
@@ -722,7 +1047,7 @@ export async function attachHumanize(browser, page, opts) {
722
1047
  await nativeUp({ button: o.button, clickCount: i }); // never leave the button down
723
1048
  }
724
1049
  if (i < n)
725
- await sleep(rand(70, 170)); // the gap inside a double click
1050
+ await sleep(dblclickGap(persona)); // the gap inside a double click: the persona's
726
1051
  }
727
1052
  }
728
1053
  finally {
@@ -745,38 +1070,108 @@ export async function attachHumanize(browser, page, opts) {
745
1070
  return null;
746
1071
  }
747
1072
  };
748
- // Node's inter-key flight (the cadence humanTypeText uses between characters).
749
- const flightMs = () => rand(45, 150);
1073
+ // One keyup->keydown flight of the persona's cadence (keys.flightMs, the planner Python and .NET use).
1074
+ const flight = (prev = null, ch = null) => flightMs(traits, prev, ch, Math.random);
750
1075
  const backspaces = async (n) => {
751
1076
  for (let k = 0; k < n; k++) {
752
- await nativeKbPress("Backspace", { delay: keyDwell(persona) });
1077
+ await nativeKbPress("Backspace", { delay: kdwell() });
753
1078
  if (k < n - 1)
754
1079
  await sleep(rand(70, 150));
755
1080
  }
756
1081
  };
757
1082
  // How many characters arrived since `before` (null = cannot tell).
758
1083
  const landed = (before, now) => before === null || now === null ? null : Array.from(now).length - Array.from(before).length;
759
- // Make the planned slip at chars[i] and correct it. Returns true when it already typed chars[i]
760
- // itself (the doubled-key case), so the caller must not type it again.
1084
+ // Bring the focused field back to `target` (what it held before a slip) from wherever a word delete
1085
+ // left it: Backspace to the common prefix, then type the rest. Nothing when unreadable.
1086
+ const restore = async (target) => {
1087
+ const got = await activeValue();
1088
+ if (got === null || got === target)
1089
+ return;
1090
+ const g = Array.from(got), t = Array.from(target);
1091
+ let k = 0;
1092
+ while (k < Math.min(g.length, t.length) && g[k] === t[k])
1093
+ k++;
1094
+ if (g.length - k > 64 || t.length - k > 64)
1095
+ return;
1096
+ if (g.length > k) {
1097
+ await backspaces(g.length - k);
1098
+ await sleep(rand(80, 200));
1099
+ }
1100
+ await emitKeys(t.slice(k));
1101
+ };
1102
+ // `chars` typed in order, one human flight apart (`prev`: the key typed just before, for the first flight), every
1103
+ // capital / shifted symbol behind a real ShiftLeft held across a run of them -- the type loop's Shift dance.
1104
+ // restore and the late-notice keys of doTypo emitted them bare: a keydown 'M' right after Control+Backspace with
1105
+ // no Shift down (lab contenteditable, SC 209 row "Capitals typed with Shift held 12/14"; SC 239).
1106
+ const emitKeys = async (chars, prev = null) => {
1107
+ let shift = false;
1108
+ try {
1109
+ for (let j = 0; j < chars.length; j++) {
1110
+ const c = chars[j];
1111
+ if (prev !== null)
1112
+ await sleep(flight(prev, c));
1113
+ if (needsShift(c) && !shift && !heldKeys.has("Shift") && nativeKbDown && nativeKbUp) {
1114
+ await nativeKbDown("Shift");
1115
+ shift = true;
1116
+ await sleep(rand(35, 120));
1117
+ }
1118
+ await emitKey(c);
1119
+ if (shift && (j === chars.length - 1 || !needsShift(chars[j + 1]))) {
1120
+ await sleep(rand(10, 70));
1121
+ await nativeKbUp("Shift");
1122
+ shift = false;
1123
+ }
1124
+ prev = c;
1125
+ }
1126
+ }
1127
+ finally {
1128
+ if (shift) {
1129
+ try {
1130
+ await nativeKbUp("Shift");
1131
+ }
1132
+ catch { /* never leave Shift held */ }
1133
+ }
1134
+ }
1135
+ };
1136
+ // The word-delete chord the ENGINE's editing honours: Alt+Backspace on macOS, else Ctrl.
1137
+ const wordDelete = () => pressKey((hostWheelPlatform() === "macos" ? "Alt" : "Control") + "+Backspace");
1138
+ // Make the planned slip at chars[i] and correct it. Returns true when it already typed chars[i] itself
1139
+ // (the doubled-key case) -- or left a substitution uncorrected (`leave`: a search field) --, so the
1140
+ // caller must not type it again.
761
1141
  //
762
1142
  // Only what actually LANDED is deleted: an input mask or a maxlength can swallow the wrong key, and
763
1143
  // a Backspace pressed for a key that never arrived deletes a real character (the
764
- // letter-typo-in-a-numeric-mask failure). Measured before and after the slip, in the isolated world,
765
- // one read each -- typos are ~2 % of keys, so this costs nearly nothing.
766
- const doTypo = async (chars, i, tp) => {
1144
+ // letter-typo-in-a-numeric-mask failure). Measured before and after the slip, in the isolated world.
1145
+ // A substitution noticed inside a word is fixed with the word-delete chord and the word typed again in
1146
+ // WORD_FIX_RATE of the cases (when the field can be read to put it back exactly).
1147
+ const doTypo = async (chars, i, tp, leave = false) => {
767
1148
  const before = await activeValue();
768
1149
  if (tp.kind === "sub") {
769
1150
  await emitKey(tp.wrong);
770
1151
  let got = landed(before, await activeValue());
771
1152
  if (got !== null && got <= 0)
772
1153
  return false; // swallowed: nothing to correct
773
- let typed = 1;
774
- for (const c of chars.slice(i + 1, i + 1 + tp.late)) { // late notice: a key or two more
775
- await sleep(flightMs());
776
- await emitKey(c);
777
- typed++;
778
- }
1154
+ if (leave)
1155
+ return true; // the slip stays: the wrong key took this place
1156
+ const late = chars.slice(i + 1, i + 1 + tp.late);
1157
+ await emitKeys(late, tp.wrong); // late notice: a key or two more
1158
+ const typed = 1 + late.length;
779
1159
  await sleep(rand(140, 340)); // noticing
1160
+ let ws = 0;
1161
+ for (let j = i - 1; j >= 0; j--)
1162
+ if (chars[j] === " " || chars[j] === "\n") {
1163
+ ws = j + 1;
1164
+ break;
1165
+ }
1166
+ // a WORD (letters only: no word delete in a code, a zip or a number), two keys of it on screen
1167
+ if (before !== null && i - ws + typed >= 2 && nativeKbDown && /^\p{L}+$/u.test(chars.slice(ws, i + 1).join(""))
1168
+ && Math.random() < WORD_FIX_RATE) {
1169
+ await wordDelete();
1170
+ await sleep(rand(120, 260));
1171
+ await restore(before);
1172
+ await sleep(rand(80, 200));
1173
+ return false;
1174
+ }
780
1175
  got = landed(before, await activeValue());
781
1176
  await backspaces(got === null ? typed : Math.max(0, Math.min(typed, got)));
782
1177
  await sleep(rand(80, 200));
@@ -797,7 +1192,7 @@ export async function attachHumanize(browser, page, opts) {
797
1192
  }
798
1193
  if (tp.kind === "swap") {
799
1194
  await emitKey(chars[i + 1]);
800
- await sleep(flightMs());
1195
+ await sleep(flight(chars[i + 1], chars[i]));
801
1196
  await emitKey(chars[i]);
802
1197
  const got = landed(before, await activeValue());
803
1198
  await sleep(rand(140, 340));
@@ -822,28 +1217,100 @@ export async function attachHumanize(browser, page, opts) {
822
1217
  // Type text key-by-key with human timing. Each char goes through the native keyboard (trusted),
823
1218
  // so this stays isTrusted===true.
824
1219
  //
825
- // Capitals and shifted symbols are typed the way a person types them: ShiftLeft goes down a moment
826
- // before the key (35-120 ms) and comes up just after it (10-70 ms), held across a run of them.
827
- // Playwright's press("A") alone sent the key with shiftKey=false and no Shift key at all (measured
828
- // on r28 with "Ab!") -- input no keyboard produces.
829
- //
830
- // Fast pairs ROLL OVER: the next key goes down before the previous one comes up. One press() per
831
- // character never overlaps (0 of 32 keydowns, measured on r32/r33), a keystroke-dynamics tell;
832
- // real typists overlap many fast pairs. The share is the persona's rolloverRate, stable per seed.
1220
+ // Cadence: keys.planGap, the planner Python and .NET use (was uniform 45-150 ms here, with the
1221
+ // thinking pause REPLACING the gap): the persona's WPM sets a base flight, scaled by how the hand
1222
+ // travels between the two keys (same finger 1.5-1.9x, same hand 1.1-1.3x, the other hand 0.85-1.0x,
1223
+ // a two-row reach 1.15x) and log-normal noise, plus a pause before a new word and after punctuation,
1224
+ // the whitespace pause and a 6 % thinking pause, ADDED. `floorMs` (the caller's `delay`) is the
1225
+ // shortest gap between two keys.
833
1226
  //
834
- // Fat-finger typos are planned by forms.planTypo and never happen where a slip is a failure rather
835
- // than a slip (passwords, e-mail, numbers, phone numbers, URLs, one-time codes).
1227
+ // Capitals and shifted symbols are typed the way a person types them: ShiftLeft goes down a moment
1228
+ // before the key (35-120 ms) and comes up just after it (10-70 ms), held across a run of them (none
1229
+ // under a Shift the caller holds through keyboard.down). Fast pairs ROLL OVER at the persona's
1230
+ // rolloverRate. Fat-finger typos are planned by forms.planTypo at the persona's rate and never happen
1231
+ // where a slip is a failure rather than a slip; `exact` false (type / pressSequentially /
1232
+ // keyboard.type, never fill) lets a search-field substitution stay uncorrected (SEARCH_SLIP_RATE).
836
1233
  const rollRate = rolloverRate(persona);
837
- const humanTypeText = async (text, field, typos = true) => {
1234
+ // Type `text` with ONE Browser.dispatchKeySequence (r43, SC 232 lane H): lane B's key dwell and lane D's bigram
1235
+ // flight per key (the caller's delay as the floor), paced in the browser. False when a character has no plain US
1236
+ // key or the call fails up front (nothing typed yet: the per-key path types it).
1237
+ const engineType = async (text, floor) => {
1238
+ const keys = engineKeyPlan(text, kdwell, (ch, nx) => Math.max(floor, planGap(traits, ch, nx, Math.random, persona.tempo ?? 1, persona.pauseScale ?? 1)), needsShift);
1239
+ if (!keys)
1240
+ return false;
1241
+ try {
1242
+ await engineSession();
1243
+ await eng.session.send(ENGINE_KEY_SEQUENCE, { targetId: eng.tid, keys });
1244
+ }
1245
+ catch {
1246
+ return false;
1247
+ }
1248
+ traceEngineTyped(keys, floor);
1249
+ return true;
1250
+ };
1251
+ // The score hook (lane G) hears an engine typed run as one "typed" line of the PLANNED down/up times (the engine
1252
+ // paces them in the browser; the per-key path records its dispatched ones). Inside an outer traced run the keys
1253
+ // join that run's record instead (verifier A's R3c: the engine run wrote nothing).
1254
+ const traceEngineTyped = (keys, floor) => {
1255
+ if (!traceEnabled())
1256
+ return;
1257
+ const outer = keyRec;
1258
+ let t = outer !== null ? kbNow() : 0;
1259
+ const rec = [];
1260
+ for (const k of keys) {
1261
+ const down = t;
1262
+ const up = down + (Number(k.dwellMs) || 0);
1263
+ rec.push({ key: String(k.key), down, up });
1264
+ t = up + (Number(k.gapMs) || 0);
1265
+ }
1266
+ if (outer !== null)
1267
+ outer.push(...rec);
1268
+ else
1269
+ traceRecord("typed", rec, { n: keys.length, typos: false, floor_ms: floor, engine: true });
1270
+ };
1271
+ const humanTypeText = async (text, field, typos = true, floorMs = 0, exact = true) => {
838
1272
  const chars = Array.from(text);
839
1273
  const n = chars.length;
840
1274
  let shift = false;
841
- const rate = typos ? typoRate() : 0;
842
- const allow = rate > 0 && typosAllowed(await typingField(field));
1275
+ const extShift = heldKeys.has("Shift");
1276
+ const rate = typos ? personaTypoRate() : 0;
1277
+ const fld = rate > 0 ? await typingField(field) : null;
1278
+ const allow = rate > 0 && typosAllowed(fld);
1279
+ const search = allow && !exact && !!fld && String(fld.type || "").toLowerCase() === "search";
1280
+ const floor = Math.max(0, Number(floorMs) || 0);
1281
+ // ROLLOVER, decided up front: the pairs this run overlaps (index of the first key), one unseeded draw per
1282
+ // eligible pair at lane B's rollover rate (12-38 % per identity). Eligible: unshifted single-key pairs
1283
+ // (ROLL_KEYS), never a key with itself, never under a caller's delay floor. Drawn before the route is chosen so
1284
+ // the engine run below is taken exactly for the runs that would have had no rollover, and the per-key path
1285
+ // realises the persona's share on the others -- the distribution of overlaps per run is the per-key path's.
1286
+ const rolls = new Set();
1287
+ if (floor <= 0 && nativeKbDown && nativeKbUp) {
1288
+ for (let i = 0; i < n - 1; i++) {
1289
+ if (ROLL_KEYS.has(chars[i]) && ROLL_KEYS.has(chars[i + 1]) && chars[i] !== chars[i + 1] && Math.random() < rollRate)
1290
+ rolls.add(i);
1291
+ }
1292
+ }
1293
+ // r43 engine (SC 232 lane H): a run with no slip to plan (typos off, or a field where a slip is a failure), no
1294
+ // caller-held Shift and NO ROLLOVER goes out as ONE dispatchKeySequence -- the same dwell and flight draws, paced
1295
+ // in the browser, so the rhythm carries no CDP round trips. A run the persona rolls over stays per key: the
1296
+ // command cannot overlap keys (the engine clamps gapMs at 0), and an identity whose credential fields typed with
1297
+ // zero overlap next to text fields with its 12-38 % would contradict itself (verifier A's R3b). Not with engine
1298
+ // "off" (R3a): that is the documented way to keep everything SDK-side.
1299
+ if (!allow && n > 1 && !extShift && rolls.size === 0 && engineModeFor(page, engineClicksMode) !== "off"
1300
+ && await engineExtOk() && await engineType(text, floor)) {
1301
+ st.typed = Date.now(); // a following Enter / Tab still waits (afterTyping)
1302
+ return;
1303
+ }
1304
+ // the score hook records this run's keys (nativeKb* wrappers) and scores it as "typed" at the end
1305
+ const outerRec = keyRec;
1306
+ if (outerRec === null && traceEnabled()) {
1307
+ keyRec = [];
1308
+ keyPend.clear();
1309
+ }
843
1310
  try {
844
1311
  for (let i = 0; i < n; i++) {
845
1312
  let ch = chars[i];
846
- const need = needsShift(ch);
1313
+ const need = needsShift(ch) && !extShift;
847
1314
  if (need && !shift && nativeKbDown && nativeKbUp) {
848
1315
  await nativeKbDown("Shift");
849
1316
  shift = true;
@@ -856,20 +1323,23 @@ export async function attachHumanize(browser, page, opts) {
856
1323
  const tp = planTypo(chars, i, Math.random, rate);
857
1324
  if (tp !== null) {
858
1325
  typo = true;
1326
+ const leave = search && tp.kind === "sub" && Math.random() < SEARCH_SLIP_RATE;
859
1327
  try {
860
- consumed = await doTypo(chars, i, tp);
1328
+ consumed = await doTypo(chars, i, tp, leave);
1329
+ }
1330
+ catch (e) {
1331
+ if (isStrict(e))
1332
+ throw e; /* typo path best-effort */
861
1333
  }
862
- catch { /* typo path best-effort */ }
863
1334
  }
864
1335
  }
865
- // Rollover of ch and the next char: unshifted single-key pairs only, never a key with itself,
866
- // never after a typo. keyboard.down inserts the character exactly as press does, so the typed
867
- // value is unchanged. The overlap leaves ch down alone for at least 8 ms first.
1336
+ // Rollover of ch and the next char (the pairs were drawn up front: `rolls`); a typo or a Shift in
1337
+ // flight still cancels one. keyboard.down inserts the character exactly as press does, so the typed
1338
+ // value is unchanged.
868
1339
  const nx = chars[i + 1];
869
1340
  let rolled = false;
870
- if (nativeKbDown && nativeKbUp && !shift && i + 1 < n && !typo && ROLL_KEYS.has(ch)
871
- && ROLL_KEYS.has(nx) && ch !== nx && Math.random() < rollRate) {
872
- const d1 = keyDwell(persona), d2 = keyDwell(persona);
1341
+ if (nativeKbDown && nativeKbUp && !shift && i + 1 < n && !typo && rolls.has(i)) {
1342
+ const d1 = kdwell(), d2 = kdwell();
873
1343
  if (d1 - 8 >= 12) {
874
1344
  const overlap = rand(12, Math.min(55, d1 - 8));
875
1345
  try {
@@ -902,7 +1372,9 @@ export async function attachHumanize(browser, page, opts) {
902
1372
  try {
903
1373
  await emitKey(ch);
904
1374
  }
905
- catch {
1375
+ catch (e) {
1376
+ if (isStrict(e))
1377
+ throw e;
906
1378
  break;
907
1379
  }
908
1380
  }
@@ -911,14 +1383,8 @@ export async function attachHumanize(browser, page, opts) {
911
1383
  await nativeKbUp("Shift");
912
1384
  shift = false;
913
1385
  }
914
- if (i < n - 1) {
915
- if (Math.random() < 0.06)
916
- await sleep(rand(180, 450)); // brief thinking pause
917
- else
918
- await sleep(flightMs());
919
- if (/\s/.test(ch))
920
- await sleep(rand(20, 100)); // slight extra pause at word boundaries
921
- }
1386
+ if (i < n - 1)
1387
+ await sleep(Math.max(floor, planGap(traits, ch, chars[i + 1], Math.random, persona.tempo ?? 1, persona.pauseScale ?? 1)));
922
1388
  }
923
1389
  }
924
1390
  finally {
@@ -929,6 +1395,96 @@ export async function attachHumanize(browser, page, opts) {
929
1395
  }
930
1396
  catch { /* best-effort */ }
931
1397
  }
1398
+ if (n)
1399
+ st.typed = Date.now(); // a following Enter / Tab waits (afterTyping)
1400
+ if (outerRec === null && keyRec !== null) {
1401
+ const rec = keyRec;
1402
+ keyRec = null;
1403
+ traceRecord("typed", rec, { n, typos: allow, floor_ms: floor });
1404
+ }
1405
+ }
1406
+ };
1407
+ // The pause between the last typed character and Enter (250-900 ms) or Tab (120-400 ms), centred per
1408
+ // persona, less whatever the caller already spent. Once per typed run; a glide in between cancels it.
1409
+ const afterTyping = async (k) => {
1410
+ const t = st.typed;
1411
+ st.typed = null;
1412
+ if (t === null)
1413
+ return;
1414
+ const [mods, base] = splitChord(k);
1415
+ let ms;
1416
+ if (base === "Enter" && !mods.length)
1417
+ ms = submitPauseMs(traits, Math.random);
1418
+ else if (base === "Tab" && mods.every((m) => m === "Shift"))
1419
+ ms = tabPauseMs(traits, Math.random);
1420
+ else
1421
+ return;
1422
+ const rest = ms - (Date.now() - t);
1423
+ if (rest > 0)
1424
+ await sleep(rest);
1425
+ };
1426
+ // One key: pressed with the persona's hold (or the caller's `delay`); with `repeat` > 1 HELD the way an
1427
+ // OS auto-repeats it -- one keydown, the machine's repeat delay (250-500 ms, a persona trait), then a
1428
+ // keydown with repeat=true at its repeat interval (25-40 ms, likewise; Playwright sends a key that is
1429
+ // already down as an autoRepeat keydown), `repeat` keydowns in all, then one keyup.
1430
+ const holdKey = async (k, delay = null, repeat = 1) => {
1431
+ const n = Math.max(1, Math.floor(Number(repeat) || 1));
1432
+ if (n === 1 || !nativeKbDown || !nativeKbUp) {
1433
+ for (let j = 0; j < n; j++) {
1434
+ await nativeKbPress(k, { delay: delay && delay > 0 ? delay : kdwell() });
1435
+ if (j < n - 1)
1436
+ await sleep(rand(60, 150));
1437
+ }
1438
+ return;
1439
+ }
1440
+ const rp = planRepeat(traits, Math.random);
1441
+ await nativeKbDown(k);
1442
+ try {
1443
+ await sleep(rp.firstMs);
1444
+ for (let j = 0; j < n - 1; j++) {
1445
+ if (j)
1446
+ await sleep(rp.gapMs);
1447
+ await nativeKbDown(k);
1448
+ }
1449
+ await sleep(rp.releaseMs);
1450
+ }
1451
+ finally {
1452
+ await nativeKbUp(k); // never leave the key held
1453
+ }
1454
+ };
1455
+ // keyboard.press, humanized: a chord ("Control+a", "ControlOrMeta+Shift+ArrowLeft") is split into its
1456
+ // modifiers and its key -- each modifier goes down in order, 40-110 ms before the next, the key is
1457
+ // held, 20-80 ms later the modifiers come up in reverse order (as one Playwright press the modifier and
1458
+ // the key went down within ~1 ms). A modifier the caller holds (keyboard.down) is not pressed again.
1459
+ const pressKey = async (k, delay = null, repeat = 1) => {
1460
+ const [all, base] = splitChord(k);
1461
+ const mods = all.filter((m) => !heldKeys.has(m));
1462
+ if (!mods.length)
1463
+ return holdKey(base, delay, repeat);
1464
+ if (!nativeKbDown || !nativeKbUp) {
1465
+ await nativeKbPress(k, { delay: delay && delay > 0 ? delay : kdwell() });
1466
+ return;
1467
+ }
1468
+ const down = [];
1469
+ try {
1470
+ for (const m of mods) {
1471
+ await nativeKbDown(m);
1472
+ down.push(m);
1473
+ await sleep(modifierLeadMs(Math.random));
1474
+ }
1475
+ await holdKey(base, delay, repeat);
1476
+ await sleep(modifierLagMs(Math.random));
1477
+ }
1478
+ finally {
1479
+ let j = 0;
1480
+ for (const m of down.reverse()) {
1481
+ if (j++)
1482
+ await sleep(rand(10, 40));
1483
+ try {
1484
+ await nativeKbUp(m);
1485
+ }
1486
+ catch { /* one failed keyup must not strand the others */ }
1487
+ }
932
1488
  }
933
1489
  };
934
1490
  // Keystrokes from a session in which the mouse never existed. Selector-based typing glides to the
@@ -947,7 +1503,31 @@ export async function attachHumanize(browser, page, opts) {
947
1503
  kbWarmed = true;
948
1504
  await ambient(rand(280, 620));
949
1505
  };
950
- keyboard.type = (text) => locked(async () => { await keyboardWarmup(); await humanTypeText(text); });
1506
+ keyboard.type = (text, options = {}) => locked(async () => {
1507
+ await keyboardWarmup();
1508
+ await humanTypeText(text, undefined, true, Number(options?.delay) || 0, false);
1509
+ });
1510
+ // keyboard.down / up, tracked: a chord does not press a modifier the caller holds, typing does not
1511
+ // press Shift under the caller's Shift, and a down() straight followed by up() still holds the key
1512
+ // for a persona dwell (no finger lifts a key in 0 ms).
1513
+ if (nativeKbDown && nativeKbUp) {
1514
+ keyboard.down = (k) => locked(async () => {
1515
+ await keyboardWarmup();
1516
+ if (!heldKeys.has(k))
1517
+ heldKeys.set(k, [Date.now(), kdwell()]);
1518
+ return nativeKbDown(k);
1519
+ });
1520
+ keyboard.up = (k) => locked(async () => {
1521
+ const t = heldKeys.get(k);
1522
+ heldKeys.delete(k);
1523
+ if (t) {
1524
+ const rest = t[1] - (Date.now() - t[0]);
1525
+ if (rest > 0)
1526
+ await sleep(rest);
1527
+ }
1528
+ return nativeKbUp(k);
1529
+ });
1530
+ }
951
1531
  // keyboard.press with the persona's hold, unless the caller specified their own.
952
1532
  //
953
1533
  // WHY THIS EXISTS. keyboard.type was humanised from the start and keyboard.press was not, which
@@ -958,20 +1538,36 @@ export async function attachHumanize(browser, page, opts) {
958
1538
  // session sees the press path — so one un-humanised call undid the whole keyboard persona.
959
1539
  //
960
1540
  // The caller's own `delay` wins: press(key, {delay}) is the documented way to hold a key for a
961
- // specific time, and silently overriding it would break that. Only the DEFAULT changes -- and
962
- // `delay: 0` IS Playwright's default ("no hold"), so it, like any non-positive value, gets the
963
- // persona's hold too (a 0 ms key hold is the tell this wrapper exists to remove).
964
- keyboard.press = (key, options = {}) => locked(async () => {
1541
+ // specific time. `delay: 0` IS Playwright's default ("no hold"), so it gets the persona's hold. A
1542
+ // chord is pressed modifier first (pressKey); `repeat: n` (the SDK's) holds the key through n OS
1543
+ // auto-repeat keydowns; Enter or Tab right after typing waits the persona's pause (afterTyping).
1544
+ keyboard.press = (k, options = {}) => locked(async () => {
965
1545
  await keyboardWarmup();
966
- const opts = { ...(options && typeof options === "object" ? options : {}) };
967
- if (!(typeof opts.delay === "number" && opts.delay > 0))
968
- opts.delay = keyDwell(persona);
969
- return nativeKbPress(key, opts);
1546
+ const o = options && typeof options === "object" ? options : {};
1547
+ await afterTyping(k);
1548
+ return pressKey(k, typeof o.delay === "number" && o.delay > 0 ? o.delay : null, o.repeat ?? 1);
970
1549
  });
971
1550
  // ------------------------------------------------------- page-level targeted helpers
972
1551
  // Points tried when resolving a control through the browser's hit test: a floating label or an icon
973
1552
  // often sits over a field's CENTRE, so the edges get a chance too.
974
1553
  const probePoints = [[0.5, 0.5], [0.82, 0.5], [0.18, 0.5], [0.5, 0.8], [0.5, 0.2]];
1554
+ // The Fitts target width of a glide onto `box`: its smaller side (floor 6 px). Every targeted glide passed
1555
+ // 24 whatever the box, so duration did not follow the target's size.
1556
+ const aimW = (box) => Math.max(6, Math.min(box.width, box.height));
1557
+ // When the persona's point is covered (a badge, a floating label over the centre): the first probe point
1558
+ // (edges, then bottom/top) the isolated hit test proves reaches the element, as a whole pixel inside the
1559
+ // box; null when none does (the caller falls back).
1560
+ const provenClickPoint = async (box, sel = null) => {
1561
+ for (const [fx, fy] of probePoints.slice(1)) {
1562
+ // spread around the probe (3 % of the width, 8 % of the height): a fixed probe pixel would land every
1563
+ // covered click on the same spot
1564
+ const x = roundHalfEven(clamp(box.x + box.width * fx + gauss() * Math.max(1.5, box.width * 0.03), box.x + 1, box.x + box.width - 1));
1565
+ const y = roundHalfEven(clamp(box.y + box.height * fy + gauss() * Math.max(1.0, box.height * 0.08), box.y + 1, box.y + box.height - 1));
1566
+ if ((await hitInBox(box, x, y, sel)) === true)
1567
+ return { x, y };
1568
+ }
1569
+ return null;
1570
+ };
975
1571
  // The control filling `box` (Playwright's resolved box for a locator), read in the isolated world
976
1572
  // through the browser's own hit test: works for every Playwright selector (getByRole, getByLabel,
977
1573
  // `>> nth=`, .filter()) where document.querySelector threw and dropped the call to stock input. The
@@ -1106,27 +1702,99 @@ export async function attachHumanize(browser, page, opts) {
1106
1702
  // Playwright's utility world), the scroll only for a box not already inside the viewport, and a
1107
1703
  // plain-CSS `selector` needs no handle at all (cssBox). What remains, for other selectors, is the
1108
1704
  // one boundingBox.
1109
- const boxOf = async (loc, timeout, force = false, selector = null) => {
1705
+ // Is `selector` plain CSS that the browser's querySelectorAll resolves to exactly the elements Playwright
1706
+ // counts (see cssBox)? Then the box and its scroller are read in the isolated world, with no handle.
1707
+ const cssPlain = async (selector) => {
1708
+ if (typeof selector !== "string" || !selector)
1709
+ return false;
1710
+ const r = await worldFor(page).evaluate(ISO_CSS_BOX, { sel: selector, scroll: false });
1711
+ if (!r || !r.n)
1712
+ return false;
1713
+ try {
1714
+ return (await page.locator(selector).count()) === r.n;
1715
+ }
1716
+ catch {
1717
+ return false;
1718
+ }
1719
+ };
1720
+ const scrollerOf = async (selector) => {
1721
+ const r = await worldFor(page).evaluate(ISO_SCROLLER, { sel: selector });
1722
+ return r && Array.isArray(r.rect) ? r : null;
1723
+ };
1724
+ // Bring the target in with the WHEEL (scroll.ts bringIntoView): the box where it shows and owns its centre,
1725
+ // else null and why ("not_scrollable", "notch_budget", "covered"). A plain-CSS target's nearest scrollable
1726
+ // ancestor is wheeled over; any other selector scrolls the window, its box read from the window's scroll
1727
+ // offset (no new handle per read).
1728
+ const wheelIntoView = async (loc, selector, css, box) => {
1729
+ const w = worldFor(page);
1730
+ const s0 = await w.scroll();
1731
+ const boxFn = async () => {
1732
+ if (css)
1733
+ return rectBox(await w.evaluate(ISO_CSS_BOX, { sel: selector, scroll: false }));
1734
+ const [sx, sy] = await w.scroll();
1735
+ return { x: box.x - (sx - s0[0]), y: box.y - (sy - s0[1]), width: box.width, height: box.height };
1736
+ };
1737
+ const res = await bringIntoView(scrollIO, boxFn, null, undefined, css ? () => scrollerOf(selector) : null);
1738
+ const last = res.box;
1739
+ if (!res.ok)
1740
+ return { got: null, why: res.notches >= 60 ? "notch_budget" : "not_scrollable", last };
1741
+ if (!last || !((await inView(last)) && (await hitOk(last, selector))))
1742
+ return { got: null, why: "covered", last };
1743
+ return { got: last, why: null, last };
1744
+ };
1745
+ const needsScroll = async (box, selector, css) => {
1746
+ if (!(await inView(box)))
1747
+ return true;
1748
+ if (css) {
1749
+ const sc = await scrollerOf(selector);
1750
+ if (sc)
1751
+ return !boxIn(box, sc.rect);
1752
+ }
1753
+ return false;
1754
+ };
1755
+ // Wait the way Playwright would, with the CALLER's timeout (undefined = the page default), and return the
1756
+ // box, in view. With `force` nothing is waited for: a hidden target goes native at once.
1757
+ //
1758
+ // An out-of-view target is brought in with the WHEEL (wheelIntoView): whole notches (or a trackpad swipe)
1759
+ // to 25-60 % of the viewport, an undershoot and a correction, over the scrolling container that clips it.
1760
+ // The programmatic scroll (isolated scrollIntoViewIfNeeded, an instant window scrollBy, Playwright's
1761
+ // scroll) is only the FALLBACK -- a container the wheel does not move, the 60-notch budget spent,
1762
+ // `wheel: false` (a trial, which must not move the pointer) -- and a fallback after a wheel attempt is
1763
+ // reported (fallback()). Measured on r42 / 0.51.0: every humanized action on an off-screen target scrolled
1764
+ // programmatically, a `scroll` event with no wheel before it, the target at the exact centre.
1765
+ //
1766
+ // Each Playwright call that resolves the element to a handle makes a MAIN-world handle whose preview
1767
+ // reads its textContent where the page can see it (verifier B), so each is made only when needed and a
1768
+ // plain-CSS `selector` is read in the isolated world without one.
1769
+ const boxOf = async (loc, timeout, force = false, selector = null, wheel = true) => {
1110
1770
  if (!(await loc.isVisible())) {
1111
1771
  if (force)
1112
- throw new NativeSignal();
1772
+ throw new NativeSignal("forced on a hidden target");
1113
1773
  await loc.waitFor({ state: "visible", timeout });
1114
1774
  }
1115
- const css = await cssBox(selector);
1775
+ const css = await cssPlain(selector);
1776
+ const w = worldFor(page);
1777
+ let box = css ? rectBox(await w.evaluate(ISO_CSS_BOX, { sel: selector, scroll: false }))
1778
+ : await loc.boundingBox();
1779
+ if (!box)
1780
+ return box;
1781
+ if (wheel && (await needsScroll(box, selector, css))) {
1782
+ const r = await wheelIntoView(loc, selector, css, box);
1783
+ if (r.got)
1784
+ return r.got;
1785
+ if (r.why !== "covered")
1786
+ fallback("scroll_into_view", "scroll into view: " + r.why);
1787
+ box = r.last ?? box;
1788
+ }
1789
+ if ((await inView(box)) && (await hitOk(box, selector)))
1790
+ return box;
1116
1791
  if (css)
1117
- return css;
1118
- let box = await loc.boundingBox();
1119
- if (box && !((await inView(box)) && (await hitOk(box, selector)))) {
1120
- // Off-screen: scroll the window to it and prove it shows there (hit test), with no new handle.
1121
- // Clipped by a scrolling container, covered, or the window scroll did not bring it out:
1122
- // Playwright's scroll, which also scrolls containers, and a fresh box.
1123
- const moved = !(await inView(box)) ? await scrollWindowTo(box) : null;
1124
- if (moved && (await inView(moved)) && (await hitOk(moved, selector)))
1125
- return moved;
1126
- await loc.scrollIntoViewIfNeeded({ timeout });
1127
- box = await loc.boundingBox();
1128
- }
1129
- return box;
1792
+ return rectBox(await w.evaluate(ISO_CSS_BOX, { sel: selector, scroll: true }));
1793
+ const moved = !(await inView(box)) ? await scrollWindowTo(box) : null;
1794
+ if (moved && (await inView(moved)) && (await hitOk(moved, selector)))
1795
+ return moved;
1796
+ await loc.scrollIntoViewIfNeeded({ timeout });
1797
+ return await loc.boundingBox();
1130
1798
  };
1131
1799
  // Does `loc` hold the keyboard focus? Asked through Playwright's utility-world selector engine
1132
1800
  // (`:focus`), so it works for every element and every locator and the page sees nothing. The
@@ -1182,7 +1850,7 @@ export async function attachHumanize(browser, page, opts) {
1182
1850
  }
1183
1851
  const p0 = at ? { x: at[0], y: at[1] } : clickPoint(box, st, persona); // 2D gaussian toward the centre
1184
1852
  const pt = { x: roundHalfEven(p0.x), y: roundHalfEven(p0.y) }; // the pixel the hit test answered for
1185
- await glide(pt.x, pt.y);
1853
+ await glide(pt.x, pt.y, { targetW: aimW(box) });
1186
1854
  await pressHere(pt.x, pt.y);
1187
1855
  return true;
1188
1856
  };
@@ -1198,7 +1866,7 @@ export async function attachHumanize(browser, page, opts) {
1198
1866
  await nativeKbDown("ControlOrMeta");
1199
1867
  try {
1200
1868
  await sleep(rand(40, 110));
1201
- await nativeKbPress("a", { delay: keyDwell(persona) });
1869
+ await nativeKbPress("a", { delay: kdwell() });
1202
1870
  await sleep(rand(20, 80));
1203
1871
  }
1204
1872
  finally {
@@ -1235,29 +1903,149 @@ export async function attachHumanize(browser, page, opts) {
1235
1903
  const nativePageHover = page.hover.bind(page);
1236
1904
  const nativePageSelect = typeof page.selectOption === "function" ? page.selectOption.bind(page) : null;
1237
1905
  const nativeType = (selector, text, options) => nativePageType ? nativePageType(selector, text, options) : nativePageFill(selector, text, options);
1238
- // Make `selector` the focus the way a person does (a click), unless it already is. Only text-entry
1239
- // controls are clicked; for anything else, and when the click did not actually put the caret there
1240
- // (an overlay took it), the caller goes native.
1906
+ // Where the control `info` (described, with its hit-test node) sits in the page's Tab order relative to
1907
+ // the focused element (keys.TAB_DISTANCE, read in the isolated world), or null.
1908
+ const tabDistance = async (info, selector = null) => {
1909
+ if (!info || info.node === undefined || info.node === null || !info.rect)
1910
+ return null;
1911
+ const [x, y, width, height] = info.rect;
1912
+ const arg = { x, y, width, height };
1913
+ if (typeof selector === "string" && selector)
1914
+ arg.sel = selector;
1915
+ try {
1916
+ return (await worldFor(page).callOnNode(info.node, TAB_DISTANCE, arg)) ?? null;
1917
+ }
1918
+ catch {
1919
+ return null;
1920
+ }
1921
+ };
1922
+ // Press Tab `d` times (Shift+Tab when d < 0): the first after the persona's Tab pause when it follows
1923
+ // typing, the rest 110-260 ms apart (the eye follows the focus ring).
1924
+ const tabSteps = async (d) => {
1925
+ const k = d > 0 ? "Tab" : "Shift+Tab";
1926
+ for (let j = 0; j < Math.abs(d); j++) {
1927
+ if (j === 0)
1928
+ await afterTyping(k);
1929
+ else
1930
+ await sleep(rand(110, 260));
1931
+ await pressKey(k);
1932
+ }
1933
+ };
1934
+ // Tab into the control `info` instead of clicking it, the way a person moves between adjacent fields:
1935
+ // when focus sits in a TEXT field 1-3 stops before it (or 1 after: Shift+Tab), in the persona's share
1936
+ // (60-85 %, keys.typingTraits tabPref). `force`: any focused element, up to 3 stops either way, no roll
1937
+ // (a button a press goes to). `needEmpty`: only an empty field (Tab selects a field's text; type()
1938
+ // appends at the caret). True once focus is verified there; false = click.
1939
+ const tabInto = async (loc, info, selector = null, needEmpty = false, force = false) => {
1940
+ if (needEmpty && info && info.value)
1941
+ return false;
1942
+ const td = await tabDistance(info, selector);
1943
+ if (!td || td.dist === null || td.focused)
1944
+ return false;
1945
+ const d = td.dist;
1946
+ if (force) {
1947
+ if (!(Math.abs(d) >= 1 && Math.abs(d) <= 3))
1948
+ return false;
1949
+ }
1950
+ else if (!td.fromText || !((d >= 1 && d <= 3) || d === -1) || Math.random() >= tabPref()) {
1951
+ return false;
1952
+ }
1953
+ await tabSteps(d);
1954
+ await sleep(rand(40, 120));
1955
+ return focused(loc);
1956
+ };
1957
+ // Make `selector` the focus the way a person does -- Tab from the field before it (tabInto) or a click
1958
+ // --, unless it already is. Only text-entry controls are clicked; for anything else, and when the click
1959
+ // did not actually put the caret there (an overlay took it), the caller goes native. Tab only into an
1960
+ // EMPTY field.
1241
1961
  const clickInto = async (selector, timeout) => {
1242
1962
  const loc = page.locator(selector).first();
1243
1963
  if (await focused(loc))
1244
1964
  return;
1245
1965
  const te = await textEntry(loc, timeout, selector);
1246
- if (!te || !(await focusClick(te.box, provenPoint(te.box, te.info), loc, selector)) || !(await focused(loc))) {
1247
- throw new NativeSignal();
1966
+ if (!te)
1967
+ throw new NativeSignal("not a visible text field");
1968
+ if (await tabInto(loc, te.info, selector, true))
1969
+ return;
1970
+ if (!(await focusClick(te.box, provenPoint(te.box, te.info), loc, selector)) || !(await focused(loc))) {
1971
+ throw new NativeSignal("the click did not put the caret in the field");
1972
+ }
1973
+ await sleep(rand(40, 120));
1974
+ };
1975
+ // Give `selector` -- any focusable element -- the keyboard focus the way a person does: Tab when it is
1976
+ // 1-3 stops from the focused element (always for what a click would ACTIVATE: a button, a link, a
1977
+ // checkbox), else a humanized click for what a click only focuses. True when focus is verified there;
1978
+ // false for an activatable target out of Tab reach (the pointer has glided onto it; the caller gives
1979
+ // the focus natively, reported) -- never Playwright's 0 ms focus-and-press.
1980
+ const focusTarget = async (selector, timeout) => {
1981
+ const loc = page.locator(selector).first();
1982
+ if (await focused(loc))
1983
+ return true;
1984
+ const box = await boxOf(loc, timeout, false, selector);
1985
+ const info = box ? await describe(box, FOCUSABLE) : null;
1986
+ if (!box || !info)
1987
+ throw new NativeSignal("the target cannot be described (no box)");
1988
+ const td = await tabDistance(info, selector);
1989
+ const act = td === null || td.activatable; // unknown: never risk an activating click
1990
+ if (td && td.dist !== null && Math.abs(td.dist) >= 1 && Math.abs(td.dist) <= 3) {
1991
+ if ((act || Math.random() < tabPref()) && await tabInto(loc, info, selector, false, true))
1992
+ return true;
1993
+ }
1994
+ if (!act && !info.disabled) {
1995
+ if (await focusClick(box, provenPoint(box, info), loc, selector) && await focused(loc)) {
1996
+ await sleep(rand(40, 120));
1997
+ return true;
1998
+ }
1999
+ throw new NativeSignal("the focus click did not focus it");
2000
+ }
2001
+ if (act && td && !info.disabled) {
2002
+ // SC 232 lab triage (10-16): an activatable target out of Tab reach -- the usual case for a button when the
2003
+ // focus is far away or nowhere -- got the pointer over it and Playwright's focus (reported): 0 of 4 presses
2004
+ // on verifier B's buttons, 6 of 12 in the lab, on d2b9ab6. A person reaches it as a keyboard user does.
2005
+ if (await tabViaField(loc, info, selector, td))
2006
+ return true;
2007
+ if (td.noAnchor && await tabFromStart(loc, info, selector))
2008
+ return true;
1248
2009
  }
2010
+ const p0 = clickPoint(box, st, persona);
2011
+ await glide(roundHalfEven(p0.x), roundHalfEven(p0.y)); // the hand goes to it; the focus has to be given
2012
+ return false;
2013
+ };
2014
+ // Reach the activatable control `info`, out of Tab reach of the focus, the way a keyboard user does: a click
2015
+ // into the text-entry stop 1-3 before it (or 1 after; `td.near` from TAB_DISTANCE), then Tab across. True once
2016
+ // focus is verified on it; false (nothing pressed, or the click or the Tabs went elsewhere) = the next route.
2017
+ const tabViaField = async (loc, info, selector, td) => {
2018
+ const near = td?.near;
2019
+ if (!near || !near.rect)
2020
+ return false;
2021
+ const [x, y, width, height] = near.rect;
2022
+ if (!(await focusClick({ x, y, width, height })))
2023
+ return false;
1249
2024
  await sleep(rand(40, 120));
2025
+ return tabInto(loc, info, selector, false, true);
2026
+ };
2027
+ // Nothing has the focus: one Tab enters the page (its first stop, or the one after whatever had the focus
2028
+ // last), then the control is reached when it is within 3 stops of the focus ring.
2029
+ const tabFromStart = async (loc, info, selector) => {
2030
+ await pressKey("Tab");
2031
+ await sleep(rand(110, 260)); // the eye finds the focus ring
2032
+ if (await focused(loc))
2033
+ return true;
2034
+ return tabInto(loc, info, selector, false, true);
1250
2035
  };
1251
2036
  const htype = async (selector, text, options) => {
2037
+ let why = "the humane route cannot apply";
1252
2038
  try {
1253
2039
  await clickInto(selector, options?.timeout);
1254
- await humanTypeText(text);
2040
+ await humanTypeText(text, undefined, true, Number(options?.delay) || 0, false);
1255
2041
  return;
1256
2042
  }
1257
2043
  catch (e) {
1258
2044
  if (isTimeout(e))
1259
2045
  throw e;
2046
+ why = whyOf(e);
1260
2047
  }
2048
+ reportFallback(page, "page.type", why, selector);
1261
2049
  // outside the try: a native call that raises must raise ONCE, not be retried by the handler
1262
2050
  return nativeType(selector, text, options);
1263
2051
  };
@@ -1285,11 +2073,14 @@ export async function attachHumanize(browser, page, opts) {
1285
2073
  const bulk = Array.from(want).length > 200; // what the field holds: a 300-character value cut to 5 is typed
1286
2074
  if (bulk && !nativeKbInsert)
1287
2075
  return false;
1288
- if (!(await focusClick(box, box ? provenPoint(box, info) : null, loc, selector)))
1289
- return false;
1290
- await sleep(rand(40, 120));
1291
- if (!(await focused(loc)))
1292
- return false;
2076
+ // From the field before it, a person Tabs (persona share, focus verified); else a click.
2077
+ if (!(info && await tabInto(loc, info, selector))) {
2078
+ if (!(await focusClick(box, box ? provenPoint(box, info) : null, loc, selector)))
2079
+ return false;
2080
+ await sleep(rand(40, 120));
2081
+ if (!(await focused(loc)))
2082
+ return false;
2083
+ }
1293
2084
  const read = async () => {
1294
2085
  try {
1295
2086
  return await loc.inputValue({ timeout: COVER_RETRY_MS });
@@ -1369,11 +2160,18 @@ export async function attachHumanize(browser, page, opts) {
1369
2160
  await glide(cx, cy, { targetW: 16 });
1370
2161
  await prePress();
1371
2162
  const { grabMs, releaseMs } = dragDwell(persona);
2163
+ const x0 = rangePoint(box, rangeFraction(cur, lo, hi), rtl)[0];
2164
+ const span = Math.abs(rangePoint(box, 1, false)[0] - rangePoint(box, 0, false)[0]);
2165
+ const stepPx = step && hi > lo ? span * (step / (hi - lo)) : 1;
2166
+ const moved = async () => {
2167
+ const v = await now();
2168
+ return v === null ? null : [rangePoint(box, rangeFraction(v, lo, hi), rtl)[0] - x0, 0];
2169
+ };
1372
2170
  await nativeDown();
1373
2171
  st.held = true;
1374
2172
  try {
1375
- await sleep(grabMs);
1376
- await glide(tx, ty, { settle: true });
2173
+ // closed loop (dragBy): past the value by a few px, read the value, correct
2174
+ await dragByCore(cx, cy, tx - x0, 0, moved, Math.max(1, stepPx / 2), grabMs);
1377
2175
  await sleep(releaseMs);
1378
2176
  }
1379
2177
  finally {
@@ -1437,7 +2235,7 @@ export async function attachHumanize(browser, page, opts) {
1437
2235
  }
1438
2236
  await glide(px, py, { targetW: fw });
1439
2237
  await pressHere(px, py);
1440
- await sleep(rand(150, 350));
2238
+ await sleep(pauseMs(persona, 150, 350));
1441
2239
  for (const a of plan) {
1442
2240
  if (a[0] === "type") {
1443
2241
  // The same typing model as text (persona dwell, gaussian gaps, thinking pauses, rollover): the
@@ -1449,7 +2247,7 @@ export async function attachHumanize(browser, page, opts) {
1449
2247
  else {
1450
2248
  await key(a[1], a.length > 2 ? a[2] : 1, [70, 170]);
1451
2249
  }
1452
- await sleep(rand(60, 220)); // between fields: the eye checks what it typed
2250
+ await sleep(pauseMs(persona, 60, 220)); // between fields: the eye checks what it typed
1453
2251
  }
1454
2252
  return datetimeEqual(kind, await loc.inputValue(), value);
1455
2253
  };
@@ -1469,6 +2267,7 @@ export async function attachHumanize(browser, page, opts) {
1469
2267
  // verified), a range is dragged/clicked and nudged, a date-like editor is typed segment by segment.
1470
2268
  // color, unfillable types and anything the humane route cannot prove it did right go to Playwright.
1471
2269
  const hfill = async (selector, value, options) => {
2270
+ let why = "the value is not a string";
1472
2271
  try {
1473
2272
  if (typeof value === "string") {
1474
2273
  const timeout = options?.timeout; // undefined: the page's default, as Playwright would use
@@ -1476,6 +2275,8 @@ export async function attachHumanize(browser, page, opts) {
1476
2275
  const box = await boxOf(loc, timeout, Boolean(options?.force), selector);
1477
2276
  const info = await describe(box);
1478
2277
  const kind = info ? classifyField(info.tag, info.type, info.ce) : await classifyFallback(loc);
2278
+ why = info && (info.disabled || info.readonly) ? "the field is disabled or read-only"
2279
+ : ["text", "range", "datetime"].includes(kind) ? `the ${kind} route did not verify` : `no humane route for a ${kind} field`;
1479
2280
  if (!(info && (info.disabled || info.readonly))) {
1480
2281
  if (kind === "text" && await fillText(loc, box, value, info, selector))
1481
2282
  return;
@@ -1489,9 +2290,11 @@ export async function attachHumanize(browser, page, opts) {
1489
2290
  catch (e) {
1490
2291
  if (isTimeout(e))
1491
2292
  throw e;
2293
+ why = whyOf(e);
1492
2294
  }
1493
2295
  // Native: color (Playwright sets it -- the OS dialog is no route), unfillable types (Playwright
1494
2296
  // raises, as before humanize), and anything the humane route could not prove it did right.
2297
+ reportFallback(page, "page.fill", why, selector);
1495
2298
  return nativePageFill(selector, value, options);
1496
2299
  };
1497
2300
  page.fill = apiErrors("page.fill", (selector, value, options = {}) => locked(() => hfill(selector, value, options)));
@@ -1501,46 +2304,193 @@ export async function attachHumanize(browser, page, opts) {
1501
2304
  o.clickCount = 2;
1502
2305
  return targetedClick(nativePageDblclick, selector, o, false, options ?? {});
1503
2306
  }));
2307
+ const nativePageFocus = typeof page.focus === "function" ? page.focus.bind(page) : null;
2308
+ // A humanized route handed this call to Playwright: told to lane A's on_fallback hook when the page
2309
+ // carries one (page._clearcoteOnFallback), else nothing (as before).
2310
+ // Lane A's report: strict mode throws ClearcoteStrictError (nothing is sent), else onFallback hears it. Not caught.
2311
+ const fallback = (api, reason, selector) => { reportFallback(page, api, reason, selector); };
2312
+ // Give `selector` the focus before a key goes to it: a text field by Tab from the field before it
2313
+ // (only when empty) or a click; anything else through focusTarget; an activatable target out of Tab
2314
+ // reach gets the pointer over it and Playwright's focus (reported), and the key is still held.
2315
+ const focusForPress = async (selector, timeout) => {
2316
+ const loc = page.locator(selector).first();
2317
+ if (await focused(loc))
2318
+ return;
2319
+ if (!(await loc.isVisible()))
2320
+ throw new NativeSignal("not visible"); // Playwright waits for it
2321
+ const box = await boxOf(loc, timeout, false, selector);
2322
+ const info = await describe(box);
2323
+ if (box && info && classifyField(info.tag, info.type, info.ce) === "text") {
2324
+ if (await tabInto(loc, info, selector, true))
2325
+ return;
2326
+ if (!(await focusClick(box, provenPoint(box, info), loc, selector)) || !(await focused(loc)))
2327
+ throw new NativeSignal("the click did not put the caret in the field");
2328
+ await sleep(rand(40, 120));
2329
+ return;
2330
+ }
2331
+ if (await focusTarget(selector, timeout))
2332
+ return;
2333
+ if (!nativePageFocus)
2334
+ throw new NativeSignal("no humane focus route (out of Tab reach, no page.focus)");
2335
+ fallback("page.press", "focus: an activatable target out of Tab reach");
2336
+ await nativePageFocus(selector, timeout !== undefined ? { timeout } : {});
2337
+ await sleep(rand(40, 120));
2338
+ };
2339
+ // page.press (and locator.press): the target gets the focus the way a person gives it (never
2340
+ // Playwright's focus-and-press in 0 ms), then the key goes through the keyboard model -- a chord's
2341
+ // modifier first, the persona's hold (or the caller's `delay`), `repeat: n` as OS auto-repeat, and the
2342
+ // submit / Tab pause after typing.
1504
2343
  const hpress = async (selector, key, options) => {
2344
+ let why = "the humane route cannot apply";
2345
+ const { repeat, ...opts } = options ?? {};
1505
2346
  try {
1506
- // Click into text fields only: a press on a button or a link that is not focused yet is
1507
- // Playwright's (it focuses without activating); clicking it first activated it twice.
1508
- await clickInto(selector, options?.timeout);
1509
- // The persona's hold unless the caller set a real one, for the same reason keyboard.press above
1510
- // carries one: this is the path locator.press() delegates to.
1511
- const d = options?.delay;
1512
- await nativeKbPress(key, { delay: typeof d === "number" && d > 0 ? d : keyDwell(persona) });
2347
+ await focusForPress(selector, opts.timeout);
2348
+ await afterTyping(key);
2349
+ const d = opts.delay;
2350
+ await pressKey(key, typeof d === "number" && d > 0 ? d : null, repeat ?? 1);
1513
2351
  return;
1514
2352
  }
1515
2353
  catch (e) {
1516
- if (isTimeout(e))
2354
+ if (isTimeout(e) || isStrict(e))
1517
2355
  throw e;
2356
+ why = whyOf(e);
1518
2357
  }
1519
- return nativePagePress(selector, key, options);
2358
+ reportFallback(page, "page.press", why, selector);
2359
+ let r;
2360
+ for (let j = 0; j < Math.max(1, Math.floor(Number(repeat) || 1)); j++)
2361
+ r = await nativePagePress(selector, key, opts);
2362
+ return r;
1520
2363
  };
1521
2364
  page.press = apiErrors("page.press", (selector, key, options = {}) => locked(() => hpress(selector, key, options)));
1522
- // ------------------------------------------------------------------------- selectOption
1523
- // Open the drop-down with a click, move its highlight with the planned keys, commit with Enter: one
1524
- // trusted input+change, the sequence a mouse-and-keyboard user produces. While the popup is open its
1525
- // keys never reach the page (measured on r37: value unchanged until Enter). The opening click is the
1526
- // full humanized click -- including the covered-point check -- at the point the hit test proved when
1527
- // the centre is covered (`at`, a Playwright `position`), so a floating label over the select's centre
1528
- // cannot swallow it and leave the letters to change a closed select one per key.
2365
+ // page.focus / locator.focus: Tab or a click (focusTarget), verified; Playwright's focus for an
2366
+ // activatable target out of Tab reach (reported) and for anything the humane route cannot do.
2367
+ if (nativePageFocus) {
2368
+ page.focus = apiErrors("page.focus", (selector, options = {}) => locked(async () => {
2369
+ try {
2370
+ if (await focusTarget(selector, options?.timeout))
2371
+ return;
2372
+ fallback("page.focus", "an activatable target out of Tab reach");
2373
+ }
2374
+ catch (e) {
2375
+ if (isTimeout(e))
2376
+ throw e;
2377
+ fallback("page.focus", "native focus");
2378
+ }
2379
+ return nativePageFocus(selector, options);
2380
+ }));
2381
+ }
2382
+ // locator.blur, humanized: a focused element is left the way the persona leaves fields -- Tab to the
2383
+ // next stop, or a click on a blank point beside it (keys.BLANK_POINT; Tab when there is none). True when
2384
+ // focus is verified gone; false = Playwright's blur.
2385
+ const blurHuman = async (selector, options) => {
2386
+ const loc = page.locator(selector).first();
2387
+ if (!(await focused(loc)))
2388
+ return false;
2389
+ if (traits.blurStyle === "click") {
2390
+ const box = await boxOf(loc, options?.timeout, false, selector);
2391
+ const vp = await viewport();
2392
+ const pt = box ? await worldFor(page).evaluate(BLANK_POINT, { box, vw: vp.width, vh: vp.height }) : null;
2393
+ if (Array.isArray(pt) && pt.length === 2) {
2394
+ const x = roundHalfEven(pt[0] + gauss() * 3), y = roundHalfEven(pt[1] + gauss() * 3);
2395
+ await glide(x, y, { targetW: 60 });
2396
+ await pressHere(x, y);
2397
+ await sleep(rand(40, 120));
2398
+ if (!(await focused(loc)))
2399
+ return true;
2400
+ }
2401
+ }
2402
+ await afterTyping("Tab");
2403
+ await pressKey("Tab");
2404
+ await sleep(rand(40, 120));
2405
+ return !(await focused(loc));
2406
+ };
2407
+ const selectedAll = async () => {
2408
+ const s = await worldFor(page).evaluate(SELECTION_STATE);
2409
+ return Array.isArray(s) && s.length === 3 && Math.min(s[0], s[1]) === 0 && Math.max(s[0], s[1]) === s[2];
2410
+ };
2411
+ // locator.selectText, humanized: a triple click (an <input>) or the keys -- End then Shift+Home
2412
+ // (Ctrl+End, Ctrl+Shift+Home in a textarea; Cmd+A on macOS) --, per persona; verified in the isolated
2413
+ // world (SELECTION_STATE), one select-all retry; false = Playwright's selectText.
2414
+ const selectTextHuman = async (selector, options) => {
2415
+ const loc = page.locator(selector).first();
2416
+ const box = await boxOf(loc, options?.timeout, !!options?.force, selector);
2417
+ const info = box ? await describe(box) : null;
2418
+ if (!box || !info || info.disabled || classifyField(info.tag, info.type, info.ce) !== "text")
2419
+ return false;
2420
+ if (traits.selectStyle === "triple" && info.tag === "input") {
2421
+ const at = provenPoint(box, info);
2422
+ const p0 = at ? { x: at[0], y: at[1] } : clickPoint(box, st, persona);
2423
+ await glide(roundHalfEven(p0.x), roundHalfEven(p0.y));
2424
+ await pressAt(normalizeClickOptions({ clickCount: 3 }));
2425
+ }
2426
+ else {
2427
+ if (!(await focused(loc))) {
2428
+ if (!(await focusClick(box, provenPoint(box, info), loc, selector)) || !(await focused(loc)))
2429
+ return false;
2430
+ await sleep(rand(120, 300));
2431
+ }
2432
+ if (hostWheelPlatform() === "macos")
2433
+ await pressKey("ControlOrMeta+a");
2434
+ else if (info.tag === "input") {
2435
+ await pressKey("End");
2436
+ await sleep(rand(80, 200));
2437
+ await pressKey("Shift+Home");
2438
+ }
2439
+ else {
2440
+ await pressKey("ControlOrMeta+End");
2441
+ await sleep(rand(80, 200));
2442
+ await pressKey("ControlOrMeta+Shift+Home");
2443
+ }
2444
+ }
2445
+ await sleep(rand(60, 160));
2446
+ if (await selectedAll())
2447
+ return true;
2448
+ await selectAll();
2449
+ await sleep(rand(60, 160));
2450
+ return selectedAll();
2451
+ };
2452
+ // Run the humane `fn` (true = done); Playwright's own locator method when it declines or fails (a
2453
+ // timeout propagates).
2454
+ const guarded = (api, fn, name) => (selector, options = {}) => locked(async () => {
2455
+ try {
2456
+ if (await fn(selector, options))
2457
+ return;
2458
+ }
2459
+ catch (e) {
2460
+ if (isTimeout(e))
2461
+ throw e;
2462
+ }
2463
+ fallback(api, "native");
2464
+ return LOCATOR_NATIVE[name].call(page.locator(selector).first(), options);
2465
+ });
2466
+ page._clearcoteBlur = guarded("locator.blur", blurHuman, "blur");
2467
+ page._clearcoteSelectText = guarded("locator.selectText", selectTextHuman, "selectText");
2468
+ // ------------------------------------------------------------------------- selectOption
2469
+ // Open the drop-down with a click, move its highlight with the planned keys, commit with Enter: one
2470
+ // trusted input+change, the sequence a mouse-and-keyboard user produces. While the popup is open its
2471
+ // keys never reach the page (measured on r37: value unchanged until Enter). The opening click is the
2472
+ // full humanized click -- including the covered-point check -- at the point the hit test proved when
2473
+ // the centre is covered (`at`, a Playwright `position`), so a floating label over the select's centre
2474
+ // cannot swallow it and leave the letters to change a closed select one per key.
1529
2475
  const openAndPick = async (selector, plan, at) => {
1530
- await targetedClick(nativePageClick, selector, at ? { position: at } : {}, false, null);
1531
- await sleep(rand(220, 480)); // the list opens; the eye finds the option
2476
+ // moveOff false: the popup is open now and this sequence owns the pointer until the pick lands.
2477
+ await targetedClick(nativePageClick, selector, at ? { position: at } : {}, false, null, undefined, false);
2478
+ // Every pause here is the persona's (timingTraits.pauseScale): the windows were one fixed set for
2479
+ // every identity.
2480
+ await sleep(pauseMs(persona, 220, 480)); // the list opens; the eye finds the option
2481
+ const pace = timingTraits(persona).pauseScale * tempo; // the persona's deliberation x the preset
1532
2482
  for (const ch of plan.keys) {
1533
- await nativeKbPress(ch, { delay: keyDwell(persona) });
1534
- await sleep(Math.max(40, 100 + gauss() * 35)); // well inside type-ahead's 1 s window
2483
+ await nativeKbPress(ch, { delay: kdwell() });
2484
+ await sleep(Math.max(40, (100 + gauss() * 35) * pace)); // well inside type-ahead's 1 s window
1535
2485
  }
1536
2486
  const n = plan.arrows;
1537
2487
  if (n) {
1538
- await sleep(rand(120, 300));
2488
+ await sleep(pauseMs(persona, 120, 300));
1539
2489
  await arrowRun(n > 0 ? "ArrowDown" : "ArrowUp", Math.abs(n));
1540
2490
  }
1541
- await sleep(rand(150, 400));
2491
+ await sleep(pauseMs(persona, 150, 400));
1542
2492
  await key("Enter");
1543
- await sleep(rand(80, 160));
2493
+ await sleep(pauseMs(persona, 80, 160));
1544
2494
  };
1545
2495
  // `n` presses of an arrow key in an OPEN drop-down. A long run is HELD, the way a person crosses a
1546
2496
  // long list: one press, the keyboard's repeat delay, then auto-repeat at its rate -- Playwright sends
@@ -1548,23 +2498,11 @@ export async function attachHumanize(browser, page, opts) {
1548
2498
  // each, 370 rows took 68 s (verifier B). The open popup takes these keys, so the page sees none of
1549
2499
  // them, only how long the pick took.
1550
2500
  const arrowRun = async (k, n) => {
1551
- if (n < 8 || !nativeKbDown || !nativeKbUp) {
2501
+ if (n < 8) {
1552
2502
  await key(k, n);
1553
2503
  return;
1554
2504
  }
1555
- await nativeKbDown(k);
1556
- try {
1557
- await sleep(rand(380, 560)); // the repeat delay
1558
- const gap = rand(28, 36); // ~30 repeats a second
1559
- for (let j = 0; j < n - 1; j++) {
1560
- await sleep(gap);
1561
- await nativeKbDown(k);
1562
- }
1563
- }
1564
- finally {
1565
- await sleep(rand(20, 60));
1566
- await nativeKbUp(k); // never leave the key down
1567
- }
2505
+ await holdKey(k, null, n); // OS auto-repeat (keys.planRepeat)
1568
2506
  };
1569
2507
  const listboxRow = async (info, i) => {
1570
2508
  if (info.node === undefined)
@@ -1727,15 +2665,19 @@ export async function attachHumanize(browser, page, opts) {
1727
2665
  // (which fails 'interaction-select-change-trust' on clearcotelabs.com/audit).
1728
2666
  if (nativePageSelect) {
1729
2667
  const hselect = async (selector, values, options) => {
2668
+ let why;
1730
2669
  try {
1731
2670
  const res = await selectHumanized(selector, values, options ?? {});
1732
2671
  if (res !== null)
1733
2672
  return res;
2673
+ why = selectWhy(values, options ?? {});
1734
2674
  }
1735
2675
  catch (e) {
1736
2676
  if (isTimeout(e))
1737
2677
  throw e;
2678
+ why = whyOf(e);
1738
2679
  }
2680
+ reportFallback(page, "page.selectOption", why, selector);
1739
2681
  return nativePageSelect(selector, values, options);
1740
2682
  };
1741
2683
  page.selectOption = apiErrors("page.selectOption", (selector, values, options = {}) => locked(() => hselect(selector, values, options)));
@@ -1757,11 +2699,86 @@ export async function attachHumanize(browser, page, opts) {
1757
2699
  }
1758
2700
  if ((await loc.isChecked({ timeout: opts.timeout })) === checked)
1759
2701
  return;
1760
- await targetedClick(nativePageClick, selector, { ...opts }, false, null);
2702
+ // The click lands on the input's box, or on its <label> (labelAim): always for a hidden custom checkbox
2703
+ // (the box click waited for it to show and timed out), 40 % of the time otherwise.
2704
+ let clicked = false;
2705
+ if (!opts.force && !opts.position) {
2706
+ try {
2707
+ const lbox = await labelAim(selector, loc, opts.timeout);
2708
+ clicked = !!lbox && await clickLabel(lbox);
2709
+ }
2710
+ catch (e) {
2711
+ if (isTimeout(e))
2712
+ throw e;
2713
+ clicked = false;
2714
+ }
2715
+ }
2716
+ if (!clicked)
2717
+ await targetedClick(nativePageClick, selector, { ...opts }, false, null);
1761
2718
  if ((await loc.isChecked()) === checked)
1762
2719
  return;
1763
2720
  throw sdkPlaywrightError("Clicking the checkbox did not change its state");
1764
2721
  };
2722
+ // Where a person clicks a checkbox / radio when not on its own box: its <label> (see Python _label_aim).
2723
+ const labelAim = async (selector, loc, timeout) => {
2724
+ const w = worldFor(page);
2725
+ if (await loc.isVisible()) {
2726
+ const box = await boxOf(loc, timeout, false, selector);
2727
+ const info = box ? await describe(box) : null;
2728
+ if (!info || info.node === undefined || info.tag !== "input" || !["checkbox", "radio"].includes(info.type))
2729
+ return null;
2730
+ const lab = await w.callOnNode(info.node, ISO_LABEL_OF);
2731
+ if (!lab || !lab.label || lab.hidden)
2732
+ return null;
2733
+ if (!labelDraw(persona))
2734
+ return null; // the persona's share; THIS click's choice is unseeded
2735
+ // A label that WRAPS its control: ISO_LABEL_OF's text rect is the content clear of the input's box (SC 239 box
2736
+ // probe, 10-17: the first content rect IS the input's box, and taking it for the text put every "label" click on
2737
+ // the input -- lab F_label_visible 0/60, verifier B 0/20). No text left (a label holding only the control), or an
2738
+ // aim box still over the input's box: the input is the only target.
2739
+ if (lab.label.text == null && lab.label.contains)
2740
+ return null;
2741
+ const r = lab.label.text ?? lab.label.rect;
2742
+ if (!(r[2] >= 2 && r[3] >= 2) || boxesOverlap(r, lab.rect))
2743
+ return null;
2744
+ // The click AIMS inside the label's text, but the hit test must be asked about the LABEL ELEMENT's box:
2745
+ // HIT_IN_BOX proves "the node at (x, y) is the element filling box b", and no element fills the text's own
2746
+ // rect. Asked with the text rect it failed on every visible label, so the click went to the input (0 of 20,
2747
+ // verifier B; 0 of 18, the lab; SC 232 triage 10-16).
2748
+ const lr = lab.label.rect;
2749
+ return { x: r[0], y: r[1], width: r[2], height: r[3], hit: { x: lr[0], y: lr[1], width: lr[2], height: lr[3] } };
2750
+ }
2751
+ if (!selector)
2752
+ return null;
2753
+ const lab = await w.evaluate(ISO_LABEL_BY_SEL, { sel: selector });
2754
+ if (!lab || !lab.n || !lab.hidden || !lab.label)
2755
+ return null;
2756
+ try {
2757
+ if ((await page.locator(selector).count()) !== lab.n)
2758
+ return null;
2759
+ }
2760
+ catch {
2761
+ return null;
2762
+ }
2763
+ const r = lab.label.rect;
2764
+ let lbox = { x: r[0], y: r[1], width: r[2], height: r[3] };
2765
+ if (lbox.width < 2 || lbox.height < 2)
2766
+ return null;
2767
+ if (!(await inView(lbox)))
2768
+ lbox = (await scrollWindowTo(lbox)) ?? lbox;
2769
+ return (await inView(lbox)) ? lbox : null;
2770
+ };
2771
+ // One humanized click inside a label's box where the hit test proves the label owns the point.
2772
+ const clickLabel = async (lbox) => {
2773
+ const p = clickPoint(lbox, st, persona);
2774
+ const x = roundHalfEven(p.x), y = roundHalfEven(p.y);
2775
+ await sleep(50);
2776
+ if ((await hitInBox(lbox.hit ?? lbox, x, y)) === false)
2777
+ return false; // the label element's box (labelAim)
2778
+ await glide(x, y);
2779
+ await pressAt(normalizeClickOptions({}));
2780
+ return true;
2781
+ };
1765
2782
  for (const [name, want] of [["check", true], ["uncheck", false]]) {
1766
2783
  if (typeof page[name] === "function") {
1767
2784
  const orig = page[name].bind(page);
@@ -1817,7 +2834,8 @@ export async function attachHumanize(browser, page, opts) {
1817
2834
  }
1818
2835
  for (;;) {
1819
2836
  let why = "element is not visible";
1820
- const box = await boxOf(loc, left(), false, selector); // waits for visible; throws Playwright's timeout
2837
+ // waits for visible; throws Playwright's timeout. No wheel: a trial must not move the pointer.
2838
+ const box = await boxOf(loc, left(), false, selector, false);
1821
2839
  if (box) {
1822
2840
  if (!noClick && !(await loc.isEnabled())) {
1823
2841
  why = "element is not enabled";
@@ -1844,7 +2862,7 @@ export async function attachHumanize(browser, page, opts) {
1844
2862
  // (and, as in Playwright, every wait); `trial` performs NO action: its checks run here (trial), with
1845
2863
  // no pointer move and no press. The caller's `timeout` is passed through unchanged. No Playwright
1846
2864
  // trial runs before a humanized press either (reachesPoint).
1847
- const targetedClick = async (orig, selector, options, noClick, nativeOpts) => {
2865
+ const targetedClick = async (orig, selector, options, noClick, nativeOpts, dwell = undefined, moveOff = true) => {
1848
2866
  const opts = options ?? {};
1849
2867
  const o = normalizeClickOptions(opts);
1850
2868
  let aim = null; // where Playwright's own click lands, once the box is known (native)
@@ -1869,6 +2887,7 @@ export async function attachHumanize(browser, page, opts) {
1869
2887
  };
1870
2888
  if (o.trial)
1871
2889
  return trial(selector, opts, noClick);
2890
+ let why = "the humane route cannot apply";
1872
2891
  try {
1873
2892
  const timeout = opts.timeout; // undefined: the page's default, as Playwright would use
1874
2893
  const loc = page.locator(selector).first();
@@ -1876,10 +2895,10 @@ export async function attachHumanize(browser, page, opts) {
1876
2895
  // native at once instead of timing out first.
1877
2896
  const box = await boxOf(loc, timeout, o.force, selector);
1878
2897
  if (!box)
1879
- throw new NativeSignal();
2898
+ throw new NativeSignal("the element has no box");
1880
2899
  aim = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
1881
2900
  if (!o.force && !(await loc.isEnabled()))
1882
- throw new NativeSignal();
2901
+ throw new NativeSignal("the element is not enabled");
1883
2902
  let x, y;
1884
2903
  if (o.position) {
1885
2904
  ({ x, y } = await positionPoint(box, o.position));
@@ -1898,16 +2917,33 @@ export async function attachHumanize(browser, page, opts) {
1898
2917
  // flight does not) and own the click point -- no trusted press at a point some overlay owns.
1899
2918
  // Either failing goes native: Playwright waits for it.
1900
2919
  await sleep(50);
1901
- if (!(await reachesPoint(box, x, y, selector)))
1902
- throw new NativeSignal();
2920
+ const hit = await reachesPoint(box, x, y, selector);
2921
+ if (hit === false && !o.position) {
2922
+ // The persona's point is covered (a badge, an icon, a floating label over the centre). Before
2923
+ // giving the click to Playwright -- which waited out its timeout on 5-7 of 16 badge-covered
2924
+ // buttons (EVAL B) -- aim at the first probe point the hit test proves reaches the element.
2925
+ const alt = await provenClickPoint(box, selector);
2926
+ if (!alt)
2927
+ throw new NativeSignal("the click point does not reach the element (covered, moving or clipped)");
2928
+ ({ x, y } = alt);
2929
+ aim = { x, y };
2930
+ }
2931
+ else if (!hit)
2932
+ throw new NativeSignal(hit === null ? "the hit test cannot run here"
2933
+ : "the click point does not reach the element (covered, moving or clipped)");
1903
2934
  }
1904
2935
  if (o.modifiers.length && !(nativeKbDown && nativeKbUp))
1905
- throw new NativeSignal();
1906
- if (!noClick && !o.force && orig && engineClicksMode() === "all" && enginePathOk(o) && await engineGlide(x, y, false)) {
1907
- // Opt-in (CLEARCOTE_HUMANIZE_ENGINE_CLICKS=all): the engine walks the approach and clicks the
1908
- // point the hit test above proved; plain left single clicks only, and only while the engine
1909
- // knows where the pointer is (engineInSync). Otherwise: the planner.
1910
- return;
2936
+ throw new NativeSignal("modifiers need keyboard.down");
2937
+ if (!noClick && !o.force && orig && engineModeFor(page, engineClicksMode) === "all") {
2938
+ // Opt-in (engine "all" / CLEARCOTE_HUMANIZE_ENGINE_CLICKS=all): the engine walks the approach and
2939
+ // clicks the point the hit test above proved. A plain left click takes the r42 route (while the engine
2940
+ // knows where the pointer is, engineInSync; an r43 engine re-syncs from the SDK's position, fromX/fromY);
2941
+ // a right / double / modified click takes the r43 extensions, as mouse.click does (engineExtClick,
2942
+ // verifier A's R5). Otherwise: the planner.
2943
+ if (enginePathOk(o) && await engineGlide(x, y, false))
2944
+ return;
2945
+ if (await engineExtClick(x, y, o))
2946
+ return;
1911
2947
  }
1912
2948
  if (noClick && o.modifiers.length) {
1913
2949
  // hover with modifiers: Playwright holds them across the move
@@ -1918,7 +2954,8 @@ export async function attachHumanize(browser, page, opts) {
1918
2954
  held.push(m);
1919
2955
  await sleep(rand(40, 110));
1920
2956
  }
1921
- await glide(x, y);
2957
+ await glide(x, y, { targetW: aimW(box) });
2958
+ await dwellOn(x, y, box, dwell);
1922
2959
  }
1923
2960
  finally {
1924
2961
  for (const m of held.reverse()) {
@@ -1931,20 +2968,32 @@ export async function attachHumanize(browser, page, opts) {
1931
2968
  }
1932
2969
  return;
1933
2970
  }
1934
- await glide(x, y);
1935
- if (!noClick)
2971
+ await glide(x, y, { targetW: aimW(box) });
2972
+ if (noClick) {
2973
+ await dwellOn(x, y, box, dwell); // the hand rests on what it hovered (SC 232 lane C)
2974
+ }
2975
+ else {
1936
2976
  await pressAt(o);
2977
+ if (moveOff)
2978
+ scheduleMoveOff();
2979
+ }
1937
2980
  return;
1938
2981
  }
1939
2982
  catch (e) {
1940
2983
  if (isTimeout(e))
1941
2984
  throw e;
2985
+ why = whyOf(e);
1942
2986
  }
2987
+ reportFallback(page, noClick ? "page.hover" : "page.click", why, selector);
1943
2988
  // outside the try, so a native call that raises is not run a second time by the handler
1944
2989
  return native();
1945
2990
  };
1946
2991
  page.click = apiErrors("page.click", (selector, options = {}) => locked(() => targetedClick(nativePageClick, selector, options, false, null)));
1947
- page.hover = apiErrors("page.hover", (selector, options = {}) => locked(() => targetedClick(nativePageHover, selector, options, true, null)));
2992
+ page.hover = apiErrors("page.hover", (selector, options = {}) => {
2993
+ // `dwell` (ms; 0: none) is the SDK's, not Playwright's: never forwarded to a native hover
2994
+ const { dwell, ...rest } = options ?? {};
2995
+ return locked(() => targetedClick(nativePageHover, selector, rest, true, null, dwell));
2996
+ });
1948
2997
  // Locator.dragTo({ trial: true }) answers its checks here too (see the Locator patch).
1949
2998
  page._clearcoteTrial = (selector, options, noClick) => locked(() => trial(selector, options, noClick));
1950
2999
  // pressAndHold (hold.ts): the hooks it reads off the page. It holds the page lock for the whole hold
@@ -1952,6 +3001,18 @@ export async function attachHumanize(browser, page, opts) {
1952
3001
  // the tremor step: a native move (no glide) that keeps the tracked position where the pointer is.
1953
3002
  page._clearcoteBoxOf = (loc, timeout, selector = null) => boxOf(loc, timeout, false, selector);
1954
3003
  page._clearcotePointer = () => ({ x: st.x, y: st.y });
3004
+ // ... and for its press point: a glide with the box's own Fitts width, the covered-point check (the same
3005
+ // isolated hit test as a click, retried COVER_CHECK_MS), the probe-proven point when the chosen one is
3006
+ // covered, and the border widths that make `position` padding-box relative like click's.
3007
+ page._clearcoteAimGlide = (x, y, box) => glide(x, y, { targetW: aimW(box) });
3008
+ page._clearcoteReachesPoint = reachesPoint;
3009
+ page._clearcoteProvenPoint = provenClickPoint;
3010
+ page._clearcoteBorderOf = async (box) => {
3011
+ const info = await describe(box, null);
3012
+ return info ? [info.bl || 0, info.bt || 0] : [0, 0];
3013
+ };
3014
+ // the frame route (frames.ts) clears a field with the same held chord as the page routes
3015
+ page._clearcoteSelectAll = () => selectAll();
1955
3016
  page._clearcoteNudge = async (x, y) => {
1956
3017
  await nativeMove(x, y);
1957
3018
  st.x = x;
@@ -1960,6 +3021,448 @@ export async function attachHumanize(browser, page, opts) {
1960
3021
  };
1961
3022
  page._clearcoteHold = (loc, o) => locked(() => pressAndHold(loc, o));
1962
3023
  page.pressAndHold = apiErrors("page.pressAndHold", (selector, o) => page._clearcoteHold(page.locator(selector).first(), o));
3024
+ // ------------------------------------------------------------- drags (dragTo / dragAndDrop / dragBy)
3025
+ const peekBox = async (loc, selector) => (await cssPlain(selector)) ? rectBox(await worldFor(page).evaluate(ISO_CSS_BOX, { sel: selector, scroll: false }))
3026
+ : await loc.boundingBox();
3027
+ // The press point inside `box`: Playwright's `position` (padding-box relative, as click), else the
3028
+ // persona's click point. Unless `force`, the hit test must prove it reaches the element (retried like a
3029
+ // click); a covered point tries the probe points; null when nothing reaches it (the caller goes native).
3030
+ const aim = async (box, position, force, selector) => {
3031
+ let x, y;
3032
+ if (position)
3033
+ ({ x, y } = await positionPoint(box, position));
3034
+ else
3035
+ ({ x, y } = clickPoint(box, st, persona));
3036
+ x = roundHalfEven(x);
3037
+ y = roundHalfEven(y);
3038
+ if (force)
3039
+ return [x, y];
3040
+ await sleep(50);
3041
+ const hit = await reachesPoint(box, x, y, selector);
3042
+ if (hit === null || hit)
3043
+ return [x, y];
3044
+ if (position)
3045
+ return null;
3046
+ for (const [fx, fy] of probePoints.slice(1)) {
3047
+ const px = Math.round(box.x + box.width * fx), py = Math.round(box.y + box.height * fy);
3048
+ if ((await hitInBox(box, px, py, selector)) === true)
3049
+ return [px, py];
3050
+ }
3051
+ return null;
3052
+ };
3053
+ const creep = async (from, toward, grabMs) => {
3054
+ const steps = dragHesitation(from, toward, persona, Math.random, grabMs / tempo); // dispatch scales by tempo
3055
+ await dispatch(steps, "drag", 1);
3056
+ if (steps.length) {
3057
+ st.x = steps[steps.length - 1].x;
3058
+ st.y = steps[steps.length - 1].y;
3059
+ }
3060
+ };
3061
+ // Hesitation + the held leg in one walk (motion.ts hesitateThenDrag): inside 8 px of the press for the
3062
+ // persona's grab window (100-300 ms), then the drag leg.
3063
+ const heldDrag = async (from, to, grabMs, settle = true) => {
3064
+ const { steps } = hesitateThenDrag(from, to, persona, grabMs / tempo, settle); // dispatch scales by tempo
3065
+ await dispatch(steps, "drag", 1);
3066
+ st.x = to.x;
3067
+ st.y = to.y;
3068
+ };
3069
+ const locSel = (loc) => { try {
3070
+ return loc._selector ?? null;
3071
+ }
3072
+ catch {
3073
+ return null;
3074
+ } };
3075
+ // The humanized drag of `src` onto `dst` (Locator.dragTo, page.dragAndDrop). Honours sourcePosition /
3076
+ // targetPosition (padding-box relative, like click), force (no hit tests) and timeout; both ends are hit
3077
+ // tested like a click (probe points on a covered end), else NativeSignal: the caller's native fallback.
3078
+ // Before 0.52 the drag used the exact box centres, no hit test, and ignored every option.
3079
+ const drag = async (src, dst, o = {}) => {
3080
+ const timeout = o.timeout;
3081
+ const force = Boolean(o.force);
3082
+ const ssel = locSel(src), dsel = locSel(dst);
3083
+ const sbox = await boxOf(src, timeout, force, ssel);
3084
+ if (!sbox)
3085
+ throw new NativeSignal("the source has no box");
3086
+ const sp = await aim(sbox, o.sourcePosition, force, ssel);
3087
+ if (!sp)
3088
+ throw new NativeSignal("the source point is covered (no probe point reaches it)");
3089
+ if (!(await dst.isVisible())) {
3090
+ if (force)
3091
+ throw new NativeSignal("the target is hidden and force is set");
3092
+ await dst.waitFor({ state: "visible", timeout });
3093
+ }
3094
+ const tbox = await peekBox(dst, dsel);
3095
+ if (!tbox)
3096
+ throw new NativeSignal("the target has no box");
3097
+ let tp = null;
3098
+ if (await inView(tbox)) {
3099
+ tp = await aim(tbox, o.targetPosition, force, dsel);
3100
+ if (!tp)
3101
+ throw new NativeSignal("the target point is covered (no probe point reaches it)");
3102
+ }
3103
+ const { grabMs, releaseMs } = dragDwell(persona);
3104
+ await glide(sp[0], sp[1], { targetW: Math.max(6, Math.min(sbox.width, sbox.height)) });
3105
+ await prePress();
3106
+ st.held = true;
3107
+ try {
3108
+ await nativeDown();
3109
+ if (!tp) {
3110
+ await creep({ x: sp[0], y: sp[1] }, { x: tbox.x + tbox.width / 2, y: tbox.y + tbox.height / 2 }, grabMs);
3111
+ // the drop zone is out of view: the free hand scrolls it in while the other holds
3112
+ const r = await bringIntoView(scrollIO, () => peekBox(dst, dsel));
3113
+ let got = r.box;
3114
+ if (!r.ok || !got) {
3115
+ fallback("locator.dragTo", "scroll into view: target_out_of_view");
3116
+ await dst.scrollIntoViewIfNeeded({ timeout });
3117
+ got = await peekBox(dst, dsel);
3118
+ }
3119
+ if (!got)
3120
+ throw new Error("drag target vanished");
3121
+ const q = o.targetPosition ? await positionPoint(got, o.targetPosition) : clickPoint(got, st, persona);
3122
+ tp = [roundHalfEven(q.x), roundHalfEven(q.y)];
3123
+ await glide(tp[0], tp[1], { settle: true, held: true });
3124
+ }
3125
+ else {
3126
+ await heldDrag({ x: sp[0], y: sp[1] }, { x: tp[0], y: tp[1] }, grabMs);
3127
+ }
3128
+ await sleep(releaseMs);
3129
+ }
3130
+ finally {
3131
+ try {
3132
+ await nativeUp();
3133
+ }
3134
+ finally {
3135
+ st.held = false;
3136
+ }
3137
+ }
3138
+ };
3139
+ const settledRead = async (read) => {
3140
+ let a = await read();
3141
+ for (let i = 0; i < 12; i++) {
3142
+ await sleep(50);
3143
+ const b = await read();
3144
+ if (a && b && Math.abs(a[0] - b[0]) < 0.01 && Math.abs(a[1] - b[1]) < 0.01)
3145
+ return b;
3146
+ a = b;
3147
+ }
3148
+ return a ?? [0, 0];
3149
+ };
3150
+ let dragLegs = 0;
3151
+ // Closed-loop held drag from (px, py), already pressed: hesitate, glide PAST the target by 3-8 px, read
3152
+ // where the dragged thing is, correct up to twice with a settle in between; the achieved delta. Legs 1-3.
3153
+ const dragByCore = async (px, py, dx, dy, read, tol = 2, grabMs) => {
3154
+ const d = Math.hypot(dx, dy);
3155
+ const g = grabMs ?? dragDwell(persona).grabMs;
3156
+ if (d < 0.5) {
3157
+ dragLegs = 0;
3158
+ return settledRead(read);
3159
+ }
3160
+ const ux = dx / d, uy = dy / d;
3161
+ const past = rand(3, 8);
3162
+ await heldDrag({ x: px, y: py }, { x: px + dx + ux * past, y: py + dy + uy * past }, g, false);
3163
+ let legs = 1;
3164
+ let got = [0, 0];
3165
+ for (;;) {
3166
+ await sleep(rand(60, 140));
3167
+ got = await settledRead(read);
3168
+ const ex = dx - got[0], ey = dy - got[1];
3169
+ if (Math.hypot(ex, ey) <= tol || legs >= 3)
3170
+ break;
3171
+ await glide(st.x + ex, st.y + ey, { settle: true, held: true });
3172
+ legs++;
3173
+ }
3174
+ dragLegs = legs;
3175
+ return got;
3176
+ };
3177
+ // locator.dragBy / page.dragBy: press on the element (`position` or the persona's point), drag it by
3178
+ // (dx, dy) closed-loop, release. `read`: returns the achieved [dx, dy] (or the x delta alone); default:
3179
+ // how far the element's own box moved. Resolves to the final achieved { x, y }.
3180
+ const dragBy = async (loc, dx, dy, o = {}) => {
3181
+ const force = Boolean(o.force);
3182
+ const sel = locSel(loc);
3183
+ const box = await boxOf(loc, o.timeout, force, sel);
3184
+ if (!box)
3185
+ throw new Error("dragBy: the element has no box (not rendered)");
3186
+ const p0 = await aim(box, o.position, force, sel);
3187
+ if (!p0)
3188
+ throw new Error("dragBy: another element would receive the press");
3189
+ const c0 = [box.x + box.width / 2, box.y + box.height / 2];
3190
+ const read = async () => {
3191
+ if (o.read) {
3192
+ const v = await o.read();
3193
+ if (v === null || v === undefined)
3194
+ return null;
3195
+ if (typeof v === "number")
3196
+ return [v, 0];
3197
+ return Array.isArray(v) ? [Number(v[0]), Number(v[1])] : [Number(v.x), Number(v.y)];
3198
+ }
3199
+ const b = await peekBox(loc, sel);
3200
+ return b ? [b.x + b.width / 2 - c0[0], b.y + b.height / 2 - c0[1]] : null;
3201
+ };
3202
+ const { grabMs, releaseMs } = dragDwell(persona);
3203
+ await glide(p0[0], p0[1], { targetW: Math.max(6, Math.min(box.width, box.height)) });
3204
+ await prePress();
3205
+ st.held = true;
3206
+ let got;
3207
+ try {
3208
+ await nativeDown();
3209
+ got = await dragByCore(p0[0], p0[1], dx, dy, read, o.tolerance ?? 2, grabMs);
3210
+ page._clearcoteDragLegs = dragLegs;
3211
+ await sleep(releaseMs);
3212
+ }
3213
+ finally {
3214
+ try {
3215
+ await nativeUp();
3216
+ }
3217
+ finally {
3218
+ st.held = false;
3219
+ }
3220
+ }
3221
+ return { x: got[0], y: got[1] };
3222
+ };
3223
+ page._clearcoteDrag = (src, dst, o) => locked(() => drag(src, dst, o));
3224
+ page._clearcoteDragBy = (loc, dx, dy, o) => locked(() => dragBy(loc, dx, dy, o));
3225
+ const nativeDnd = typeof page.dragAndDrop === "function" ? page.dragAndDrop.bind(page) : null;
3226
+ if (nativeDnd) {
3227
+ // page.dragAndDrop, humanized like Locator.dragTo (the first match of each selector; more than one match
3228
+ // goes to the native call, which raises Playwright's strict-mode error).
3229
+ page.dragAndDrop = apiErrors("page.dragAndDrop", (source, target, o = {}) => locked(async () => {
3230
+ if (o?.trial) {
3231
+ for (const [s2, pos] of [[source, o.sourcePosition], [target, o.targetPosition]]) {
3232
+ const t = pickOptions(o, ["force", "timeout"]);
3233
+ if (pos)
3234
+ t.position = pos;
3235
+ await trial(s2, t, true);
3236
+ }
3237
+ return;
3238
+ }
3239
+ let why = null; // more than one match is not a fallback: Playwright raises its strict error
3240
+ try {
3241
+ const src = page.locator(source), dst = page.locator(target);
3242
+ if ((await src.count()) <= 1 && (await dst.count()) <= 1) {
3243
+ await drag(src.first(), dst.first(), o);
3244
+ return;
3245
+ }
3246
+ }
3247
+ catch (e) {
3248
+ if (isTimeout(e) || isStrict(e))
3249
+ throw e;
3250
+ why = whyOf(e);
3251
+ }
3252
+ if (why)
3253
+ reportFallback(page, "page.dragAndDrop", why, source); // lane A: strict throws, onFallback hears it
3254
+ return nativeDnd(source, target, o); // the native fallback site
3255
+ }));
3256
+ }
3257
+ page.dragBy = apiErrors("page.dragBy", (selector, dx, dy, o) => locked(() => dragBy(page.locator(selector).first(), dx, dy, o)));
3258
+ // ------------------------------------------------------------ after-action (SC 232 lane C)
3259
+ // What the hand does once an action has landed (a port of the Python humanizer's): it rests on a hovered
3260
+ // element (dwellOn), drifts off a clicked one (scheduleMoveOff / runMoveOff), and between actions it
3261
+ // reads and idles (attention.ts). All LAZY: run at the start of the next action inside the page lock
3262
+ // (afterRun), or by page.settle(), never from a timer. The seed fixes the persona's traits (motion.afterTraits,
3263
+ // a salted stream: every existing draw keeps its order); every per-action draw is unseeded.
3264
+ // (Function declarations: hoisted, so locked()/targetedClick above can call them.)
3265
+ // Hidden switch for the attention model until lane A's `ambient: "idle"` / `attention` option lands.
3266
+ page._clearcoteAttention = false;
3267
+ // Test seam: what the after-action model did, newest last (bounded).
3268
+ page._clearcoteAfterTrace = af.trace;
3269
+ const wheelInner = mouse.wheel; // the humanized wheel, before the after-action wrapper below
3270
+ // Wrap the UNLOCKED public entry points: mouse.move / wheel run the step first; down / up only mark
3271
+ // activity (a press lands where the pointer is). The locked ones run it inside locked() (afterRun).
3272
+ const unlocked = (fn) => async (...a) => {
3273
+ if (af.depth > 0)
3274
+ return fn(...a);
3275
+ await preAction(true);
3276
+ af.depth++;
3277
+ try {
3278
+ return await fn(...a);
3279
+ }
3280
+ finally {
3281
+ af.depth--;
3282
+ af.lastEnd = Date.now();
3283
+ }
3284
+ };
3285
+ const touch = (fn) => async (...a) => {
3286
+ try {
3287
+ return await fn(...a);
3288
+ }
3289
+ finally {
3290
+ af.lastEnd = Date.now();
3291
+ }
3292
+ };
3293
+ mouse.move = unlocked(mouse.move);
3294
+ mouse.wheel = unlocked(mouse.wheel);
3295
+ mouse.down = touch(mouse.down);
3296
+ mouse.up = touch(mouse.up);
3297
+ // Tell locked() what each public call is (see nextCall): set synchronously, read by the locked() the call
3298
+ // reaches before its first await.
3299
+ const tag = (obj, name, info) => {
3300
+ const fn = obj[name];
3301
+ if (typeof fn !== "function")
3302
+ return;
3303
+ obj[name] = (...a) => { nextCall = info(a); try {
3304
+ return fn(...a);
3305
+ }
3306
+ finally {
3307
+ nextCall = null;
3308
+ } };
3309
+ };
3310
+ tag(mouse, "click", () => ({ coords: true, after: true }));
3311
+ tag(mouse, "dblclick", () => ({ coords: true, after: true }));
3312
+ for (const [name, at] of [["click", 1], ["hover", 1], ["dblclick", 1], ["check", 1], ["uncheck", 1], ["setChecked", 2]]) {
3313
+ tag(page, name, (a) => ({ coords: false, after: !a[at]?.trial }));
3314
+ }
3315
+ tag(page, "_clearcoteTrial", () => ({ coords: false, after: false }));
3316
+ const ambientInner = page.ambientMotion;
3317
+ page.ambientMotion = (ms = 1200) => locked(() => ambientInner(ms));
3318
+ page.settle = () => { nextCall = { coords: false, after: false }; return locked(settleNow); };
3319
+ async function afterRun(fn, o) {
3320
+ if (!o.after || af.depth > 0)
3321
+ return fn();
3322
+ await preAction(o.coords);
3323
+ af.depth++;
3324
+ try {
3325
+ return await fn();
3326
+ }
3327
+ finally {
3328
+ af.depth--;
3329
+ af.lastEnd = Date.now();
3330
+ }
3331
+ }
3332
+ function attentionOn() {
3333
+ return page._clearcoteAttention === true || ambientMode(page) === "idle";
3334
+ }
3335
+ async function dwellOn(x, y, box, dwell) {
3336
+ let ms = null;
3337
+ if (dwell !== undefined && dwell !== null) {
3338
+ const v = Number(dwell);
3339
+ if (Number.isFinite(v)) {
3340
+ if (v <= 0)
3341
+ return;
3342
+ ms = v;
3343
+ }
3344
+ }
3345
+ if (ms === null)
3346
+ ms = dwellMs(persona, af.rng);
3347
+ const steps = planDwell({ x, y }, box, persona, ms, af.rng);
3348
+ af.trace.push(["dwell", ms, steps.length]);
3349
+ trimTrace();
3350
+ await dispatch(steps, "hover");
3351
+ if (steps.length) {
3352
+ st.x = steps[steps.length - 1].x;
3353
+ st.y = steps[steps.length - 1].y;
3354
+ }
3355
+ }
3356
+ function scheduleMoveOff() {
3357
+ const hit = moveOffRoll(persona, af.rng, af.moHits, af.moN);
3358
+ af.moN++;
3359
+ af.mo = null;
3360
+ if (hit) {
3361
+ af.moHits++;
3362
+ af.mo = { due: Date.now() + moveOffDelayMs(persona, af.rng), x: st.x, y: st.y };
3363
+ }
3364
+ }
3365
+ async function runMoveOff(wait) {
3366
+ const mo = af.mo;
3367
+ af.mo = null;
3368
+ if (!mo || st.held || st.x !== mo.x || st.y !== mo.y)
3369
+ return false;
3370
+ const left = mo.due - Date.now();
3371
+ if (left > 0) {
3372
+ if (!wait)
3373
+ return false;
3374
+ await sleep(left);
3375
+ }
3376
+ const vp = (await viewBounds()) ?? (await viewport());
3377
+ const to = planMoveOff({ x: st.x, y: st.y }, vp, persona, af.rng);
3378
+ af.trace.push(["move_off", [st.x, st.y], [to.x, to.y]]);
3379
+ trimTrace();
3380
+ await glide(to.x, to.y, { targetW: 140 }); // one coarse glide: nothing to acquire
3381
+ return true;
3382
+ }
3383
+ async function idleDrift(ms) {
3384
+ af.trace.push(["drift", ms]);
3385
+ trimTrace();
3386
+ const vp = (await viewBounds()) ?? (await viewport());
3387
+ const steps = trimTo(planAmbient({ x: st.x, y: st.y }, vp, persona, ms, af.rng), ms);
3388
+ await dispatch(steps, "ambient");
3389
+ if (steps.length) {
3390
+ st.x = steps[steps.length - 1].x;
3391
+ st.y = steps[steps.length - 1].y;
3392
+ }
3393
+ }
3394
+ async function attend(coords, now) {
3395
+ // `now`: when the action started -- a move-off glide just made does not count as idle time
3396
+ const la = af.loadAt;
3397
+ if (la !== null) {
3398
+ af.loadAt = null;
3399
+ let n = 0;
3400
+ try {
3401
+ n = await worldFor(page).evaluate(ISO_TEXT_LENGTH);
3402
+ }
3403
+ catch {
3404
+ n = 0;
3405
+ }
3406
+ const pause = readPauseMs(n, persona, af.rng);
3407
+ const notches = exploreNotches(af.rng);
3408
+ af.trace.push(["read", pause, n, coords ? 0 : notches]);
3409
+ trimTrace();
3410
+ const left = pause - (now - la);
3411
+ if (left > 350)
3412
+ await idleDrift(Math.min(left * 0.5, IDLE_DRIFT_MAX_MS)); // the eyes read; the hand drifts once
3413
+ const rest = la + pause - Date.now();
3414
+ if (rest > 0)
3415
+ await sleep(rest);
3416
+ // A coordinate action names a point in the current layout: never scroll that away.
3417
+ if (notches && !coords)
3418
+ await wheelInner(0, notches * (await wheelNotchPx()));
3419
+ return;
3420
+ }
3421
+ if (af.lastEnd !== null) {
3422
+ for (const ms of idleDrifts((now - af.lastEnd) / 1000, af.rng))
3423
+ await idleDrift(ms);
3424
+ }
3425
+ }
3426
+ async function preAction(coords) {
3427
+ if (af.depth > 0 || st.held)
3428
+ return;
3429
+ af.depth++;
3430
+ try {
3431
+ const now = Date.now();
3432
+ await runMoveOff(false);
3433
+ if (attentionOn())
3434
+ await attend(coords, now);
3435
+ }
3436
+ catch { /* the after-action model never stops the action */ }
3437
+ finally {
3438
+ af.depth--;
3439
+ }
3440
+ }
3441
+ async function settleNow() {
3442
+ if (af.depth > 0)
3443
+ return false;
3444
+ af.depth++;
3445
+ let done = false;
3446
+ try {
3447
+ done = await runMoveOff(true);
3448
+ }
3449
+ catch {
3450
+ done = false;
3451
+ }
3452
+ finally {
3453
+ af.depth--;
3454
+ }
3455
+ if (done)
3456
+ af.lastEnd = Date.now();
3457
+ return done;
3458
+ }
3459
+ function trimTrace() {
3460
+ if (af.trace.length > 256)
3461
+ af.trace.splice(0, af.trace.length - 256);
3462
+ }
3463
+ // Outermost, after the after-action wrappers: a per-call `humanize: false` goes straight to the stock
3464
+ // call and skips the after-action step too.
3465
+ wirePerCallOff(page, st, stockPage, stockMouse, stockKb);
1963
3466
  // Marker the Locator-class patch keys off: humanize is active for THIS page.
1964
3467
  page._clearcoteHumanized = true;
1965
3468
  patchLocatorClass(page.locator("html"));
@@ -2007,17 +3510,131 @@ export function wantIndex(opts, w) {
2007
3510
  case "valueOnly": return opts.findIndex((o) => o.value === w.v);
2008
3511
  }
2009
3512
  }
3513
+ // --------------------------------------------------------------------------- per-call humanize: false
3514
+ // Every wrapped page / mouse / keyboard / locator method takes { humanize: false } in its options: the stock
3515
+ // Playwright call, the keyword stripped. Wired outermost, after attach has wrapped everything.
3516
+ const PAGE_METHODS = ["click", "hover", "dblclick", "type", "fill", "press", "selectOption", "check", "uncheck", "setChecked", "focus",
3517
+ "dragAndDrop"];
3518
+ const MOUSE_METHODS = ["move", "click", "wheel", "dblclick", "down", "up"];
3519
+ const KB_METHODS = ["type", "press", "down", "up"];
3520
+ /** @internal exported for tests. `fn`, except when its last argument is an options object saying
3521
+ * humanize: false: then `stock`, with the keyword removed (`after` runs once the stock call settles). */
3522
+ const SDK_ONLY_KEYS = ["dwell", "repeat"];
3523
+ export function perCallOff(stock, fn, after) {
3524
+ return function (...a) {
3525
+ const last = a[a.length - 1];
3526
+ if (last && typeof last === "object" && !Array.isArray(last) && Object.prototype.hasOwnProperty.call(last, "humanize")) {
3527
+ const { humanize, ...rest } = last;
3528
+ const args = [...a.slice(0, -1), rest];
3529
+ if (humanize === false) {
3530
+ // the SDK's own keys (hover dwell): Playwright's call takes none of them
3531
+ const stockArgs = [...a.slice(0, -1), Object.fromEntries(Object.entries(rest).filter(([k]) => !SDK_ONLY_KEYS.includes(k)))];
3532
+ // press({ repeat: n }): n stock presses
3533
+ const n = Math.max(1, Math.floor(Number(rest.repeat) || 1));
3534
+ const r = n === 1 ? stock.apply(this, stockArgs)
3535
+ : (async () => { let out; for (let j = 0; j < n; j++)
3536
+ out = await stock.apply(this, stockArgs); return out; })();
3537
+ if (after)
3538
+ return Promise.resolve(r).finally(() => after(args));
3539
+ return r;
3540
+ }
3541
+ return fn.apply(this, args);
3542
+ }
3543
+ return fn.apply(this, a);
3544
+ };
3545
+ }
3546
+ function wirePerCallOff(page, st, stockPage, stockMouse, stockKb) {
3547
+ const placed = () => { st.placed = true; };
3548
+ const moved = (a) => {
3549
+ st.placed = true;
3550
+ if (typeof a[0] === "number" && typeof a[1] === "number") {
3551
+ st.x = a[0];
3552
+ st.y = a[1];
3553
+ }
3554
+ };
3555
+ for (const [n, s] of Object.entries(stockPage)) {
3556
+ if (typeof page[n] === "function")
3557
+ page[n] = perCallOff(s, page[n], ["click", "hover", "dblclick"].includes(n) ? placed : undefined);
3558
+ }
3559
+ const mouse = page.mouse;
3560
+ for (const [n, s] of Object.entries(stockMouse)) {
3561
+ if (typeof mouse[n] !== "function")
3562
+ continue;
3563
+ if (n === "down") {
3564
+ // the stock press, but the held state stays tracked (a later move is a drag leg)
3565
+ mouse[n] = perCallOff(async (...a) => { st.held = true; try {
3566
+ return await s(...a);
3567
+ }
3568
+ catch (e) {
3569
+ st.held = false;
3570
+ throw e;
3571
+ } }, mouse[n]);
3572
+ }
3573
+ else if (n === "up") {
3574
+ mouse[n] = perCallOff(async (...a) => { try {
3575
+ return await s(...a);
3576
+ }
3577
+ finally {
3578
+ st.held = false;
3579
+ } }, mouse[n]);
3580
+ }
3581
+ else {
3582
+ mouse[n] = perCallOff(s, mouse[n], ["move", "click", "dblclick"].includes(n) ? moved : undefined);
3583
+ }
3584
+ }
3585
+ for (const [n, s] of Object.entries(stockKb)) {
3586
+ if (typeof page.keyboard[n] === "function")
3587
+ page.keyboard[n] = perCallOff(s, page.keyboard[n]);
3588
+ }
3589
+ // locator.dragBy({ humanize: false }) drags with these (there is no Playwright dragBy); page.dragBy likewise
3590
+ page._clearcoteStockMouse = { ...stockMouse };
3591
+ if (typeof page.dragBy === "function") {
3592
+ page.dragBy = perCallOff((selector, dx, dy, o) => page.locator(selector).first().dragBy(dx, dy, { ...(o ?? {}), humanize: false }), page.dragBy);
3593
+ }
3594
+ }
3595
+ /** @internal exported for tests. Why selectOption went to Playwright when the humane route returned nothing. */
3596
+ export function selectWhy(values, options) {
3597
+ if (options?.element)
3598
+ return "element handles go to Playwright";
3599
+ for (const v of Array.isArray(values) ? values : [values]) {
3600
+ if (v && typeof v === "object") {
3601
+ if (typeof v.asElement === "function" || /Handle/.test(v.constructor?.name ?? ""))
3602
+ return "element handles go to Playwright";
3603
+ const keys = ["value", "label", "index"].filter((k) => v[k] !== undefined && v[k] !== null);
3604
+ if (keys.length !== 1)
3605
+ return "an option object with several fields goes to Playwright";
3606
+ }
3607
+ }
3608
+ return "no humane route, or the pick could not be shown to have worked";
3609
+ }
3610
+ /** Why a locator on a humanized page is not routed: it enters or lives in a child frame. undefined when
3611
+ * the page is not humanized (not a fallback) or the locator is routable. */
3612
+ function frameWhy(self) {
3613
+ try {
3614
+ const pg = self.page();
3615
+ if (!pg || !pg._clearcoteHumanized)
3616
+ return undefined;
3617
+ if (String(self._selector ?? "").includes("internal:control=enter-frame"))
3618
+ return "frame locators go to Playwright";
3619
+ if (self._frame !== pg.mainFrame())
3620
+ return "a locator in a child frame goes to Playwright";
3621
+ }
3622
+ catch {
3623
+ return undefined;
3624
+ }
3625
+ return undefined;
3626
+ }
2010
3627
  // --------------------------------------------------------------------------- locator patch
2011
3628
  let locatorPatched = false;
2012
3629
  // The options each page-level humanized method understands. Everything the caller passed that a page
2013
3630
  // method accepts travels with it: the old fwd sent ONLY `timeout`, which turned
2014
3631
  // click({button: "right"}) into a left click and click({trial: true}) into a real one.
2015
3632
  const CLICK_OPTS = ["button", "clickCount", "delay", "force", "modifiers", "noWaitAfter", "position", "timeout", "trial"];
2016
- const HOVER_OPTS = ["force", "modifiers", "noWaitAfter", "position", "timeout", "trial"];
3633
+ const HOVER_OPTS = ["force", "modifiers", "noWaitAfter", "position", "timeout", "trial", "dwell"];
2017
3634
  const DBL_OPTS = ["button", "delay", "force", "modifiers", "noWaitAfter", "position", "timeout", "trial"];
2018
3635
  const FILL_OPTS = ["force", "noWaitAfter", "timeout"];
2019
- const TYPE_OPTS = ["timeout"];
2020
- const PRESS_OPTS = ["delay", "noWaitAfter", "timeout"];
3636
+ const TYPE_OPTS = ["delay", "timeout"]; // delay: the shortest gap between two keys (humanized typing)
3637
+ const PRESS_OPTS = ["delay", "noWaitAfter", "timeout", "repeat"]; // repeat: the SDK's OS auto-repeat
2021
3638
  const SELECT_OPTS = ["force", "noWaitAfter", "timeout"];
2022
3639
  const CHECK_OPTS = ["force", "noWaitAfter", "position", "timeout", "trial"];
2023
3640
  /** @internal exported for tests: the subset of `kw` named in `names` (null/undefined dropped). */
@@ -2036,6 +3653,8 @@ export function pickOptions(kw, names) {
2036
3653
  * Playwright's own strict-mode error. Once routed, errors propagate as they are (the page method
2037
3654
  * already ran its own native fallback, so nothing is retried). Composes if another library already
2038
3655
  * patched the prototype. */
3656
+ // Playwright's own Locator methods the humanized blur / selectText fall back to.
3657
+ const LOCATOR_NATIVE = {};
2039
3658
  function patchLocatorClass(sample) {
2040
3659
  if (locatorPatched)
2041
3660
  return;
@@ -2043,7 +3662,9 @@ function patchLocatorClass(sample) {
2043
3662
  const proto = Object.getPrototypeOf(sample);
2044
3663
  if (!proto)
2045
3664
  return;
2046
- const oFill = proto.fill, oClick = proto.click, oType = proto.type, oDbl = proto.dblclick, oHover = proto.hover, oPress = proto.press, oPressSeq = proto.pressSequentially, oClear = proto.clear, oTap = proto.tap, oCheck = proto.check, oUncheck = proto.uncheck, oDragTo = proto.dragTo, oSelectOption = proto.selectOption, oSetChecked = proto.setChecked;
3665
+ const oFill = proto.fill, oClick = proto.click, oType = proto.type, oDbl = proto.dblclick, oHover = proto.hover, oPress = proto.press, oPressSeq = proto.pressSequentially, oClear = proto.clear, oTap = proto.tap, oCheck = proto.check, oUncheck = proto.uncheck, oDragTo = proto.dragTo, oSelectOption = proto.selectOption, oSetChecked = proto.setChecked, oFocus = proto.focus, oBlur = proto.blur, oSelectText = proto.selectText;
3666
+ LOCATOR_NATIVE.blur = oBlur;
3667
+ LOCATOR_NATIVE.selectText = oSelectText;
2047
3668
  // Main-frame locators only: a FrameLocator's child keeps the MAIN frame as its _frame and enters the
2048
3669
  // iframe through its selector, so the selector is what tells. Routed through page.fill, its
2049
3670
  // prefilled field was never cleared ("old" + "new" = "oldnew"); frame locators stay native.
@@ -2075,20 +3696,37 @@ function patchLocatorClass(sample) {
2075
3696
  // Once routed, every error propagates: the page-level wrappers own the native fallback, so retrying
2076
3697
  // the original locator method here ran the action a second (or third) time -- a checkbox whose click
2077
3698
  // is cancelled was clicked three times.
2078
- const route = async (self, fn) => {
3699
+ const route = async (self, fn, frameRouted = true) => {
2079
3700
  if (on(self) && await strict(self))
2080
3701
  return [true, await fn()];
3702
+ // A frame locator: the frame route (froute, lane F) runs next and reports its own fallbacks; only an action
3703
+ // without a frame route (tap) reports here.
3704
+ const why = frameRouted ? null : frameWhy(self);
3705
+ if (why)
3706
+ reportFallback(self.page(), "locator", why, sel(self));
2081
3707
  return [false, undefined];
2082
3708
  };
3709
+ // A locator inside a child frame (FrameLocator, frame.locator) on a humanized page: the frame route (frames.ts:
3710
+ // the frame's own isolated world for the hit test, the page's humanized mouse and keyboard for the input).
3711
+ // [false] when it does not apply -- the native method runs, and the route has reported why.
3712
+ const froute = async (self, action, args, kw) => {
3713
+ if (!(frameHumanized(self.page()) && frameLocatorOf(self)) || !(await strict(self)))
3714
+ return [false, undefined];
3715
+ const r = await frameRoute(self, action, args, kw);
3716
+ return r === NATIVE ? [false, undefined] : [true, r];
3717
+ };
2083
3718
  // Every routed method words its errors as Playwright words the Locator method (asApiError): through
2084
3719
  // page.*, an error read "page.click: ..." or "locator.waitFor: ...".
2085
3720
  const apiMethod = (api, fn) => async function (...a) {
2086
- try {
2087
- return await fn.apply(this, a);
2088
- }
2089
- catch (e) {
2090
- throw asApiError(e, api);
2091
- }
3721
+ const self = this;
3722
+ return withCallerApi(api, async () => {
3723
+ try {
3724
+ return await fn.apply(self, a);
3725
+ }
3726
+ catch (e) {
3727
+ throw asApiError(e, api);
3728
+ }
3729
+ });
2092
3730
  };
2093
3731
  // Playwright's tap rejects at once in a context without hasTouch ("The page does not support tap");
2094
3732
  // routed as a click it clicked instead (SC 210 error parity). A context it cannot read is routed.
@@ -2102,54 +3740,132 @@ function patchLocatorClass(sample) {
2102
3740
  };
2103
3741
  proto.fill = apiMethod("locator.fill", async function (value, kw = {}) {
2104
3742
  const [done, r] = await route(this, () => this.page().fill(sel(this), value, pickOptions(kw, FILL_OPTS)));
2105
- return done ? r : oFill.call(this, value, kw);
3743
+ if (done)
3744
+ return r;
3745
+ const [fdone, fr] = await froute(this, 'fill', [value], kw);
3746
+ return fdone ? fr : oFill.call(this, value, kw);
2106
3747
  });
2107
3748
  proto.click = apiMethod("locator.click", async function (kw = {}) {
2108
3749
  const [done, r] = await route(this, () => this.page().click(sel(this), pickOptions(kw, CLICK_OPTS)));
2109
- return done ? r : oClick.call(this, kw);
3750
+ if (done)
3751
+ return r;
3752
+ const [fdone, fr] = await froute(this, 'click', [], kw);
3753
+ return fdone ? fr : oClick.call(this, kw);
2110
3754
  });
2111
3755
  proto.type = apiMethod("locator.type", async function (text, kw = {}) {
2112
3756
  const [done, r] = await route(this, () => this.page().type(sel(this), text, pickOptions(kw, TYPE_OPTS)));
2113
- return done ? r : oType.call(this, text, kw);
3757
+ if (done)
3758
+ return r;
3759
+ const [fdone, fr] = await froute(this, 'type', [text], kw);
3760
+ return fdone ? fr : oType.call(this, text, kw);
2114
3761
  });
2115
3762
  proto.dblclick = apiMethod("locator.dblclick", async function (kw = {}) {
2116
3763
  const [done, r] = await route(this, () => this.page().dblclick(sel(this), pickOptions(kw, DBL_OPTS)));
2117
- return done ? r : oDbl.call(this, kw);
3764
+ if (done)
3765
+ return r;
3766
+ const [fdone, fr] = await froute(this, 'dblclick', [], kw);
3767
+ return fdone ? fr : oDbl.call(this, kw);
2118
3768
  });
2119
3769
  proto.hover = apiMethod("locator.hover", async function (kw = {}) {
2120
3770
  const [done, r] = await route(this, () => this.page().hover(sel(this), pickOptions(kw, HOVER_OPTS)));
2121
- return done ? r : oHover.call(this, kw);
3771
+ if (done)
3772
+ return r;
3773
+ const [fdone, fr] = await froute(this, 'hover', [], kw);
3774
+ if (fdone)
3775
+ return fr;
3776
+ const { dwell: _dwell, ...pw } = kw ?? {}; // `dwell` is the SDK's: Playwright's own hover does not take it
3777
+ return oHover.call(this, pw);
2122
3778
  });
2123
3779
  proto.press = apiMethod("locator.press", async function (key, kw = {}) {
2124
3780
  const [done, r] = await route(this, () => this.page().press(sel(this), key, pickOptions(kw, PRESS_OPTS)));
2125
- return done ? r : oPress.call(this, key, kw);
3781
+ if (done)
3782
+ return r;
3783
+ // `repeat` is the SDK's (OS auto-repeat on the humanized route); the frame route presses once
3784
+ const { repeat, ...rest } = kw ?? {};
3785
+ const n = Math.max(1, Math.floor(Number(repeat) || 1));
3786
+ if (n === 1) {
3787
+ const [fdone, fr] = await froute(this, 'press', [key], rest);
3788
+ if (fdone)
3789
+ return fr;
3790
+ }
3791
+ let out;
3792
+ for (let j = 0; j < n; j++)
3793
+ out = await oPress.call(this, key, rest); // not humanized: Playwright's own each
3794
+ return out;
2126
3795
  });
3796
+ if (typeof oFocus === "function") {
3797
+ proto.focus = apiMethod("locator.focus", async function (kw = {}) {
3798
+ const [done, r] = await route(this, () => this.page().focus(sel(this), pickOptions(kw, ["timeout"])));
3799
+ return done ? r : oFocus.call(this, kw);
3800
+ });
3801
+ }
3802
+ if (typeof oBlur === "function") {
3803
+ proto.blur = apiMethod("locator.blur", async function (kw = {}) {
3804
+ const fn = this.page()?._clearcoteBlur;
3805
+ if (typeof fn === "function") {
3806
+ const [done, r] = await route(this, () => fn(sel(this), pickOptions(kw, ["timeout"])));
3807
+ if (done)
3808
+ return r;
3809
+ }
3810
+ return oBlur.call(this, kw);
3811
+ });
3812
+ }
3813
+ if (typeof oSelectText === "function") {
3814
+ proto.selectText = apiMethod("locator.selectText", async function (kw = {}) {
3815
+ const fn = this.page()?._clearcoteSelectText;
3816
+ if (typeof fn === "function") {
3817
+ const [done, r] = await route(this, () => fn(sel(this), pickOptions(kw, ["force", "timeout"])));
3818
+ if (done)
3819
+ return r;
3820
+ }
3821
+ return oSelectText.call(this, kw);
3822
+ });
3823
+ }
2127
3824
  proto.pressSequentially = apiMethod("locator.pressSequentially", async function (text, kw = {}) {
2128
3825
  const [done, r] = await route(this, () => this.page().type(sel(this), text, pickOptions(kw, TYPE_OPTS)));
2129
- return done ? r : oPressSeq.call(this, text, kw);
3826
+ if (done)
3827
+ return r;
3828
+ const [fdone, fr] = await froute(this, 'pressSequentially', [text], kw);
3829
+ return fdone ? fr : oPressSeq.call(this, text, kw);
2130
3830
  });
2131
3831
  proto.clear = apiMethod("locator.clear", async function (kw = {}) {
2132
3832
  const [done, r] = await route(this, () => this.page().fill(sel(this), "", pickOptions(kw, FILL_OPTS)));
2133
- return done ? r : oClear.call(this, kw);
3833
+ if (done)
3834
+ return r;
3835
+ const [fdone, fr] = await froute(this, 'clear', [], kw);
3836
+ return fdone ? fr : oClear.call(this, kw);
2134
3837
  });
2135
3838
  proto.tap = apiMethod("locator.tap", async function (kw = {}) {
2136
3839
  if (noTouch(this))
2137
3840
  return oTap.call(this, kw);
2138
- const [done, r] = await route(this, () => this.page().click(sel(this), pickOptions(kw, HOVER_OPTS)));
3841
+ // A touch context: no humanized touch sequence yet, so the tap goes out as the humanized MOUSE click. Lane A's
3842
+ // report: strict mode throws ClearcoteStrictError and nothing is sent; otherwise onFallback hears it.
3843
+ if (on(this))
3844
+ reportFallback(this.page(), "locator.tap", TAP_NOT_HUMANIZED + ": sent as a humanized mouse click", sel(this));
3845
+ const [done, r] = await route(this, () => this.page().click(sel(this), pickOptions(kw, HOVER_OPTS)), false);
2139
3846
  return done ? r : oTap.call(this, kw);
2140
3847
  });
2141
3848
  proto.check = apiMethod("locator.check", async function (kw = {}) {
2142
3849
  const [done, r] = await route(this, () => this.page().check(sel(this), pickOptions(kw, CHECK_OPTS)));
2143
- return done ? r : oCheck.call(this, kw);
3850
+ if (done)
3851
+ return r;
3852
+ const [fdone, fr] = await froute(this, 'check', [], kw);
3853
+ return fdone ? fr : oCheck.call(this, kw);
2144
3854
  });
2145
3855
  proto.uncheck = apiMethod("locator.uncheck", async function (kw = {}) {
2146
3856
  const [done, r] = await route(this, () => this.page().uncheck(sel(this), pickOptions(kw, CHECK_OPTS)));
2147
- return done ? r : oUncheck.call(this, kw);
3857
+ if (done)
3858
+ return r;
3859
+ const [fdone, fr] = await froute(this, 'uncheck', [], kw);
3860
+ return fdone ? fr : oUncheck.call(this, kw);
2148
3861
  });
2149
3862
  if (typeof oSetChecked === "function") {
2150
3863
  proto.setChecked = apiMethod("locator.setChecked", async function (checked, kw = {}) {
2151
3864
  const [done, r] = await route(this, () => this.page().setChecked(sel(this), checked, pickOptions(kw, CHECK_OPTS)));
2152
- return done ? r : oSetChecked.call(this, checked, kw);
3865
+ if (done)
3866
+ return r;
3867
+ const [fdone, fr] = await froute(this, 'setChecked', [checked], kw);
3868
+ return fdone ? fr : oSetChecked.call(this, checked, kw);
2153
3869
  });
2154
3870
  }
2155
3871
  // Delegate to the humanized page.selectOption, like every other method here: one implementation
@@ -2157,7 +3873,10 @@ function patchLocatorClass(sample) {
2157
3873
  if (typeof oSelectOption === "function") {
2158
3874
  proto.selectOption = apiMethod("locator.selectOption", async function (values, kw = {}) {
2159
3875
  const [done, r] = await route(this, () => this.page().selectOption(sel(this), values, pickOptions(kw, SELECT_OPTS)));
2160
- return done ? r : oSelectOption.call(this, values, kw);
3876
+ if (done)
3877
+ return r;
3878
+ const [fdone, fr] = await froute(this, 'selectOption', [values], kw);
3879
+ return fdone ? fr : oSelectOption.call(this, values, kw);
2161
3880
  });
2162
3881
  }
2163
3882
  // New, not a Playwright method: press and hold this element (hold.ts), under the page lock when the
@@ -2182,44 +3901,83 @@ function patchLocatorClass(sample) {
2182
3901
  return;
2183
3902
  }
2184
3903
  }
2185
- if (on(this) && !kw?.trial) {
2186
- try {
2187
- const pg = this.page();
2188
- const sb = await this.boundingBox();
2189
- const tb = await target.boundingBox();
2190
- if (sb && tb) {
2191
- const sx = sb.x + sb.width / 2, sy = sb.y + sb.height / 2;
2192
- const tx = tb.x + tb.width / 2, ty = tb.y + tb.height / 2;
2193
- // Human endpoint dynamics (the two worst slider tells): a grab hesitation AFTER pressing and
2194
- // a settle dwell BEFORE releasing, drawn from the page's motor persona.
2195
- const persona = pg._clearcotePersona;
2196
- const { grabMs, releaseMs } = persona ? dragDwell(persona) : { grabMs: rand(130, 360), releaseMs: rand(90, 230) };
2197
- await pg.mouse.move(sx, sy);
2198
- await pg.mouse.down();
2199
- await sleep(grabMs); // pre-press pause inside down(); then the grab hesitation
2200
- const heldGlide = pg._clearcoteHeldGlide; // humanized held-button drag + seating jiggle (settle)
2201
- if (heldGlide)
2202
- await heldGlide(tx, ty);
2203
- else
2204
- await pg.mouse.move(tx, ty);
2205
- await sleep(releaseMs); // pre-release settle before letting go
2206
- await pg.mouse.up();
3904
+ if (!on(this) && !kw?.trial && frameWhy(this))
3905
+ reportFallback(this.page(), "locator.dragTo", frameWhy(this), sel(this));
3906
+ if (!kw?.trial && on(this) && on(target) && await strict(this) && await strict(target)) {
3907
+ const d = this.page()._clearcoteDrag;
3908
+ if (typeof d === "function") {
3909
+ let why = "the humane drag cannot apply";
3910
+ try {
3911
+ await d(this, target, kw ?? {});
2207
3912
  return;
2208
3913
  }
3914
+ catch (e) {
3915
+ if (isTimeout(e) || isStrict(e))
3916
+ throw e;
3917
+ // a covered end, no CDP, a vanished element: Playwright's own drag (the fallback site)
3918
+ why = whyOf(e);
3919
+ }
3920
+ // lane A's report: strict throws, onFallback hears it; then Playwright's own drag
3921
+ reportFallback(this.page(), "locator.dragTo", why, sel(this));
2209
3922
  }
2210
- catch { /* fall back */ }
2211
3923
  }
2212
3924
  return oDragTo.call(this, target, kw);
2213
3925
  });
3926
+ // New, not a Playwright method: drag this element by (dx, dy) px, closed loop (glide past, read where it
3927
+ // went, correct up to twice); resolves to the achieved { x, y }. Needs a humanized page.
3928
+ proto.dragBy = apiMethod("locator.dragBy", async function (dx, dy, kw) {
3929
+ const fn = this.page()._clearcoteDragBy;
3930
+ if (typeof fn !== "function")
3931
+ throw new Error("dragBy needs humanize: true");
3932
+ return fn(this, dx, dy, kw);
3933
+ });
3934
+ // dragBy({ humanize: false }): there is no Playwright dragBy, so the stock mouse does the plain thing -- press at
3935
+ // `position` (else the box centre), one move by (dx, dy), release -- and the asked delta is returned.
3936
+ const stockDragBy = async function (dx, dy, kw = {}) {
3937
+ const pg = this.page();
3938
+ const m = pg._clearcoteStockMouse ?? {};
3939
+ const b = await this.boundingBox(kw.timeout !== undefined ? { timeout: kw.timeout } : undefined);
3940
+ if (!b)
3941
+ throw new Error("dragBy: the element has no box (not rendered)");
3942
+ const x = b.x + (kw.position ? kw.position.x : b.width / 2), y = b.y + (kw.position ? kw.position.y : b.height / 2);
3943
+ const move = m.move ?? pg.mouse.move.bind(pg.mouse), down = m.down ?? pg.mouse.down.bind(pg.mouse), up = m.up ?? pg.mouse.up.bind(pg.mouse);
3944
+ await move(x, y);
3945
+ await down();
3946
+ try {
3947
+ await move(x + dx, y + dy);
3948
+ }
3949
+ finally {
3950
+ await up();
3951
+ }
3952
+ return { x: dx, y: dy };
3953
+ };
3954
+ // { humanize: false } on any of these: the stock Playwright method, the keyword stripped.
3955
+ const stockOf = {
3956
+ fill: oFill, click: oClick, type: oType, dblclick: oDbl, hover: oHover, press: oPress,
3957
+ pressSequentially: oPressSeq, clear: oClear, tap: oTap, check: oCheck, uncheck: oUncheck, dragTo: oDragTo,
3958
+ selectOption: oSelectOption, setChecked: oSetChecked, focus: oFocus, blur: oBlur, selectText: oSelectText, dragBy: stockDragBy,
3959
+ };
3960
+ for (const [name, stock] of Object.entries(stockOf)) {
3961
+ if (typeof stock === "function" && typeof proto[name] === "function")
3962
+ proto[name] = perCallOff(stock, proto[name]);
3963
+ }
2214
3964
  }
2215
3965
  /** Install humanize/showCursor on a browser: wraps newPage/newContext so every page is covered. */
2216
- export function installHumanize(browser, opts) {
3966
+ export function installHumanize(browser, opts0) {
3967
+ // true | "strict" | HumanizeOptions: validated now (an unknown option throws), resolved once
3968
+ const opts = { ...opts0, humanize: resolveHumanize(opts0.humanize) ?? false };
2217
3969
  if (!opts.humanize && !opts.showCursor)
2218
3970
  return;
2219
3971
  const origNewPage = browser.newPage.bind(browser);
2220
3972
  browser.newPage = async (options) => {
2221
3973
  const page = await origNewPage(options);
2222
3974
  await attachHumanize(browser, page, opts);
3975
+ // browser.newPage makes its context inside Playwright (not through the wrapped newContext below): hook
3976
+ // that implicit context too, so a popup it opens (window.open, target=_blank) is humanized.
3977
+ try {
3978
+ installHumanizeOnContext(page.context(), opts, browser);
3979
+ }
3980
+ catch { /* a page-like object */ }
2223
3981
  return page;
2224
3982
  };
2225
3983
  const origNewContext = browser.newContext.bind(browser);
@@ -2237,14 +3995,19 @@ export function installHumanize(browser, opts) {
2237
3995
  * silently off. attachHumanize needs only the page; the engine route takes the browser from the
2238
3996
  * page's context when there is one and uses the page's own CDP session when there is not (there the
2239
3997
  * engine answers only to the pre-r34 name, POINTER_PATH_LEGACY: one miss per context, measured on r38). */
2240
- export function installHumanizeOnContext(context, opts, browser) {
3998
+ export function installHumanizeOnContext(context, opts0, browser) {
3999
+ const opts = { ...opts0, humanize: resolveHumanize(opts0.humanize) ?? false };
2241
4000
  if (!opts.humanize && !opts.showCursor)
2242
4001
  return;
2243
4002
  const b = browser ?? context.browser();
2244
4003
  if (opts.showCursor) {
2245
4004
  context.addInitScript(CURSOR_OVERLAY).catch(() => { });
2246
4005
  }
2247
- context.on("page", (p) => { attachHumanize(b, p, opts).catch(() => { }); });
4006
+ // One listener per context: a second install (browser.newPage's implicit context, hooked again) adds none.
4007
+ if (context._clearcoteHooked !== true) {
4008
+ context._clearcoteHooked = true;
4009
+ context.on("page", (p) => { attachHumanize(b, p, opts).catch(() => { }); });
4010
+ }
2248
4011
  for (const p of context.pages())
2249
4012
  attachHumanize(b, p, opts).catch(() => { });
2250
4013
  }