diff --git a/docs/decisioni.md b/docs/decisioni.md index 6066bf6..341f076 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -426,3 +426,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Impostazione `sessione.copia-incompleta` (`SessionCopySettings`, tabella `setting`): `sostituisci` (predefinita) o `tieni-completa`. Con `tieni-completa` una copia a cui manca un valore o un `doc_id` che un'operazione configurata manda non sostituisce una copia salvata che li ha tutti, e «Ho finito» lo dice; altrimenti sostituisce come in S4. Letta a ogni copia (nessun riavvio), `GET`/`PUT /api/connection/settings`, scelta nel riquadro della pagina Collegamento | Risposta 9 di Alberto: un'opzione, con il comportamento di S4 come predefinito perché una copia più vecchia potrebbe avere i cookie di un altro accesso; il messaggio consiglia «Sostituisci comunque» dopo un nuovo accesso o un cambio di account | | 2026-11-18 | La pagina Collegamento mostra la sessione salvata (riquadro «Sessione salvata per le richieste»): data della copia, valori della pagina e `doc_id` presenti su quelli letti, numero di cookie, nomi di quelli mancanti e quanti servono alle operazioni configurate; `GET /api/connection` li porta in `savedSession` (solo conteggi e nomi, mai valori; `null` con «pagine»). La data si scrive nel fuso del browser | Risposta 10 di Alberto. I nomi dei campi e delle operazioni non sono valori (regola 10); il rapporto (`ISessionCopier.Report`) li calcola dalla sessione in memoria, senza leggere il file | | 2026-11-18 | Correzioni della revisione di S4b. (1) Un errore imprevisto durante la copia senza «Ho finito» (database, disco, Febe che si ferma) non trattiene più il permesso di guida: la copia lo scrive nel registro con il solo tipo d'errore e la fine del permesso arriva lo stesso; il controllo della fine della guida, se si interrompe per un errore, rilascia il permesso. (2) Un «Ho finito» tardivo, dopo che lo stesso uso del browser ha già copiato quando è tornato al motore, non legge nulla e dice che la sessione era già stata copiata (senza chiedere un nuovo accesso se la copia è completa); un nuovo «Accedi» / «Usa il browser» dimentica quella copia. (3) Il registro distingue «Finestra del browser chiusa» da «Finestra del browser ridotta a icona troppo a lungo» (`BrowserWindowLetGo`). (4) `EngineSnapshot.SessionCopyMissing`: con il motore in funzione `/api/engine` e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore, senza chiedere al browser; il collegamento si interroga solo con il motore spento | Il permesso tenuto per sempre lasciava il motore in «Stai usando il browser» senza un errore nel registro; il messaggio tardivo diceva «non è stata copiata, rifai l'accesso» di una sessione appena salvata; il registro diceva «chiusa» di una finestra solo ridotta a icona; ogni evento del flusso costava un indirizzo e un controllo del cookie via CDP | +| 2026-11-18 | Seconda revisione di S4b. (1) La scelta «sessione.copia-incompleta» si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto (`mayKeep`), non dopo; se non si legge (database occupato o in errore) vale la predefinita «Sostituisci comunque» e il registro scrive solo il tipo d'errore. (2) Ogni volta che lo stesso uso del browser viene lasciato senza «Ho finito» (finestra chiusa, fine della guida) dimentica la copia fatta a un abbandono precedente prima di provare la sua: un «Ho finito» tardivo segue l'ultimo abbandono | (1) Regola 7: fra l'ultimo sguardo alla pagina e la scrittura non deve passare nessuna attesa; un errore dell'impostazione faceva fallire «Ho finito» senza rilasciare il permesso di guida. (2) Dopo una copia riuscita e un secondo abbandono rifiutato (pagina di accesso, forse un altro account) il messaggio diceva «era già stata copiata… Non serve rifare l'accesso» | diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 436bdb2..f3e188b 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -841,6 +841,13 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa 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. + lock (_gate) + { + _letGoCopy = null; + } + if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true) { _log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare."); diff --git a/src/Febe.App/SessionCopier.cs b/src/Febe.App/SessionCopier.cs index 467ff5a..96c2c51 100644 --- a/src/Febe.App/SessionCopier.cs +++ b/src/Febe.App/SessionCopier.cs @@ -159,12 +159,6 @@ 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}"); - 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); - } - // 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(); @@ -172,10 +166,17 @@ public sealed class BrowserSessionCopier : ISessionCopier 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. - if (needed.Count > 0 - && IsComplete(_store.Read()) - && await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete) + // 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); + } + + if (keepComplete) { _log($"Sessione letta ma non salvata: mancano {string.Join(", ", needed)}, che 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); @@ -251,6 +252,24 @@ public sealed class BrowserSessionCopier : ISessionCopier _ => "il browser non ha risposto", }; + /// + /// 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). + /// + private async Task 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; + } + } + /// True when holds every value and doc_id a configured operation sends. private bool IsComplete(SiteSessionValues? saved) { diff --git a/tests/Febe.Tests/Browser/SessionCaptureTests.cs b/tests/Febe.Tests/Browser/SessionCaptureTests.cs index 7bcb2e2..622bdab 100644 --- a/tests/Febe.Tests/Browser/SessionCaptureTests.cs +++ b/tests/Febe.Tests/Browser/SessionCaptureTests.cs @@ -333,6 +333,59 @@ public sealed class SessionCaptureTests AssertNoSecret(string.Join("\n", log)); } + [TestMethod] + public async Task AChoiceThatCannotBeReadIsTheDefaultAndTheCopyGoesOn() + { + // The setting lives in the database: a failure there must not make «Ho finito» fail (the lease would stay held). + var log = new List(); + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), log.Add).CopyAsync(() => true, CancellationToken.None); + var complete = store.Read(); + Assert.IsNotNull(complete); + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), log.Add) + { + IncompleteCopy = _ => throw new InvalidOperationException("prova: impostazione illeggibile"), + }; + + var outcome = await copier.CopyAsync(() => true, CancellationToken.None); + + Assert.AreEqual(SessionCopyStatus.Saved, outcome.Status, "«Sostituisci comunque», the default"); + Assert.AreNotSame(complete, store.Read()); + var text = string.Join("\n", log); + StringAssert.Contains(text, "Scelta per la copia incompleta non letta (InvalidOperationException)"); + Assert.DoesNotContain("impostazione illeggibile", text, "the kind of error only (rule 10)"); + AssertNoSecret(text); + } + + [TestMethod] + public async Task ThePageIsLookedAtLastAfterTheChoiceIsRead() + { + // Rule 7: nothing awaited between the last look at whose page it is and the decision on the saved session. Here + // the page goes back to the engine while the choice is read: the copy is thrown away, not kept nor saved. + var store = new InMemorySiteSession(null); + await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None); + var complete = store.Read(); + var lacking = PageValues(); + ((JsonObject)lacking["values"]!).Remove("lsd"); + var lost = false; + var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: lacking), Plan, store, new VirtualClock(), _ => { }) + { + IncompleteCopy = _ => + { + lost = true; + return Task.FromResult(IncompleteCopyChoice.KeepComplete); + }, + }; + + var outcome = await copier.CopyAsync(() => !lost, CancellationToken.None); + + Assert.IsTrue(lost, "the choice was read"); + Assert.AreEqual(SessionCopyStatus.Discarded, outcome.Status); + Assert.AreSame(complete, store.Read()); + } + [TestMethod] public async Task TheReportCountsAndNamesWhatTheSavedSessionHoldsAndNeverAValue() { diff --git a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs index 6a20db5..48427d0 100644 --- a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs +++ b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs @@ -118,6 +118,36 @@ 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 ALateHoFinitoFollowsTheLastLettingGoNotAnEarlierOne() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.DrivingGrace = TimeSpan.FromMilliseconds(400); + + // «Usa il browser», the window closed on the site's home: copied. + await BeginAsync(bed, openLogin: false); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + await browser.CloseWindowAsync(ct); + Assert.AreEqual(1, browser.FakeCdp.CaptureReads); + + // Same use: the window back in front, then closed again on the login page (perhaps another account): refused. + await connection.ShowBrowserAsync(openLogin: false, ct); + browser.FakeCdp.Navigated(Site + "/accesso/"); + await browser.CloseWindowAsync(ct); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida"); + + // A late «Ho finito» must not say that the session was already copied: the last letting go copied nothing. + var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish"); + var message = finish.GetProperty("message").GetString()!; + StringAssert.Contains(message, "non è stata copiata"); + Assert.DoesNotContain("era già stata copiata", message); + } + [TestMethod] [Timeout(60_000, CooperativeCancellation = true)] public async Task AnErrorDuringTheCopyWhenAlbertoLetsGoStillGivesThePageBackToTheEngine()