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

+36 -12
View File
@@ -724,22 +724,34 @@ public sealed class EngineHost : IAsyncDisposable
// using the browser (spec §6.1, §7.6).
var breaker = s.Breaker.State;
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
if (!keepPage)
{
// This rest also serves a driving period that ended during the session.
Interlocked.Exchange(ref _restAfterDriving, 0);
try
// The rest takes the page turn (issue #37). When the profile search holds or waits for the page, the rest is
// left to it (PageTurns.RestOwed): it rests the page when it is done, no session running.
var turn = await s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
if (turn is not null)
{
await _runner.RestAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeFailed,
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
sessionId: record.Id,
ct: ct).ConfigureAwait(false);
await using (turn.ConfigureAwait(false))
{
try
{
await _runner.RestAsync(ct).ConfigureAwait(false);
s.PageTurns.NoteRested();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeFailed,
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
sessionId: record.Id,
ct: ct).ConfigureAwait(false);
}
}
}
}
@@ -799,7 +811,19 @@ public sealed class EngineHost : IAsyncDisposable
try
{
await _runner.RestAsync(ct).ConfigureAwait(false);
// With the page turn (issue #37): a search step in progress is never cut by the rest. When the search holds
// or waits for the page, the rest is left to it.
var turn = await _s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
if (turn is null)
{
return;
}
await using (turn.ConfigureAwait(false))
{
await _runner.RestAsync(ct).ConfigureAwait(false);
_s.PageTurns.NoteRested();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
+6
View File
@@ -27,6 +27,12 @@ public sealed record EngineOptions
/// <summary>Minimum distance between two counted actions at the «naturale» gesture pace (spec §7.2); scaled by the pace.</summary>
public TimeSpan MinimumSpacing { get; init; } = TimeSpan.FromSeconds(4);
/// <summary>
/// Minimum distance between two profile-search steps, and between a search step and an engine action in either
/// direction, at the «naturale» pace (issue #37); scaled by the pace. A pace, not a refusal.
/// </summary>
public TimeSpan SearchSpacing { get; init; } = TimeSpan.FromSeconds(1.2);
/// <summary>The first session starts 2–10 minutes after the program (spec §7.2).</summary>
public TimeSpan StartupDelayMin { get; init; } = TimeSpan.FromMinutes(2);
+3
View File
@@ -65,6 +65,9 @@ public sealed class EngineServices
/// <summary>Current engine and caution settings.</summary>
public EngineSettings Settings { get; private set; }
/// <summary>The turns of the one browser page, shared by the recipes and the profile search (issue #37).</summary>
public PageTurns PageTurns { get; } = new();
/// <summary>
/// The recorder of the diagnostic report (issue #39): told when sessions start and end, and why. Null: nothing is
/// recorded. Set by the composition before the engine starts.
+109 -8
View File
@@ -15,6 +15,9 @@ namespace Febe.Core.Engine;
/// <remarks>
/// <para>The minimum spacing is a pace, not a refusal: <see cref="RequestAsync"/> waits for it (on <see cref="IClock"/>)
/// and then grants; <see cref="EvaluateAsync"/> reports it as <see cref="DenialReason.MinimumSpacing"/>.</para>
/// <para>The profile search (<see cref="ActionKind.ProfileSearch"/>, issue #37) has its own branch: no session is needed,
/// it has its own gate, budget and spacing, and it keeps a short crossing gap from the engine's actions both ways; the
/// breaker, Alberto at the browser, the pause and the active window stop it as they stop the engine.</para>
/// <para>CDN downloads are not site actions: <see cref="ActionKind.DataDownload"/> only checks the daily byte budget, also
/// during a stop (spec §7.6: queued downloads may complete), and bytes are recorded with <see cref="RecordAsync"/>.</para>
/// </remarks>
@@ -30,6 +33,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
private readonly EngineOptions _options;
private readonly EngineEvents? _events;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly SemaphoreSlim _searchGate = new(1, 1);
private readonly Lock _noticeGate = new();
private readonly HashSet<(ActionKind, DateOnly)> _dailyNoticesSent = [];
@@ -60,6 +64,9 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
/// <summary>Minimum distance between two counted actions at the current gesture pace.</summary>
public TimeSpan MinimumSpacing => _options.MinimumSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
/// <summary>Distance between two search steps, and between a search step and an engine action, at the current pace.</summary>
public TimeSpan SearchSpacing => _options.SearchSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
/// <summary>Budgets in force at <paramref name="now"/>: profile, gradual start and halved budgets, strongest reduction.</summary>
public EffectiveBudgets GetEffectiveBudgets(DateTimeOffset now) =>
BudgetLimits.Compute(_runtime.Profile, _runtime.RampStart, _breaker.State.HalvedBudgetsUntil, now);
@@ -71,13 +78,17 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
return await EvaluateDataAsync(accountId, ct).ConfigureAwait(false);
}
await _gate.WaitAsync(ct).ConfigureAwait(false);
var search = kind == ActionKind.ProfileSearch;
var gate = search ? _searchGate : _gate;
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
while (true)
{
var now = _clock.Now;
var permit = await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
var permit = search
? await EvaluateSearchAsync(now, ct).ConfigureAwait(false)
: await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
if (permit.Reason == DenialReason.MinimumSpacing && permit.RetryAfter is { } retry)
{
// Spacing is a pace: wait for it, then look again (the state may have changed meanwhile).
@@ -92,7 +103,8 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
return permit;
}
var session = _runtime.CurrentSession;
// A search step belongs to no session and is not one of its actions (issue #37).
var session = search ? null : _runtime.CurrentSession;
await _storage.ActionLog.AppendAsync(
new ActionLogRecord { At = now, Category = kind, AccountId = accountId, SessionId = session?.SessionId },
ct).ConfigureAwait(false);
@@ -103,7 +115,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
}
finally
{
_gate.Release();
gate.Release();
}
}
@@ -111,10 +123,12 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
/// What <see cref="RequestAsync"/> would answer now, without recording or waiting (spacing is reported as a
/// refusal with its retry time). The scheduler uses it to skip work whose budget is exhausted.
/// </summary>
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) =>
kind == ActionKind.DataDownload
? EvaluateDataAsync(accountId, ct)
: EvaluateCoreAsync(kind, accountId, _clock.Now, ct);
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) => kind switch
{
ActionKind.DataDownload => EvaluateDataAsync(accountId, ct),
ActionKind.ProfileSearch => EvaluateSearchAsync(_clock.Now, ct),
_ => EvaluateCoreAsync(kind, accountId, _clock.Now, ct),
};
/// <summary>Budget checks only (no breaker, window, session or spacing): «is there room today for this?».</summary>
public async Task<Permit> EvaluateBudgetAsync(ActionKind kind, long? accountId, CancellationToken ct = default)
@@ -279,10 +293,97 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
previous + spacing);
}
// The crossing gap from the last profile-search step (issue #37), which does not move the spacing above.
var crossing = await CrossingGapAsync(ActionKind.ProfileSearch, kind, accountId, now, ct).ConfigureAwait(false);
if (crossing is not null)
{
return crossing;
}
return await CheckAccountAsync(kind, accountId, now, budgets, session, ct).ConfigureAwait(false)
?? Permit.Grant(kind, accountId);
}
/// <summary>
/// The rules of the profile search (issue #37), in order: breaker (every stop of spec §7.6 stops the search too),
/// Alberto at the browser, pause, active window, the search's own budgets (reductions apply), its own spacing, and
/// the crossing gap from the engine's last action. No session check and no account check.
/// </summary>
private async Task<Permit> EvaluateSearchAsync(DateTimeOffset now, CancellationToken ct)
{
const ActionKind kind = ActionKind.ProfileSearch;
var zone = _clock.LocalZone;
var breaker = _breaker.State;
if (!breaker.AllowsSiteActions)
{
return Permit.Deny(kind, null, DenialReason.BreakerOpen, BreakerMessage(breaker, now, zone), breaker.Until);
}
if (_runtime.UserIsDriving)
{
return Permit.Deny(kind, null, DenialReason.UserIsDriving, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
}
if (_runtime.IsPaused)
{
return Permit.Deny(kind, null, DenialReason.Paused, "Febe è in pausa: la ricerca su Instagram riprende quando premi «Riprendi».");
}
var window = await _planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
if (window is null)
{
var next = await _planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
var when = next is null ? "nei giorni attivi" : ItalianText.Around(next.Start, now, zone);
return Permit.Deny(
kind,
null,
DenialReason.OutsideActiveWindow,
$"Fuori dalla fascia oraria Febe non apre Instagram: per ora vedi solo i profili che segui. Riprende {when}.",
next?.Start);
}
var denial = await CheckCategoryBudgetsAsync(kind, null, now, GetEffectiveBudgets(now), ct).ConfigureAwait(false);
if (denial is not null)
{
return denial;
}
var spacing = SearchSpacing;
var lastSearch = await _storage.ActionLog.GetLastActionAtAsync(kind, ct).ConfigureAwait(false);
if (lastSearch is { } previous && now - previous < spacing)
{
return Permit.Deny(
kind,
null,
DenialReason.MinimumSpacing,
$"Troppo vicino al passo di ricerca precedente: fra due passi passano almeno {ItalianText.Decimal(spacing.TotalSeconds, 1)} secondi.",
previous + spacing);
}
return await CrossingGapAsync(null, kind, null, now, ct).ConfigureAwait(false) ?? Permit.Grant(kind, null);
}
/// <summary>
/// The short distance between a search step and an engine action, both ways: <paramref name="other"/> is
/// <see cref="ActionKind.ProfileSearch"/> for an engine request, and null (the engine's own actions) for a search.
/// </summary>
private async Task<Permit?> CrossingGapAsync(ActionKind? other, ActionKind kind, long? accountId, DateTimeOffset now, CancellationToken ct)
{
var last = await _storage.ActionLog.GetLastActionAtAsync(other, ct).ConfigureAwait(false);
var gap = SearchSpacing;
if (last is { } previous && now - previous < gap)
{
return Permit.Deny(
kind,
accountId,
DenialReason.MinimumSpacing,
$"Troppo vicino all'azione precedente: fra la ricerca e il motore passano almeno {ItalianText.Decimal(gap.TotalSeconds, 1)} secondi.",
previous + gap);
}
return null;
}
private async Task<Permit?> CheckBudgetsAsync(ActionKind kind, long? accountId, DateTimeOffset now, EffectiveBudgets budgets, CancellationToken ct) =>
await CheckCategoryBudgetsAsync(kind, accountId, now, budgets, ct).ConfigureAwait(false)
?? await CheckAccountAsync(kind, accountId, now, budgets, _runtime.CurrentSession, ct).ConfigureAwait(false);
+1
View File
@@ -192,6 +192,7 @@ public static class ItalianText
ActionKind.BackfillPage => "pagine di storico",
ActionKind.SinglePost => "post singoli",
ActionKind.FollowingListPage => "pagine dell'elenco dei seguiti",
ActionKind.ProfileSearch => "ricerche di profili",
ActionKind.DataDownload => "dati scaricati",
_ => kind.ToString(),
};
+370
View File
@@ -0,0 +1,370 @@
using System.Diagnostics;
namespace Febe.Core.Engine;
/// <summary>Who uses the one page of Febe's browser.</summary>
public enum PageUser
{
/// <summary>The engine: a recipe of a session.</summary>
Engine,
/// <summary>The profile search (issue #37).</summary>
Search,
}
/// <summary>
/// One page, two users (issue #37): the engine's recipes and the profile search take turns on Febe's single browser
/// page. A FIFO queue with one holder at a time; cancellable; no timers. The engine takes a turn at the start of each
/// recipe and gives it back before an action that opens a page when the search is waiting (<see cref="YieldAsync"/>);
/// the search takes it for one step (and keeps it while Alberto keeps typing, bounded by the search itself).
/// </summary>
/// <remarks>The session never stops for a search: the search only slides in between two engine actions.</remarks>
public sealed class PageTurns
{
private readonly Lock _gate = new();
private readonly LinkedList<Waiter> _queue = new();
private PageTurn? _holder;
private PageUser? _lastUser;
private bool _searchTouchedPage;
private bool _restOwed;
private long _generation;
private List<TaskCompletionSource>? _freeWaiters;
/// <summary>Raised after every rest of the page (the search's photo queue forgets its addresses).</summary>
public event Action? Rested;
/// <summary>Raised when the rest of the page is left to the search (<see cref="TakeForRestAsync"/>).</summary>
public event Action? RestLeftToSearch;
/// <summary>
/// Changes every time a page is opened or put to rest: what the search typed in the box holds only within one
/// generation (the engine may open pages between two search steps without the search seeing it).
/// </summary>
public long Generation
{
get
{
lock (_gate)
{
return _generation;
}
}
}
/// <summary>
/// The engine wanted to rest the page while the search held or waited for it (end of a session, Alberto let go
/// of the browser): the search rests it when it is done, no session running. Cleared by a rest, by a page the
/// engine opens (the next session rests it), or by <see cref="ForgetOwedRest"/>.
/// </summary>
public bool RestOwed
{
get
{
lock (_gate)
{
return _restOwed;
}
}
}
/// <summary>Who opened the page last (null before anyone did, or after a rest).</summary>
public PageUser? LastUser
{
get
{
lock (_gate)
{
return _lastUser;
}
}
}
/// <summary>True from a search step until the next page the engine opens: the page state of a recipe may be gone.</summary>
public bool SearchTouchedPage
{
get
{
lock (_gate)
{
return _searchTouchedPage;
}
}
}
/// <summary>Who holds the page now, if anyone.</summary>
public PageUser? Holder
{
get
{
lock (_gate)
{
return _holder?.User;
}
}
}
/// <summary>True while <paramref name="user"/> waits for a turn.</summary>
public bool IsWaiting(PageUser user)
{
lock (_gate)
{
return _queue.Any(w => w.Turn.User == user);
}
}
/// <summary>Waits for a turn of <paramref name="user"/>; dispose the result to give it back.</summary>
public async ValueTask<PageTurn> TakeAsync(PageUser user, CancellationToken ct)
{
var turn = new PageTurn(this, user);
await AcquireAsync(turn, ct).ConfigureAwait(false);
return turn;
}
/// <summary>
/// When the other user waits, gives the page to it and waits to have it back (FIFO, so right after the other's
/// step). Returns true when it yielded. Does nothing when <paramref name="turn"/> does not hold the page.
/// </summary>
public async ValueTask<bool> YieldAsync(PageTurn turn, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(turn);
var other = turn.User == PageUser.Engine ? PageUser.Search : PageUser.Engine;
lock (_gate)
{
if (!ReferenceEquals(_holder, turn) || !_queue.Any(w => w.Turn.User == other))
{
return false;
}
ReleaseLocked(turn);
}
await AcquireAsync(turn, ct).ConfigureAwait(false);
return true;
}
/// <summary>The engine's current turn, for the recipes' yield points; null when the engine holds none.</summary>
public PageTurn? EngineTurn
{
get
{
lock (_gate)
{
return _holder is { User: PageUser.Engine } turn ? turn : null;
}
}
}
/// <summary>
/// A turn for a navigation of the engine outside its recipes (the rest page, Alberto's login page): at once when
/// the page is free. When the search holds or waits for the page, returns null and records that the rest is left to
/// the search (<see cref="RestOwed"/>): it rests the page itself when it is done. Otherwise waits for the turn.
/// </summary>
public async ValueTask<PageTurn?> TakeForRestAsync(CancellationToken ct)
{
var turn = new PageTurn(this, PageUser.Engine);
bool leftToSearch;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
_holder = turn;
return turn;
}
leftToSearch = _holder?.User == PageUser.Search || _queue.Any(w => w.Turn.User == PageUser.Search);
if (leftToSearch)
{
_restOwed = true;
}
}
if (leftToSearch)
{
RestLeftToSearch?.Invoke();
return null;
}
await AcquireAsync(turn, ct).ConfigureAwait(false);
return turn;
}
/// <summary>The search will not rest the page after all (it stays as it is after a verification, no browser).</summary>
public void ForgetOwedRest()
{
lock (_gate)
{
_restOwed = false;
}
}
/// <summary>Completes when nobody holds the page and nobody waits.</summary>
public Task WhenFreeAsync(CancellationToken ct)
{
TaskCompletionSource tcs;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
return Task.CompletedTask;
}
tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
(_freeWaiters ??= []).Add(tcs);
}
return tcs.Task.WaitAsync(ct);
}
/// <summary>A page was opened by <paramref name="user"/>.</summary>
public void NoteOpened(PageUser user)
{
lock (_gate)
{
_lastUser = user;
_searchTouchedPage = user == PageUser.Search;
_generation++;
if (user == PageUser.Engine)
{
// A session is on the page again: its end rests it.
_restOwed = false;
}
}
}
/// <summary>The search used the page (typed, opened its panel): the engine's page state may be gone.</summary>
public void NoteSearchUsedPage()
{
lock (_gate)
{
_searchTouchedPage = true;
}
}
/// <summary>The page went to rest (spec §6.1).</summary>
public void NoteRested()
{
lock (_gate)
{
_lastUser = null;
_searchTouchedPage = false;
_restOwed = false;
_generation++;
}
Rested?.Invoke();
}
internal void Release(PageTurn turn)
{
lock (_gate)
{
if (ReferenceEquals(_holder, turn))
{
ReleaseLocked(turn);
}
}
}
private async ValueTask AcquireAsync(PageTurn turn, CancellationToken ct)
{
Waiter waiter;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
_holder = turn;
return;
}
waiter = new Waiter(turn, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously));
waiter.Node = _queue.AddLast(waiter);
}
try
{
await waiter.Ready.Task.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
lock (_gate)
{
if (waiter.Node?.List is not null)
{
_queue.Remove(waiter.Node);
NotifyFreeLocked();
throw;
}
// Granted while being cancelled: give it back at once.
if (ReferenceEquals(_holder, turn))
{
ReleaseLocked(turn);
}
}
throw;
}
}
private void ReleaseLocked(PageTurn turn)
{
Debug.Assert(ReferenceEquals(_holder, turn), "Only the holder gives the page back.");
_holder = null;
if (_queue.First is { } first)
{
_queue.RemoveFirst();
first.Value.Node = null;
_holder = first.Value.Turn;
first.Value.Ready.TrySetResult();
return;
}
NotifyFreeLocked();
}
private void NotifyFreeLocked()
{
if (_holder is not null || _queue.Count > 0 || _freeWaiters is null)
{
return;
}
foreach (var waiter in _freeWaiters)
{
waiter.TrySetResult();
}
_freeWaiters = null;
}
private sealed class Waiter(PageTurn turn, TaskCompletionSource ready)
{
public PageTurn Turn { get; } = turn;
public TaskCompletionSource Ready { get; } = ready;
public LinkedListNode<Waiter>? Node { get; set; }
}
}
/// <summary>A turn on the page; disposing it gives the page back (to the next in the queue).</summary>
public sealed class PageTurn : IAsyncDisposable, IDisposable
{
private readonly PageTurns _owner;
internal PageTurn(PageTurns owner, PageUser user)
{
_owner = owner;
User = user;
}
public PageUser User { get; }
public void Dispose() => _owner.Release(this);
public ValueTask DisposeAsync()
{
_owner.Release(this);
return ValueTask.CompletedTask;
}
}
+29
View File
@@ -864,6 +864,35 @@ internal sealed class SessionComposer
}
}
// The page is shared with the profile search (issue #37): a recipe starts on its turn. While the search holds
// the page the activity says so; the checks below run again once the turn is ours.
var turns = _s.PageTurns;
var waitsForSearch = turns.Holder is PageUser.Search || turns.IsWaiting(PageUser.Search);
if (waitsForSearch)
{
_s.Runtime.Activity = "In attesa della ricerca dei profili";
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
}
PageTurn turn;
try
{
turn = await turns.TakeAsync(PageUser.Engine, ct).ConfigureAwait(false);
}
finally
{
if (waitsForSearch)
{
_s.Runtime.Activity = null;
}
}
await using var heldTurn = turn;
if (waitsForSearch && Clock.Now >= state.Context.PlannedEnd && !request.Manual)
{
return null;
}
if (!_s.Breaker.State.AllowsSiteActions || _s.Runtime.IsPaused || _s.Runtime.UserIsDriving)
{
state.Stop = true;