using System.Text.Json.Nodes; using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Pacing; namespace Febe.Browser.Gestures; /// A gesture was not performed because Alberto is using the browser (spec §4.1: the engine stays still). public sealed class GestureInterruptedException() : OperationCanceledException("Alberto sta usando il browser: il gesto non è stato eseguito."); /// /// Human gestures through Input.* only (spec §6.1, §7.7): never Runtime.evaluate to scroll or click. /// All timing goes through and every draw through , so tests run /// under a virtual clock with a fixed seed. /// /// /// Rules: the pointer never jumps (it travels along a slightly curved path at about 60 events per second); /// it lands on a random point in the central part of the target, never the exact centre; every wait is multiplied /// by the session mood and the pace factor. Not thread-safe: one gesture at a time. /// public sealed class HumanGestures { private readonly ICdpSession _cdp; private readonly IClock _clock; private readonly IRandomSource _random; private readonly Func _userIsDriving; private int _burstsUntilReading; private PagePoint? _pointer; /// Page session. /// Time source for every wait. /// Random source for every draw. /// Session mood (see ), drawn once per session. /// The «Ritmo dei gesti» slider. /// When it returns true, gestures throw . /// Timings; by default. public HumanGestures( ICdpSession cdp, IClock clock, IRandomSource random, double mood = 1.0, GesturePace pace = GesturePace.Natural, Func? userIsDriving = null, GestureSettings? settings = null) { _cdp = cdp ?? throw new ArgumentNullException(nameof(cdp)); _clock = clock ?? throw new ArgumentNullException(nameof(clock)); _random = random ?? throw new ArgumentNullException(nameof(random)); if (mood <= 0 || double.IsNaN(mood)) { throw new ArgumentOutOfRangeException(nameof(mood), mood, "The mood must be positive."); } Mood = mood; Pace = pace; _userIsDriving = userIsDriving ?? (static () => false); Settings = settings ?? GestureSettings.Natural; _burstsUntilReading = _random.CountBetween(Settings.BurstsBeforeReading.Min, Settings.BurstsBeforeReading.Max); } public double Mood { get; } public GesturePace Pace { get; } public GestureSettings Settings { get; } /// Factor applied to every wait: mood × pace. public double Multiplier => Mood * GesturePaceFactors.For(Pace); /// Where the pointer is, or null before the first gesture. public PagePoint? Pointer => _pointer; /// Viewport size in CSS pixels; used to place the pointer before its first move. public (double Width, double Height) Viewport { get; set; } = (1280, 900); /// Moves the pointer to along a slightly curved, eased path. public async Task MoveToAsync(PagePoint target, CancellationToken ct = default) { EnsureUserNotDriving(); var start = _pointer ?? InitialPointer(); var distance = start.DistanceTo(target); if (distance < 0.5) { _pointer = target; return; } var duration = Draw(Settings.MoveDurationMs) * Multiplier; var path = BuildPath(start, target); var steps = Math.Max(3, (int)Math.Ceiling(duration / Settings.PointerEventIntervalMs)); var stepDelay = duration / steps; // Plan the events first: a step that does not change pixel sends nothing (a mouse that does not move // fires no event) and its time is added to the next event; the still tail at the end is dropped, so the // movement ends with its last visible event. var plan = new List<(double DelayMs, PagePoint At)>(steps); var pending = 0.0; var last = new PagePoint(Math.Round(start.X), Math.Round(start.Y)); for (var i = 1; i <= steps; i++) { pending += stepDelay * _random.Between(0.85, 1.15); var p = i == steps ? target : path.At(EaseInOut((double)i / steps)); var rounded = new PagePoint(Math.Round(p.X), Math.Round(p.Y)); if (rounded == last) { continue; } plan.Add((pending, rounded)); pending = 0; last = rounded; } foreach (var (delay, at) in plan) { await _clock.Delay(TimeSpan.FromMilliseconds(delay), ct).ConfigureAwait(false); EnsureUserNotDriving(); await DispatchMouseAsync("mouseMoved", at, "none", buttons: 0, clickCount: 0, ct).ConfigureAwait(false); _pointer = at; } _pointer = target; } /// /// A point inside the central part of , never its exact centre /// (offsets follow a normal distribution, kept within the central fraction). /// public PagePoint ChooseTargetPoint(PageRect box) { var half = Settings.CentralFraction / 2; var dx = DrawOffset(half) * box.Width; var dy = DrawOffset(half) * box.Height; if (Math.Abs(dx) < 1 && Math.Abs(dy) < 1) { // Never the exact centre: nudge by at least one pixel when the box allows it. dx = Math.Min(box.Width * half, 1 + (box.Width * 0.05)) * (_random.Chance(0.5) ? 1 : -1); } var center = box.Center; return new PagePoint(center.X + dx, center.Y + dy); } /// Travels to a random point of the central part of , hovers, presses and releases. public async Task ClickAsync(PageRect box, CancellationToken ct = default) { var point = ChooseTargetPoint(box); await MoveToAsync(point, ct).ConfigureAwait(false); var at = new PagePoint(Math.Round(point.X), Math.Round(point.Y)); await WaitAsync(Settings.HoverMs, ct).ConfigureAwait(false); EnsureUserNotDriving(); await DispatchMouseAsync("mousePressed", at, "left", buttons: 1, clickCount: 1, ct).ConfigureAwait(false); await WaitAsync(Settings.PressMs, ct).ConfigureAwait(false); await DispatchMouseAsync("mouseReleased", at, "left", buttons: 0, clickCount: 1, ct).ConfigureAwait(false); return at; } /// /// One burst of wheel events (3–8 of 80–140 px, 12–40 ms apart) with decreasing speed: deltas shrink and /// intervals grow. is +1 down, -1 up. Returns the pixels requested. /// public async Task ScrollBurstAsync(int direction = 1, CancellationToken ct = default) { EnsureUserNotDriving(); var count = _random.CountBetween(Settings.WheelEventsPerBurst.Min, Settings.WheelEventsPerBurst.Max); var deltas = Enumerable.Range(0, count).Select(_ => Math.Round(Draw(Settings.WheelDeltaPx))).OrderByDescending(d => d).ToArray(); var intervals = Enumerable.Range(0, count - 1).Select(_ => Draw(Settings.WheelIntervalMs) * Multiplier).Order().ToArray(); return await WheelAsync(deltas, intervals, Math.Sign(direction == 0 ? 1 : direction), ct).ConfigureAwait(false); } /// A small scroll back: one or two short wheel events in the opposite direction. public async Task ScrollBackAsync(int direction = 1, CancellationToken ct = default) { EnsureUserNotDriving(); var count = _random.Chance(0.5) ? 1 : 2; var deltas = Enumerable.Range(0, count).Select(_ => Math.Round(Draw(Settings.ScrollBackDeltaPx))).OrderByDescending(d => d).ToArray(); var intervals = Enumerable.Range(0, count - 1).Select(_ => Draw(Settings.WheelIntervalMs) * Multiplier).Order().ToArray(); return await WheelAsync(deltas, intervals, -Math.Sign(direction == 0 ? 1 : direction), ct).ConfigureAwait(false); } /// /// The pause after a burst: normally 0.4–4 s (median 1.1 s); every 6–10 bursts a reading pause of 3–20 s (median 6 s). /// Returns true when it was a reading pause. /// public async Task PauseAfterBurstAsync(CancellationToken ct = default) { if (--_burstsUntilReading <= 0) { _burstsUntilReading = _random.CountBetween(Settings.BurstsBeforeReading.Min, Settings.BurstsBeforeReading.Max); await WaitAsync(Settings.ReadingPauseMs, ct).ConfigureAwait(false); return true; } await WaitAsync(Settings.BetweenBurstsMs, ct).ConfigureAwait(false); return false; } /// /// Scrolls with up to bursts, with pauses, reading pauses and occasional small scroll /// backs. After each burst and its pause decides whether to go on (e.g. the /// recipe met known content). Returns the number of bursts. /// public async Task ScrollAsync(int maxBursts, Func>? shouldContinue = null, int direction = 1, CancellationToken ct = default) { var bursts = 0; while (bursts < maxBursts) { await ScrollBurstAsync(direction, ct).ConfigureAwait(false); bursts++; if (_random.Chance(Settings.ScrollBackProbability)) { await WaitAsync(new Interval(150, 600), ct).ConfigureAwait(false); await ScrollBackAsync(direction, ct).ConfigureAwait(false); } await PauseAfterBurstAsync(ct).ConfigureAwait(false); if (shouldContinue is not null && !await shouldContinue(ct).ConfigureAwait(false)) { break; } } return bursts; } /// The wait after a page load before the first gesture (median 2.2 s, 1–6 s). public Task WaitAfterLoadAsync(CancellationToken ct = default) => WaitAsync(Settings.AfterLoadMs, ct); /// With 8% probability, an extra wait of 15–90 s after an action. Returns true when it happened. public async Task MaybeDistractionAsync(CancellationToken ct = default) { if (!_random.Chance(Settings.DistractionProbability)) { return false; } await WaitAsync(Settings.DistractionMs, ct).ConfigureAwait(false); return true; } /// /// Presses one key with a human hold time, through Input.dispatchKeyEvent; with a real Shift key down and /// up around it when the stroke needs Shift. Throws while Alberto drives. /// public async Task PressKeyAsync(KeyStroke key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); EnsureUserNotDriving(); var shift = (key.Modifiers & KeyModifiers.Shift) != 0; var shiftKey = new KeyStroke("Shift", "ShiftLeft", 16, KeyModifiers.Shift, null); var shiftDown = false; var keyDown = false; try { if (shift) { shiftDown = true; await Keyboard.KeyDownAsync(_cdp, shiftKey, ct).ConfigureAwait(false); await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(30, 90))), ct).ConfigureAwait(false); } keyDown = true; await Keyboard.KeyDownAsync(_cdp, key, ct).ConfigureAwait(false); await _clock.Delay(TimeSpan.FromMilliseconds(Draw(Settings.KeyHoldMs)), ct).ConfigureAwait(false); await Keyboard.KeyUpAsync(_cdp, key, ct).ConfigureAwait(false); keyDown = false; if (shift) { await _clock.Delay(TimeSpan.FromMilliseconds(Draw(new Interval(20, 70))), ct).ConfigureAwait(false); await Keyboard.KeyUpAsync(_cdp, shiftKey with { Modifiers = KeyModifiers.None }, ct).ConfigureAwait(false); shiftDown = false; } } finally { // A cancelled step never leaves a key or Shift down in the page, which goes to the engine or to Alberto next. if (keyDown || shiftDown) { await ReleaseQuietlyAsync(keyDown ? key : null, shiftDown ? shiftKey with { Modifiers = KeyModifiers.None } : null).ConfigureAwait(false); } } } private async Task ReleaseQuietlyAsync(KeyStroke? key, KeyStroke? shiftKey) { try { if (key is not null) { await Keyboard.KeyUpAsync(_cdp, key, CancellationToken.None).ConfigureAwait(false); } if (shiftKey is not null) { await Keyboard.KeyUpAsync(_cdp, shiftKey, CancellationToken.None).ConfigureAwait(false); } } catch (Exception ex) when (ex is not OutOfMemoryException) { // The browser is gone or restarting: no key stays down in a page that no longer exists. } } /// /// The gap before the next key while typing: 60–250 ms (median 110) times mood and pace, now and then a short /// hesitation. /// public async Task TypingGapAsync(CancellationToken ct = default) { var gap = Draw(Settings.KeyGapMs); if (_random.Chance(Settings.TypingHesitationProbability)) { gap += Draw(Settings.TypingHesitationMs); } await _clock.Delay(TimeSpan.FromMilliseconds(gap * Multiplier), ct).ConfigureAwait(false); } /// Waits a drawn time from (milliseconds), multiplied by mood and pace. public async Task WaitAsync(Interval interval, CancellationToken ct = default) { var wait = TimeSpan.FromMilliseconds(Draw(interval) * Multiplier); await _clock.Delay(wait, ct).ConfigureAwait(false); return wait; } private async Task WheelAsync(double[] deltas, double[] intervals, int sign, CancellationToken ct) { if (_pointer is not { } at) { // The page has never seen the pointer: it enters where the mouse rests, as when it enters the window. at = InitialPointer(); await DispatchMouseAsync("mouseMoved", at, "none", buttons: 0, clickCount: 0, ct).ConfigureAwait(false); await WaitAsync(new Interval(120, 500), ct).ConfigureAwait(false); } var position = new PagePoint(Math.Round(at.X), Math.Round(at.Y)); double total = 0; for (var i = 0; i < deltas.Length; i++) { if (i > 0) { await _clock.Delay(TimeSpan.FromMilliseconds(intervals[i - 1]), ct).ConfigureAwait(false); } EnsureUserNotDriving(); await _cdp.SendAsync( "Input.dispatchMouseEvent", new JsonObject { ["type"] = "mouseWheel", ["x"] = position.X, ["y"] = position.Y, ["deltaX"] = 0, ["deltaY"] = sign * deltas[i], ["pointerType"] = "mouse", }, ct).ConfigureAwait(false); total += deltas[i]; } return sign * total; } private Task DispatchMouseAsync(string type, PagePoint at, string button, int buttons, int clickCount, CancellationToken ct) { var parameters = new JsonObject { ["type"] = type, ["x"] = at.X, ["y"] = at.Y, ["button"] = button, ["buttons"] = buttons, ["pointerType"] = "mouse", }; if (clickCount > 0) { parameters["clickCount"] = clickCount; } return _cdp.SendAsync("Input.dispatchMouseEvent", parameters, ct); } private void EnsureUserNotDriving() { if (_userIsDriving()) { throw new GestureInterruptedException(); } } private PagePoint InitialPointer() { // Somewhere in the middle of the page, as if the mouse had been left there. var x = Viewport.Width * _random.Between(0.35, 0.65); var y = Viewport.Height * _random.Between(0.35, 0.65); var p = new PagePoint(Math.Round(x), Math.Round(y)); _pointer = p; return p; } private double Draw(Interval interval) => _random.Between(interval.Min, interval.Max, interval.Median); /// Offset in [-limit, limit] around 0, normal with σ = limit/2, never exactly 0. private double DrawOffset(double limit) { for (var attempt = 0; attempt < 16; attempt++) { var value = _random.Normal(0, limit / 2); if (Math.Abs(value) <= limit) { return value; } } return limit / 3; } private BezierPath BuildPath(PagePoint start, PagePoint end) { var dx = end.X - start.X; var dy = end.Y - start.Y; var length = Math.Sqrt((dx * dx) + (dy * dy)); var nx = -dy / length; var ny = dx / length; // An arc most of the time, an S now and then; both bends are a small fraction of the distance. var side = _random.Chance(0.5) ? 1 : -1; var bend1 = Draw(Settings.PathBendFraction) * length * side; var bend2 = Draw(Settings.PathBendFraction) * length * (_random.Chance(0.8) ? side : -side); var t1 = _random.Between(0.2, 0.4); var t2 = _random.Between(0.6, 0.8); var c1 = new PagePoint(start.X + (dx * t1) + (nx * bend1), start.Y + (dy * t1) + (ny * bend1)); var c2 = new PagePoint(start.X + (dx * t2) + (nx * bend2), start.Y + (dy * t2) + (ny * bend2)); return new BezierPath(start, c1, c2, end); } /// /// Ease-in-out with the minimum-jerk profile of human reaching movements (10t³ − 15t⁴ + 6t⁵): /// slow start, slow arrival, peak speed 1.875 times the average. /// internal static double EaseInOut(double t) => t * t * t * (10 + (t * ((6 * t) - 15))); private readonly record struct BezierPath(PagePoint P0, PagePoint P1, PagePoint P2, PagePoint P3) { public PagePoint At(double t) { var u = 1 - t; var a = u * u * u; var b = 3 * u * u * t; var c = 3 * u * t * t; var d = t * t * t; return new PagePoint( (a * P0.X) + (b * P1.X) + (c * P2.X) + (d * P3.X), (a * P0.Y) + (b * P1.Y) + (c * P2.Y) + (d * P3.Y)); } } }