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

+10 -1
View File
@@ -2,6 +2,7 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Desktop.Browser;
using Febe.SitoDiProva;
@@ -162,7 +163,14 @@ public sealed class BrowserWindowTests
public async Task AMinimisedWindowKeepsAlbertoAtTheWheelUntilItIsMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta");
// What the window tells the connection when it lets go (S4b): the log must not say «chiusa» for this.
var letGo = new System.Collections.Concurrent.ConcurrentQueue<BrowserWindowLetGo>();
await using var bed = await BrowserBed.CreateAsync("finestra-ridotta", copyOnWindowClosed: (how, _) =>
{
letGo.Enqueue(how);
return Task.CompletedTask;
});
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
await bed.OnUiAsync(() => window.MinimizedLimit = TimeSpan.FromSeconds(1));
@@ -174,6 +182,7 @@ public sealed class BrowserWindowTests
// Left there: restored and put out of view, as if closed (S2: never minimised for long).
await bed.WaitUntilAsync(() => !bed.Browser.UserIsDriving, TimeSpan.FromSeconds(15), "la fine della guida dopo la finestra ridotta a icona", ct);
CollectionAssert.AreEqual(new[] { BrowserWindowLetGo.MinimizedTooLong }, letGo.ToArray());
Assert.AreEqual(WindowState.Normal, await bed.OnUiAsync(() => window.WindowState));
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(await bed.OnUiAsync(() => window.ShowInTaskbar));
@@ -50,7 +50,8 @@ internal sealed class BrowserBed : IAsyncDisposable
/// does nothing (never the default login page of the options, which is Instagram's).
/// </param>
/// <param name="openStartPage">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null, Func<CancellationToken, Task>? openStartPage = null)
/// <param name="copyOnWindowClosed">What closing the window, or leaving it minimised too long, does (S4b); null: nothing.</param>
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func<string>? startPage = null, Func<CancellationToken, Task>? openStartPage = null, Func<BrowserWindowLetGo, CancellationToken, Task>? copyOnWindowClosed = null)
{
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
@@ -63,7 +64,7 @@ internal sealed class BrowserBed : IAsyncDisposable
var tracker = new BrowserUseTracker();
WebView2Browser? built = null;
openStartPage ??= startPage is null ? null : async ct => await built!.Cdp.NavigateAsync(startPage(), ct);
var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage);
var context = new FebePlatformContext(options, data, database, clock, log, tracker, openStartPage, copyOnWindowClosed);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
@@ -92,7 +92,8 @@ public sealed class WebView2ConnectionTests
window.Close();
return true;
});
await bed.WaitUntilAsync(() => Task.FromResult(savedSession.Read() is not null), TimeSpan.FromSeconds(30), "la copia alla chiusura della finestra", ct);
// The saved session is readable before it is written to disk and before the log lines: wait for the last of them.
await bed.WaitUntilAsync(() => Task.FromResult(savedSession.Read() is not null && bed.Lines.Any("Finestra del browser chiusa: sessione copiata")), TimeSpan.FromSeconds(30), "la copia alla chiusura della finestra", ct);
var saved = savedSession.Read()!;
Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]);
Assert.AreEqual(Febe.SitoDiProva.TestSite.EntryNonce, saved.Fields["entry_nonce"]);
@@ -109,7 +109,7 @@ public sealed class SavedSessionConnectionTests
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ALateHoFinitoAfterTheLeaseEndedDoesNotCopy()
public async Task ALateHoFinitoAfterTheLeaseEndedReadsNothingAndSaysTheSessionWasAlreadyCopied()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
@@ -128,11 +128,28 @@ public sealed class SavedSessionConnectionTests
var copied = bed.App.SavedSession!.Read();
Assert.IsNotNull(copied);
// «Ho finito» pressed late: nothing is read from a page that is not his, and he is not asked to log in again
// for a session copied a moment before.
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean());
StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata");
var message = finish.GetProperty("message").GetString()!;
StringAssert.Contains(message, "era già stata copiata quando il browser è tornato al motore");
StringAssert.Contains(message, "Non serve rifare l'accesso");
Assert.DoesNotContain("non è stata copiata", message);
Assert.DoesNotContain("Rifai l'accesso", message);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.AreSame(copied, bed.App.SavedSession.Read());
// A new use of the browser whose end copies nothing (the login page): a late «Ho finito» now says that this time
// the session was not copied, even if an earlier use had copied it.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/accesso/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida sulla pagina di accesso");
finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
StringAssert.Contains(finish.GetProperty("message").GetString(), "non è stata copiata");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.AreSame(copied, bed.App.SavedSession.Read());
}
[TestMethod]
@@ -118,6 +118,64 @@ public sealed class SessionCopyOnLetGoTests
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "refused before the modules are read");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AnErrorDuringTheCopyWhenAlbertoLetsGoStillGivesThePageBackToTheEngine()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.DrivingGrace = TimeSpan.FromMilliseconds(300);
// An error nobody expects in the middle of the copy (the database busy, say): the end of the lease must still
// come, or the engine would stay in «Stai usando il browser» for ever.
browser.FakeCdp.OnCapture = () => throw new Microsoft.Data.Sqlite.SqliteException("prova: database occupato", 5);
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo un errore della copia");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession!.Read());
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("il motore può riprendere", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della fine della guida");
var log = ReadLog(bed);
StringAssert.Contains(log, "Fine della guida del browser: copia della sessione non riuscita per un errore (SqliteException).");
Assert.DoesNotContain("database occupato", log, "the kind of error only (rule 10)");
// The same error when the window is closed: the page goes back all the same.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(2, browser.FakeCdp.CaptureReads);
Assert.IsFalse(browser.UserIsDriving);
StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: copia della sessione non riuscita per un errore (SqliteException).");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheLogSaysWhetherTheWindowWasClosedOrLeftMinimisedTooLong()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct, Febe.App.BrowserWindowLetGo.MinimizedTooLong);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
var log = ReadLog(bed);
StringAssert.Contains(log, "Finestra del browser ridotta a icona troppo a lungo: sessione copiata");
Assert.DoesNotContain("Finestra del browser chiusa", log, "it was not closed");
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
StringAssert.Contains(ReadLog(bed), "Finestra del browser chiusa: sessione copiata");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt()
@@ -244,6 +302,34 @@ public sealed class SessionCopyOnLetGoTests
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0)), "mancano 2 valori");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0)), "resta quella completa");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Refused, Febe.Browser.Session.CaptureRefusal.CheckpointPage, 0, 0, 0)), "pagina di accesso o di verifica");
// A late «Ho finito» after the copy made when the browser went back to the engine.
var before = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0), earlier: true);
StringAssert.Contains(before, "era già stata copiata quando il browser è tornato al motore");
StringAssert.Contains(before, "Non serve rifare l'accesso");
Assert.DoesNotContain("non è stata copiata", before);
var beforeIncomplete = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 2, 0), earlier: true);
StringAssert.Contains(beforeIncomplete, "era già stata copiata");
StringAssert.Contains(beforeIncomplete, "mancavano 2 valori");
Assert.DoesNotContain("Non serve rifare l'accesso", beforeIncomplete);
StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.SavedInMemoryOnly, null, 3, 0, 0), earlier: true), "non ancora scritta su disco");
StringAssert.Contains(BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0), earlier: true), "Quando il browser è tornato al motore alla pagina mancavano 1 valori");
}
/// <summary>The log files of this start, read while Febe still writes them.</summary>
private static string ReadLog(DesktopTestBed bed)
{
var folder = bed.App.Log.Folder;
Assert.IsNotNull(folder, "the log has a folder");
var text = new System.Text.StringBuilder();
foreach (var file in Directory.GetFiles(folder))
{
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new StreamReader(stream);
text.Append(reader.ReadToEnd());
}
return text.ToString();
}
private async Task<DesktopTestBed> StartAsync()
@@ -199,8 +199,9 @@ internal sealed class FakeBrowser : IFebeBrowser
/// <summary>
/// Like Alberto closing the real window «Browser di Febe» (WebView2Host.Done, issue #36, S4b): out of view at once,
/// the copy of the session before the page goes back to the engine (a hold keeps it his meanwhile), then the lease ends.
/// <paramref name="how"/>: closed, or left minimised too long.
/// </summary>
public async Task CloseWindowAsync(CancellationToken ct)
public async Task CloseWindowAsync(CancellationToken ct, BrowserWindowLetGo how = BrowserWindowLetGo.Closed)
{
Hidden++;
if (_lease is null || _context.CopyOnWindowClosed is not { } copy)
@@ -215,7 +216,7 @@ internal sealed class FakeBrowser : IFebeBrowser
_lease = null;
try
{
await copy(ct);
await copy(how, ct);
}
finally
{
@@ -61,6 +61,33 @@ public sealed class EngineConnectionStateTests
Assert.AreEqual(JsonValueKind.Null, (await LinkAsync(EngineMode.NotConnected)).GetProperty("username").ValueKind, "Not connected: no name.");
}
[TestMethod]
public async Task NotConnectedTakesCopyMissingFromTheSnapshotWithoutAskingTheBrowser()
{
// Issue #36, S4b: the engine already knows whether the copy for the requests is missing (its headline says
// «Serve «Ho finito»»); every event of the stream must not cost a look at the browser for it.
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.SessionCopyMissing, null, null, false, null) };
await using var server = await Part2.StartAsync(services: s =>
{
s.AddSingleton<IEngineMonitor>(sp => new FixedModeMonitor(sp.GetRequiredService<IClock>()) { Mode = EngineMode.NotConnected });
s.AddSingleton<IConnectionService>(connection);
});
var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService<IEngineMonitor>();
var reads = connection.StatusReads;
Assert.AreEqual("notConnected", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"), "the engine's word, not the connection's");
monitor.CopyMissing = true;
var engine = await server.GetJsonAsync("/api/engine");
Assert.AreEqual("copyMissing", engine.GetProperty("connection").Str("state"));
Assert.IsTrue(engine.GetProperty("snapshot").GetProperty("sessionCopyMissing").GetBoolean());
Assert.AreEqual(reads, connection.StatusReads, "no status asked while the engine runs");
// Only when the engine loop does not run is the connection asked.
monitor.Mode = EngineMode.Off;
Assert.AreEqual("copyMissing", (await server.GetJsonAsync("/api/engine")).GetProperty("connection").Str("state"));
Assert.AreEqual(reads + 1, connection.StatusReads);
}
[TestMethod]
public async Task WithoutEngineAndBrowserTheSidebarSaysNotConnectedEvenIfTuIsKnown()
{
@@ -76,8 +103,10 @@ public sealed class EngineConnectionStateTests
{
public EngineMode Mode { get; set; } = EngineMode.Resting;
public bool CopyMissing { get; set; }
public Task<EngineSnapshot> GetSnapshotAsync(CancellationToken ct = default) =>
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent));
Task.FromResult(SnapshotParts.Build(clock, Mode, "Prova", [], "Prova", CautionProfile.Prudent) with { SessionCopyMissing = CopyMissing });
public async IAsyncEnumerable<EngineNotification> SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
@@ -69,6 +69,7 @@ internal sealed class FixedProblems(params ConfigurationProblem[] problems) : IC
internal sealed class RecordingConnection : IConnectionService
{
private readonly Lock _gate = new();
private int _statusReads;
public List<string> Calls { get; } = [];
@@ -86,7 +87,14 @@ internal sealed class RecordingConnection : IConnectionService
}
}
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
/// <summary>How many times the status was asked (each one costs the real connection a look at the browser).</summary>
public int StatusReads => Volatile.Read(ref _statusReads);
public Task<ConnectionStatus> GetStatusAsync(CancellationToken ct)
{
Interlocked.Increment(ref _statusReads);
return Task.FromResult(Status);
}
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{