'use strict'; // Human-behavior primitives used by the daemon to make every mouse / keyboard // action look like a real person. Applied by default to click/type/hover/fill/ // scroll/press/drag/... — callers opt out with raw:true when they truly need // robotic precision (e.g. invisible elements, programmatic fills). // // Design: // - All randomness flows through a single PRNG (Math.random by default; a // seeded mulberry32 if a seed is provided). This means nothing in here // reaches for `Math.random` directly — pass `rng()` everywhere. // - All timing distributions are log-normal, not uniform. Real human // key-press intervals and think-times are heavy-tailed. // - Mouse paths are cubic Bézier with perpendicular control-point offsets // plus per-sample Gaussian jitter. Time along the path follows an // ease-in-out curve (slow start, fast middle, slow arrival). // - Never moves to the dead center of a bbox. Lands somewhere inside with // a truncated Gaussian around the center. // - Per-page INPUT STATE (pointer position, held buttons/keys, modifier mask, // keyboard layout) lives in a WeakMap keyed on the Page, so holds persist // across commands, raw-CDP pointer bursts carry the same buttons/modifiers // Playwright's own mouse would, and `release` can undo everything. const layouts = require('./layouts'); const K = require('./keys'); const wheel = require('./wheel'); const inspect = require('./inspect'); const coords = require('./coords'); const timing = require('./timing'); // -------------------------------------------------------------------------- // RNG // -------------------------------------------------------------------------- function mulberry32(seed) { let a = seed >>> 0; return function () { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; } function makeRng(seed) { if (seed == null) return Math.random; const n = Number(seed); if (!Number.isFinite(n)) return Math.random; return mulberry32(Math.trunc(n)); } // Standard Normal via Box–Muller (rejecting the 0-case). function gaussian(rng) { let u = 0, v = 0; while (u === 0) u = rng(); while (v === 0) v = rng(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); } // Log-normal sample with a clamp to avoid absurd tails on UI actions. function logNormal(rng, meanMs, sigma = 0.35, minMs = 10, maxMs = 5000) { const mu = Math.log(meanMs); const x = Math.exp(mu + sigma * gaussian(rng)); return Math.max(minMs, Math.min(maxMs, x)); } /** * Sleep `ms` with sub-millisecond accuracy (see ./timing.js: Node's own timer lands on the OS tick, 15.6 ms on * Windows, and every dwell and gap the page observed was a multiple of it). Use for EVERY wait that is followed by an * input event: settle, dwell, lead/lag, typing delays, wheel gaps, frame pacing, think times. */ const sleep = timing.preciseSleep; /** * Plain setTimeout, for internal polling that does not end in an input event (waiting on page state, overlay refresh, * a verify loop). It rounds up to the timer tick, which is fine there. */ const coarseSleep = timing.coarseSleep; /** Sleep until an absolute epoch-ms deadline (no drift accumulation), precisely. Kept for callers that think in epoch ms. */ function sleepUntil(epochMs) { return timing.preciseSleepUntil(timing.now() + (epochMs - Date.now())); } // -------------------------------------------------------------------------- // Geometry // -------------------------------------------------------------------------- function dist(a, b) { const dx = a.x - b.x, dy = a.y - b.y; return Math.sqrt(dx * dx + dy * dy); } // Cubic Bézier point at t ∈ [0,1]. function bezier(p0, p1, p2, p3, t) { const u = 1 - t; const uu = u * u, uuu = uu * u; const tt = t * t, ttt = tt * t; return { x: uuu * p0.x + 3 * uu * t * p1.x + 3 * u * tt * p2.x + ttt * p3.x, y: uuu * p0.y + 3 * uu * t * p1.y + 3 * u * tt * p2.y + ttt * p3.y, }; } // Build control points perpendicular to the direct line from→to, offset // proportional to distance with Gaussian noise. This gives the mouse a // natural curve instead of a straight line. function buildControlPoints(from, to, rng) { const d = dist(from, to); if (d < 1) return { p1: from, p2: to }; const mx = (from.x + to.x) / 2; const my = (from.y + to.y) / 2; const dx = to.x - from.x, dy = to.y - from.y; // unit perpendicular vector const nx = -dy / d, ny = dx / d; // two control points at ~1/3 and ~2/3 of the line, pushed off-axis const offsetA = (gaussian(rng) * 0.15 + (rng() - 0.5) * 0.25) * d; const offsetB = (gaussian(rng) * 0.15 + (rng() - 0.5) * 0.25) * d; const p1 = { x: from.x + dx / 3 + nx * offsetA + (rng() - 0.5) * 6, y: from.y + dy / 3 + ny * offsetA + (rng() - 0.5) * 6, }; const p2 = { x: from.x + (2 * dx) / 3 + nx * offsetB + (rng() - 0.5) * 6, y: from.y + (2 * dy) / 3 + ny * offsetB + (rng() - 0.5) * 6, }; return { p1, p2 }; } // Family of easing functions. Real human pointing uses different speed // profiles depending on confidence and distance: ease-in-out for deliberate // moves, asymmetric ease-out for short flicks, near-linear for "dragged" // mouse paths. We pick one per call so a detector can't fingerprint a // single velocity profile. function easeInOut(t) { return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; } function easeOut(t) { return 1 - Math.pow(1 - t, 2.5); } function easeLinearish(t) { // near-linear with a mild S bend — sampled closer to a constant-velocity move return 0.85 * t + 0.15 * (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2); } function pickEasing(rng) { const r = rng(); if (r < 0.55) return easeInOut; if (r < 0.85) return easeOut; return easeLinearish; } // Sample the Bézier path into N steps with a randomly-chosen easing plus // jitter. Occasionally inserts a mid-path "hesitation" where the mouse // briefly slows and wobbles — real users do this when the target is // non-obvious or the cursor is on the wrong line. function samplePath(from, to, rng, opts = {}) { const d = dist(from, to); const steps = Math.max(8, Math.min(80, Math.round(d / 14 + 6))); const { p1, p2 } = buildControlPoints(from, to, rng); const easing = opts.easing || pickEasing(rng); // 12% chance of a mid-path hesitation (only for moves > 80px) const hesitate = d > 80 && rng() < 0.12 ? { atT: 0.35 + rng() * 0.3, extraSamples: 3 + Math.floor(rng() * 4) } : null; const path = []; for (let i = 1; i <= steps; i++) { const tLinear = i / steps; const t = easing(tLinear); const pt = bezier(from, p1, p2, to, t); const jitter = 1.2 * (1 - tLinear) + 0.2; pt.x += gaussian(rng) * jitter; pt.y += gaussian(rng) * jitter; pt.pauseMs = 0; path.push(pt); if (hesitate && tLinear >= hesitate.atT && !hesitate.done) { hesitate.done = true; // append a few near-stationary jitter samples before resuming for (let j = 0; j < hesitate.extraSamples; j++) { const last = path[path.length - 1]; path.push({ x: last.x + gaussian(rng) * 1.5, y: last.y + gaussian(rng) * 1.5, pauseMs: 40 + rng() * 90, }); } } } path[path.length - 1] = { x: to.x, y: to.y, pauseMs: 0 }; return { path, steps }; } // Fitts-like total duration for a move of distance `d` to a target of // effective width `w`. Real human pointing is ~150ms for easy targets and // grows log-linearly with d/w. Tuned to feel natural at 1080p. function moveDurationMs(d, w, rng) { const a = 80, b = 90; const width = Math.max(8, w || 20); const idx = Math.log2(d / width + 1); const mean = a + b * idx; return logNormal(rng, mean, 0.22, 40, 1400); } // -------------------------------------------------------------------------- // Per-page input state // -------------------------------------------------------------------------- const BUTTON_BIT = { left: 1, right: 2, middle: 4 }; const INPUT = new WeakMap(); /** * The input state of a page. Created on first use. * pos {x,y} CSS px — where the pointer is, or null until it was placed * buttons Set of held mouse buttons * keys Set of held keys (canonical names; modifiers included) * modifiers Alt=1 Control=2 Meta=4 Shift=8 (what is logically held) * layout active keyboard layout ('en' | 'ru') * plus bookkeeping: lastButton (mirrors Playwright's Mouse), order (press * order, for reverse release), synced (does Playwright's mouse know `pos`), * html5 (the held button started an HTML5 drag: moves must use Playwright's mouse), * dpr (the page's devicePixelRatio when last measured: every pointer coordinate * is snapped to that device-pixel grid, see q()). */ function inputState(page) { let s = INPUT.get(page); if (!s) { s = { pos: null, buttons: new Set(), keys: new Set(), keyDescs: new Map(), modifiers: 0, lastButton: 'none', order: [], synced: false, html5: false, layout: 'en', dpr: null, lastTs: null, // the event-clock stamp (s) of the last coalesced sub-sample sent: the next burst never goes back before it }; INPUT.set(page, s); } return s; } // -------------------------------------------------------------------------- // The device-pixel grid // // A real mouse reports PHYSICAL pixels, so the page sees integer coordinates at // devicePixelRatio 1 and multiples of 1/dpr at any other ratio. Playwright passes // whatever float it is given straight through (measured: mouse.down at (120.43, // 60.29) -> PointerEvent.clientX 120.43000030517578; 16 of 569 pointer coordinates // of a click grid were fractional), and a burst sub-sample rounded to a whole CSS // pixel is off the grid at dpr 1.5 (101 css px = 151.5 device px, unreachable). // So every pointer coordinate the daemon dispatches goes through q(). Touch is // the exception: a digitizer reports sub-pixel positions. // -------------------------------------------------------------------------- /** Snap a CSS-pixel coordinate to the device-pixel grid: round(v * dpr) / dpr (an unknown dpr counts as 1). */ function q(v, dpr) { const d = Number.isFinite(dpr) && dpr > 0 ? dpr : 1; return Math.round(v * d) / d; } /** The dpr noted for this page (1 until a viewport was measured). */ function dprOf(page) { const st = INPUT.get(page); return st && st.dpr > 0 ? st.dpr : 1; } /** Remember the page's devicePixelRatio (ignored when it is not a positive number). */ function noteDpr(page, dpr) { if (Number.isFinite(dpr) && dpr > 0) inputState(page).dpr = dpr; } /** A point snapped to the page's device-pixel grid. */ function snapPoint(page, p) { const d = dprOf(page); return { x: q(p.x, d), y: q(p.y, d) }; } /** Read-only view for `pages` / `state`: where the pointer is and what is still held. */ function inputSnapshot(page) { const st = INPUT.get(page); if (!st) return { pointer: null, held: { buttons: [], keys: [] }, layout: 'en' }; const r1 = (n) => Math.round(n * 10) / 10; return { pointer: st.pos ? { x: r1(st.pos.x), y: r1(st.pos.y) } : null, held: { buttons: [...st.buttons], keys: [...st.keys] }, layout: st.layout, }; } function buttonsMask(set) { let m = 0; for (const b of set) m |= BUTTON_BIT[b] || 0; return m; } function track(st, kind, name) { st.order.push({ kind, name }); } function untrack(st, kind, name) { for (let i = st.order.length - 1; i >= 0; i--) { if (st.order[i].kind === kind && st.order[i].name === name) { st.order.splice(i, 1); return; } } } /** * The REAL viewport, measured fresh on every call (windows can be resized). * `page.viewportSize()` is null here because the context is launched with * `viewport: null`, which used to make everything fall back to 1280x800 while * the actual window was 758x482 (headless) / ~1180x730 (agent windows). * Falls back to an estimate only if the evaluate itself fails (page navigating). */ async function viewportMetrics(page) { try { const m = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight, dpr: window.devicePixelRatio, scrollX: window.scrollX, scrollY: window.scrollY, })); if (m && Number.isFinite(m.width) && Number.isFinite(m.height)) { noteDpr(page, m.dpr); // the pointer grid follows the page's current devicePixelRatio return m; } } catch { /* fall through to the estimate */ } const vs = page.viewportSize(); return { width: vs ? vs.width : 1280, height: vs ? vs.height : 800, dpr: 1, scrollX: 0, scrollY: 0, estimated: true, }; } // Track the mouse's logical position because Playwright's mouse object is // stateless between moves. The first move of a daemon lifetime starts from // a random on-screen point (not 0,0, which is bot-telltale) inside the REAL // viewport. async function getPos(page, rng) { const st = inputState(page); if (st.pos) return st.pos; const r = rng || Math.random; const vp = await viewportMetrics(page); const d = vp.dpr; st.pos = { x: q(Math.round(vp.width * (0.2 + 0.6 * r())), d), y: q(Math.round(vp.height * (0.2 + 0.6 * r())), d), }; st.synced = false; return st.pos; } /** Record where the pointer is (snapped to the device-pixel grid, like everything the daemon dispatches). */ function setPos(page, p) { inputState(page).pos = snapPoint(page, p); } /** Make Playwright's own Mouse aware of the tracked pointer position (a harmless move sample). */ async function syncPointer(page) { const st = inputState(page); if (st.pos && !st.synced) { await page.mouse.move(st.pos.x, st.pos.y, { steps: 1 }); st.synced = true; } } /** * The raw (--raw) coordinate commands' straight move from `from` to `to` in `steps` Playwright moves, every step on the * device-pixel grid (Playwright's own `steps` interpolation is fractional). The pointer state follows. */ async function rawMove(page, from, to, steps = 1) { const d = dprOf(page); const n = Math.max(1, Math.floor(steps)); for (let i = 1; i <= n; i++) { const f = i / n; await page.mouse.move(q(from.x + (to.x - from.x) * f, d), q(from.y + (to.y - from.y) * f, d), { steps: 1 }); } setPos(page, to); inputState(page).synced = true; } // --- CDP-backed coalesced pointer dispatch --------------------------------- // Real mice poll at 125-1000Hz while displays refresh at 60-144Hz, so Chromium // coalesces several raw samples into each dispatched `pointermove`; // `PointerEvent.getCoalescedEvents()` then returns those sub-samples. A path // driven by one *awaited* `page.mouse.move` per point produces exactly ONE // coalesced sub-event every time — a well-known synthetic-input signature — // because each awaited dispatch fully round-trips before the next is sent. // (Empirically verified: awaited Playwright OR awaited raw CDP both yield // length 1; only un-awaited bursts coalesce.) // // We reproduce real coalescing by dispatching each display-frame of motion as // a BURST of sub-samples fired WITHOUT awaiting between them (so they reach the // renderer inside one frame and coalesce), each carrying an explicit, // monotonically-increasing CDP `timestamp` (so the coalesced sub-events have // realistic distinct `timeStamp`s: a real mouse polls 125-1000 Hz, far finer // than a display frame). These sub-samples are the ONLY events that carry an // explicit timestamp; they come from timing.nowSec(), a monotonic clock pinned // to the browser's own, and every discrete event (click, key, wheel, touch) is // left for Chrome to stamp at dispatch, like real input. // This needs a CDP session; if one can't be created we fall back to the // classic per-point awaited dispatch (functionally correct, coalesced len 1). const CDP_SESSIONS = new WeakMap(); async function getCdpSession(page) { const cached = CDP_SESSIONS.get(page); if (cached !== undefined) return cached; // cache null too — don't retry let s = null; try { s = await page.context().newCDPSession(page); } catch { s = null; } CDP_SESSIONS.set(page, s); return s; } // Dispatch one display-frame of motion: K sub-samples interpolated from `prev` // to `p`, fired un-awaited so Chromium coalesces them into a single // `pointermove`. K scales with segment length (faster motion → more coalesced // samples, like real hardware). Sub-sample timestamps come from the monotonic // event clock (timing.nowSec()), spaced by the simulated polling interval, the // last one = now and none later, so the page never sees an event dated in the // future. Sub-sample positions are on the device-pixel grid (q()). // // Every sample carries the page's current input state — `buttons` (pressed // mask), `button` (the last pressed button, else 'none') and `modifiers` — // exactly as patchright's own mouse would stamp them (server/chromium/crInput.js), // so a drag's event stream stays consistent with the Playwright-dispatched // mousedown/mouseup around it. async function dispatchFrameBurst(cdp, st, prev, p, frameDurMs, rng) { const segLen = dist(prev, p); let k = Math.max(1, Math.min(7, Math.round(segLen / 5))); if (k > 2 && rng() < 0.3) k -= 1; // jitter count; keep slow segs low const now = timing.nowSec(); // The sub-samples span (k-1) polling intervals ending at `now`, but never reach back before the previous burst's last // sample (a real mouse's timestamps only go forward, also from one pointermove to the next): when the frame is // shorter than that, the span shrinks and so does k (>= 0.1 ms between samples). let span = (k - 1) * (frameDurMs / k) / 1000; if (st.lastTs != null) span = Math.min(span, Math.max(0, now - st.lastTs - 5e-5)); k = Math.max(1, Math.min(k, Math.floor(span / 1e-4) + 1)); const step = k > 1 ? span / (k - 1) : 0; const buttons = buttonsMask(st.buttons); const dpr = st.dpr; const subs = []; for (let j = 0; j < k; j++) { const f = (j + 1) / k; subs.push({ x: q(prev.x + (p.x - prev.x) * f, dpr), y: q(prev.y + (p.y - prev.y) * f, dpr), ts: j === k - 1 ? now : now - (k - 1 - j) * step, // strictly increasing; the last = now, none later }); } st.lastTs = now; const base = { type: 'mouseMoved', button: buttons ? st.lastButton : 'none', buttons, modifiers: st.modifiers }; if (buttons) base.force = 0.5; // pressure of a held mouse button, like Playwright's moves await Promise.all(subs.map((s) => cdp.send('Input.dispatchMouseEvent', { ...base, x: s.x, y: s.y, timestamp: s.ts, }))); } // Walk a sampled path: one dispatched `pointermove` per point, sleeping // `perStepMs` (jittered) between points. Uses coalesced CDP bursts when a // session is given, else classic awaited single moves through Playwright's // mouse (which an HTML5 drag requires: patchright only intercepts drags // caused by its own mouse). Returns final pos. async function traversePath(page, cdp, fromPoint, path, perStepMs, rng) { const st = inputState(page); let prev = { x: fromPoint.x, y: fromPoint.y }; for (let i = 0; i < path.length; i++) { const p = { x: q(path[i].x, st.dpr), y: q(path[i].y, st.dpr), pauseMs: path[i].pauseMs }; // on the device-pixel grid const frameDur = perStepMs * (1 + (rng() - 0.5) * 0.5); const t0 = timing.now(); if (cdp) { try { await dispatchFrameBurst(cdp, st, prev, p, frameDur, rng); } catch { await page.mouse.move(p.x, p.y, { steps: 1 }); } } else { await page.mouse.move(p.x, p.y, { steps: 1 }); } // Pace on an absolute schedule: the dispatch itself (a CDP / Playwright round trip) counts against the frame. // Hesitation samples carry their own extra pause; the others use the frame time. await timing.preciseSleepUntil(t0 + (p.pauseMs || 0) + frameDur); prev = { x: p.x, y: p.y }; st.pos = { x: p.x, y: p.y }; } return prev; } // Move the mouse along a natural path to (x,y). `targetW` is the effective // size of the target (used for Fitts timing); pass the bbox width when // moving toward an element. // opts.noOvershoot never overshoot-and-correct (drags) // opts.durationScale stretch the Fitts duration (drags are ~1.4x slower) // opts.viaPlaywright force moves through Playwright's mouse async function moveTo(page, x, y, opts = {}) { const rng = opts.rng || Math.random; const st = inputState(page); if (!(st.dpr > 0)) await viewportMetrics(page); // the grid needs the dpr before the first coordinate const from = await getPos(page, rng); const to = { x: q(x, st.dpr), y: q(y, st.dpr) }; // everything dispatched sits on the device-pixel grid const d = dist(from, to); // While a button that started an HTML5 drag is held, EVERY move must go // through Playwright's mouse: its DragManager only intercepts drags caused // by its own moves. Raw CDP moves would start a native OS drag that // delivers no dragenter/dragover/drop (verified empirically). const viaPw = !!opts.viaPlaywright || (st.buttons.size > 0 && st.html5); // Even when already at (or near) target, emit a small idle jitter so // repeat-clicks don't produce an empty-move signature. Cheap and cheap // to skip in raw mode (callers don't call moveTo there). if (d < 2) { const j = 1 + rng() * 3; const ang = rng() * Math.PI * 2; const jitterTo = { x: q(from.x + Math.cos(ang) * j, st.dpr), y: q(from.y + Math.sin(ang) * j, st.dpr) }; await page.mouse.move(jitterTo.x, jitterTo.y, { steps: 1 }); await sleep(20 + rng() * 40); await page.mouse.move(to.x, to.y, { steps: 1 }); setPos(page, to); st.synced = true; return; } const cdp = viaPw ? null : await getCdpSession(page); let durationMs = moveDurationMs(d, opts.targetW || 20, rng); if (opts.durationScale) durationMs *= opts.durationScale; // Optional overshoot: for longer moves, ~20% chance to overshoot the // target slightly then correct back. Never overshoot tiny targets. const doOvershoot = !opts.noOvershoot && d > 120 && opts.targetW > 12 && rng() < 0.2; let primaryTarget = to; let overshootPoint = null; if (doOvershoot) { const overshootMag = 6 + rng() * 18; const dx = (to.x - from.x) / d, dy = (to.y - from.y) / d; overshootPoint = { x: q(to.x + dx * overshootMag + (rng() - 0.5) * 4, st.dpr), y: q(to.y + dy * overshootMag + (rng() - 0.5) * 4, st.dpr), }; primaryTarget = overshootPoint; } const { path, steps } = samplePath(from, primaryTarget, rng); st.synced = false; // raw bursts bypass Playwright's own mouse position await traversePath(page, cdp, from, path, durationMs / steps, rng); if (overshootPoint) { setPos(page, overshootPoint); const { path: corr } = samplePath(overshootPoint, to, rng, { easing: easeOut }); const corrDur = logNormal(rng, 90, 0.25, 60, 220); await traversePath(page, cdp, overshootPoint, corr, corrDur / corr.length, rng); } // Sync Playwright's own mouse position to the final target: the CDP burst // path bypasses Playwright's internal mouse state, so a subsequent // page.mouse.down()/up() (the click) must be re-anchored here or it would // fire at a stale coordinate. The cursor is already at `to` (CDP moved it), // so this trailing move dispatches a harmless final settle sample. if (cdp) { try { await page.mouse.move(to.x, to.y, { steps: 1 }); } catch { /* ignore */ } } st.synced = true; setPos(page, to); } // -------------------------------------------------------------------------- // Held inputs: mouse buttons and modifier keys // // Buttons go through Playwright's page.mouse.down/up (keeps its own Mouse and // DragManager state coherent) and are mirrored into the page's input state. // Modifier keys go through page.keyboard.down/up, so Playwright stamps them // onto its own mouse events, and are mirrored into state.modifiers. // -------------------------------------------------------------------------- async function mouseDown(page, button = 'left', clickCount = 1) { const st = inputState(page); // a physical button cannot be pressed twice: a click needs it UP first if (st.buttons.has(button)) { throw new Error(`the ${button} mouse button is already held on this page (mouse-up it first, or run \`release\`)`); } await syncPointer(page); st.buttons.add(button); st.lastButton = button; // mirrors Playwright's Mouse.down track(st, 'button', button); await page.mouse.down({ button, clickCount }); } async function mouseUp(page, button = 'left', clickCount = 1) { const st = inputState(page); try { await page.mouse.up({ button, clickCount }); } finally { st.buttons.delete(button); st.lastButton = 'none'; // mirrors Playwright's Mouse.up untrack(st, 'button', button); if (st.buttons.size === 0) st.html5 = false; } } /** Press a modifier (Shift/Control/Alt/Meta). Resolves false if it was already held (nothing pressed). */ async function pressModifier(page, name) { const st = inputState(page); if (st.keys.has(name)) return false; st.keys.add(name); st.modifiers |= K.MOD_BITS[name]; track(st, 'key', name); try { await page.keyboard.down(name); } catch (e) { st.keys.delete(name); st.modifiers &= ~K.MOD_BITS[name]; untrack(st, 'key', name); throw e; } return true; } async function releaseModifier(page, name) { const st = inputState(page); try { await page.keyboard.up(name); } finally { st.keys.delete(name); st.modifiers &= ~K.MOD_BITS[name]; untrack(st, 'key', name); } } /** Run an async cleanup, swallowing its errors (used in `finally` blocks). */ async function quietly(fn) { try { await fn(); } catch { /* best effort */ } } // -------------------------------------------------------------------------- // Landing points // -------------------------------------------------------------------------- // Pick a point inside the bbox. For roughly-square targets we use a // Gaussian around the center. For wide elements (buttons, nav links with // text), we widen the X distribution so clicks land across the element // proportionally — approximating where the visible label text is rather // than always dead-center. function pointInBox(box, rng) { const cx = box.x + box.width / 2; const cy = box.y + box.height / 2; // Aspect-aware σ: for wide elements use closer-to-uniform along the long // axis (σ scales up). For ~square elements stay Gaussian. const aspect = box.width / Math.max(1, box.height); const sigmaXFrac = Math.min(0.45, 0.2 + Math.max(0, Math.log2(aspect)) * 0.08); const sigmaYFrac = 0.22; const sx = box.width * sigmaXFrac; const sy = box.height * sigmaYFrac; let x = cx + gaussian(rng) * sx; let y = cy + gaussian(rng) * sy; // keep a small margin from the edges (bigger margin on tall elements) const mx = Math.min(6, Math.max(2, box.width * 0.04)); const my = Math.min(6, Math.max(2, box.height * 0.1)); x = Math.min(box.x + box.width - mx, Math.max(box.x + mx, x)); y = Math.min(box.y + box.height - my, Math.max(box.y + my, y)); return { x, y }; } // The bottom-right corner of a resizable element (a