Sessione salvata: correzioni della revisione di S4b (#36)

Un errore imprevisto durante la copia senza «Ho finito» (database, disco) non trattiene più per sempre il permesso di guida: la copia scrive solo il tipo d'errore e la guida finisce lo stesso, così il motore non resta in «Stai usando il browser». Un «Ho finito» tardivo dopo una copia fatta lasciando il browser dice che la sessione era già stata copiata invece di chiedere un nuovo accesso. Il registro distingue la finestra chiusa da quella ridotta a icona troppo a lungo. /api/engine e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore (EngineSnapshot.SessionCopyMissing) senza chiedere al browser a ogni evento. La prova di WebView2 aspetta la riga del registro, non solo la sessione in memoria. Documenti: nove operazioni GraphQL con __spin_*, H23 descritta in prove-dal-vivo (parte E), guida aggiornata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-18 12:13:25 +01:00
1 parent 883ea4683c
commit c69755db23
20 files changed
+310 -54

No files matched your search

+66 -19
View File
@@ -84,6 +84,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
private SessionCopyOutcome? _letGoCopy;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -205,14 +206,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
/// <summary>
/// The window «Browser di Febe» was closed by Alberto without «Ho finito» (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.
/// 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(CancellationToken ct)
public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct)
{
const string What = "Finestra del browser chiusa";
var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa";
if (_copier is null || !_browser.IsAvailable)
{
return;
@@ -226,7 +227,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
catch (OperationCanceledException) when (limit.IsCancellationRequested)
{
_log.Info("collegamento", $"{What}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
return;
}
catch (ObjectDisposedException)
@@ -236,7 +237,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
try
{
await CopyOnLetGoAsync(What, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
await CopyOnLetGoAsync(what, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
}
finally
{
@@ -254,6 +255,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;
@@ -403,7 +406,7 @@ 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();
@@ -427,9 +430,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.");
@@ -748,6 +751,12 @@ 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>
@@ -773,7 +782,15 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide.
await _commands.WaitAsync(ct).ConfigureAwait(false);
try
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
return true; // Febe is stopping
}
try
{
bool StillAlbertos()
@@ -844,6 +861,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
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)}.");
@@ -857,6 +879,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
_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>
@@ -977,20 +1005,30 @@ 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);
}
var hold = _browser.UserDriving.Begin();
@@ -1000,7 +1038,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()
@@ -1011,7 +1049,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
{
@@ -1023,11 +1061,14 @@ 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 missingClause = missing == 0
@@ -1037,6 +1078,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
$" 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}");
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 => string.Create(
CultureInfo.InvariantCulture,
$"Quando il browser è tornato al motore alla pagina mancavano {missing} valori che servono alle richieste: 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,
+1 -1
View File
@@ -270,7 +270,7 @@ public sealed class FebeApp : IAsyncDisposable
Log,
Tracker,
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
ct => Connection?.CopyOnWindowClosedAsync(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);
+15 -4
View File
@@ -73,11 +73,22 @@ public interface IFebePlatform
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
/// <param name="CopyOnWindowClosed">
/// What closing the browser window 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.
/// 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<CancellationToken, Task>? CopyOnWindowClosed = null);
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
+7 -2
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,7 +189,7 @@ 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 runtime.SessionCopyMissing:
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");
+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);
}
}
+9 -8
View File
@@ -24,10 +24,11 @@ namespace Febe.Desktop.Browser;
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
/// </param>
/// <param name="CopyOnClose">
/// What closing the window 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.
/// 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<CancellationToken, Task>? CopyOnClose = null);
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
@@ -353,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();
@@ -563,7 +564,7 @@ internal sealed class WebView2Host : IBrowserHost
/// (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()
private void Done(BrowserWindowLetGo how)
{
_window?.MoveOffScreen();
NotifyPositionChanged();
@@ -575,14 +576,14 @@ internal sealed class WebView2Host : IBrowserHost
var hold = UserDriving.Begin();
ReleaseLease();
_ = CopyThenLetGoAsync(copy, hold);
_ = CopyThenLetGoAsync(copy, how, hold);
}
private async Task CopyThenLetGoAsync(Func<CancellationToken, Task> copy, IDisposable hold)
private async Task CopyThenLetGoAsync(Func<BrowserWindowLetGo, CancellationToken, Task> copy, BrowserWindowLetGo how, IDisposable hold)
{
try
{
await copy(CancellationToken.None).ConfigureAwait(true);
await copy(how, CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
+4 -3
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)
{
@@ -99,7 +100,7 @@ public static class EngineApi
var state = snapshot.Mode switch
{
// The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account.
EngineMode.NotConnected => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.SessionCopyMissing ? "copyMissing" : "notConnected",
EngineMode.NotConnected => snapshot.SessionCopyMissing ? "copyMissing" : "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch