Files
Febe/src/Febe.Browser/Gestures/HumanGestures.cs
T
Alby96andClaude Opus 5.5 9941a2fa1f
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
Ricerca dei profili con suggerimenti e foto (#37)
«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono
subito i suggerimenti locali, poi i profili di Instagram con la foto, come
chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram
con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima
il fuoco, legge la risposta della pagina e non clicca mai un risultato.

La ricerca ha una categoria propria nel Governatore, con tetti larghi che
non consumano quelli della raccolta, e si dà il turno con il motore
sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le
foto passano dal CDN con un permesso ciascuna e restano solo in memoria.

Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento
requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in
docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli
search-open e search-box saranno raccolti dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 16:30:03 +01:00

460 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>
/// Presses one key with a human hold time, through <c>Input.dispatchKeyEvent</c>; with a real Shift key down and
/// up around it when the stroke needs Shift. Throws <see cref="GestureInterruptedException"/> while Alberto drives.
/// </summary>
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.
}
}
/// <summary>
/// The gap before the next key while typing: 60–250 ms (median 110) times mood and pace, now and then a short
/// hesitation.
/// </summary>
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);
}
/// <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));
}
}
}