diff --git a/docs/decisioni.md b/docs/decisioni.md
index 82296f5..6066bf6 100644
--- a/docs/decisioni.md
+++ b/docs/decisioni.md
@@ -420,8 +420,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-17 | Il messaggio di «Ho finito» per una copia con valori mancanti conta solo i valori della pagina e i `doc_id` che un'operazione configurata manda (`SessionCapturePlan.NeededValues`, `NeededDocIds`; gli altri si leggono lo stesso e il registro li nomina a parte) e dice com'è: la copia ha sostituito quella di prima, le richieste che li usano non partono e alla prima Febe si ferma come disconnessione. Dopo un rifiuto il messaggio dice di riaprire il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premere di nuovo «Ho finito». La copia incompleta sostituisce comunque quella salvata | Il messaggio prometteva che quelle operazioni «restano al browser», ma il codice le ferma come disconnessione (§6.0, mai un ritorno alle pagine); e «Ho finito» chiude sempre il permesso di guida, quindi un secondo «Ho finito» da solo non copia nulla. Tenere una copia più vecchia ma completa potrebbe tenere i cookie di un altro accesso (regola 7) |
| 2026-11-17 | `chiave.bin` si crea intero o non si crea: file `.part` nella stessa cartella, scritto fino al disco, poi rinominato senza sostituire (`OwnerOnlyFiles.CreateNew`) | Prima il file nasceva vuoto e poi si scriveva: con il disco pieno restava un `chiave.bin` corto, scambiato per la chiave di un altro processo, e da lì ogni avvio con «richieste» si fermava finché Alberto non lo cancellava a mano |
| 2026-11-17 | Con la raccolta «pagine» il registro scrive una riga «Raccolta «pagine»: tutte le ricette con il browser» all'avvio | §6.0 dice che il registro nomina la strada presa; prima la scriveva solo con «richieste» |
-| 2026-11-18 | Nuovi valori della sessione `spin_r`, `spin_b`, `spin_t` (`__spin_r`, `__spin_b`, `__spin_t`), copiati dalla pagina a «Ho finito» come gli altri: su Instagram dalle chiavi omonime di `SiteData` (`SiteData.__spin_r` …), nel sito di prova dal modulo suo `GiroProva` (`revisione` e `tempo` numeri, `ramo` testo), che il sito controlla nella richiesta GraphQL. Nelle dieci operazioni di Instagram le tre fonti passano da `pending` a `session:spin_*`, ma restano tutte non configurate | Risposta 1 di Alberto (#36, S4): un'istantanea della pagina; i valori che cambiano mentre la pagina gira (`__req`, `__s`, `__dyn`, `__csr` …) restano al browser. Che `SiteData` tenga quelle chiavi viene dalla forma del codice pubblico della pagina già usata in S4; chi le mette nella richiesta resta da vedere dal vivo (H23), e finché `__req`, `__s`, `__dyn`, `__csr` non hanno fonte nessuna operazione si configura comunque |
+| 2026-11-18 | Nuovi valori della sessione `spin_r`, `spin_b`, `spin_t` (`__spin_r`, `__spin_b`, `__spin_t`), copiati dalla pagina a «Ho finito» come gli altri: su Instagram dalle chiavi omonime di `SiteData` (`SiteData.__spin_r` …), nel sito di prova dal modulo suo `GiroProva` (`revisione` e `tempo` numeri, `ramo` testo), che il sito controlla nella richiesta GraphQL. Nelle nove operazioni GraphQL di Instagram (`media-info` non ha campi `__spin_*`) le tre fonti passano da `pending` a `session:spin_*`, ma tutte e dieci le operazioni restano non configurate | Risposta 1 di Alberto (#36, S4): un'istantanea della pagina; i valori che cambiano mentre la pagina gira (`__req`, `__s`, `__dyn`, `__csr` …) restano al browser. Che `SiteData` tenga quelle chiavi viene dalla forma del codice pubblico della pagina già usata in S4; chi le mette nella richiesta e se i nomi esatti di `SiteData` (con i due trattini bassi) sono quelli resta da vedere dal vivo (H23, ipotesi nuova da aggiungere a §6.6; intanto descritta in `docs/prove-dal-vivo.md`, parte E), e finché `__req`, `__s`, `__dyn`, `__csr` non hanno fonte nessuna operazione si configura comunque |
| 2026-11-18 | La sessione si copia anche alla chiusura della finestra «Browser di Febe» su Windows (anche ridotta a icona troppo a lungo) e quando il permesso di guida di «Accedi» / «Usa il browser» finisce da solo, sempre prima che la pagina torni al motore: la finestra tiene una presa del permesso di guida finché la copia non è finita (`WebView2HostOptions.CopyOnClose`, `FebePlatformContext.CopyOnWindowClosed`), la fine del permesso copia prima di rilasciarlo; in tutti e due i casi i comandi del collegamento, la presa del permesso e il turno della pagina come a «Ho finito», solo con il cookie di sessione nel browser, solo da una pagina del sito che non sia di accesso o di verifica. Nessun messaggio, una riga di registro con soli conteggi; la fine del permesso non copia di nuovo se la finestra ha appena copiato (un segno di guida entro un giro di controllo dalla copia è la presa della finestra) | Risposta 5 di Alberto. Sotto le stesse garanzie di «Ho finito» per la regola 7: la pagina non è mai letta quando è del motore. In Docker c'è solo la fine del permesso (la vista remota non ha una finestra da chiudere); la chiusura della finestra ha un limite di 30 s (`LetGoWait`) perché non trattenga il motore se un altro comando del collegamento è in corso |
| 2026-11-18 | Con la raccolta «richieste» e una sessione salvata nella composizione, «Collegato» vuole anche una sessione salvata leggibile: senza, lo stato è `SessionCopyMissing` (`copyMissing`, «Serve «Ho finito»»), `EngineRuntime.IsConnected` è falso e il motore aspetta con il titolo «Serve «Ho finito»»; la pagina Collegamento apre la pagina iniziale (non l'accesso) e spiega che cosa fare. Con «pagine» non cambia nulla | Risposta 6 di Alberto. Senza copia le ricette per richieste si fermerebbero alla prima come disconnessione: meglio aspettare e dirlo. La strada di «Pagina iniziale» resta quella del cookie |
| 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 |
diff --git a/docs/guida/Primo-collegamento.md b/docs/guida/Primo-collegamento.md
index dd184b7..dc7bd95 100644
--- a/docs/guida/Primo-collegamento.md
+++ b/docs/guida/Primo-collegamento.md
@@ -50,7 +50,8 @@ pagina del sito che non sia di accesso o di verifica:
e la guida finisce da sola.
In questi casi non compare nessun messaggio: il registro dice com'è andata (solo conteggi, mai valori), e la pagina
-Collegamento mostra la copia.
+Collegamento mostra la copia. Se poi premi «Ho finito» lo stesso, Febe non rilegge la pagina (è già tornata al
+motore) e ti dice che la sessione era già stata copiata: se la copia era completa non serve rifare l'accesso.
**«Collegato» con la raccolta «richieste».** Il cookie di sessione nel browser non basta: serve anche una copia
leggibile della sessione. Se manca (per esempio dopo «Annulla», o se il file non si legge più), lo stato è **«Serve «Ho
diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md
index 07874d7..6a8953e 100644
--- a/docs/guida/Problemi-comuni.md
+++ b/docs/guida/Problemi-comuni.md
@@ -32,7 +32,7 @@ dati.
| La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso |
| Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) |
| «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» |
-| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era |
+| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser: se il messaggio non dice che mancano valori, non serve fare nulla |
| «Serve «Ho finito»» (barra laterale o pagina Collegamento) | Solo con la raccolta «richieste»: il browser ha la sessione, ma Febe non ha una copia leggibile per le richieste (dopo «Annulla», o con un file che non si legge più). Il motore aspetta: dalla pagina Collegamento apri la tua pagina iniziale nel browser e premi «Ho finito» |
| «Alla pagina mancavano … Febe tiene la copia completa salvata prima e non usa quella nuova» | Hai scelto «Tieni la copia completa» nella pagina Collegamento e alla pagina mancava un valore che le richieste usano. Se hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque» e premi di nuovo «Ho finito» |
| «Sessione copiata…, ma non ancora scritta su disco» | Il disco ha rifiutato la scrittura (spazio, permessi di `/dati/sessione`): Febe usa la copia in memoria e riprova alla prossima scrittura. Controlla lo spazio e i permessi; il registro dice il tipo d'errore |
diff --git a/docs/prove-dal-vivo.md b/docs/prove-dal-vivo.md
index d61b471..c35b30c 100644
--- a/docs/prove-dal-vivo.md
+++ b/docs/prove-dal-vivo.md
@@ -519,3 +519,30 @@ Gli avvisi sono gli stessi nelle due vesti (stessa composizione); su Windows arr
- Nel contenitore su Unraid: il risultato di «Invia una prova» (dice se il contenitore raggiunge Telegram).
- Su Windows (D4): «sì/no» per la notifica di prova e per quella della verifica; se manca, la riga `[avvisi]` del
registro di quell'ora.
+
+---
+
+## E. Prima di configurare un'operazione di Instagram per richieste (issue #36)
+
+Le dieci operazioni di `richieste.instagram.json` restano non configurate finché queste ipotesi non sono confermate
+dal vivo (oltre a H21 e H22 di §6.6 e alle fonti ancora `pending`). Non serve Febe: bastano gli strumenti per
+sviluppatori del tuo browser di tutti i giorni, con la stessa preparazione di A ter 1 e A ter 2 (filtro «Tutti»).
+**Non mandare valori**: solo «sì/no», «uguali/diversi» e i nomi.
+
+### E1. H23 — `__spin_r`, `__spin_b`, `__spin_t`
+
+Il catalogo (decisione del 18 novembre 2026) li copia dalla pagina come `SiteData.__spin_r`, `SiteData.__spin_b` e
+`SiteData.__spin_t`. Il nome viene solo dalla forma del codice pubblico della pagina nel HAR: nessun campione ripulito
+lo documenta, e nemmeno chi li mette nella richiesta.
+
+1. Apri la pagina iniziale di Instagram con il pannello Rete aperto, poi un profilo.
+2. Nel pannello Rete usa «Cerca» (la lente, cerca in tutte le risposte) con `__spin_r`. Deve comparire nel documento
+ della pagina, dentro un blocco `SiteData`. Annota il nome esatto della chiave (con i due trattini bassi o senza),
+ e lo stesso per `__spin_b` e `__spin_t`.
+3. Apri una richiesta `graphql/query` del profilo, scheda «Payload»: annota se ci sono i campi `__spin_r`,
+ `__spin_b`, `__spin_t` e se i loro valori sono **uguali** a quelli del blocco `SiteData` del documento (solo
+ «uguali/diversi»).
+4. Ricarica la pagina e ripeti il passo 3: annota se i valori cambiano da una pagina all'altra.
+
+Che cosa riferire: i tre nomi esatti, «sì/no» per ciascun campo nella richiesta, «uguali/diversi» e «cambiano/non
+cambiano». Se i nomi sono diversi, il catalogo va corretto prima di configurare qualunque operazione.
diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs
index 3a56e4d..436bdb2 100644
--- a/src/Febe.App/BrowserConnectionService.cs
+++ b/src/Febe.App/BrowserConnectionService.cs
@@ -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;
/// The browser of Febe.
/// The database (first connection, «Scollega»).
@@ -205,14 +206,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
///
- /// 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 . 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
+ /// . Never throws for the browser; logs counts only, and says which of the two happened.
///
- 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);
+ }
}
///
@@ -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}).");
+ }
}
/// What a copy without «Ho finito» did, for the log (counts only).
@@ -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
+ /// (Earlier), as long as the saved session is still there.
///
- private async Task 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 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.
///
- 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,
diff --git a/src/Febe.App/FebeApp.cs b/src/Febe.App/FebeApp.cs
index 502a112..3d61ba0 100644
--- a/src/Febe.App/FebeApp.cs
+++ b/src/Febe.App/FebeApp.cs
@@ -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);
diff --git a/src/Febe.App/IFebePlatform.cs b/src/Febe.App/IFebePlatform.cs
index 11bbc58..0187a55 100644
--- a/src/Febe.App/IFebePlatform.cs
+++ b/src/Febe.App/IFebePlatform.cs
@@ -73,11 +73,22 @@ public interface IFebePlatform
/// (BrowserConnectionService.OpenStartPageAsync). Null: the button does nothing.
///
///
-/// 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 (BrowserConnectionService.CopyOnWindowClosedAsync). 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
+/// (BrowserConnectionService.CopyOnWindowClosedAsync). The window holds the driving gate until the task ends.
+/// Null: nothing.
///
-public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null, Func? CopyOnWindowClosed = null);
+public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func? OpenStartPage = null, Func? CopyOnWindowClosed = null);
+
+/// How Alberto let go of the window «Browser di Febe» without «Ho finito» (Windows): the log says which.
+public enum BrowserWindowLetGo
+{
+ /// He closed it.
+ Closed,
+
+ /// He left it minimised longer than its limit: it went out of view as if closed.
+ MinimizedTooLong,
+}
/// Options of the shared composition, filled by each shell from its own configuration.
public sealed record FebeAppOptions
diff --git a/src/Febe.Core/Engine/Monitor.cs b/src/Febe.Core/Engine/Monitor.cs
index ba99900..b50be18 100644
--- a/src/Febe.Core/Engine/Monitor.cs
+++ b/src/Febe.Core/Engine/Monitor.cs
@@ -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 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");
diff --git a/src/Febe.Core/Engine/MonitorModels.cs b/src/Febe.Core/Engine/MonitorModels.cs
index 25d7ad0..972286a 100644
--- a/src/Febe.Core/Engine/MonitorModels.cs
+++ b/src/Febe.Core/Engine/MonitorModels.cs
@@ -190,4 +190,10 @@ public sealed record EngineSnapshot
public required IReadOnlyList SuspendedRecipes { get; init; }
public required BreakerState Breaker { get; init; }
+
+ ///
+ /// 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»».
+ ///
+ public bool SessionCopyMissing { get; init; }
}
diff --git a/src/Febe.Desktop/Browser/BrowserWindow.cs b/src/Febe.Desktop/Browser/BrowserWindow.cs
index c3d1a5e..9b8933e 100644
--- a/src/Febe.Desktop/Browser/BrowserWindow.cs
+++ b/src/Febe.Desktop/Browser/BrowserWindow.cs
@@ -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
/// Raised by «Pagina iniziale».
public event EventHandler? HomeRequested;
- /// Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view.
- public event EventHandler? DoneRequested;
+ ///
+ /// Raised when Alberto closes the window, or leaves it minimised too long (which one is the argument): the owner puts
+ /// it out of view.
+ ///
+ public event EventHandler? DoneRequested;
/// Raised when the page area changed size (a new fit): the owner sizes WebView2 again.
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);
}
}
diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs
index d95b10f..15a160c 100644
--- a/src/Febe.Desktop/Browser/WebView2Host.cs
+++ b/src/Febe.Desktop/Browser/WebView2Host.cs
@@ -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.
///
///
-/// 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.
///
-internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null, Func? CopyOnClose = null);
+internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func? OpenStartPage = null, Func? CopyOnClose = null);
/// What the host does when a process of WebView2 fails (issue #52).
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).
///
- 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 copy, IDisposable hold)
+ private async Task CopyThenLetGoAsync(Func 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)
{
diff --git a/src/Febe.Web/Api/EngineApi.cs b/src/Febe.Web/Api/EngineApi.cs
index b5efbc1..89eab65 100644
--- a/src/Febe.Web/Api/EngineApi.cs
+++ b/src/Febe.Web/Api/EngineApi.cs
@@ -84,8 +84,9 @@ public static class EngineApi
///
/// 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 (, 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.
///
public static async Task 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
diff --git a/tests/Febe.Tests.Windows/BrowserWindowTests.cs b/tests/Febe.Tests.Windows/BrowserWindowTests.cs
index 41631cd..a972531 100644
--- a/tests/Febe.Tests.Windows/BrowserWindowTests.cs
+++ b/tests/Febe.Tests.Windows/BrowserWindowTests.cs
@@ -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();
+ 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));
diff --git a/tests/Febe.Tests.Windows/Support/BrowserBed.cs b/tests/Febe.Tests.Windows/Support/BrowserBed.cs
index 03f3928..fe082de 100644
--- a/tests/Febe.Tests.Windows/Support/BrowserBed.cs
+++ b/tests/Febe.Tests.Windows/Support/BrowserBed.cs
@@ -50,7 +50,8 @@ internal sealed class BrowserBed : IAsyncDisposable
/// does nothing (never the default login page of the options, which is Instagram's).
///
/// What «Pagina iniziale» does instead (it wins over ).
- public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null, Func? openStartPage = null)
+ /// What closing the window, or leaving it minimised too long, does (S4b); null: nothing.
+ public static async Task CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window, Func? startPage = null, Func? openStartPage = null, Func? 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.
diff --git a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs
index 0c00b69..d444503 100644
--- a/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs
+++ b/tests/Febe.Tests.Windows/WebView2ConnectionTests.cs
@@ -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"]);
diff --git a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs
index 5269674..8e53aa5 100644
--- a/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs
+++ b/tests/Febe.Tests/Desktop/SavedSessionConnectionTests.cs
@@ -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]
diff --git a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs
index 69fa82b..6a20db5 100644
--- a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs
+++ b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs
@@ -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");
+ }
+
+ /// The log files of this start, read while Febe still writes them.
+ 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 StartAsync()
diff --git a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs
index aab8520..f4fca2c 100644
--- a/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs
+++ b/tests/Febe.Tests/Desktop/Support/FakeDesktopShell.cs
@@ -199,8 +199,9 @@ internal sealed class FakeBrowser : IFebeBrowser
///
/// 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.
+ /// : closed, or left minimised too long.
///
- 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
{
diff --git a/tests/Febe.Tests/Web/EngineConnectionStateTests.cs b/tests/Febe.Tests/Web/EngineConnectionStateTests.cs
index 46a1500..014a43d 100644
--- a/tests/Febe.Tests/Web/EngineConnectionStateTests.cs
+++ b/tests/Febe.Tests/Web/EngineConnectionStateTests.cs
@@ -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(sp => new FixedModeMonitor(sp.GetRequiredService()) { Mode = EngineMode.NotConnected });
+ s.AddSingleton(connection);
+ });
+ var monitor = (FixedModeMonitor)server.App.Services.GetRequiredService();
+ 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 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 SubscribeAsync([EnumeratorCancellation] CancellationToken ct = default)
{
diff --git a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs
index f268362..255981c 100644
--- a/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs
+++ b/tests/Febe.Tests/Web/Part2Support/Part2Helpers.cs
@@ -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 Calls { get; } = [];
@@ -86,7 +87,14 @@ internal sealed class RecordingConnection : IConnectionService
}
}
- public Task GetStatusAsync(CancellationToken ct) => Task.FromResult(Status);
+ /// How many times the status was asked (each one costs the real connection a look at the browser).
+ public int StatusReads => Volatile.Read(ref _statusReads);
+
+ public Task GetStatusAsync(CancellationToken ct)
+ {
+ Interlocked.Increment(ref _statusReads);
+ return Task.FromResult(Status);
+ }
public Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
{