Ricerca dei profili con suggerimenti e foto (#37)
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped

«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>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:30:03 +01:00
1 parent 5e417c666d
commit 9941a2fa1f
98 files changed
+8021 -229

No files matched your search

+66 -3
View File
@@ -54,6 +54,7 @@ public sealed record ResponseTapStats(long Responses, long JsonBodies, long Body
/// </remarks>
public sealed class ResponseTap : IAsyncDisposable
{
private const int MaxRequestOrders = 4096;
private static readonly JsonDocumentOptions BodyOptions = new() { MaxDepth = 256 };
private readonly ICdpSession _cdp;
@@ -68,6 +69,8 @@ public sealed class ResponseTap : IAsyncDisposable
private readonly Channel<PendingBody> _queue = Channel.CreateUnbounded<PendingBody>(new UnboundedChannelOptions { SingleReader = true });
private readonly CancellationTokenSource _lifetime = new();
private readonly List<IDisposable> _subscriptions = [];
private readonly Dictionary<string, long> _requestOrders = new(StringComparer.Ordinal);
private long _requestCounter;
private Task? _worker;
private volatile string? _mainFrameId;
private long _responses;
@@ -137,6 +140,7 @@ public sealed class ResponseTap : IAsyncDisposable
throw new InvalidOperationException("La cattura è già avviata.");
}
_subscriptions.Add(_cdp.On("Network.requestWillBeSent", OnRequestWillBeSent));
_subscriptions.Add(_cdp.On("Network.responseReceived", OnResponseReceived));
_subscriptions.Add(_cdp.On("Network.loadingFinished", OnLoadingFinished));
_subscriptions.Add(_cdp.On("Network.loadingFailed", OnLoadingFailed));
@@ -216,6 +220,51 @@ public sealed class ResponseTap : IAsyncDisposable
});
}
/// <summary>
/// The page starts a request: a site request gets its order (issue #37), kept until its response. Only the host
/// kind of the address is looked at; nothing of the request is kept or logged.
/// </summary>
private void OnRequestWillBeSent(JsonElement p)
{
if (p.ValueKind != JsonValueKind.Object
|| !p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId
|| !p.TryGetProperty("request", out var request) || request.ValueKind != JsonValueKind.Object)
{
return;
}
var url = request.TryGetProperty("url", out var u) ? u.GetString() : null;
if (_hosts.Classify(url) != HostKind.Site)
{
return;
}
var order = Interlocked.Increment(ref _requestCounter);
lock (_requestOrders)
{
if (_requestOrders.Count >= MaxRequestOrders)
{
// Requests whose response never came: their order is forgotten, and their answers count by arrival.
_requestOrders.Clear();
}
// A redirect starts the same request again: the later order holds.
_requestOrders[requestId] = order;
}
foreach (var observer in SnapshotObservers())
{
try
{
observer.OnRequestStarted(order);
}
catch (Exception ex)
{
_log.Warn("Cattura: errore in un osservatore delle richieste.", ex);
}
}
}
private void OnResponseReceived(JsonElement p)
{
if (p.ValueKind != JsonValueKind.Object || !p.TryGetProperty("requestId", out var idElement) || !p.TryGetProperty("response", out var response))
@@ -245,7 +294,8 @@ public sealed class ResponseTap : IAsyncDisposable
mime,
type,
isMainDocument,
_clock.Now);
_clock.Now,
TakeRequestOrder(requestId));
Interlocked.Increment(ref _responses);
foreach (var observer in SnapshotObservers())
@@ -271,6 +321,14 @@ public sealed class ResponseTap : IAsyncDisposable
}
}
private long TakeRequestOrder(string requestId)
{
lock (_requestOrders)
{
return _requestOrders.Remove(requestId, out var order) ? order : 0;
}
}
private void OnLoadingFinished(JsonElement p)
{
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
@@ -297,8 +355,13 @@ public sealed class ResponseTap : IAsyncDisposable
private void OnLoadingFailed(JsonElement p)
{
if (p.TryGetProperty("requestId", out var idElement) && idElement.GetString() is { } requestId
&& _inFlight.TryRemove(requestId, out _))
if (!p.TryGetProperty("requestId", out var idElement) || idElement.GetString() is not { } requestId)
{
return;
}
TakeRequestOrder(requestId);
if (_inFlight.TryRemove(requestId, out _))
{
NotifyDropped(requestId, BodyDropReason.LoadingFailed);
}
@@ -79,4 +79,16 @@ public sealed record GestureSettings
/// <summary>Length of a distraction.</summary>
public Interval DistractionMs { get; init; } = new(15000, 90000);
/// <summary>Gap between two keys while typing (issue #37), before mood and pace.</summary>
public Interval KeyGapMs { get; init; } = new(60, 250, 110);
/// <summary>How long a key is held down.</summary>
public Interval KeyHoldMs { get; init; } = new(40, 120);
/// <summary>Probability of a short hesitation before a key, as a person who thinks of the next letter.</summary>
public double TypingHesitationProbability { get; init; } = 0.03;
/// <summary>Length of such a hesitation, before mood and pace.</summary>
public Interval TypingHesitationMs { get; init; } = new(300, 900);
}
@@ -239,6 +239,84 @@ public sealed class HumanGestures
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)
{
+48
View File
@@ -0,0 +1,48 @@
using System.Globalization;
namespace Febe.Browser.Gestures;
/// <summary>
/// The closed key map of the profile search (issue #37): the only characters Febe may type into the site's search
/// box, each with its full key stroke. Letters a–z, digits, «.», «_» (Shift and Minus, with a real Shift key) and the
/// space. There is no path to Enter, Tab or Escape: <see cref="Keyboard.ForText"/>, which maps a line break to Enter,
/// is never used by the search.
/// </summary>
public static class SearchKeyMap
{
/// <summary>The stroke for <paramref name="c"/>, or null when the search may not type it.</summary>
public static KeyStroke? For(char c)
{
var text = c.ToString(CultureInfo.InvariantCulture);
return c switch
{
>= 'a' and <= 'z' => new KeyStroke(text, "Key" + char.ToUpperInvariant(c).ToString(CultureInfo.InvariantCulture), char.ToUpperInvariant(c), KeyModifiers.None, text),
>= '0' and <= '9' => new KeyStroke(text, "Digit" + text, c, KeyModifiers.None, text),
'.' => new KeyStroke(".", "Period", 190, KeyModifiers.None, "."),
'_' => new KeyStroke("_", "Minus", 189, KeyModifiers.Shift, "_"),
' ' => new KeyStroke(" ", "Space", 32, KeyModifiers.None, " "),
_ => null,
};
}
/// <summary>True when every character of <paramref name="text"/> is in the map.</summary>
public static bool CanType(string text)
{
ArgumentNullException.ThrowIfNull(text);
foreach (var c in text)
{
if (For(c) is null)
{
return false;
}
}
return true;
}
/// <summary>Backspace: the only key the search uses to erase.</summary>
public static KeyStroke Backspace { get; } = Keyboard.Special(SpecialKey.Backspace);
/// <summary>End: the only key the search uses to move the caret.</summary>
public static KeyStroke End { get; } = Keyboard.Special(SpecialKey.End);
}
+52 -1
View File
@@ -38,7 +38,12 @@ public sealed record BrowserDriverOptions
/// read-only state with <c>Runtime.evaluate</c>, targets found with the target map and clicked with human gestures
/// through <c>Input</c>, wheel bursts, and the rest page. It never opens an address outside the site.
/// </summary>
public sealed class BrowserPageDriver : IPageDriver
/// <remarks>
/// As <see cref="ISearchInput"/> it types into the site's search box for the profile search (issue #37): the focus
/// check is one read-only <c>Runtime.evaluate</c> that never returns the text, and keys come only from the closed
/// <see cref="SearchKeyMap"/>.
/// </remarks>
public sealed class BrowserPageDriver : IPageDriver, ISearchInput
{
/// <summary>Read-only: the page has loaded and painted (input before the first paint is ignored by Chromium).</summary>
private const string ReadyExpression =
@@ -190,6 +195,52 @@ public sealed class BrowserPageDriver : IPageDriver
public Task RestAsync(CancellationToken ct) => _cdp.RestAsync(ct);
public async Task<SearchFocus> FocusAsync(CancellationToken ct)
{
var (found, focused, length, atEnd) = await _resolver.FocusAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
return found ? new SearchFocus(true, focused, length, atEnd) : SearchFocus.None;
}
public Task EndKeyAsync(CancellationToken ct) => _gestures.PressKeyAsync(SearchKeyMap.End, ct);
public async Task EraseAsync(int count, Action? beforeKey, CancellationToken ct)
{
for (var i = 0; i < count; i++)
{
if (i > 0)
{
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
}
beforeKey?.Invoke();
await _gestures.PressKeyAsync(SearchKeyMap.Backspace, ct).ConfigureAwait(false);
}
}
public async Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(next);
var typed = 0;
while (true)
{
if (typed > 0)
{
await _gestures.TypingGapAsync(ct).ConfigureAwait(false);
}
// The checks of the caller run right before the key they allow.
if (await next(typed, ct).ConfigureAwait(false) is not { } c)
{
return typed;
}
// A second line behind the text rules of Core: a character outside the map is never sent.
var stroke = SearchKeyMap.For(c) ?? throw new ArgumentException("Carattere che la ricerca non scrive.", nameof(next));
await _gestures.PressKeyAsync(stroke, ct).ConfigureAwait(false);
typed++;
}
}
private (HumanGestures, TargetActions) CreateGestures(double mood)
{
var gestures = new HumanGestures(_cdp, _clock, _random, mood, _options.Pace, _options.UserIsDriving, _options.Gestures);
+69 -3
View File
@@ -9,6 +9,7 @@ using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
@@ -91,6 +92,18 @@ public sealed record CollectionPipelineOptions
/// recipes, the stop signals and the download queue. Null: nothing is recorded.
/// </summary>
public CollectionDiagnostics? Diagnostics { get; init; }
/// <summary>
/// The turns of the one page shared by the recipes and the profile search (issue #37). Null: no profile search
/// (the pipeline builds no search runner).
/// </summary>
public PageTurns? PageTurns { get; init; }
/// <summary>Times and bounds of the profile search.</summary>
public ProfileSearchOptions SearchOptions { get; init; } = ProfileSearchOptions.Default;
/// <summary>Where the photos of the search results are kept (memory). Null: the search fetches no photo.</summary>
public SearchPhotoCache? SearchPhotos { get; init; }
}
/// <summary>
@@ -101,8 +114,10 @@ public sealed class CollectionPipeline : IAsyncDisposable
{
private readonly List<IDisposable> _subscriptions = [];
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets)
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets, ProfileSearchRunner? search, SearchPhotoQueue? searchPhotos)
{
Search = search;
SearchPhotos = searchPhotos;
Tap = tap;
Signals = signals;
Capture = capture;
@@ -126,6 +141,12 @@ public sealed class CollectionPipeline : IAsyncDisposable
public DownloadQueue Downloads { get; }
/// <summary>The browser half of the profile search (issue #37); null without <see cref="CollectionPipelineOptions.PageTurns"/>.</summary>
public ProfileSearchRunner? Search { get; }
/// <summary>The photo queue of the profile search; null without a photo cache.</summary>
public SearchPhotoQueue? SearchPhotos { get; }
public SiteMap SiteMap { get; }
public TargetMap Targets { get; }
@@ -169,18 +190,58 @@ public sealed class CollectionPipeline : IAsyncDisposable
Breaker = options.Breaker,
Options = options.Recipes,
Diagnostics = diagnostics,
PageTurns = options.PageTurns,
});
var fetcher = new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log);
var downloads = new DownloadQueue(
options.Storage,
options.Ingest,
new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log),
fetcher,
options.DataBudget,
options.Clock,
options.Random,
new DownloadOptions { StagingFolder = options.StagingFolder },
signals);
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets);
ProfileSearchRunner? search = null;
SearchPhotoQueue? searchPhotos = null;
if (options.PageTurns is { } turns)
{
search = new ProfileSearchRunner(
driver,
driver,
capture,
siteMap,
options.Governor,
signals,
options.Breaker,
options.Clock,
options.Random,
turns,
options.SearchOptions,
options.UserIsDriving,
diagnostics);
if (options.SearchPhotos is { } photos)
{
// Photos only while the page is on the site: from the rest page the browser may block the CDN (H7).
searchPhotos = new SearchPhotoQueue(
photos,
fetcher,
options.Governor,
options.DataBudget,
options.Breaker,
options.Clock,
options.Random,
options.SearchOptions,
signals,
() => turns.LastUser is not null)
{
Diagnostics = diagnostics,
};
}
}
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets, search, searchPhotos);
pipeline._subscriptions.Add(tap.AddObserver(signals));
pipeline._subscriptions.Add(tap.AddConsumer(signals));
pipeline._subscriptions.Add(tap.AddObserver(capture));
@@ -208,6 +269,11 @@ public sealed class CollectionPipeline : IAsyncDisposable
subscription.Dispose();
}
if (SearchPhotos is not null)
{
await SearchPhotos.DisposeAsync().ConfigureAwait(false);
}
await Tap.DisposeAsync().ConfigureAwait(false);
}
@@ -139,6 +139,39 @@ public sealed class TargetResolver
};
const nameRe = spec.name ? new RegExp(spec.name, 'i') : null;
const hrefRe = spec.href ? new RegExp(spec.href, 'i') : null;
if (spec.focus) {
// The focus check of the search box (issue #37): whether the focus is in the box, how many characters it
// holds and whether the caret is at the end. Never its text, and nothing about any other field.
const boxes = [];
for (const el of document.querySelectorAll('*')) {
const role = roleOf(el);
if (spec.roles.length > 0 && !spec.roles.includes(role)) continue;
if (nameRe && !nameRe.test(nameOf(el, role))) continue;
const r = el.getBoundingClientRect();
let shown = r.width > 0 && r.height > 0;
if (shown && typeof el.checkVisibility === 'function') {
shown = el.checkVisibility({ opacityProperty: true, visibilityProperty: true });
}
if (shown) boxes.push(el);
if (boxes.length >= 50) break;
}
const at = spec.index < 0 ? boxes.length + spec.index : spec.index;
const box = at >= 0 && at < boxes.length ? boxes[at] : null;
if (!box) return { found: false, focused: false, length: null, atEnd: false };
const active = document.activeElement;
const inBox = !!active && (active === box || box.contains(active));
let length = null;
let atEnd = false;
if (inBox) {
const tag = active.tagName.toLowerCase();
const type = (active.getAttribute('type') || '').toLowerCase();
if ((tag === 'input' && type !== 'password') || tag === 'textarea') {
length = active.value.length;
atEnd = active.selectionStart === length && active.selectionEnd === length;
}
}
return { found: true, focused: inBox, length, atEnd };
}
const candidates = document.querySelectorAll(hrefRe ? 'a[href], area[href]' : '*');
const vw = window.innerWidth;
const vh = window.innerHeight;
@@ -241,6 +274,45 @@ public sealed class TargetResolver
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
}
/// <summary>
/// The read-only focus check of a text box target (issue #37): the same role and name query as
/// <see cref="BuildExpression"/>, answering only «found, focused, length, caret at the end», never the text.
/// </summary>
public static string BuildFocusExpression(TargetSpec spec)
{
ArgumentNullException.ThrowIfNull(spec);
var json = new JsonObject
{
["roles"] = new JsonArray([.. spec.Roles.Select(r => (JsonNode?)JsonValue.Create(r))]),
["name"] = spec.NamePattern is null ? null : TargetMap.ExpandNamePattern(spec.NamePattern, null),
["href"] = null,
["index"] = spec.Index,
["focus"] = true,
};
return Script.Replace("__SPEC__", json.ToJsonString(), StringComparison.Ordinal);
}
/// <summary>Runs the focus check of <paramref name="id"/>; a target not configured is never looked up.</summary>
public async Task<(bool Found, bool Focused, int? Length, bool AtEnd)> FocusAsync(string id, CancellationToken ct = default)
{
if (!_map.Contains(id) || _map.Get(id) is not { IsConfigured: true } spec)
{
return (false, false, null, false);
}
var value = await _cdp.EvaluateAsync(BuildFocusExpression(spec), ct).ConfigureAwait(false);
if (value.ValueKind != JsonValueKind.Object)
{
return (false, false, null, false);
}
var found = value.TryGetProperty("found", out var f) && f.ValueKind == JsonValueKind.True;
var focused = found && value.TryGetProperty("focused", out var g) && g.ValueKind == JsonValueKind.True;
int? length = focused && value.TryGetProperty("length", out var l) && l.ValueKind == JsonValueKind.Number && l.TryGetInt32(out var n) ? n : null;
var atEnd = focused && value.TryGetProperty("atEnd", out var e) && e.ValueKind == JsonValueKind.True;
return (found, focused, length, atEnd);
}
private async Task<(List<TargetElement> All, double Width, double Height)> MeasureAsync(TargetSpec spec, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
{
var value = await _cdp.EvaluateAsync(BuildExpression(spec, parameters), ct).ConfigureAwait(false);