Strato browser (M0/M2): client CDP con elenco dei comandi ammessi, ChromiumProcessHost e Xvfb sorvegliati, gesti umani, mappa dei bersagli, cattura delle risposte, segnali di arresto, scaricamento dal browser, vista remota, distribuzioni del ritmo; prove unitarie e d'insieme con Chromium su Xvfb; esito locale di S5 e S6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
44 files changed
+8396
No files matched your search
@@ -0,0 +1,381 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Pacing;
|
||||
|
||||
namespace Febe.Browser.Gestures;
|
||||
|
||||
/// <summary>A gesture was not performed because Alberto is using the browser (spec §4.1: the engine stays still).</summary>
|
||||
public sealed class GestureInterruptedException()
|
||||
: OperationCanceledException("Alberto sta usando il browser: il gesto non è stato eseguito.");
|
||||
|
||||
/// <summary>
|
||||
/// Human gestures through <c>Input.*</c> only (spec §6.1, §7.7): never <c>Runtime.evaluate</c> to scroll or click.
|
||||
/// All timing goes through <see cref="IClock"/> and every draw through <see cref="IRandomSource"/>, so tests run
|
||||
/// under a virtual clock with a fixed seed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public sealed class HumanGestures
|
||||
{
|
||||
private readonly ICdpSession _cdp;
|
||||
private readonly IClock _clock;
|
||||
private readonly IRandomSource _random;
|
||||
private readonly Func<bool> _userIsDriving;
|
||||
private int _burstsUntilReading;
|
||||
private PagePoint? _pointer;
|
||||
|
||||
/// <param name="cdp">Page session.</param>
|
||||
/// <param name="clock">Time source for every wait.</param>
|
||||
/// <param name="random">Random source for every draw.</param>
|
||||
/// <param name="mood">Session mood (see <see cref="Distributions.SessionMood"/>), drawn once per session.</param>
|
||||
/// <param name="pace">The «Ritmo dei gesti» slider.</param>
|
||||
/// <param name="userIsDriving">When it returns true, gestures throw <see cref="GestureInterruptedException"/>.</param>
|
||||
/// <param name="settings">Timings; <see cref="GestureSettings.Natural"/> by default.</param>
|
||||
public HumanGestures(
|
||||
ICdpSession cdp,
|
||||
IClock clock,
|
||||
IRandomSource random,
|
||||
double mood = 1.0,
|
||||
GesturePace pace = GesturePace.Natural,
|
||||
Func<bool>? 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; }
|
||||
|
||||
/// <summary>Factor applied to every wait: mood × pace.</summary>
|
||||
public double Multiplier => Mood * GesturePaceFactors.For(Pace);
|
||||
|
||||
/// <summary>Where the pointer is, or null before the first gesture.</summary>
|
||||
public PagePoint? Pointer => _pointer;
|
||||
|
||||
/// <summary>Viewport size in CSS pixels; used to place the pointer before its first move.</summary>
|
||||
public (double Width, double Height) Viewport { get; set; } = (1280, 900);
|
||||
|
||||
/// <summary>Moves the pointer to <paramref name="target"/> along a slightly curved, eased path.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A point inside the central part of <paramref name="box"/>, never its exact centre
|
||||
/// (offsets follow a normal distribution, kept within the central fraction).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Travels to a random point of the central part of <paramref name="box"/>, hovers, presses and releases.</summary>
|
||||
public async Task<PagePoint> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One burst of wheel events (3–8 of 80–140 px, 12–40 ms apart) with decreasing speed: deltas shrink and
|
||||
/// intervals grow. <paramref name="direction"/> is +1 down, -1 up. Returns the pixels requested.
|
||||
/// </summary>
|
||||
public async Task<double> 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);
|
||||
}
|
||||
|
||||
/// <summary>A small scroll back: one or two short wheel events in the opposite direction.</summary>
|
||||
public async Task<double> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<bool> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Scrolls with up to <paramref name="maxBursts"/> bursts, with pauses, reading pauses and occasional small scroll
|
||||
/// backs. After each burst and its pause <paramref name="shouldContinue"/> decides whether to go on (e.g. the
|
||||
/// recipe met known content). Returns the number of bursts.
|
||||
/// </summary>
|
||||
public async Task<int> ScrollAsync(int maxBursts, Func<CancellationToken, ValueTask<bool>>? 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;
|
||||
}
|
||||
|
||||
/// <summary>The wait after a page load before the first gesture (median 2.2 s, 1–6 s).</summary>
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct = default) => WaitAsync(Settings.AfterLoadMs, ct);
|
||||
|
||||
/// <summary>With 8% probability, an extra wait of 15–90 s after an action. Returns true when it happened.</summary>
|
||||
public async Task<bool> MaybeDistractionAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (!_random.Chance(Settings.DistractionProbability))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await WaitAsync(Settings.DistractionMs, ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Waits a drawn time from <paramref name="interval"/> (milliseconds), multiplied by mood and pace.</summary>
|
||||
public async Task<TimeSpan> 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<double> 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);
|
||||
|
||||
/// <summary>Offset in [-limit, limit] around 0, normal with σ = limit/2, never exactly 0.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user