Unione di funzione/sessione-s4b in funzione/codec-immagini (catena della 0.3.0)

Porta nel ramo dei codec le regole e le risposte del 25 novembre (ramo dei
documenti) e la tappa S4b della sessione salvata, così che il ramo si unisca
in main dopo i due precedenti senza conflitti da risolvere di nuovo.

Conflitti risolti tenendo le due intenzioni:
- Directory.Packages.props: il commento «Niente componenti esterni» dei
  documenti, senza le righe di SkiaSharp, che questo ramo ha già tolto (C1).
- docs/decisioni.md: tutte le righe aggiunte dai due lati, prima le 39 della
  catena (documenti e S4b), poi le 23 dei codec.
- docs/docker.md: ffmpeg «fino alla tappa C3» dei documenti più la riga dei
  codec «Nessuna libreria per le immagini».
- docs/guida/Sviluppo.md: la regola «Niente componenti esterni» dei
  documenti, con SkiaSharp detto già uscito con la tappa C1 e i codec e il
  disegnatore di casa che lo sostituiscono.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-25 10:57:54 +01:00
commit a0e7404297
62 files changed
+2944 -242

No files matched your search

+493 -23
View File
@@ -4,6 +4,7 @@ using Febe.Browser.Hosting;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
@@ -40,6 +41,16 @@ namespace Febe.App;
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
/// </para>
/// <para>
/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>), the page
/// of the browser left in Docker (<see cref="LeavePageAsync"/>, <see cref="RemoteViewClosed"/>: after
/// <see cref="PageLeaveGrace"/> without a view open again, answer of 25 November 2026) and the lease of «Accedi» /
/// «Usa il browser» ending by itself. «Annulla» never copies. Always before the page goes back to the engine, with the
/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is
/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
/// </para>
/// </remarks>
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
{
@@ -55,6 +66,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
/// <summary>How the log names leaving the page of the browser in Docker (answer of 25 November 2026).</summary>
private const string PageLeftText = "Pagina del browser lasciata";
private readonly IFebeBrowser _browser;
private readonly IFebeStorage _storage;
private readonly BrowserUseTracker _tracker;
@@ -74,6 +88,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private bool? _connected;
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
private SessionCopyOutcome? _letGoCopy;
private DateTimeOffset? _leftAt;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -119,6 +136,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie
/// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6).
/// </summary>
public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present;
/// <summary>
/// Whether the engine may collect (<see cref="EngineRuntime.IsConnected"/>): the session cookie is in the browser
/// and, with a saved session, a readable copy of it is there too.
/// </summary>
public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing;
/// <summary>
/// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for
/// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it.
/// </summary>
public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
@@ -140,6 +175,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
/// before. Read at every look; tests shorten it.
/// </summary>
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
/// wait; tests shorten it.
@@ -161,6 +204,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
var saved = _copier?.Report();
if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present)
{
state = ConnectionState.SessionCopyMissing;
}
Account? mine = null;
if (state != ConnectionState.NotConnected)
@@ -168,7 +216,55 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
}
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false), ToStatus(saved));
}
/// <summary>
/// The window «Browser di Febe» was closed by Alberto without «Ho finito», or left minimised too long (Windows, issue
/// #36, S4b, answer 5): the session is copied while the page is still his. The caller (the window) holds the driving
/// gate until this returns, so the page goes back to the engine only afterwards. Gives up after
/// <see cref="LetGoWait"/>. Never throws for the browser; logs counts only, and says which of the two happened.
/// </summary>
public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct)
{
var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa";
if (_copier is null)
{
return;
}
if (!_browser.IsAvailable)
{
// A letting go that copies nothing: a late «Ho finito» must not report a copy of an earlier one.
ForgetLetGoCopy();
return;
}
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(LetGoWait);
try
{
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (limit.IsCancellationRequested)
{
ForgetLetGoCopy();
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
return;
}
catch (ObjectDisposedException)
{
return; // Febe is stopping
}
try
{
await CopyOnLetGoAsync(what, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
}
finally
{
ReleaseCommands();
}
}
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
@@ -181,6 +277,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
if (_lease is null)
{
// A new use of the browser: what an earlier one copied when it let go is no longer this one's.
_letGoCopy = null;
_lease = _browser.UserDriving.Begin();
var watch = new CancellationTokenSource();
_leaseWatch = watch;
@@ -189,6 +287,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
_lastDrivingSign = _clock.Now;
// Alberto is back (a reload of the page left a moment ago): not a letting go.
_leftAt = null;
}
_tracker.MarkUsed(_clock.Now);
@@ -313,6 +414,52 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing
/// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the
/// lease lets go of the browser once, for <see cref="PageLeaveGrace"/> after this and after the last view closed, no
/// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on
/// Windows, then the lease ends and the page goes back to the engine (which puts it to rest).
/// </summary>
public Task LeavePageAsync(CancellationToken ct)
{
if (NoteLeft())
{
_log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere.");
}
return Task.CompletedTask;
}
/// <summary>
/// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking
/// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page
/// (<see cref="LeavePageAsync"/>): the last view closed, the moment starts again from now.
/// </summary>
public void RemoteViewClosed()
{
// The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back).
if (_browser.IsAvailable)
{
NoteLeft();
}
}
/// <summary>Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser».</summary>
private bool NoteLeft()
{
lock (_gate)
{
if (_lease is null)
{
return false;
}
_leftAt = _clock.Now;
return true;
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
@@ -320,7 +467,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
if (!_browser.IsAvailable)
{
ReleaseLease();
EndUseWithHoFinito();
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
}
@@ -330,10 +477,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
// The copy for the site client (S4): while the page still holds the session and is still Alberto's.
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null;
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : default;
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
EndUseWithHoFinito();
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
string message;
@@ -354,9 +501,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
if (copy is not null)
if (copy.Outcome is { } outcome)
{
message += " " + CopyMessage(copy);
message += " " + CopyMessage(outcome, copy.Earlier);
}
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
@@ -634,9 +781,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
while (true)
{
var grace = DrivingGrace;
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
var leaveGrace = PageLeaveGrace;
var shortest = leaveGrace < grace ? leaveGrace : grace;
var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
await _clock.Delay(poll, ct).ConfigureAwait(false);
DateTimeOffset lastSign;
DateTimeOffset? leftAt;
lock (_gate)
{
if (!ReferenceEquals(_lease, lease))
@@ -651,11 +801,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
lastSign = _lastDrivingSign;
leftAt = _leftAt;
}
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
// Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came
// back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses.
var now = _clock.Now;
var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace;
if (!left && now - lastSign < grace)
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
continue;
}
// Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in
// Docker, answer of 25 November 2026).
var what = left ? PageLeftText : "Fine della guida del browser";
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false))
{
continue;
}
// The copy may have lasted long (the page's turn, the browser, the database): the remote view, the window
// or «Accedi» / «Usa il browser» may have come back meanwhile. Looked at again in the same step that ends
// the lease, so that nothing slips in between.
if (ReleaseIdleLease(lease, lastSign))
{
_log.Info("collegamento", left
? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere."
: $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
}
}
@@ -664,6 +837,205 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
// The lease ended with a command of Alberto.
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Whatever failed, the lease must not hold the engine still for ever (rule 10: the kind of error only).
_log.Warn("collegamento", $"Controllo della fine della guida del browser interrotto da un errore ({ex.GetType().Name}): il motore può riprendere.");
ReleaseLease(lease);
}
}
/// <summary>
/// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still
/// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a
/// moment before): the window's own hold lasts a moment after its copy, so a sign within one look
/// (<paramref name="poll"/>) of the copy is that hold, not Alberto. False when the lease must not end now: a sign of
/// driving came while the copy waited for its turn.
/// </summary>
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, string what, CancellationToken ct)
{
if (_copier is null)
{
return true;
}
lock (_gate)
{
if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll)
{
return true;
}
}
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide.
try
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
return true; // Febe is stopping
}
try
{
bool StillAlbertos()
{
lock (_gate)
{
return ReferenceEquals(_lease, lease);
}
}
if (!StillAlbertos())
{
return true;
}
if (_browser.UserDriving.Leases > 1)
{
// The remote view or the window came back while this waited: the lease goes on.
lock (_gate)
{
_lastDrivingSign = _clock.Now;
}
return false;
}
await CopyOnLetGoAsync(what, StillAlbertos, ct).ConfigureAwait(false);
return true;
}
finally
{
ReleaseCommands();
}
}
/// <summary>
/// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the
/// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a
/// page off the site or a login or verification page. One log line with the outcome (counts only).
/// </summary>
private async Task CopyOnLetGoAsync(string what, Func<bool> stillAlbertos, CancellationToken ct)
{
try
{
if (!_browser.UserIsDriving)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore.");
return;
}
// The last time this use of the browser let go decides what a late «Ho finito» says: a copy that does not
// happen now (no session, the page busy, refused, an error) forgets one made at an earlier letting go.
ForgetLetGoCopy();
if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true)
{
_log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare.");
return;
}
var hold = _browser.UserDriving.Begin();
try
{
const string PageBusy = "sessione non copiata, la pagina era occupata dalla ricerca dei profili";
PageTurn? taken;
try
{
taken = await TakePageAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The time of the letting go ran out while a step of the search held the page: not the browser's fault.
_log.Info("collegamento", $"{what}: {PageBusy}.");
return;
}
using var turn = taken;
if (_engine is not null && turn is null)
{
_log.Info("collegamento", $"{what}: {PageBusy}.");
return;
}
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
lock (_gate)
{
_lastCopyAt = _clock.Now;
if (outcome.Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly or SessionCopyStatus.KeptComplete)
{
// A late «Ho finito» of this use says that the session was already copied (S4b).
_letGoCopy = outcome;
}
}
_log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}.");
}
finally
{
hold.Dispose();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo.");
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The database, the disk, Febe stopping: never the lease held for ever because of it. The kind of error only
// (rule 10): the page and the saved session hold what the session holds.
_log.Warn("collegamento", $"{what}: copia della sessione non riuscita per un errore ({ex.GetType().Name}).");
}
}
/// <summary>What a copy without «Ho finito» did, for the log (counts only).</summary>
internal static string LetGoSummary(SessionCopyOutcome copy)
{
ArgumentNullException.ThrowIfNull(copy);
var missing = copy.MissingValues + copy.MissingDocIds;
var clause = missing == 0 ? string.Empty : ", ma " + MissingNeeded(missing, past: false);
return copy.Status switch
{
SessionCopyStatus.Saved => "sessione copiata" + clause,
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
SessionCopyStatus.KeptComplete => $"copia incompleta ({ItalianText.Count(missing, "valore mancante", "valori mancanti")}), resta quella completa salvata prima",
SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore",
_ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era",
};
}
/// <summary>The saved session for the interface, in counts and names; null without a saved session in this start.</summary>
private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null
? null
: new SavedSessionStatus(
report.State switch
{
SavedSessionState.Present => SavedSessionStatus.Present,
SavedSessionState.Unreadable => SavedSessionStatus.Unreadable,
_ => SavedSessionStatus.None,
},
report.CopiedAt,
report.Cookies,
report.ValuesPresent,
report.ValuesExpected,
report.MissingValues,
report.DocIdsPresent,
report.DocIdsExpected,
report.MissingDocIds,
report.NeededMissing);
private void ReleaseCommands()
{
try
{
_commands.Release();
}
catch (ObjectDisposedException)
{
// Febe stopped while the copy ran.
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
@@ -736,22 +1108,35 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
/// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
/// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
/// page; a lease that ended all the same before the copy is saved throws the copy away.
/// page; a lease that ended all the same before the copy is saved throws the copy away. A late «Ho finito», after
/// this use of the browser already copied when it let go (S4b), reads nothing and reports that earlier copy
/// (<c>Earlier</c>), as long as the saved session is still there.
/// </summary>
private async Task<SessionCopyOutcome> CopySessionAsync(CancellationToken ct)
private async Task<(SessionCopyOutcome? Outcome, bool Earlier)> CopySessionAsync(CancellationToken ct)
{
IDisposable? lease;
SessionCopyOutcome? earlier;
lock (_gate)
{
lease = _lease;
earlier = _letGoCopy;
}
if (lease is null || !_browser.UserIsDriving)
{
if (earlier is not null && _copier!.SavedState == SavedSessionState.Present)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata di nuovo, era già stata copiata quando il browser è tornato al motore.");
return (earlier, true);
}
_log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0);
return (new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0), false);
}
// «Ho finito» copies again: from now on its own outcome is what a later «Ho finito» refers to, not an earlier copy
// made when the browser was let go (that copy may be of another login).
ForgetLetGoCopy();
var hold = _browser.UserDriving.Begin();
try
{
@@ -759,7 +1144,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
if (_engine is not null && turn is null)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
return (new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0), false);
}
bool StillAlbertos()
@@ -770,7 +1155,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false);
return (await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false), false);
}
finally
{
@@ -782,25 +1167,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
/// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
/// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
/// «Ho finito» always ends the lease.
/// «Ho finito» always ends the lease. With <paramref name="earlier"/> the copy is the one made a moment before, when
/// the browser went back to the engine without «Ho finito» (S4b): the message says so, and never asks for a new login
/// when that copy is complete.
/// </summary>
internal static string CopyMessage(SessionCopyOutcome copy)
internal static string CopyMessage(SessionCopyOutcome copy, bool earlier = false)
{
ArgumentNullException.ThrowIfNull(copy);
const string Before = "La sessione per le richieste era già stata copiata quando il browser è tornato al motore";
const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
var missing = copy.MissingValues + copy.MissingDocIds;
var needed = MissingNeeded(missing, past: true);
var missingClause = missing == 0
? string.Empty
: string.Create(
CultureInfo.InvariantCulture,
$" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}");
: $" Alla pagina però {needed}: la copia ha comunque sostituito quella salvata prima, e le richieste che {(missing == 1 ? "lo" : "li")} usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}";
return copy.Status switch
{
SessionCopyStatus.Saved when earlier => Before + "." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
SessionCopyStatus.SavedInMemoryOnly when earlier =>
Before + ", ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
SessionCopyStatus.KeptComplete when earlier =>
$"Quando il browser è tornato al motore alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
SessionCopyStatus.SavedInMemoryOnly =>
"Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
SessionCopyStatus.Discarded =>
"La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
SessionCopyStatus.KeptComplete =>
$"Alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
_ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
_ =>
@@ -808,6 +1202,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
};
}
/// <summary>
/// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (<paramref name="past"/>:
/// «mancava», «mancavano»): the count with the Italian singular.
/// </summary>
internal static string MissingNeeded(int missing, bool past)
{
var one = missing == 1;
var verb = past ? (one ? "mancava" : "mancavano") : (one ? "manca" : "mancano");
return $"{verb} {ItalianText.Count(missing, "valore", "valori")} che {(one ? "serve" : "servono")} alle richieste";
}
/// <summary>«Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.</summary>
private async Task<Exception?> ForgetSavedSessionAsync()
{
@@ -938,6 +1343,27 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito».</summary>
private void ForgetLetGoCopy()
{
lock (_gate)
{
_letGoCopy = null;
}
}
/// <summary>
/// «Ho finito» ends the lease. When it ends one, that use of the browser is over: a further «Ho finito» (a double
/// click, a second tab) must not report a copy made when that use was let go earlier.
/// </summary>
private void EndUseWithHoFinito()
{
if (ReleaseLease())
{
ForgetLetGoCopy();
}
}
/// <summary>Ends the lease (only <paramref name="expected"/>, when given). True when a lease ended.</summary>
private bool ReleaseLease(IDisposable? expected = null)
{
@@ -950,12 +1376,56 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return false;
}
lease = _lease;
watch = _leaseWatch;
_lease = null;
_leaseWatch = null;
(lease, watch) = TakeLeaseLocked();
}
return EndLease(lease, watch);
}
/// <summary>
/// Ends <paramref name="expected"/> by itself only if, in the same look, it is still the only lease of the browser and
/// no sign that Alberto uses the browser came after <paramref name="lastSign"/>: another lease (the remote view, the
/// window, a hold of the connection) is a sign now. True when the lease ended.
/// </summary>
private bool ReleaseIdleLease(IDisposable expected, DateTimeOffset lastSign)
{
IDisposable? lease;
CancellationTokenSource? watch;
lock (_gate)
{
if (!ReferenceEquals(_lease, expected))
{
return false;
}
if (_browser.UserDriving.Leases > 1)
{
_lastDrivingSign = _clock.Now;
return false;
}
if (_lastDrivingSign > lastSign)
{
return false;
}
(lease, watch) = TakeLeaseLocked();
}
return EndLease(lease, watch);
}
private (IDisposable? Lease, CancellationTokenSource? Watch) TakeLeaseLocked()
{
var taken = (_lease, _leaseWatch);
_lease = null;
_leaseWatch = null;
_leftAt = null;
return taken;
}
private static bool EndLease(IDisposable? lease, CancellationTokenSource? watch)
{
if (watch is not null)
{
watch.Cancel();
+39 -8
View File
@@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable
// Browser, connection, engine. The engine loop starts only once the browser is up.
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens.
var context = new FebePlatformContext(
o,
data,
Database,
Clock,
Log,
Tracker,
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
(how, ct) => Connection?.CopyOnWindowClosedAsync(how, ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
PrepareSavedSession(context, browser);
@@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable
random,
engineOptions,
userIsDriving: () => browser.UserIsDriving,
isConnected: () => connection.IsConnected == true,
ct: ct).ConfigureAwait(false);
isConnected: () => connection.IsReadyToCollect,
ct: ct,
sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false);
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
// capture sees goes to the session in progress, if any.
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
@@ -500,9 +510,7 @@ public sealed class FebeApp : IAsyncDisposable
InBackground(() => Connection.RunAsync(ct));
await engine.StartAsync(ct).ConfigureAwait(false);
Log.Info("motore", Connection.IsConnected == true
? "Motore avviato: il browser è collegato."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
Log.Info("motore", StartedMessage(Connection));
_running.TrySetResult();
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
@@ -576,10 +584,15 @@ public sealed class FebeApp : IAsyncDisposable
var protector = _platform.CreateSessionProtector(context);
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
var rules = LoadSignalRules(context.Data);
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
var settings = context.Storage.Settings;
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message))
{
// What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once.
IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy,
};
_requestCatalog = catalog;
SavedSession = saved;
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
{
@@ -665,6 +678,24 @@ public sealed class FebeApp : IAsyncDisposable
}
}
/// <summary>
/// The start-up line of the engine, with what it waits for: the same state as the engine's own gate
/// (<see cref="BrowserConnectionService.IsReadyToCollect"/>), so that the log never says «collegato» while the monitor
/// says «Serve «Ho finito»».
/// </summary>
internal static string StartedMessage(BrowserConnectionService connection)
{
ArgumentNullException.ThrowIfNull(connection);
if (connection.IsReadyToCollect)
{
return "Motore avviato: il browser è collegato.";
}
return connection.IsConnected == true && connection.SessionCopyMissing
? "Motore avviato: il browser è collegato, ma aspetta la copia della sessione per le richieste (pagina Collegamento, «Ho finito»)."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).";
}
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
+17 -1
View File
@@ -72,7 +72,23 @@ public interface IFebePlatform
/// the login page otherwise, once the engine's session ended and with the page's turn
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnWindowClosed">
/// What closing the browser window (or leaving it minimised too long) does before the page goes back to the engine
/// (issue #36, S4b): the connection copies the session into the saved session, when there is one
/// (<c>BrowserConnectionService.CopyOnWindowClosedAsync</c>). The window holds the driving gate until the task ends.
/// Null: nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null, Func<BrowserWindowLetGo, CancellationToken, Task>? CopyOnWindowClosed = null);
/// <summary>How Alberto let go of the window «Browser di Febe» without «Ho finito» (Windows): the log says which.</summary>
public enum BrowserWindowLetGo
{
/// <summary>He closed it.</summary>
Closed,
/// <summary>He left it minimised longer than its limit: it went out of view as if closed.</summary>
MinimizedTooLong,
}
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
+169 -15
View File
@@ -19,6 +19,12 @@ public enum SessionCopyStatus
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
Discarded,
/// <summary>
/// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose
/// «Tieni la copia completa» (<see cref="IncompleteCopyChoice.KeepComplete"/>). The saved session stays as it was.
/// </summary>
KeptComplete,
}
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
@@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e
/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop
/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the
/// saved session as it is.
/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how
/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value.
/// </summary>
/// <param name="State">Whether a saved session is there and can be read.</param>
/// <param name="CopiedAt">When the browser's session was copied; null without a session or when not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds, of <paramref name="ValuesExpected"/>.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values of the page it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds, of <paramref name="DocIdsExpected"/>.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of the missing values and doc_id a configured operation sends.</param>
public sealed record SavedSessionReport(
SavedSessionState State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>True when a readable session is there and nothing a configured operation sends is missing.</summary>
public bool Complete => State == SavedSessionState.Present && NeededMissing == 0;
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the
/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease
/// ends by itself. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e sostituisce»), also when
/// some value of the page is missing — unless Alberto chose «Tieni la copia completa» and the saved one is complete.
/// The requests that send a missing value do not leave and stop the engine as a disconnection until a new copy has it
/// (never a way back to the pages). A refused copy leaves the saved session as it is.
/// </summary>
public interface ISessionCopier
{
@@ -48,6 +85,12 @@ public interface ISessionCopier
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
/// <summary>Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often).</summary>
SavedSessionState SavedState { get; }
/// <summary>The saved session now, in counts and names (the Collegamento page, «Collegato»).</summary>
SavedSessionReport Report();
}
/// <summary>
@@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>
/// What an incomplete copy does, asked at every copy (the setting of the Collegamento page,
/// <see cref="SessionCopySettings"/>); by default it replaces the saved session, as before.
/// </summary>
public Func<CancellationToken, Task<IncompleteCopyChoice>> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace);
/// <summary>
/// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
/// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
@@ -110,24 +159,34 @@ public sealed class BrowserSessionCopier : ISessionCopier
var counts = string.Create(
CultureInfo.InvariantCulture,
$"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}");
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
var needed = neededValues.Concat(neededDocIds).ToList();
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
// An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless
// Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete. The choice
// is read before the last look at whose page it is, so that nothing awaited comes between that look and the write.
var keepComplete = needed.Count > 0 && IsComplete(_store.Read()) && await KeepsCompleteAsync().ConfigureAwait(false);
if (!mayKeep())
{
_log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts}).");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
}
// Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
// saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
if (keepComplete)
{
_log($"Sessione letta ma non salvata: {Missing(needed)}, che {(needed.Count == 1 ? "serve" : "servono")} alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts}).");
return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count);
}
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
var needed = neededValues.Concat(neededDocIds).ToList();
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
// Not cancelled from here: the copy was made, and a half-written replacement is never left.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
_log($"Sessione copiata: {counts}"
+ (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
+ (needed.Count == 0 ? string.Empty : "; " + Missing(needed) + ", che " + (needed.Count == 1 ? "serve" : "servono") + " alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; " + Missing(unused, also: true) + ", che nessuna operazione configurata usa")
+ (onDisk ? string.Empty : "; non ancora scritta su disco")
+ ".");
return new SessionCopyOutcome(
@@ -138,6 +197,56 @@ public sealed class BrowserSessionCopier : ISessionCopier
neededDocIds.Count);
}
public SavedSessionState SavedState => _store.State;
public SavedSessionReport Report()
{
var state = _store.State;
var values = state == SavedSessionState.Present ? _store.Read() : null;
if (values is null)
{
var none = state == SavedSessionState.Present ? SavedSessionState.None : state;
return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0);
}
var missingValues = new List<string>();
var needed = 0;
foreach (var read in _plan.Values)
{
if (!values.Fields.ContainsKey(read.Field))
{
missingValues.Add(read.Field);
needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0;
}
}
var missingDocIds = new List<string>();
foreach (var read in _plan.DocIds)
{
if (!values.DocIds.ContainsKey(read.Field))
{
missingDocIds.Add(read.Field);
needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0;
}
}
return new SavedSessionReport(
SavedSessionState.Present,
values.CopiedAt,
values.Cookies.Count,
_plan.Values.Count - missingValues.Count,
_plan.Values.Count,
missingValues,
_plan.DocIds.Count - missingDocIds.Count,
_plan.DocIds.Count,
missingDocIds,
needed);
}
/// <summary>«manca app_id», «mancano hsi, rev» (with <paramref name="also"/>: «manca anche …»), for the log: names only.</summary>
private static string Missing(IReadOnlyList<string> names, bool also = false) =>
(names.Count == 1 ? "manca " : "mancano ") + (also ? "anche " : string.Empty) + string.Join(", ", names);
/// <summary>Why a copy was refused, in Italian.</summary>
public static string Reason(CaptureRefusal refusal) => refusal switch
{
@@ -146,4 +255,49 @@ public sealed class BrowserSessionCopier : ISessionCopier
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
_ => "il browser non ha risposto",
};
/// <summary>
/// Whether Alberto chose «Tieni la copia completa». A choice that cannot be read (the database busy or failing) is
/// the default, «Sostituisci comunque»: the copy goes on, and «Ho finito» never fails because of the setting. The log
/// gets the kind of error only (rule 10).
/// </summary>
private async Task<bool> KeepsCompleteAsync()
{
try
{
return await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log($"Scelta per la copia incompleta non letta ({ex.GetType().Name}): vale la predefinita, la copia sostituisce quella salvata.");
return false;
}
}
/// <summary>True when <paramref name="saved"/> holds every value and doc_id a configured operation sends.</summary>
private bool IsComplete(SiteSessionValues? saved)
{
if (saved is null)
{
return false;
}
foreach (var field in _plan.NeededValues)
{
if (!saved.Fields.ContainsKey(field))
{
return false;
}
}
foreach (var operation in _plan.NeededDocIds)
{
if (!saved.DocIds.ContainsKey(operation))
{
return false;
}
}
return true;
}
}
@@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
/// <c>page</c> section of the catalog says where to read (<see cref="PageSources"/>): <c>lsd</c>, <c>fb_dtsg</c>,
/// <c>app_id</c>, <c>account_id</c>, and since S4 <c>rev</c> (<c>__rev</c>), <c>hs</c> (<c>__hs</c>), <c>hsi</c>
/// (<c>__hsi</c>), <c>dpr</c>, <c>ccg</c> (<c>__ccg</c>), <c>comet_req</c> (<c>__comet_req</c>) and
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>).
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>), and since S4b <c>spin_r</c>, <c>spin_b</c> and <c>spin_t</c>
/// (<c>__spin_r</c>, <c>__spin_b</c>, <c>__spin_t</c>: a snapshot of the page at «Ho finito», decision of 18 November
/// 2026).
/// </summary>
public static IReadOnlySet<string> SessionFields { get; } = new[]
{
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce",
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t",
}.ToFrozenSet(StringComparer.Ordinal);
/// <summary>The session fields that need no <c>page</c> entry: the browser's user agent and the claim the site sets (H13).</summary>
@@ -0,0 +1,65 @@
using Febe.Core.Storage;
namespace Febe.Core.Collection.Requests;
/// <summary>What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b).</summary>
public enum IncompleteCopyChoice
{
/// <summary>
/// «Sostituisci comunque» (the default): the new copy replaces the saved one all the same, because keeping an older
/// copy could keep the cookies of another login (§6.0).
/// </summary>
Replace,
/// <summary>
/// «Tieni la copia completa»: when the saved copy has every value the configured operations need and the new one
/// does not, the saved one stays and the message says so.
/// </summary>
KeepComplete,
}
/// <summary>
/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the
/// <c>setting</c> table like the other settings. Read at every copy: a change holds from the next copy, no restart.
/// </summary>
/// <param name="IncompleteCopy">What an incomplete copy does.</param>
public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy)
{
/// <summary>The key of <see cref="IncompleteCopy"/>: <c>sostituisci</c> or <c>tieni-completa</c>.</summary>
public const string IncompleteCopyKey = "sessione.copia-incompleta";
/// <summary>The text of <see cref="IncompleteCopyChoice.Replace"/> in the table and in the API.</summary>
public const string ReplaceText = "sostituisci";
/// <summary>The text of <see cref="IncompleteCopyChoice.KeepComplete"/> in the table and in the API.</summary>
public const string KeepCompleteText = "tieni-completa";
/// <summary>The settings of a database that never stored them: an incomplete copy replaces the saved one.</summary>
public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace);
/// <summary>The text of <paramref name="choice"/>.</summary>
public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText;
/// <summary>The choice of <paramref name="text"/>; null for any other text.</summary>
public static IncompleteCopyChoice? Parse(string? text) => text switch
{
ReplaceText => IncompleteCopyChoice.Replace,
KeepCompleteText => IncompleteCopyChoice.KeepComplete,
_ => null,
};
/// <summary>The stored settings; an unknown or missing value is the default.</summary>
public static async Task<SessionCopySettings> LoadAsync(ISettingsStore settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
var text = await settings.GetAsync(IncompleteCopyKey, ct).ConfigureAwait(false);
return Parse(text) is { } choice ? new SessionCopySettings(choice) : Default;
}
/// <summary>Stores these settings.</summary>
public Task SaveAsync(ISettingsStore settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct);
}
}
+32 -29
View File
@@ -1,6 +1,6 @@
{
"site": "instagram",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, __spin_r, __spin_b e __spin_t dalle chiavi omonime di SiteData (decisione di Alberto del 18 novembre 2026: si copiano dalla pagina a «Ho finito», come gli altri; chi le aggiunge alla richiesta resta da vedere, H23), i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce, spin_r, spin_b, spin_t), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn e __d, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"page": {
"note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
"docIdModule": "{operation}_instagramRelayOperation",
@@ -15,7 +15,10 @@
"dpr": "SiteData.pr",
"comet_req": "SiteData.comet_env",
"ccg": "WebConnectionClassServerGuess.connectionClass",
"entry_nonce": "BootloaderConfig.nonce"
"entry_nonce": "BootloaderConfig.nonce",
"spin_r": "SiteData.__spin_r",
"spin_b": "SiteData.__spin_b",
"spin_t": "SiteData.__spin_t"
}
},
"operations": [
@@ -66,9 +69,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -148,9 +151,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -226,9 +229,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -310,9 +313,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -389,9 +392,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -465,9 +468,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -538,9 +541,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -618,9 +621,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -699,9 +702,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
+8 -2
View File
@@ -15,7 +15,10 @@
"dpr": "VersioneProva.dpr",
"comet_req": "VersioneProva.comet",
"ccg": "ConnessioneProva.classe",
"entry_nonce": "AvvioProva.nonce"
"entry_nonce": "AvvioProva.nonce",
"spin_r": "GiroProva.revisione",
"spin_b": "GiroProva.ramo",
"spin_t": "GiroProva.tempo"
}
},
"operations": [
@@ -104,6 +107,9 @@
"__hs": "session:hs",
"__hsi": "session:hsi",
"__rev": "session:rev",
"__spin_r": "session:spin_r",
"__spin_b": "session:spin_b",
"__spin_t": "session:spin_t",
"dpr": "session:dpr",
"fb_dtsg": "session:fb_dtsg",
"lsd": "session:lsd",
@@ -121,7 +127,7 @@
"profilo"
],
"sample": "000002-profilo-pubblico",
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req, __spin_r, __spin_b, __spin_t) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
},
{
"name": "profilo-altri",
+10 -1
View File
@@ -12,6 +12,7 @@ public sealed class EngineRuntime
private readonly Lock _gate = new();
private readonly Func<bool> _userIsDriving;
private readonly Func<bool>? _isConnected;
private readonly Func<bool>? _sessionCopyMissing;
private CautionProfile _profile = CautionProfile.Prudent;
private DateTimeOffset? _rampStart;
private SessionContext? _session;
@@ -23,10 +24,15 @@ public sealed class EngineRuntime
/// <param name="userIsDriving">True while Alberto uses the browser (<see cref="IBrowserHost.UserIsDriving"/>).</param>
/// <param name="isConnected">Whether the Instagram session exists in the browser; null when unknown.</param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null)
/// <param name="sessionCopyMissing">
/// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36,
/// S4b): <paramref name="isConnected"/> is then false and the monitor says «Serve «Ho finito»». Null: never.
/// </param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null, Func<bool>? sessionCopyMissing = null)
{
_userIsDriving = userIsDriving ?? (() => false);
_isConnected = isConnected;
_sessionCopyMissing = sessionCopyMissing;
}
/// <summary>The effective caution profile (settings applied).</summary>
@@ -56,6 +62,9 @@ public sealed class EngineRuntime
/// <summary>Whether the browser holds an Instagram session; null when the host does not say.</summary>
public bool? IsConnected => _isConnected?.Invoke();
/// <summary>True when the browser holds the session but the copy for the requests is missing (S4b).</summary>
public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true;
/// <summary>The session in progress, if any. The Governor refuses every site action without one.</summary>
public SessionContext? CurrentSession
{
+4 -2
View File
@@ -85,6 +85,7 @@ public sealed class EngineServices
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
/// <param name="ct">Cancellation.</param>
/// <param name="sessionCopyMissing">True when the session is in the browser but its saved copy is missing (S4b).</param>
public static async Task<EngineServices> CreateAsync(
IFebeStorage storage,
IClock clock,
@@ -92,14 +93,15 @@ public sealed class EngineServices
EngineOptions? options = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null,
CancellationToken ct = default)
CancellationToken ct = default,
Func<bool>? sessionCopyMissing = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(random);
options ??= EngineOptions.Default;
var runtime = new EngineRuntime(userIsDriving, isConnected);
var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing);
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
runtime.Profile = settings.EffectiveProfile;
runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
+8 -1
View File
@@ -35,7 +35,10 @@ public sealed class EngineMonitor : IEngineMonitor
var session = runtime.CurrentSession;
var mode = ModeOf(runtime, breaker, session, window);
var resumes = ResumesAround(mode, runtime, breaker, nextWindow, now);
var (headline, details, sidebar) = Texts(mode, runtime, breaker, session, resumes, now, zone);
// Read once: the headline and the flag of the snapshot say the same thing.
var copyMissing = mode == EngineMode.NotConnected && runtime.SessionCopyMissing;
var (headline, details, sidebar) = Texts(mode, copyMissing, runtime, breaker, session, resumes, now, zone);
var budgets = _s.Governor.GetEffectiveBudgets(now);
var statuses = await _s.Governor.GetBudgetStatusAsync(ct).ConfigureAwait(false);
@@ -62,6 +65,7 @@ public sealed class EngineMonitor : IEngineMonitor
RecentActions = await RecentAsync(now, zone, ct).ConfigureAwait(false),
SuspendedRecipes = [.. _host.SuspendedRecipes.Select(r => new SuspendedRecipeView(r.Key, ItalianText.Capitalize(SessionComposer.RecipeName(r.Key)), r.Value))],
Breaker = breaker,
SessionCopyMissing = copyMissing,
};
}
@@ -136,6 +140,7 @@ public sealed class EngineMonitor : IEngineMonitor
private static (string Headline, IReadOnlyList<string> Details, string Sidebar) Texts(
EngineMode mode,
bool copyMissing,
EngineRuntime runtime,
BreakerState breaker,
SessionContext? session,
@@ -184,6 +189,8 @@ public sealed class EngineMonitor : IEngineMonitor
case EngineMode.Disconnected:
return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo");
case EngineMode.NotConnected when copyMissing:
return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»");
case EngineMode.NotConnected:
return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato");
case EngineMode.UserDriving:
+6
View File
@@ -190,4 +190,10 @@ public sealed record EngineSnapshot
public required IReadOnlyList<SuspendedRecipeView> SuspendedRecipes { get; init; }
public required BreakerState Breaker { get; init; }
/// <summary>
/// Not connected because the copy for the requests is missing (issue #36, S4b): the browser has the session cookie,
/// the raccolta «richieste» has no readable saved session. The headline is then «Serve «Ho finito»».
/// </summary>
public bool SessionCopyMissing { get; init; }
}
+8 -4
View File
@@ -4,6 +4,7 @@ using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.App;
using Febe.Desktop.Native;
namespace Febe.Desktop.Browser;
@@ -135,8 +136,11 @@ internal sealed class BrowserWindow : Window
/// <summary>Raised by «Pagina iniziale».</summary>
public event EventHandler? HomeRequested;
/// <summary>Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view.</summary>
public event EventHandler? DoneRequested;
/// <summary>
/// Raised when Alberto closes the window, or leaves it minimised too long (which one is the argument): the owner puts
/// it out of view.
/// </summary>
public event EventHandler<BrowserWindowLetGo>? DoneRequested;
/// <summary>Raised when the page area changed size (a new fit): the owner sizes WebView2 again.</summary>
public event EventHandler? PageAreaChanged;
@@ -253,7 +257,7 @@ internal sealed class BrowserWindow : Window
{
// The browser stays open: closing the window means «ho finito», it goes out of view.
e.Cancel = true;
DoneRequested?.Invoke(this, EventArgs.Empty);
DoneRequested?.Invoke(this, BrowserWindowLetGo.Closed);
}
base.OnClosing(e);
@@ -283,7 +287,7 @@ internal sealed class BrowserWindow : Window
if (WindowState == WindowState.Minimized)
{
// Restored out of view by the owner (MoveOffScreen), never first on screen where it was.
DoneRequested?.Invoke(this, EventArgs.Empty);
DoneRequested?.Invoke(this, BrowserWindowLetGo.MinimizedTooLong);
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
Host = new WebView2Host(
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage),
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed),
context.Log);
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
+40 -5
View File
@@ -23,7 +23,12 @@ namespace Febe.Desktop.Browser;
/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise,
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnClose">
/// What closing the window (or leaving it minimised too long, the argument says which) does before the page goes back
/// to the engine (issue #36, S4b): the connection copies the session, when it keeps a saved one. The window keeps the
/// engine still until the task ends. Null: nothing.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null, Func<BrowserWindowLetGo, CancellationToken, Task>? CopyOnClose = null);
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
internal enum ProcessFailureResponse
@@ -349,7 +354,7 @@ internal sealed class WebView2Host : IBrowserHost
window.MoveOffScreen();
window.Show();
window.Activated += OnActivated;
window.DoneRequested += (_, _) => Done();
window.DoneRequested += (_, how) => Done(how);
window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack);
window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true);
window.HomeRequested += (_, _) => OpenStartPage();
@@ -554,12 +559,42 @@ internal sealed class WebView2Host : IBrowserHost
TakeLease();
}
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
private void Done()
/// <summary>
/// Alberto closed the window (or left it minimised too long): done, out of view at once. With a saved session
/// (S4b) the session is copied first: a hold of the driving gate keeps the page his until the copy is over, and only
/// then does it go back to the engine (rule 7).
/// </summary>
private void Done(BrowserWindowLetGo how)
{
_window?.MoveOffScreen();
ReleaseLease();
NotifyPositionChanged();
if (_lease is null || _closing || _settings.CopyOnClose is not { } copy)
{
ReleaseLease();
return;
}
var hold = UserDriving.Begin();
ReleaseLease();
_ = CopyThenLetGoAsync(copy, how, hold);
}
private async Task CopyThenLetGoAsync(Func<BrowserWindowLetGo, CancellationToken, Task> copy, BrowserWindowLetGo how, IDisposable hold)
{
try
{
await copy(how, CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The kind of error only: the page and the browser may hold what the session holds.
_log.Warn("browser", $"Copia della sessione alla chiusura della finestra non riuscita ({ex.GetType().Name}).");
}
finally
{
hold.Dispose();
_settings.MarkUsed();
}
}
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
+20 -5
View File
@@ -26,6 +26,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly Action? _viewClosed;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
@@ -43,7 +44,12 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
/// with the page's turn; null: the button does nothing.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
/// <param name="viewClosed">
/// Told when a view ends from the page's side (the page left, the tab closed, the link lost), not when another view
/// takes its place or Febe stops: the connection then knows that Alberto may have left the browser (Docker, answer of
/// 25 November 2026, spec §6.0 «Quando si copia»); null: nobody is told.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null, Action? viewClosed = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
@@ -51,6 +57,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
_openStartPage = openStartPage;
_viewClosed = viewClosed;
}
/// <summary>
@@ -104,8 +111,8 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
catch (Exception ex)
{
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
// no lease, no screencast, no subscription.
await connection.DisposeAsync().ConfigureAwait(false);
// no lease, no screencast, no subscription. Ended by the server: the page did not leave the browser.
await connection.EndAsync(RemoteViewEnd.BrowserStopped).ConfigureAwait(false);
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
@@ -158,7 +165,9 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
}
internal void Closed(BrowserRemoteViewConnection connection)
/// <param name="connection">The view that ended.</param>
/// <param name="byPage">True when the page ended it (left, tab closed, link lost), false when the server did.</param>
internal void Closed(BrowserRemoteViewConnection connection, bool byPage)
{
lock (_gate)
{
@@ -169,6 +178,10 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
_log.Info("vista", "Vista remota chiusa.");
if (byPage)
{
_viewClosed?.Invoke();
}
}
}
@@ -445,6 +458,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
return;
}
// No reason given by the server (another view, Febe stopping, the browser gone): the page closed it.
var byPage = Ended is null;
Ended ??= RemoteViewEnd.BrowserStopped;
await _ended.CancelAsync().ConfigureAwait(false);
_session.Screencast.FrameReceived -= OnFrame;
@@ -462,7 +477,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
// The browser is gone: the lease is released anyway.
}
_owner.Closed(this);
_owner.Closed(this, byPage);
}
private void MarkUsed()
+9 -1
View File
@@ -87,7 +87,15 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// A view closed by its page may be Alberto leaving the browser (answer of 25 November 2026): the connection copies
// the session and gives the page back if no other view opens within a moment (spec §6.0 «Quando si copia»).
RemoteView = new BrowserRemoteViewHost(
app.Browser!,
app.Tracker,
app.Clock,
app.Log,
openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
viewClosed: () => app.Connection?.RemoteViewClosed());
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+45 -2
View File
@@ -1,4 +1,6 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Native;
@@ -36,7 +38,9 @@ public static class ConnectionApi
});
// «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52).
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). In Docker leaving
// the page lets go of the browser like closing that window: the session is copied, not cancelled (answer of
// 25 November 2026). Only the button «Annulla» cancels without copying.
endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) =>
{
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false);
@@ -44,6 +48,10 @@ public static class ConnectionApi
{
await connection.ReleaseAsync(ct).ConfigureAwait(false);
}
else if (body.PageLeft)
{
await connection.LeavePageAsync(ct).ConfigureAwait(false);
}
else
{
await connection.CancelAsync(ct).ConfigureAwait(false);
@@ -57,19 +65,54 @@ public static class ConnectionApi
await connection.DisconnectAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
// What an incomplete copy of the session does (issue #36, S4b, answer 9): read at every copy, no restart.
endpoints.MapGet("/api/connection/settings", async (IFebeStorage storage, CancellationToken ct) =>
ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto));
endpoints.MapPut("/api/connection/settings", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConnectionSettingsDto).ConfigureAwait(false);
var choice = SessionCopySettings.Parse(body.IncompleteCopy)
?? throw new BadRequestException($"Scelta sconosciuta per la copia incompleta: ammesse «{SessionCopySettings.ReplaceText}» e «{SessionCopySettings.KeepCompleteText}».");
await new SessionCopySettings(choice).SaveAsync(storage.Settings, ct).ConfigureAwait(false);
return ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto);
});
}
private static async Task<ConnectionSettingsDto> SettingsAsync(IFebeStorage storage, CancellationToken ct)
{
var settings = await SessionCopySettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
return new ConnectionSettingsDto(SessionCopySettings.ToText(settings.IncompleteCopy));
}
public static ConnectionStatusDto ToDto(ConnectionStatus status)
{
ArgumentNullException.ThrowIfNull(status);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl, ToDto(status.SavedSession));
}
/// <summary>The saved session in counts and names; null without one.</summary>
public static SavedSessionDto? ToDto(SavedSessionStatus? saved) => saved is null
? null
: new SavedSessionDto(
saved.State,
saved.CopiedAt?.ToUnixTimeMilliseconds(),
saved.Cookies,
saved.ValuesPresent,
saved.ValuesExpected,
saved.MissingValues,
saved.DocIdsPresent,
saved.DocIdsExpected,
saved.MissingDocIds,
saved.NeededMissing);
public static string State(ConnectionState state) => state switch
{
ConnectionState.NotConnected => "notConnected",
ConnectionState.Connected => "connected",
ConnectionState.VerificationRequired => "verificationRequired",
ConnectionState.SessionCopyMissing => "copyMissing",
_ => "browserUnavailable",
};
}
+11 -4
View File
@@ -84,8 +84,9 @@ public static class EngineApi
/// <summary>
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
/// (or there is none in this process) the connection is asked.
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so, and whether the copy for
/// the requests is missing too (<see cref="EngineSnapshot.SessionCopyMissing"/>, no round trip to the browser at every
/// event); only when it does not run (or there is none in this process) the connection is asked.
/// </summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
{
@@ -98,10 +99,16 @@ public static class EngineApi
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
{
EngineMode.NotConnected => "notConnected",
// The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account.
EngineMode.NotConnected => snapshot.SessionCopyMissing ? "copyMissing" : "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch
{
ConnectionState.Connected => "connected",
ConnectionState.SessionCopyMissing => "copyMissing",
_ => "notConnected",
},
_ => "connected",
};
var link = state == "notConnected"
+1
View File
@@ -48,6 +48,7 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(LoginDto))]
[JsonSerializable(typeof(Library.LibraryChange))]
[JsonSerializable(typeof(ConnectionStatusDto))]
[JsonSerializable(typeof(ConnectionSettingsDto))]
[JsonSerializable(typeof(BeginDrivingRequest))]
[JsonSerializable(typeof(CancelDrivingRequest))]
[JsonSerializable(typeof(FinishDto))]
+27 -2
View File
@@ -5,8 +5,33 @@ namespace Febe.Web.Api;
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
/// <summary><c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, verificationRequired, browserUnavailable.</summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
/// <summary>
/// <c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, copyMissing, verificationRequired,
/// browserUnavailable. <see cref="SavedSession"/> only with the raccolta «richieste».
/// </summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null);
/// <summary>
/// The saved session in counts and names (issue #36, S4b): <see cref="State"/> present, none or unreadable;
/// <see cref="CopiedAt"/> Unix milliseconds. Never a value.
/// </summary>
public sealed record SavedSessionDto(
string State,
long? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing);
/// <summary>
/// <c>GET/PUT /api/connection/settings</c>: what an incomplete copy of the session does, <c>sostituisci</c> (the
/// default) or <c>tieni-completa</c>.
/// </summary>
public sealed record ConnectionSettingsDto(string IncompleteCopy);
/// <summary><c>POST /api/connection/begin</c>.</summary>
public sealed record BeginDrivingRequest(bool OpenLogin);
+54 -1
View File
@@ -14,6 +14,48 @@ public enum ConnectionState
/// <summary>The browser is not available (starting, crashed, demo without browser).</summary>
BrowserUnavailable,
/// <summary>
/// The session cookie is in the browser, but the raccolta «richieste» has no readable saved session to send it with
/// (issue #36, S4b): «Serve «Ho finito»». The engine waits until a copy is made.
/// </summary>
SessionCopyMissing,
}
/// <summary>
/// The saved session of the raccolta «richieste» as the Collegamento page shows it (issue #36, S4b): counts and names
/// only, never a value (rule 10).
/// </summary>
/// <param name="State"><see cref="Present"/>, <see cref="None"/> or <see cref="Unreadable"/>.</param>
/// <param name="CopiedAt">When the copy was made; null when there is none or it is not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of those a configured operation sends (its requests do not leave).</param>
public sealed record SavedSessionStatus(
string State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>A readable saved session.</summary>
public const string Present = "present";
/// <summary>No saved session.</summary>
public const string None = "none";
/// <summary>A file that cannot be read: counts as none.</summary>
public const string Unreadable = "unreadable";
}
/// <summary>What the interface knows about the link to Instagram.</summary>
@@ -22,12 +64,14 @@ public enum ConnectionState
/// <param name="DisplayName">Display name, when known.</param>
/// <param name="UserIsDriving">True while Alberto is using the browser (login page, remote view, browser window): the engine is still.</param>
/// <param name="CurrentUrl">Address shown in the remote view's address bar, without query string.</param>
/// <param name="SavedSession">The saved session (raccolta «richieste»); null when this start keeps none.</param>
public sealed record ConnectionStatus(
ConnectionState State,
string? Username,
string? DisplayName,
bool UserIsDriving,
string? CurrentUrl);
string? CurrentUrl,
SavedSessionStatus? SavedSession = null);
/// <summary>Result of «Ho finito» on the Collegamento page.</summary>
/// <param name="Connected">True when the session cookie now exists.</param>
@@ -70,6 +114,15 @@ public interface IConnectionService
/// </summary>
Task ReleaseAsync(CancellationToken ct);
/// <summary>
/// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is the
/// remote view (Docker, answer of Alberto of 25 November 2026, spec §6.0 «Quando si copia»): like closing the window
/// «Browser di Febe» on Windows, not like «Annulla». If within a moment no view opens again and no «Accedi» / «Usa il
/// browser» comes (a reload is not leaving), the session is copied while the page is still his, and then the page goes
/// back to the engine. By default, for a service without a saved session to copy, it is «Annulla».
/// </summary>
Task LeavePageAsync(CancellationToken ct) => CancelAsync(ct);
/// <summary>«Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile.</summary>
Task DisconnectAsync(CancellationToken ct);
}
+17 -2
View File
@@ -7,11 +7,12 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
| Endpoint | Corpo e risposta |
|---|---|
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` |
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"copyMissing"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl, savedSession }` |
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) |
| `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») |
| `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) |
| `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) |
| `GET /api/connection/settings`, `PUT /api/connection/settings` | `{ incompleteCopy: "sostituisci"\|"tieni-completa" }`: che cosa fa una copia della sessione incompleta (raccolta «richieste»); un altro valore → 400 |
| `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale |
**Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la
@@ -27,9 +28,23 @@ di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
**Raccolta «richieste»** (issue #36, S4b): `savedSession` è `null` senza sessione salvata in questo avvio («pagine», o
nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadable", copiedAt (ms Unix o null), cookies,
valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni],
neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata
leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel
collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows, lasciando la
pagina del browser in Docker (sotto) e quando il permesso di guida finisce da solo, sempre prima che la pagina torni al
motore. «Annulla» non copia mai.
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo).
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker non è «Annulla» (`IConnectionService.LeavePageAsync`,
risposta di Alberto del 25 novembre 2026): è come chiudere la finestra del browser su Windows. Febe lo nota e aspetta
5 secondi; anche la vista remota chiusa dalla sua pagina (scheda chiusa, collegamento perso, non sostituita da un'altra
scheda) fa ricominciare l'attesa. Se in quel tempo non si apre un'altra vista e non arriva un `begin` (una pagina
ricaricata fa tutti e due), copia la sessione come alla chiusura della finestra (solo da una pagina del sito che non sia
di accesso o di verifica), poi il permesso finisce e il motore rimette il browser a riposo.
Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta
com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta
fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
+9
View File
@@ -802,6 +802,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
.collega-destra h2.sez{margin-bottom:12px}
.collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px}
.nota-password{background:var(--accento-tinta)}
.sessione-salvata{padding:14px 16px;font-size:13.5px;line-height:1.5}
.sessione-salvata p{margin:0 0 6px}
.sessione-salvata h2.sez{margin-bottom:8px}
.sessione-salvata h3.sez{font-size:13.5px;font-weight:650;margin:12px 0 8px}
.sessione-salvata .avviso{margin:4px 0 8px}
.sessione-salvata .scelte{display:flex;flex-direction:column;gap:10px}
.sessione-salvata .scelte .voce{align-items:flex-start}
.sessione-salvata .scelte .voce .tondo{margin-top:2px}
.sessione-salvata .scelte small{display:block;color:var(--testo-2);font-size:12.5px}
.passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px}
.passi-collegamento li{display:flex;gap:14px}
.passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px}
+1 -1
View File
@@ -63,7 +63,7 @@ function renderStatus(state) {
const s = state.snapshot;
const meter = s.profilesOpenedToday;
const connection = state.connection;
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato');
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : connection.state === 'copyMissing' ? 'stato.copiaMancante' : 'stato.collegato');
// The own account is known only after the first sweep (a verification can come before it): no «@null».
const who = connection.state === 'notConnected'
? h('div.chi', h('span.av.segnaposto', icon('user', 's')),
+2 -2
View File
@@ -1,8 +1,8 @@
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito»
// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it
// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// (another page, a reload, closing the tab) gives the browser back, like closing the window on Windows: the server copies
// the session if no view opens again within a moment (on Windows the window stays as it is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// opens the login page, once: the parameter leaves the address straight away.
import { api } from '../core/api.js';
+95 -10
View File
@@ -2,7 +2,9 @@
// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still.
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste»
// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an
// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing.
import { api } from '../core/api.js';
import { caps } from '../core/context.js';
@@ -10,10 +12,10 @@ import { h, icon, fill } from '../core/dom.js';
import { engineState, refreshEngine } from '../core/engine.js';
import { navigate } from '../core/shell.js';
import { t } from '../core/text.js';
import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js';
import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js';
import { remoteView } from './remote-view.js';
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' };
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' };
/** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */
function waitsForResume(state) {
@@ -40,9 +42,10 @@ export async function beginDriving(openLogin) {
/**
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the
* browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as
* it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like closing the
* window on Windows, not like «Annulla» (answer of 25 November 2026: if no view opens again within a moment, the
* server copies the session and the engine may work again; a reload opens the view again); on Windows the window
* «Browser di Febe» stays as it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
*/
export function drivingLease(page) {
let held = false;
@@ -120,6 +123,7 @@ export async function mountConnection(page) {
fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
if (status.state === 'connected') drawConnected();
else if (status.state === 'browserUnavailable') drawUnavailable();
else if (status.state === 'copyMissing') drawLogin({ copyMissing: true });
else drawLogin();
}
@@ -145,15 +149,17 @@ export async function mountConnection(page) {
});
// ------------------------------------------------------------------------------------------- login or verification
function drawLogin() {
function drawLogin({ copyMissing = false } = {}) {
const verification = status.state === 'verificationRequired';
// Connected but without the copy for the requests: the start page (the site's home), never the login page.
const login = !verification && !copyMissing;
waitingResume = false;
closeView();
lease.begin(!verification);
lease.begin(login);
if (windows) {
fill(left, windowPanel());
} else {
view = remoteView(page, { url: status.currentUrl, login: !verification });
view = remoteView(page, { url: status.currentUrl, login });
fill(left, view.element);
}
const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
@@ -161,6 +167,8 @@ export async function mountConnection(page) {
fill(right,
verification
? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
: copyMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto')))
: h('div',
h('h2.sez', t('impostazioni.collegamento.come')),
h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))),
@@ -168,6 +176,7 @@ export async function mountConnection(page) {
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
// Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is.
windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null,
copyMissing ? savedSessionBox(status.savedSession, page) : null,
message,
h('div.molla'),
h('div.bottoni-collegamento',
@@ -235,7 +244,8 @@ export async function mountConnection(page) {
fill(right,
passwordNote(windows),
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))));
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))),
savedSessionBox(status.savedSession, page));
}
async function useBrowser() {
@@ -287,6 +297,81 @@ export async function mountConnection(page) {
await draw();
}
/**
* The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present
* and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an
* incomplete copy. Nothing without a saved session in this start («pagine»).
*/
export function savedSessionBox(saved, page) {
if (!saved) return null;
const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars);
const lines = [];
if (saved.state === 'present') {
if (saved.copiedAt) {
const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' });
lines.push(h('p', k('copiata', { quando: when })));
}
lines.push(h('p.muto', [
k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }),
k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }),
k('cookie', { n: String(saved.cookies) }),
].join(' ')));
const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])];
if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') })));
lines.push(saved.neededMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) })))
: h('p', k('completa')));
} else {
lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna')));
}
// Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page
// never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it;
// a choice the server did not save goes back to the one before.
let saved = null;
let chosen = false;
const show = (value) => {
keep.input.checked = value === 'tieni-completa';
replace.input.checked = value === 'sostituisci';
};
const choose = async (value) => {
chosen = true;
const before = saved;
try {
const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
saved = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
unknown.hidden = true;
toast(k('salvato'));
} catch (error) {
show(before);
showError(error);
}
};
const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) });
const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) });
const unknown = h('p.aiuto.piccolo.scelta-ignota', { hidden: true }, k('sceltaIgnota'));
for (const choice of [replace, keep]) choice.input.disabled = true;
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
if (chosen) return;
saved = settings.incompleteCopy;
show(saved);
}).catch(() => {
if (page && page.signal && page.signal.aborted) return; // the page was left
if (!chosen) unknown.hidden = false;
}).finally(() => {
if (page && page.signal && page.signal.aborted) return;
for (const choice of [replace, keep]) choice.input.disabled = false;
});
return h('div.pannello.sessione-salvata',
h('h2.sez', k('titolo')),
...lines,
h('p.aiuto.piccolo', k('nota')),
h('h3.sez', k('incompleta')),
h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep),
unknown);
}
/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
export function passwordNote(windows) {
return h('div.avviso.nota-password', icon('shield-check', 's'),
+24
View File
@@ -24,6 +24,7 @@
"nessunAccount": "Nessun account",
"verifica": "Verifica richiesta",
"scollegato": "Sessione chiusa",
"copiaMancante": "Serve «Ho finito»",
"accountDaLeggere": "Nome non ancora noto",
"nonDisponibile": "Stato del motore non disponibile"
},
@@ -690,9 +691,32 @@
"stati": {
"notConnected": "Non collegato",
"connected": "Collegato",
"copyMissing": "Serve «Ho finito»",
"verificationRequired": "Verifica richiesta",
"browserUnavailable": "Browser non disponibile"
},
"copiaMancanteTitolo": "Manca la copia della sessione",
"copiaMancanteTesto": "Il browser è collegato, ma Febe non ha ancora una copia della sessione per le richieste (o non riesce a leggerla). Apri la tua pagina iniziale nel browser e premi «Ho finito»: fino ad allora il motore aspetta.",
"salvata": {
"titolo": "Sessione salvata per le richieste",
"copiata": "Copiata {quando}.",
"nessuna": "Nessuna copia: premi «Ho finito» sulla tua pagina iniziale.",
"illeggibile": "C'è un file, ma Febe non riesce a leggerlo (un'altra chiave o un file rovinato): conta come nessuna copia. Il prossimo «Ho finito» lo sostituisce.",
"valori": "Valori della pagina: {presenti} su {attesi}.",
"docId": "doc_id: {presenti} su {attesi}.",
"cookie": "Cookie: {n}.",
"mancano": "Mancano: {nomi}.",
"servono": "{n} di questi serve alle richieste configurate: le richieste che lo usano non partono e, alla prima, Febe si ferma come disconnessione.|{n} di questi servono alle richieste configurate: quelle richieste non partono e, alla prima, Febe si ferma come disconnessione.",
"completa": "Nulla di ciò che le richieste configurate mandano manca.",
"nota": "Qui ci sono solo conteggi e nomi, mai i valori.",
"incompleta": "Se una copia nuova è incompleta",
"sostituisci": "Sostituisci comunque (consigliato)",
"sostituisciAiuto": "La copia nuova prende sempre il posto di quella salvata: una copia più vecchia potrebbe avere i cookie di un altro accesso.",
"tieni": "Tieni la copia completa",
"tieniAiuto": "Se alla copia nuova manca qualcosa che le richieste usano e quella salvata è completa, Febe tiene quella salvata e te lo dice.",
"salvato": "Scelta salvata: vale dalla prossima copia.",
"sceltaIgnota": "Febe non è riuscito a leggere la scelta salvata: scegline una per salvarla di nuovo."
},
"come": "Come collegarti",
"passi": [
{