Compare commits

...
10 Commits
Author SHA1 Message Date
Alby96 81d5d5d946 Merge pull request 'S4b: sessione salvata, e in Docker lasciare la pagina del browser copia la sessione (#36)' (#61) from funzione/sessione-s4b into main
verifica / controlli (push) Successful in 25s
verifica / prove (push) Canceled after 0s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
2026-11-26 12:28:37 +01:00
Alby96 f4a58ee265 Merge branch 'main' into funzione/sessione-s4b
verifica / controlli (push) Successful in 23s
verifica / prove (push) Successful in 18m46s
verifica / installatore (push) Successful in 6m35s
verifica / immagine (push) Successful in 20m58s
2026-11-26 10:22:09 +01:00
Alby96andClaude Opus 5.5 e3a6c320ee Unione di documenti/esportazione-e-regole in funzione/sessione-s4b: porta la correzione dell'installatore senza ICU
verifica / controlli (push) Successful in 24s
verifica / prove (push) Successful in 23m12s
verifica / installatore (push) Successful in 4m5s
verifica / immagine (push) Successful in 19m59s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 21:00:39 +01:00
Alby96andClaude Opus 5.5 4afdba0d35 Collegamento: corretta la SyntaxError di connection.js anche su S4b
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 17m38s
verifica / installatore (push) Canceled after 0s
verifica / immagine (push) Canceled after 0s
Una «let saved» dichiarata due volte nello stesso blocco di savedSessionBox fermava tutta
la pagina Collegamento: nella CI di questo ramo cadevano 11 prove dell'interfaccia
(«Identifier 'saved' has already been declared»). La correzione era stata fatta solo in
cima alla catena (2068dd2); qui si porta la stessa, identica, insieme al controllo della
sintassi scritto in casa (ScriptSyntaxTests, ScriptCheck) che l'avrebbe colta, così i rami
seguenti la ricevono con un'unione pulita.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:05:00 +01:00
Alby96andClaude Opus 5.5 2fc4b40c41 Docker: lasciare la pagina del browser copia la sessione (#36, S4b, risposta 1)
verifica / controlli (push) Successful in 24s
verifica / prove (push) Failing after 41m21s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
In Docker lasciare la pagina «Browser» o la vista remota di Collegamento mentre
Alberto guida (un'altra pagina, la scheda chiusa, il collegamento perso) valeva
«Annulla» e la sessione non si copiava. Ora è come chiudere la finestra del
browser su Windows: `cancel` con `pageLeft` va a LeavePageAsync, la vista
remota chiusa dalla sua pagina lo dice alla connessione, e se per 5 secondi
non si apre un'altra vista né arriva un `begin` (una pagina ricaricata) il
controllo del permesso copia la sessione con CopyOnLetGoAsync, solo da una
pagina del sito che non sia di accesso o di verifica, poi rilascia il permesso
e il motore rimette il browser a riposo. Il pulsante «Annulla» continua a non
copiare; Windows non cambia.

Prove nuove per la copia lasciando la pagina, la ricarica che non è lasciare,
la pagina di accesso, la vista sostituita o chiusa da Febe; guida, protocollo
e una riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:52:51 +01:00
Alby96 537517b855 Unione di documenti/esportazione-e-regole in funzione/sessione-s4b (catena della 0.3.0)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-11-25 10:36:05 +01:00
Alby96andClaude Opus 5.5 b29b35a284 Sessione salvata: terza revisione di S4b (#36)
La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso
passo in cui rilascia il permesso: se la vista remota, la finestra o un
nuovo «Accedi» / «Usa il browser» sono tornati durante la copia, il
permesso resta. Prima finiva comunque, e alla chiusura successiva il
motore riprendeva subito, senza attesa e senza copia.

Un «Ho finito» che prova davvero a copiare, o che chiude lui il permesso,
e la chiusura della finestra che rinuncia dimenticano la copia di un
abbandono precedente: un secondo «Ho finito» non dice più «era già stata
copiata» dopo una copia appena rifiutata.

Il registro non incolpa il browser quando il tempo della finestra finisce
in attesa della pagina tenuta dalla ricerca dei profili; la riga di avvio
del motore segue IsReadyToCollect e dice quando aspetta la copia; il
riquadro «Se una copia nuova è incompleta» non mostra né accetta una
scelta finché il server non dice quella salvata, non si fa cambiare da
una risposta tardiva e torna alla scelta precedente se il salvataggio
fallisce; singolare italiano nei messaggi («manca 1 valore che serve»).

La guida e PROTOCOLLO.md dicono che in Docker copia solo «Ho finito»:
lasciare la pagina vale «Annulla». Nuova riga in decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:34:00 +01:00
Alby96andClaude Opus 5.5 74e67adbab Sessione salvata: seconda revisione di S4b (#36)
La scelta per la copia incompleta si legge prima dell'ultimo controllo che la pagina sia ancora di Alberto, così fra quello sguardo e la scrittura non passa nessuna attesa (regola 7); se l'impostazione non si legge vale «Sostituisci comunque» e il registro scrive solo il tipo d'errore, invece di far fallire «Ho finito» lasciando il permesso di guida trattenuto. Ogni abbandono del browser senza «Ho finito» dimentica la copia di un abbandono precedente dello stesso uso prima di provare la sua: un «Ho finito» tardivo dopo una seconda chiusura rifiutata (pagina di accesso) non dice più che la sessione era già stata copiata. Tre prove nuove, che senza le correzioni non passano. Fine riga già conformi: indice LF come il resto del repository, nessuna conversione necessaria.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:03:59 +01:00
Alby96andClaude Opus 5.5 c69755db23 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>
2026-11-18 12:13:25 +01:00
Alby96andClaude Opus 5.5 883ea4683c Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)
Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:41:35 +01:00
57 changed files with 3069 additions and 174 deletions

No files matched your search

+9
View File
@@ -450,4 +450,13 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-11-25 | **Attività diventa Dashboard** (§7.9, §10.2, §10.3; tappa D1): prima voce della barra laterale («Dashboard, Libreria, Account, Importa»), pagina iniziale di Febe (`/` e `/attivita` portano a `/dashboard`, la finestra di Windows e il riquadro di stato vi aprono), compatta, con l'anteprima del browser sempre visibile e aggiornata a ogni fotogramma (al più uno al secondo, comandi già ammessi da §6.1), la cronologia con le miniature di ciò che è arrivato e un'anteprima ingrandita leggera (dialogo, non il visualizzatore) con «Apri nella Libreria» e «Apri l'account». Striscia, tetti, coda e «Diagnostica» restano, ridotti. Schermata senza mockup composta da 06, 11 e 01 | Richiesta di Alberto del 25 novembre 2026: mentre Febe lavora resta su questa pagina a guardare lo scaricamento. Le miniature si caricano solo quando la riga è in vista e la cronologia a richiesta, per restare leggera con librerie grandi |
| 2026-11-25 | **«Raggruppa i post» / «Tutte le foto»** nella Libreria e nella scheda account (§4.6, §4.3): una tessera per elemento (predefinito) o per file, video compresi, con la posizione «2/4» sulle tessere di una serie e il visualizzatore che va di file in file. In «Tutte le foto» «Copia in…» e «Fotogrammi…» lavorano sui file scelti, CSV ed «Elimina» sugli elementi a cui appartengono, detto nella conferma. La scelta si ricorda nel browser di chi guarda (memoria locale, come il tema, letta e scritta in un `try`), una per la Libreria e una per le viste degli account; senza, «Raggruppa i post» | Richiesta di Alberto del 25 novembre 2026 («utile quando un post ha più foto»). Una preferenza di vista, non un dato: non serve né nel database né sugli altri dispositivi. Eliminare resta per elemento (§4.6), per non lasciare post a metà |
| 2026-11-25 | Nuova tappa **D1 Dashboard e ordine** nel traguardo 0.3.0 (§15), indipendente da C1–C6 ed E1–E5; `SpecificationConsistencyTests` controlla anche questi punti (copia in Docker lasciando la pagina, caratteri dell'immagine, immagini danneggiate, RExt, ordine, Dashboard, modo del mosaico, glossario) e la domanda 18 con la risposta del 25 novembre | Issue #59. Le prove dei documenti tengono insieme le risposte di Alberto e il testo della specifica |
| 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 |
| 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» |
| 2026-11-18 | Terza revisione di S4b. (1) La fine della guida da sola, dopo la copia, guarda di nuovo nello stesso passo in cui rilascia il permesso (sotto lo stesso lucchetto): se nel frattempo è tornata la vista remota o la finestra, o è arrivato un nuovo «Accedi» / «Usa il browser», il permesso resta e il controllo continua (`ReleaseIdleLease`). (2) Ogni «Ho finito» che prova davvero a copiare, o che chiude lui il permesso, dimentica la copia fatta a un abbandono precedente; anche la chiusura della finestra che rinuncia (browser fermo, un altro comando ancora in corso) la dimentica. (3) Se il tempo della chiusura della finestra finisce mentre la ricerca dei profili tiene la pagina, il registro dice «la pagina era occupata dalla ricerca dei profili», non «il browser non ha risposto in tempo». (4) La riga di avvio del motore segue `IsReadyToCollect`, con una terza frase per «aspetta la copia della sessione». (5) Il riquadro «Se una copia nuova è incompleta» non mostra né lascia scegliere nulla finché il server non dice la scelta salvata; una risposta tardiva non cambia una scelta già fatta; una scelta non salvata torna alla precedente; se la scelta non si legge, una riga lo dice. (6) Singolare italiano nei messaggi e nel registro («manca 1 valore che serve», «1 di questi serve»). (7) La guida dice che in Docker copia solo «Ho finito»: lasciare la pagina vale «Annulla» e non copia; la copia alla fine della guida in Docker resta solo una riserva per una pagina sparita senza avvisare. Corregge la frase «In Docker c'è solo la fine del permesso» della riga sulla copia alla chiusura della finestra | (1) Dopo una copia lunga (fino a 15 s di turno della pagina più il browser e il database) il permesso finiva anche se Alberto era tornato al browser, e alla chiusura successiva il motore riprendeva subito, senza attesa né copia. (2) Dopo un «Ho finito» rifiutato, un secondo «Ho finito» diceva «era già stata copiata… Non serve rifare l'accesso» di una copia forse di un altro accesso. (3) Il registro dava la colpa al browser. (4) Il registro diceva «collegato» mentre il monitor diceva «Serve «Ho finito»». (5) La pagina poteva mostrare una scelta diversa da quella che la copia seguente usa. (7) In Docker la pagina, lasciandola, manda «Annulla» (`pageLeft`) e la vista remota tiene il suo permesso finché è aperta: la copia alla fine della guida non scatta quasi mai. Se Alberto vuole che in Docker anche lasciare la pagina copi, va deciso (domanda aperta) |
| 2026-11-25 | **In Docker lasciare la pagina del browser copia la sessione: costruito** (risposta 1 di Alberto del 25 novembre 2026; ramo `funzione/sessione-s4b`). `cancel` con `pageLeft` in Docker va a `IConnectionService.LeavePageAsync` (predefinita: «Annulla», per i servizi senza sessione salvata come la dimostrazione) e non più a `CancelAsync`; la vista remota chiusa dalla sua pagina (né sostituita da un'altra scheda, né chiusa da Febe perché si ferma o perché la vista non è partita, né con il browser fermo) lo dice alla connessione (`BrowserRemoteViewHost`, `viewClosed` → `RemoteViewClosed`). Il controllo del permesso di guida, se dopo l'ultimo dei due segni passano `PageLeaveGrace` (5 s) senza viste aperte né `begin`, fa la copia di `CopyOnLetGoAsync` («Pagina del browser lasciata» nel registro, con le garanzie della chiusura della finestra), poi finisce il permesso e il motore rimette il browser a riposo; un `begin` (la pagina ricaricata) dimentica il segno. Il solo pulsante «Annulla» non copia. Windows non cambia (`pageLeft` → `ReleaseAsync`). Chiude la domanda aperta della riga «Terza revisione di S4b» (punto 7) e supera «la guida dice che in Docker copia solo «Ho finito»» | Prima in Docker lasciare la pagina valeva «Annulla» e la sessione non si copiava; una scheda chiusa senza `cancel` teneva il permesso fino ai 2 minuti di `DrivingGrace`. Il riposo lo fa il motore dopo la fine del permesso, come per la fine della guida: rimettere a riposo prima, sotto il permesso, avrebbe lasciato la pagina vuota a una vista riaperta proprio in quel momento |
| 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana |
+48 -9
View File
@@ -37,13 +37,50 @@ fa anche una **copia della sessione** per le richieste dirette di Febe: i cookie
browser e i pochi valori che la pagina tiene per le sue richieste, cifrati nella cartella dei dati
(`sessione/sessione.json`). La copia si fa solo se il browser è su una pagina del sito (non sulla pagina di accesso o
di una verifica) e mentre il browser è ancora tuo; il messaggio di «Ho finito» dice se è riuscita e se alla pagina
mancava qualche valore che serve alle richieste. Una copia così sostituisce comunque quella di prima, e le richieste
che usano il valore mancante non partono: alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. Se
la copia non è riuscita o è incompleta, riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina
iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale: dopo «Ho finito» il browser torna al motore, quindi
premerlo una seconda volta senza riaprirlo non copia nulla. Su Windows
chiudere la finestra del browser non copia: serve «Ho finito». Con `pagine`, il predefinito, e con Instagram per ora
anche con `richieste`, «Ho finito» non copia nulla e guarda solo se il cookie di sessione esiste.
mancava qualche valore che serve alle richieste. Le richieste che usano un valore mancante non partono: alla prima Febe
si ferma come disconnessione e chiede un nuovo accesso. Se la copia non è riuscita o è incompleta, riapri il browser
dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale:
dopo «Ho finito» il browser torna al motore, quindi premerlo una seconda volta senza riaprirlo non copia nulla.
Febe copia la sessione anche quando lasci il browser **senza** «Ho finito», sempre prima di riprenderselo e solo da una
pagina del sito che non sia di accesso o di verifica:
- **su Windows**, quando chiudi la finestra «Browser di Febe» (o la lasci ridotta a icona troppo a lungo);
- **in Docker**, quando lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza «Ho finito»: passi a
un'altra pagina di Febe, chiudi la scheda o la finestra del browser in cui la guardi, o se ne perde il collegamento.
Febe aspetta 5 secondi: se in quel tempo la vista remota non si riapre (una pagina ricaricata la riapre subito, e
ricaricare non è lasciare), copia la sessione e il motore può riprendere;
- quando dopo «Accedi a Instagram» o «Usa il browser» nessuna vista del browser resta aperta per 2 minuti (su Windows
la finestra fuori vista) e la guida finisce da sola.
Solo il pulsante **«Annulla»** non copia mai: il browser torna sulla pagina vuota e, se non c'era già una copia, lo
stato diventa «Serve «Ho finito»».
In questi casi non compare nessun messaggio: il registro dice com'è andata (solo conteggi, mai valori), e la pagina
Collegamento mostra la copia. Se poi premi «Ho finito» lo stesso:
- se il browser è **già tornato al motore** (la guida è finita), Febe non rilegge la pagina e ti dice che la sessione
era già stata copiata: se la copia era completa non serve rifare l'accesso;
- se il browser è **ancora tuo** (su Windows, entro i 2 minuti dalla chiusura della finestra, mentre «Accedi a
Instagram» o «Usa il browser» tiene ancora il browser), «Ho finito» copia di nuovo come sempre e il suo messaggio dice
com'è andata quella copia.
**«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
finito»»**, il motore aspetta e la pagina Collegamento apre la tua pagina iniziale nel browser: premi «Ho finito».
**La sessione salvata nella pagina Collegamento.** Da collegato, il riquadro «Sessione salvata per le richieste» dice
quando è stata copiata, quanti valori della pagina e quanti `doc_id` ci sono su quelli che Febe legge, quanti cookie, e
il nome di quelli che mancano (mai i valori). Sotto c'è la scelta **«Se una copia nuova è incompleta»**:
- **«Sostituisci comunque»** (il predefinito, consigliato): la copia nuova prende sempre il posto di quella salvata,
perché una copia più vecchia potrebbe avere i cookie di un altro accesso;
- **«Tieni la copia completa»**: se alla copia nuova manca qualcosa che le richieste usano e quella salvata ha tutto,
Febe tiene quella salvata e il messaggio di «Ho finito» lo dice. Se hai rifatto l'accesso o cambiato account, torna a
«Sostituisci comunque».
La scelta vale dalla copia successiva, senza riavviare. Con `pagine`, il predefinito, e con Instagram per ora anche con
`richieste`, «Ho finito» non copia nulla, guarda solo se il cookie di sessione esiste e il riquadro non c'è.
«Annulla» torna alle impostazioni senza collegarti.
@@ -66,7 +103,7 @@ sua copia cifrata): **chi ha la cartella dei dati, o una sua copia, ha la sessio
«Prudente»).
- La prima sessione parte tra 2 e 10 minuti dopo l'avvio, e solo dentro la fascia oraria.
- Lo stato del collegamento è sempre in fondo alla barra laterale: collegato, da collegare, verifica richiesta, sessione
chiusa.
chiusa e, con la raccolta «richieste», «Serve «Ho finito»».
- Il tuo profilo compare tra gli account segnato «Tu», con «Post in cui è taggato» attivo: è così che si scaricano i
post in cui sei taggato. Su Instagram i dati della pagina danno solo l'identificativo del tuo account: Febe ti
riconosce quando compare anche il tuo profilo (per esempio la tua voce nella barra delle storie); fino ad allora la
@@ -91,7 +128,9 @@ nulla: premilo di nuovo.
Se lasci la pagina Browser, o la pagina Collegamento mentre accedi, senza premere «Ho finito» (un'altra pagina, la
scheda chiusa o ricaricata):
- **in Docker** vale come «Annulla»: il browser torna sulla pagina vuota e il motore può lavorare di nuovo;
- **in Docker** è come chiudere la finestra del browser su Windows: se entro 5 secondi la vista remota non si riapre
(ricaricare la pagina la riapre), Febe copia la sessione come detto sopra e il motore può lavorare di nuovo (poi
rimette il browser a riposo sulla pagina vuota). Non è «Annulla»: quello lo fa solo il suo pulsante;
- **su Windows** la finestra «Browser di Febe» resta com'è, sullo schermo e con la sua pagina, finché non la chiudi (o
premi «Ho finito»); finché è sullo schermo il motore resta fermo.
+3 -1
View File
@@ -32,7 +32,9 @@ 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 (su Windows chiudendo la finestra, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker lasciare la pagina senza «Ho finito» non copia: premi «Ho finito» prima di uscire |
| «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 |
| Dopo un riavvio Febe chiede di nuovo l'accesso | Non dovrebbe: la sessione è nel profilo del browser in `/dati/browser`. Controlla che `/dati` sia un volume persistente e non sia stato cancellato; riferisci il caso (è la voce S3 di [Ipotesi da verificare](Ipotesi-da-verificare)) |
+7 -4
View File
@@ -17,16 +17,19 @@ copia altrove.
### La sessione salvata (raccolta «richieste»)
Con la raccolta «richieste» (`FEBE_RACCOLTA`, `--raccolta`) «Ho finito» copia la sessione del browser in
`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe. Con Instagram, per ora, non
succede: la copia si accende solo quando ci sono richieste configurate.
`sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe; la copia si fa anche quando chiudi
la finestra del browser su Windows e quando la guida del browser finisce da sola (vedi
[Primo collegamento](Primo-collegamento)). Con Instagram, per ora, non succede: la copia si accende solo quando ci sono
richieste configurate.
- Il file è **cifrato**. Su Windows con la protezione dei dati di Windows (DPAPI) per il tuo utente: lo apre solo il tuo
utente su quel computer. In Docker con AES-256 e una chiave che sta in `FEBE_CHIAVE_SESSIONE`, se la imposti, o nel
file `/dati/sessione/chiave.bin`, creato da Febe e leggibile solo dal proprietario. **Con la chiave dentro `/dati`,
chi ha `/dati` ha anche la sessione**: se vuoi che una copia di `/dati` da sola non basti, metti la chiave in
`FEBE_CHIAVE_SESSIONE` (`openssl rand -base64 32`) e tienila fuori dai backup di `/dati`.
- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia. Febe non la esporta e
non accetta sessioni incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori.
- Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia: la pagina Collegamento
ne mostra solo la data, i conteggi e i nomi dei valori che mancano. Febe non la esporta e non accetta sessioni
incollate da fuori. Nei registri ci sono solo conteggi e nomi, mai valori.
- Se cambi la chiave, o il file si rovina, Febe la tratta come assente e lo scrive nel registro: basta rifare
l'accesso. «Scollega» la cancella.
- Febe toglie `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` dall'ambiente dei programmi che avvia (il browser, Xvfb,
+27
View File
@@ -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.
+493 -23
View File
@@ -4,6 +4,7 @@ using Febe.Browser.Hosting;
using Febe.Browser.Session;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Requests;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
@@ -40,6 +41,16 @@ namespace Febe.App;
/// (spec §7.6): reported to the breaker as the recipes would, so that it is an incident with its alert and only
/// «Riprendi» restarts the engine. Not when Alberto himself is at the browser, nor after his «Scollega».
/// </para>
/// <para>
/// With a saved session (issue #36, S4b) the session is copied at «Ho finito», and also when Alberto lets go of the
/// browser without it: the window «Browser di Febe» closed on Windows (<see cref="CopyOnWindowClosedAsync"/>), the page
/// of the browser left in Docker (<see cref="LeavePageAsync"/>, <see cref="RemoteViewClosed"/>: after
/// <see cref="PageLeaveGrace"/> without a view open again, answer of 25 November 2026) and the lease of «Accedi» /
/// «Usa il browser» ending by itself. «Annulla» never copies. Always before the page goes back to the engine, with the
/// same guarantees as «Ho finito» (the driving gate held, the page's turn), and only from a page of the site that is
/// not a login or verification page. «Collegato» then also needs a readable saved session: without one the state is
/// <see cref="ConnectionState.SessionCopyMissing"/> («Serve «Ho finito»») and the engine waits.
/// </para>
/// </remarks>
public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposable
{
@@ -55,6 +66,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// <summary>How often the cookie is looked at in the background (outside sessions it is the only way to notice).</summary>
public static readonly TimeSpan BackgroundCheck = TimeSpan.FromSeconds(30);
/// <summary>How the log names leaving the page of the browser in Docker (answer of 25 November 2026).</summary>
private const string PageLeftText = "Pagina del browser lasciata";
private readonly IFebeBrowser _browser;
private readonly IFebeStorage _storage;
private readonly BrowserUseTracker _tracker;
@@ -74,6 +88,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
private bool? _connected;
private bool? _disconnectedByUser;
private DateTimeOffset _checkedAt = DateTimeOffset.MinValue;
private DateTimeOffset _lastCopyAt = DateTimeOffset.MinValue;
private SessionCopyOutcome? _letGoCopy;
private DateTimeOffset? _leftAt;
/// <param name="browser">The browser of Febe.</param>
/// <param name="storage">The database (first connection, «Scollega»).</param>
@@ -119,6 +136,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// True when the composition keeps a saved session (raccolta «richieste») and there is no readable one: the cookie
/// alone is not «Collegato», the copy of «Ho finito» is missing (issue #36, S4b, answer 6).
/// </summary>
public bool SessionCopyMissing => _copier is not null && _copier.SavedState != SavedSessionState.Present;
/// <summary>
/// Whether the engine may collect (<see cref="EngineRuntime.IsConnected"/>): the session cookie is in the browser
/// and, with a saved session, a readable copy of it is there too.
/// </summary>
public bool IsReadyToCollect => IsConnected == true && !SessionCopyMissing;
/// <summary>
/// How long a copy when Alberto closes the browser window waits, at most, for the commands of the connection and for
/// the copy itself (real time); then it gives up and the window gives the page back. Tests shorten it.
/// </summary>
public TimeSpan LetGoWait { get; set; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Where the browser goes when Alberto takes it from the rest page or presses «Pagina iniziale» (issue #52): the
/// site's home when the session is there, the login page when it is not (or not known yet) and after a disconnection
@@ -140,6 +175,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// </summary>
public TimeSpan DrivingGrace { get; set; } = TimeSpan.FromMinutes(2);
/// <summary>
/// How long after Alberto left the page of the browser in Docker (<see cref="LeavePageAsync"/>, or its remote view
/// closed by the page: <see cref="RemoteViewClosed"/>) no view may open again before Febe takes it as letting go of
/// the browser (answer of 25 November 2026, proposal of 5 seconds): a reload of the page opens its view again well
/// before. Read at every look; tests shorten it.
/// </summary>
public TimeSpan PageLeaveGrace { get; set; } = TimeSpan.FromSeconds(5);
/// <summary>
/// How long Alberto's page waits for its turn while a step of the profile search holds it (real time). Read at every
/// wait; tests shorten it.
@@ -161,6 +204,11 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var state = breaker is BreakerStatus.Challenge or BreakerStatus.Disconnected
? ConnectionState.VerificationRequired
: await CheckAsync(force: false, mayReport: true, ct).ConfigureAwait(false) == true ? ConnectionState.Connected : ConnectionState.NotConnected;
var saved = _copier?.Report();
if (state == ConnectionState.Connected && saved is not null && saved.State != SavedSessionState.Present)
{
state = ConnectionState.SessionCopyMissing;
}
Account? mine = null;
if (state != ConnectionState.NotConnected)
@@ -168,7 +216,55 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
mine = await _storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
}
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false));
return new ConnectionStatus(state, mine?.Username, mine?.DisplayName, driving, await CurrentUrlAsync(ct).ConfigureAwait(false), ToStatus(saved));
}
/// <summary>
/// The window «Browser di Febe» was closed by Alberto without «Ho finito», or left minimised too long (Windows, issue
/// #36, S4b, answer 5): the session is copied while the page is still his. The caller (the window) holds the driving
/// gate until this returns, so the page goes back to the engine only afterwards. Gives up after
/// <see cref="LetGoWait"/>. Never throws for the browser; logs counts only, and says which of the two happened.
/// </summary>
public async Task CopyOnWindowClosedAsync(BrowserWindowLetGo how, CancellationToken ct)
{
var what = how == BrowserWindowLetGo.MinimizedTooLong ? "Finestra del browser ridotta a icona troppo a lungo" : "Finestra del browser chiusa";
if (_copier is null)
{
return;
}
if (!_browser.IsAvailable)
{
// A letting go that copies nothing: a late «Ho finito» must not report a copy of an earlier one.
ForgetLetGoCopy();
return;
}
using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct);
limit.CancelAfter(LetGoWait);
try
{
await _commands.WaitAsync(limit.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (limit.IsCancellationRequested)
{
ForgetLetGoCopy();
_log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso.");
return;
}
catch (ObjectDisposedException)
{
return; // Febe is stopping
}
try
{
await CopyOnLetGoAsync(what, () => _browser.UserIsDriving, limit.Token).ConfigureAwait(false);
}
finally
{
ReleaseCommands();
}
}
public async Task BeginUserDrivingAsync(bool openLogin, CancellationToken ct)
@@ -181,6 +277,8 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
if (_lease is null)
{
// A new use of the browser: what an earlier one copied when it let go is no longer this one's.
_letGoCopy = null;
_lease = _browser.UserDriving.Begin();
var watch = new CancellationTokenSource();
_leaseWatch = watch;
@@ -189,6 +287,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
_lastDrivingSign = _clock.Now;
// Alberto is back (a reload of the page left a moment ago): not a letting go.
_leftAt = null;
}
_tracker.MarkUsed(_clock.Now);
@@ -313,6 +414,52 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>
/// Docker (answer of 25 November 2026): the page of the browser was left without «Ho finito» or «Annulla». Nothing
/// happens at once — a reload opens the page, «Usa il browser» and the view again within a moment. The watch of the
/// lease lets go of the browser once, for <see cref="PageLeaveGrace"/> after this and after the last view closed, no
/// view is open and no «Accedi» / «Usa il browser» came: the copy of the session as when the window is closed on
/// Windows, then the lease ends and the page goes back to the engine (which puts it to rest).
/// </summary>
public Task LeavePageAsync(CancellationToken ct)
{
if (NoteLeft())
{
_log.Info("collegamento", $"Pagina del browser lasciata senza «Ho finito» né «Annulla»: se entro {ItalianText.Duration(PageLeaveGrace)} non torni al browser, Febe copia la sessione e il motore può riprendere.");
}
return Task.CompletedTask;
}
/// <summary>
/// Docker: a remote view was closed by its page (the page left, the tab closed, the link lost; not another view taking
/// its place, nor Febe stopping). While the lease of «Accedi» / «Usa il browser» holds it counts as leaving the page
/// (<see cref="LeavePageAsync"/>): the last view closed, the moment starts again from now.
/// </summary>
public void RemoteViewClosed()
{
// The browser gone: its view closed with it, Alberto did not leave (the page opens it again once it is back).
if (_browser.IsAvailable)
{
NoteLeft();
}
}
/// <summary>Notes that Alberto may have left the browser; false without the lease of «Accedi» / «Usa il browser».</summary>
private bool NoteLeft()
{
lock (_gate)
{
if (_lease is null)
{
return false;
}
_leftAt = _clock.Now;
return true;
}
}
public async Task<FinishResult> FinishAsync(CancellationToken ct)
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
@@ -320,7 +467,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
if (!_browser.IsAvailable)
{
ReleaseLease();
EndUseWithHoFinito();
return new FinishResult(false, "Il browser di Febe non è in funzione in questo momento, quindi Febe non può controllare il collegamento. Riprova fra qualche minuto; se il problema resta, guarda il registro.");
}
@@ -330,10 +477,10 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
var first = connected && await MarkConnectedAsync(ct).ConfigureAwait(false);
// The copy for the site client (S4): while the page still holds the session and is still Alberto's.
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : null;
var copy = connected && _copier is not null ? await CopySessionAsync(ct).ConfigureAwait(false) : default;
await RestIfAlbertosAsync().ConfigureAwait(false);
await HideQuietlyAsync().ConfigureAwait(false);
ReleaseLease();
EndUseWithHoFinito();
var stopped = _engine?.Services.Breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected;
string message;
@@ -354,9 +501,9 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
message = "Collegato a Instagram. Febe riprende da solo alla prossima sessione.";
}
if (copy is not null)
if (copy.Outcome is { } outcome)
{
message += " " + CopyMessage(copy);
message += " " + CopyMessage(outcome, copy.Earlier);
}
_log.Info("collegamento", connected ? "«Ho finito»: sessione presente nel browser." : "«Ho finito»: sessione assente nel browser.");
@@ -634,9 +781,12 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
while (true)
{
var grace = DrivingGrace;
var poll = TimeSpan.FromTicks(Math.Clamp(grace.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
var leaveGrace = PageLeaveGrace;
var shortest = leaveGrace < grace ? leaveGrace : grace;
var poll = TimeSpan.FromTicks(Math.Clamp(shortest.Ticks / 8, TimeSpan.FromMilliseconds(20).Ticks, TimeSpan.FromSeconds(5).Ticks));
await _clock.Delay(poll, ct).ConfigureAwait(false);
DateTimeOffset lastSign;
DateTimeOffset? leftAt;
lock (_gate)
{
if (!ReferenceEquals(_lease, lease))
@@ -651,11 +801,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
lastSign = _lastDrivingSign;
leftAt = _leftAt;
}
if (_clock.Now - lastSign >= grace && ReleaseLease(lease))
// Docker: the page of the browser left, or its last view closed by the page, and for a moment nothing came
// back (answer of 25 November 2026). Otherwise the long wait of a lease nobody uses.
var now = _clock.Now;
var left = leftAt is { } at && now - (at > lastSign ? at : lastSign) >= leaveGrace;
if (!left && now - lastSign < grace)
{
_log.Info("collegamento", $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
continue;
}
// Before the page goes back to the engine: the copy of the session (S4b, answer 5; leaving the page in
// Docker, answer of 25 November 2026).
var what = left ? PageLeftText : "Fine della guida del browser";
if (!await CopyBeforeLeaseEndsAsync(lease, lastSign, poll, what, ct).ConfigureAwait(false))
{
continue;
}
// The copy may have lasted long (the page's turn, the browser, the database): the remote view, the window
// or «Accedi» / «Usa il browser» may have come back meanwhile. Looked at again in the same step that ends
// the lease, so that nothing slips in between.
if (ReleaseIdleLease(lease, lastSign))
{
_log.Info("collegamento", left
? $"{PageLeftText}: nessuna vista del browser riaperta, il motore può riprendere."
: $"Nessuna vista del browser aperta da {ItalianText.Duration(grace)} senza «Ho finito» né «Annulla»: il motore può riprendere.");
return;
}
}
@@ -664,6 +837,205 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
{
// The lease ended with a command of Alberto.
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Whatever failed, the lease must not hold the engine still for ever (rule 10: the kind of error only).
_log.Warn("collegamento", $"Controllo della fine della guida del browser interrotto da un errore ({ex.GetType().Name}): il motore può riprendere.");
ReleaseLease(lease);
}
}
/// <summary>
/// The copy when the lease of «Accedi» / «Usa il browser» is about to end by itself (S4b, answer 5), while it still
/// holds. Not when a copy was already made since the last sign that Alberto used the browser (the window closed a
/// moment before): the window's own hold lasts a moment after its copy, so a sign within one look
/// (<paramref name="poll"/>) of the copy is that hold, not Alberto. False when the lease must not end now: a sign of
/// driving came while the copy waited for its turn.
/// </summary>
private async Task<bool> CopyBeforeLeaseEndsAsync(IDisposable lease, DateTimeOffset lastSign, TimeSpan poll, string what, CancellationToken ct)
{
if (_copier is null)
{
return true;
}
lock (_gate)
{
if (_lastCopyAt != DateTimeOffset.MinValue && _lastCopyAt >= lastSign - poll)
{
return true;
}
}
// Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide.
try
{
await _commands.WaitAsync(ct).ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
return true; // Febe is stopping
}
try
{
bool StillAlbertos()
{
lock (_gate)
{
return ReferenceEquals(_lease, lease);
}
}
if (!StillAlbertos())
{
return true;
}
if (_browser.UserDriving.Leases > 1)
{
// The remote view or the window came back while this waited: the lease goes on.
lock (_gate)
{
_lastDrivingSign = _clock.Now;
}
return false;
}
await CopyOnLetGoAsync(what, StillAlbertos, ct).ConfigureAwait(false);
return true;
}
finally
{
ReleaseCommands();
}
}
/// <summary>
/// The copy when Alberto lets go of the browser without «Ho finito»: only while the page is still his, only when the
/// browser holds the session, with the driving gate held and the page's turn, like «Ho finito». The copier refuses a
/// page off the site or a login or verification page. One log line with the outcome (counts only).
/// </summary>
private async Task CopyOnLetGoAsync(string what, Func<bool> stillAlbertos, CancellationToken ct)
{
try
{
if (!_browser.UserIsDriving)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser era già tornato al motore.");
return;
}
// The last time this use of the browser let go decides what a late «Ho finito» says: a copy that does not
// happen now (no session, the page busy, refused, an error) forgets one made at an earlier letting go.
ForgetLetGoCopy();
if (await CheckAsync(force: true, mayReport: false, ct).ConfigureAwait(false) != true)
{
_log.Info("collegamento", $"{what}: nessuna sessione nel browser, niente da copiare.");
return;
}
var hold = _browser.UserDriving.Begin();
try
{
const string PageBusy = "sessione non copiata, la pagina era occupata dalla ricerca dei profili";
PageTurn? taken;
try
{
taken = await TakePageAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The time of the letting go ran out while a step of the search held the page: not the browser's fault.
_log.Info("collegamento", $"{what}: {PageBusy}.");
return;
}
using var turn = taken;
if (_engine is not null && turn is null)
{
_log.Info("collegamento", $"{what}: {PageBusy}.");
return;
}
var outcome = await _copier!.CopyAsync(stillAlbertos, ct).ConfigureAwait(false);
lock (_gate)
{
_lastCopyAt = _clock.Now;
if (outcome.Status is SessionCopyStatus.Saved or SessionCopyStatus.SavedInMemoryOnly or SessionCopyStatus.KeptComplete)
{
// A late «Ho finito» of this use says that the session was already copied (S4b).
_letGoCopy = outcome;
}
}
_log.Info("collegamento", $"{what}: {LetGoSummary(outcome)}.");
}
finally
{
hold.Dispose();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_log.Info("collegamento", $"{what}: sessione non copiata, il browser non ha risposto in tempo.");
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The database, the disk, Febe stopping: never the lease held for ever because of it. The kind of error only
// (rule 10): the page and the saved session hold what the session holds.
_log.Warn("collegamento", $"{what}: copia della sessione non riuscita per un errore ({ex.GetType().Name}).");
}
}
/// <summary>What a copy without «Ho finito» did, for the log (counts only).</summary>
internal static string LetGoSummary(SessionCopyOutcome copy)
{
ArgumentNullException.ThrowIfNull(copy);
var missing = copy.MissingValues + copy.MissingDocIds;
var clause = missing == 0 ? string.Empty : ", ma " + MissingNeeded(missing, past: false);
return copy.Status switch
{
SessionCopyStatus.Saved => "sessione copiata" + clause,
SessionCopyStatus.SavedInMemoryOnly => "sessione copiata, non ancora scritta su disco" + clause,
SessionCopyStatus.KeptComplete => $"copia incompleta ({ItalianText.Count(missing, "valore mancante", "valori mancanti")}), resta quella completa salvata prima",
SessionCopyStatus.Discarded => "sessione letta ma non salvata, il browser era tornato al motore",
_ => $"sessione non copiata, {BrowserSessionCopier.Reason(copy.Refusal ?? CaptureRefusal.BrowserError)}; la sessione salvata resta com'era",
};
}
/// <summary>The saved session for the interface, in counts and names; null without a saved session in this start.</summary>
private static SavedSessionStatus? ToStatus(SavedSessionReport? report) => report is null
? null
: new SavedSessionStatus(
report.State switch
{
SavedSessionState.Present => SavedSessionStatus.Present,
SavedSessionState.Unreadable => SavedSessionStatus.Unreadable,
_ => SavedSessionStatus.None,
},
report.CopiedAt,
report.Cookies,
report.ValuesPresent,
report.ValuesExpected,
report.MissingValues,
report.DocIdsPresent,
report.DocIdsExpected,
report.MissingDocIds,
report.NeededMissing);
private void ReleaseCommands()
{
try
{
_commands.Release();
}
catch (ObjectDisposedException)
{
// Febe stopped while the copy ran.
}
}
/// <summary>The first connection ever starts the gradual start (spec §7.2). True when it was the first.</summary>
@@ -736,22 +1108,35 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// The copy at «Ho finito» (issue #36, S4, §6.0): only while Alberto's own lease («Accedi», «Usa il browser») still
/// holds — after it ended the page is the engine's, and nothing is read from it (rule 7). A hold of the driving gate
/// keeps the lease from ending by itself meanwhile, and the page turn keeps a step of the profile search off the
/// page; a lease that ended all the same before the copy is saved throws the copy away.
/// page; a lease that ended all the same before the copy is saved throws the copy away. A late «Ho finito», after
/// this use of the browser already copied when it let go (S4b), reads nothing and reports that earlier copy
/// (<c>Earlier</c>), as long as the saved session is still there.
/// </summary>
private async Task<SessionCopyOutcome> CopySessionAsync(CancellationToken ct)
private async Task<(SessionCopyOutcome? Outcome, bool Earlier)> CopySessionAsync(CancellationToken ct)
{
IDisposable? lease;
SessionCopyOutcome? earlier;
lock (_gate)
{
lease = _lease;
earlier = _letGoCopy;
}
if (lease is null || !_browser.UserIsDriving)
{
if (earlier is not null && _copier!.SavedState == SavedSessionState.Present)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata di nuovo, era già stata copiata quando il browser è tornato al motore.");
return (earlier, true);
}
_log.Info("collegamento", "«Ho finito»: sessione non copiata, il browser era già tornato al motore.");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0);
return (new SessionCopyOutcome(SessionCopyStatus.Discarded, null, 0, 0, 0), false);
}
// «Ho finito» copies again: from now on its own outcome is what a later «Ho finito» refers to, not an earlier copy
// made when the browser was let go (that copy may be of another login).
ForgetLetGoCopy();
var hold = _browser.UserDriving.Begin();
try
{
@@ -759,7 +1144,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
if (_engine is not null && turn is null)
{
_log.Info("collegamento", "«Ho finito»: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
return new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0);
return (new SessionCopyOutcome(SessionCopyStatus.Refused, CaptureRefusal.BrowserError, 0, 0, 0), false);
}
bool StillAlbertos()
@@ -770,7 +1155,7 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
return await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false);
return (await _copier!.CopyAsync(StillAlbertos, ct).ConfigureAwait(false), false);
}
finally
{
@@ -782,25 +1167,34 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
/// The clause of the «Ho finito» message about the copy, in Italian (counts only). It says what the code does: a
/// value a configured operation needs and the page did not give stops that request as a disconnection (§6.0), never
/// a way back to the browser; and after a refusal a new «Ho finito» needs the browser opened again, because
/// «Ho finito» always ends the lease.
/// «Ho finito» always ends the lease. With <paramref name="earlier"/> the copy is the one made a moment before, when
/// the browser went back to the engine without «Ho finito» (S4b): the message says so, and never asks for a new login
/// when that copy is complete.
/// </summary>
internal static string CopyMessage(SessionCopyOutcome copy)
internal static string CopyMessage(SessionCopyOutcome copy, bool earlier = false)
{
ArgumentNullException.ThrowIfNull(copy);
const string Before = "La sessione per le richieste era già stata copiata quando il browser è tornato al motore";
const string Again = "Riapri il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e premi di nuovo «Ho finito» sulla tua pagina iniziale.";
var missing = copy.MissingValues + copy.MissingDocIds;
var needed = MissingNeeded(missing, past: true);
var missingClause = missing == 0
? string.Empty
: string.Create(
CultureInfo.InvariantCulture,
$" Alla pagina però mancavano {missing} valori che servono alle richieste: la copia ha comunque sostituito quella salvata prima, e le richieste che li usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}");
: $" Alla pagina però {needed}: la copia ha comunque sostituito quella salvata prima, e le richieste che {(missing == 1 ? "lo" : "li")} usano non partono. Alla prima Febe si ferma come disconnessione e chiede un nuovo accesso. {Again}";
return copy.Status switch
{
SessionCopyStatus.Saved when earlier => Before + "." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
SessionCopyStatus.SavedInMemoryOnly when earlier =>
Before + ", ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + (missing == 0 ? " Non serve rifare l'accesso." : missingClause),
SessionCopyStatus.KeptComplete when earlier =>
$"Quando il browser è tornato al motore alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
SessionCopyStatus.Saved => "Sessione copiata per le richieste di Febe." + missingClause,
SessionCopyStatus.SavedInMemoryOnly =>
"Sessione copiata per le richieste di Febe, ma non ancora scritta su disco: Febe riprova alla prossima scrittura." + missingClause,
SessionCopyStatus.Discarded =>
"La sessione per le richieste non è stata copiata: nel frattempo il browser era tornato al motore. Rifai l'accesso dalla pagina Collegamento e premi «Ho finito» sulla tua pagina iniziale.",
SessionCopyStatus.KeptComplete =>
$"Alla pagina {needed}: come hai scelto nella pagina Collegamento («Tieni la copia completa»), Febe tiene la copia completa salvata prima e non usa quella nuova. Se nel frattempo hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque». {Again}",
_ when copy.Refusal is CaptureRefusal.NotOnSite or CaptureRefusal.CheckpointPage =>
$"La sessione per le richieste non è stata copiata: {BrowserSessionCopier.Reason(copy.Refusal.Value)}. La sessione salvata resta com'era. {Again}",
_ =>
@@ -808,6 +1202,17 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
};
}
/// <summary>
/// «mancano 3 valori che servono alle richieste», «manca 1 valore che serve alle richieste» (<paramref name="past"/>:
/// «mancava», «mancavano»): the count with the Italian singular.
/// </summary>
internal static string MissingNeeded(int missing, bool past)
{
var one = missing == 1;
var verb = past ? (one ? "mancava" : "mancavano") : (one ? "manca" : "mancano");
return $"{verb} {ItalianText.Count(missing, "valore", "valori")} che {(one ? "serve" : "servono")} alle richieste";
}
/// <summary>«Scollega» deletes the saved session (memory first, then the file); returns the error of the disk, if any.</summary>
private async Task<Exception?> ForgetSavedSessionAsync()
{
@@ -938,6 +1343,27 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
}
}
/// <summary>Forgets the copy made when this use of the browser was let go (S4b): it no longer answers a late «Ho finito».</summary>
private void ForgetLetGoCopy()
{
lock (_gate)
{
_letGoCopy = null;
}
}
/// <summary>
/// «Ho finito» ends the lease. When it ends one, that use of the browser is over: a further «Ho finito» (a double
/// click, a second tab) must not report a copy made when that use was let go earlier.
/// </summary>
private void EndUseWithHoFinito()
{
if (ReleaseLease())
{
ForgetLetGoCopy();
}
}
/// <summary>Ends the lease (only <paramref name="expected"/>, when given). True when a lease ended.</summary>
private bool ReleaseLease(IDisposable? expected = null)
{
@@ -950,12 +1376,56 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa
return false;
}
lease = _lease;
watch = _leaseWatch;
_lease = null;
_leaseWatch = null;
(lease, watch) = TakeLeaseLocked();
}
return EndLease(lease, watch);
}
/// <summary>
/// Ends <paramref name="expected"/> by itself only if, in the same look, it is still the only lease of the browser and
/// no sign that Alberto uses the browser came after <paramref name="lastSign"/>: another lease (the remote view, the
/// window, a hold of the connection) is a sign now. True when the lease ended.
/// </summary>
private bool ReleaseIdleLease(IDisposable expected, DateTimeOffset lastSign)
{
IDisposable? lease;
CancellationTokenSource? watch;
lock (_gate)
{
if (!ReferenceEquals(_lease, expected))
{
return false;
}
if (_browser.UserDriving.Leases > 1)
{
_lastDrivingSign = _clock.Now;
return false;
}
if (_lastDrivingSign > lastSign)
{
return false;
}
(lease, watch) = TakeLeaseLocked();
}
return EndLease(lease, watch);
}
private (IDisposable? Lease, CancellationTokenSource? Watch) TakeLeaseLocked()
{
var taken = (_lease, _leaseWatch);
_lease = null;
_leaseWatch = null;
_leftAt = null;
return taken;
}
private static bool EndLease(IDisposable? lease, CancellationTokenSource? watch)
{
if (watch is not null)
{
watch.Cancel();
+39 -8
View File
@@ -261,7 +261,16 @@ public sealed class FebeApp : IAsyncDisposable
// Browser, connection, engine. The engine loop starts only once the browser is up.
// «Pagina iniziale» (issue #52) is the connection's, which exists only after the browser: looked up when pressed.
var context = new FebePlatformContext(o, data, Database, Clock, Log, Tracker, ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// The copy when Alberto closes the browser window (S4b) is the connection's too, looked up when it happens.
var context = new FebePlatformContext(
o,
data,
Database,
Clock,
Log,
Tracker,
ct => Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
(how, ct) => Connection?.CopyOnWindowClosedAsync(how, ct) ?? Task.CompletedTask);
var browser = await _platform.CreateBrowserAsync(context, ct).ConfigureAwait(false);
Browser = browser;
PrepareSavedSession(context, browser);
@@ -286,8 +295,9 @@ public sealed class FebeApp : IAsyncDisposable
random,
engineOptions,
userIsDriving: () => browser.UserIsDriving,
isConnected: () => connection.IsConnected == true,
ct: ct).ConfigureAwait(false);
isConnected: () => connection.IsReadyToCollect,
ct: ct,
sessionCopyMissing: () => connection.IsConnected == true && connection.SessionCopyMissing).ConfigureAwait(false);
// The diagnostic report (issue #39): one recorder for the engine, the pipeline and the interface. What the
// capture sees goes to the session in progress, if any.
var diagnostics = new CollectionDiagnostics(Clock, () => services.Runtime.CurrentSession?.SessionId, new DiagnosticLog(data.Diagnostics, Clock));
@@ -500,9 +510,7 @@ public sealed class FebeApp : IAsyncDisposable
InBackground(() => Connection.RunAsync(ct));
await engine.StartAsync(ct).ConfigureAwait(false);
Log.Info("motore", Connection.IsConnected == true
? "Motore avviato: il browser è collegato."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).");
Log.Info("motore", StartedMessage(Connection));
_running.TrySetResult();
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
@@ -576,10 +584,15 @@ public sealed class FebeApp : IAsyncDisposable
var protector = _platform.CreateSessionProtector(context);
var saved = new FileSiteSession(context.Data.SessionFile, protector, message => Log.Info("sessione", message));
var rules = LoadSignalRules(context.Data);
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message));
var settings = context.Storage.Settings;
_copier = new BrowserSessionCopier(browser.Cdp, SessionCapturePlan.For(o.Site, catalog, rules), saved, Clock, message => Log.Info("sessione", message))
{
// What an incomplete copy does (S4b): read at every copy, so a change on the Collegamento page holds at once.
IncompleteCopy = async token => (await SessionCopySettings.LoadAsync(settings, token).ConfigureAwait(false)).IncompleteCopy,
};
_requestCatalog = catalog;
SavedSession = saved;
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito».");
Log.Info("raccolta", $"Raccolta «richieste»: {catalog.Configured.Count().ToString(CultureInfo.InvariantCulture)} operazioni configurate in {Path.GetFileName(catalog.Source)}; la sessione si copia a «Ho finito», alla chiusura della finestra del browser e alla fine della guida.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or CryptographicException or PlatformNotSupportedException)
{
@@ -665,6 +678,24 @@ public sealed class FebeApp : IAsyncDisposable
}
}
/// <summary>
/// The start-up line of the engine, with what it waits for: the same state as the engine's own gate
/// (<see cref="BrowserConnectionService.IsReadyToCollect"/>), so that the log never says «collegato» while the monitor
/// says «Serve «Ho finito»».
/// </summary>
internal static string StartedMessage(BrowserConnectionService connection)
{
ArgumentNullException.ThrowIfNull(connection);
if (connection.IsReadyToCollect)
{
return "Motore avviato: il browser è collegato.";
}
return connection.IsConnected == true && connection.SessionCopyMissing
? "Motore avviato: il browser è collegato, ma aspetta la copia della sessione per le richieste (pagina Collegamento, «Ho finito»)."
: "Motore avviato: aspetta il collegamento (pagina Collegamento, «Accedi a Instagram»).";
}
/// <summary>The site's home page as the browser writes it (with its final slash), for «Pagina iniziale».</summary>
private static string HomeUrl(string baseUrl) =>
Uri.TryCreate(baseUrl, UriKind.Absolute, out var home) ? home.AbsoluteUri : baseUrl;
+17 -1
View File
@@ -72,7 +72,23 @@ public interface IFebePlatform
/// the login page otherwise, once the engine's session ended and with the page's turn
/// (<c>BrowserConnectionService.OpenStartPageAsync</c>). Null: the button does nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnWindowClosed">
/// What closing the browser window (or leaving it minimised too long) does before the page goes back to the engine
/// (issue #36, S4b): the connection copies the session into the saved session, when there is one
/// (<c>BrowserConnectionService.CopyOnWindowClosedAsync</c>). The window holds the driving gate until the task ends.
/// Null: nothing.
/// </param>
public sealed record FebePlatformContext(FebeAppOptions Options, DataFolderLayout Data, IFebeStorage Storage, IClock Clock, FebeLog Log, BrowserUseTracker Tracker, Func<CancellationToken, Task>? OpenStartPage = null, Func<BrowserWindowLetGo, CancellationToken, Task>? CopyOnWindowClosed = null);
/// <summary>How Alberto let go of the window «Browser di Febe» without «Ho finito» (Windows): the log says which.</summary>
public enum BrowserWindowLetGo
{
/// <summary>He closed it.</summary>
Closed,
/// <summary>He left it minimised longer than its limit: it went out of view as if closed.</summary>
MinimizedTooLong,
}
/// <summary>Options of the shared composition, filled by each shell from its own configuration.</summary>
public sealed record FebeAppOptions
+169 -15
View File
@@ -19,6 +19,12 @@ public enum SessionCopyStatus
/// <summary>Copied, then thrown away: meanwhile the page was no longer Alberto's (rule 7).</summary>
Discarded,
/// <summary>
/// Copied but not saved: a value the requests need was missing, the saved copy has them all, and Alberto chose
/// «Tieni la copia completa» (<see cref="IncompleteCopyChoice.KeepComplete"/>). The saved session stays as it was.
/// </summary>
KeptComplete,
}
/// <summary>What a copy did, for the message of «Ho finito» and the tests. Never a value.</summary>
@@ -34,11 +40,42 @@ public sealed record SessionCopyOutcome(SessionCopyStatus Status, CaptureRefusal
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», and after the
/// automatic login of the test site. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e
/// sostituisce»), also when some value of the page is missing: the requests that send it then do not leave and stop
/// the engine as a disconnection until a new copy has it (never a way back to the pages). A refused copy leaves the
/// saved session as it is.
/// The saved session as the Collegamento page shows it (issue #36, S4b, answer 10): its state, when it was copied, how
/// many values of the page and doc_id it holds and the names of those it lacks. Counts and names only, never a value.
/// </summary>
/// <param name="State">Whether a saved session is there and can be read.</param>
/// <param name="CopiedAt">When the browser's session was copied; null without a session or when not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds, of <paramref name="ValuesExpected"/>.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values of the page it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds, of <paramref name="DocIdsExpected"/>.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of the missing values and doc_id a configured operation sends.</param>
public sealed record SavedSessionReport(
SavedSessionState State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>True when a readable session is there and nothing a configured operation sends is missing.</summary>
public bool Complete => State == SavedSessionState.Present && NeededMissing == 0;
}
/// <summary>
/// Copies the session of Febe's browser into the saved session (issue #36, S4, spec §6.0): at «Ho finito», after the
/// automatic login of the test site, and (S4b) when Alberto closes the browser window on Windows or his driving lease
/// ends by itself. A new copy replaces the saved one (§6.0 «un nuovo accesso ricopia tutto e sostituisce»), also when
/// some value of the page is missing — unless Alberto chose «Tieni la copia completa» and the saved one is complete.
/// The requests that send a missing value do not leave and stop the engine as a disconnection until a new copy has it
/// (never a way back to the pages). A refused copy leaves the saved session as it is.
/// </summary>
public interface ISessionCopier
{
@@ -48,6 +85,12 @@ public interface ISessionCopier
/// <param name="mayKeep">Asked after reading, before saving: false throws the copy away (the page stopped being Alberto's).</param>
/// <param name="ct">Cancels the copy; nothing is saved then.</param>
Task<SessionCopyOutcome> CopyAsync(Func<bool> mayKeep, CancellationToken ct);
/// <summary>Whether a saved session is there and can be read (cheap: «Collegato» and the engine ask it often).</summary>
SavedSessionState SavedState { get; }
/// <summary>The saved session now, in counts and names (the Collegamento page, «Collegato»).</summary>
SavedSessionReport Report();
}
/// <summary>
@@ -76,6 +119,12 @@ public sealed class BrowserSessionCopier : ISessionCopier
_log = log ?? throw new ArgumentNullException(nameof(log));
}
/// <summary>
/// What an incomplete copy does, asked at every copy (the setting of the Collegamento page,
/// <see cref="SessionCopySettings"/>); by default it replaces the saved session, as before.
/// </summary>
public Func<CancellationToken, Task<IncompleteCopyChoice>> IncompleteCopy { get; init; } = _ => Task.FromResult(IncompleteCopyChoice.Replace);
/// <summary>
/// How long the reading may last before it counts as a browser error: «Ho finito» holds the commands of the
/// connection meanwhile, so a browser that hangs must not hold them for ever (real time).
@@ -110,24 +159,34 @@ public sealed class BrowserSessionCopier : ISessionCopier
var counts = string.Create(
CultureInfo.InvariantCulture,
$"{result.Cookies} cookie ({result.DroppedCookies} scartati), {result.ExpectedValues - result.MissingValues.Count} valori della pagina su {result.ExpectedValues}, {result.ExpectedDocIds - result.MissingDocIds.Count} doc_id su {result.ExpectedDocIds}");
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
var needed = neededValues.Concat(neededDocIds).ToList();
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
// An incomplete copy replaces the saved one (§6.0: an older copy could keep another login's cookies), unless
// Alberto chose to keep a complete one (answer 9 of 18 November 2026) and the saved one is complete. The choice
// is read before the last look at whose page it is, so that nothing awaited comes between that look and the write.
var keepComplete = needed.Count > 0 && IsComplete(_store.Read()) && await KeepsCompleteAsync().ConfigureAwait(false);
if (!mayKeep())
{
_log($"Sessione letta ma non salvata: nel frattempo il browser è tornato al motore ({counts}).");
return new SessionCopyOutcome(SessionCopyStatus.Discarded, null, result.Cookies, result.MissingValues.Count, result.MissingDocIds.Count);
}
// Not cancelled from here: the copy was made, and a half-written replacement is never left. It replaces the
// saved session also when a value is missing (§6.0): keeping an older copy could keep another login's cookies.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
if (keepComplete)
{
_log($"Sessione letta ma non salvata: {Missing(needed)}, che {(needed.Count == 1 ? "serve" : "servono")} alle operazioni configurate; come scelto, resta la copia completa salvata prima ({counts}).");
return new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, result.Cookies, neededValues.Count, neededDocIds.Count);
}
// Missing counts only what a configured operation sends: that request will not leave (a disconnection, §6.0).
var neededValues = result.MissingValues.Where(_plan.NeededValues.Contains).ToList();
var neededDocIds = result.MissingDocIds.Where(_plan.NeededDocIds.Contains).ToList();
var needed = neededValues.Concat(neededDocIds).ToList();
var unused = result.MissingValues.Concat(result.MissingDocIds).Except(needed, StringComparer.Ordinal).ToList();
// Not cancelled from here: the copy was made, and a half-written replacement is never left.
var onDisk = await _store.ReplaceAsync(values, CancellationToken.None).ConfigureAwait(false);
_log($"Sessione copiata: {counts}"
+ (needed.Count == 0 ? string.Empty : "; mancano " + string.Join(", ", needed) + ", che servono alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; mancano anche " + string.Join(", ", unused) + ", che nessuna operazione configurata usa")
+ (needed.Count == 0 ? string.Empty : "; " + Missing(needed) + ", che " + (needed.Count == 1 ? "serve" : "servono") + " alle operazioni configurate")
+ (unused.Count == 0 ? string.Empty : "; " + Missing(unused, also: true) + ", che nessuna operazione configurata usa")
+ (onDisk ? string.Empty : "; non ancora scritta su disco")
+ ".");
return new SessionCopyOutcome(
@@ -138,6 +197,56 @@ public sealed class BrowserSessionCopier : ISessionCopier
neededDocIds.Count);
}
public SavedSessionState SavedState => _store.State;
public SavedSessionReport Report()
{
var state = _store.State;
var values = state == SavedSessionState.Present ? _store.Read() : null;
if (values is null)
{
var none = state == SavedSessionState.Present ? SavedSessionState.None : state;
return new SavedSessionReport(none, null, 0, 0, _plan.Values.Count, [], 0, _plan.DocIds.Count, [], 0);
}
var missingValues = new List<string>();
var needed = 0;
foreach (var read in _plan.Values)
{
if (!values.Fields.ContainsKey(read.Field))
{
missingValues.Add(read.Field);
needed += _plan.NeededValues.Contains(read.Field) ? 1 : 0;
}
}
var missingDocIds = new List<string>();
foreach (var read in _plan.DocIds)
{
if (!values.DocIds.ContainsKey(read.Field))
{
missingDocIds.Add(read.Field);
needed += _plan.NeededDocIds.Contains(read.Field) ? 1 : 0;
}
}
return new SavedSessionReport(
SavedSessionState.Present,
values.CopiedAt,
values.Cookies.Count,
_plan.Values.Count - missingValues.Count,
_plan.Values.Count,
missingValues,
_plan.DocIds.Count - missingDocIds.Count,
_plan.DocIds.Count,
missingDocIds,
needed);
}
/// <summary>«manca app_id», «mancano hsi, rev» (with <paramref name="also"/>: «manca anche …»), for the log: names only.</summary>
private static string Missing(IReadOnlyList<string> names, bool also = false) =>
(names.Count == 1 ? "manca " : "mancano ") + (also ? "anche " : string.Empty) + string.Join(", ", names);
/// <summary>Why a copy was refused, in Italian.</summary>
public static string Reason(CaptureRefusal refusal) => refusal switch
{
@@ -146,4 +255,49 @@ public sealed class BrowserSessionCopier : ISessionCopier
CaptureRefusal.NoUserAgent => "il browser non ha dato il suo user agent",
_ => "il browser non ha risposto",
};
/// <summary>
/// Whether Alberto chose «Tieni la copia completa». A choice that cannot be read (the database busy or failing) is
/// the default, «Sostituisci comunque»: the copy goes on, and «Ho finito» never fails because of the setting. The log
/// gets the kind of error only (rule 10).
/// </summary>
private async Task<bool> KeepsCompleteAsync()
{
try
{
return await IncompleteCopy(CancellationToken.None).ConfigureAwait(false) == IncompleteCopyChoice.KeepComplete;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log($"Scelta per la copia incompleta non letta ({ex.GetType().Name}): vale la predefinita, la copia sostituisce quella salvata.");
return false;
}
}
/// <summary>True when <paramref name="saved"/> holds every value and doc_id a configured operation sends.</summary>
private bool IsComplete(SiteSessionValues? saved)
{
if (saved is null)
{
return false;
}
foreach (var field in _plan.NeededValues)
{
if (!saved.Fields.ContainsKey(field))
{
return false;
}
}
foreach (var operation in _plan.NeededDocIds)
{
if (!saved.DocIds.ContainsKey(operation))
{
return false;
}
}
return true;
}
}
@@ -57,12 +57,14 @@ public sealed record ValueSource(ValueSourceKind Kind, string? Argument)
/// <c>page</c> section of the catalog says where to read (<see cref="PageSources"/>): <c>lsd</c>, <c>fb_dtsg</c>,
/// <c>app_id</c>, <c>account_id</c>, and since S4 <c>rev</c> (<c>__rev</c>), <c>hs</c> (<c>__hs</c>), <c>hsi</c>
/// (<c>__hsi</c>), <c>dpr</c>, <c>ccg</c> (<c>__ccg</c>), <c>comet_req</c> (<c>__comet_req</c>) and
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>).
/// <c>entry_nonce</c> (<c>x-fb-entry-nonce</c>), and since S4b <c>spin_r</c>, <c>spin_b</c> and <c>spin_t</c>
/// (<c>__spin_r</c>, <c>__spin_b</c>, <c>__spin_t</c>: a snapshot of the page at «Ho finito», decision of 18 November
/// 2026).
/// </summary>
public static IReadOnlySet<string> SessionFields { get; } = new[]
{
"user_agent", "lsd", "fb_dtsg", "app_id", "claim", "account_id", "doc_id",
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce",
"rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t",
}.ToFrozenSet(StringComparer.Ordinal);
/// <summary>The session fields that need no <c>page</c> entry: the browser's user agent and the claim the site sets (H13).</summary>
@@ -0,0 +1,65 @@
using Febe.Core.Storage;
namespace Febe.Core.Collection.Requests;
/// <summary>What a copy of the browser's session does when some value the requests need is missing (issue #36, S4b).</summary>
public enum IncompleteCopyChoice
{
/// <summary>
/// «Sostituisci comunque» (the default): the new copy replaces the saved one all the same, because keeping an older
/// copy could keep the cookies of another login (§6.0).
/// </summary>
Replace,
/// <summary>
/// «Tieni la copia completa»: when the saved copy has every value the configured operations need and the new one
/// does not, the saved one stays and the message says so.
/// </summary>
KeepComplete,
}
/// <summary>
/// The settings of the copy of the session (issue #36, S4b; decision of Alberto of 18 November 2026, answer 9), in the
/// <c>setting</c> table like the other settings. Read at every copy: a change holds from the next copy, no restart.
/// </summary>
/// <param name="IncompleteCopy">What an incomplete copy does.</param>
public sealed record SessionCopySettings(IncompleteCopyChoice IncompleteCopy)
{
/// <summary>The key of <see cref="IncompleteCopy"/>: <c>sostituisci</c> or <c>tieni-completa</c>.</summary>
public const string IncompleteCopyKey = "sessione.copia-incompleta";
/// <summary>The text of <see cref="IncompleteCopyChoice.Replace"/> in the table and in the API.</summary>
public const string ReplaceText = "sostituisci";
/// <summary>The text of <see cref="IncompleteCopyChoice.KeepComplete"/> in the table and in the API.</summary>
public const string KeepCompleteText = "tieni-completa";
/// <summary>The settings of a database that never stored them: an incomplete copy replaces the saved one.</summary>
public static SessionCopySettings Default { get; } = new(IncompleteCopyChoice.Replace);
/// <summary>The text of <paramref name="choice"/>.</summary>
public static string ToText(IncompleteCopyChoice choice) => choice == IncompleteCopyChoice.KeepComplete ? KeepCompleteText : ReplaceText;
/// <summary>The choice of <paramref name="text"/>; null for any other text.</summary>
public static IncompleteCopyChoice? Parse(string? text) => text switch
{
ReplaceText => IncompleteCopyChoice.Replace,
KeepCompleteText => IncompleteCopyChoice.KeepComplete,
_ => null,
};
/// <summary>The stored settings; an unknown or missing value is the default.</summary>
public static async Task<SessionCopySettings> LoadAsync(ISettingsStore settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
var text = await settings.GetAsync(IncompleteCopyKey, ct).ConfigureAwait(false);
return Parse(text) is { } choice ? new SessionCopySettings(choice) : Default;
}
/// <summary>Stores these settings.</summary>
public Task SaveAsync(ISettingsStore settings, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(settings);
return settings.SetAsync(IncompleteCopyKey, ToText(IncompleteCopy), ct);
}
}
+32 -29
View File
@@ -1,6 +1,6 @@
{
"site": "instagram",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn, __d e __spin_r/__spin_b/__spin_t, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"note": "Operazioni che il client del sito può chiedere a Instagram (issue #36, specifica §6.0). Scritte il 16 novembre 2026 dalle forme reali delle richieste ricavate con «febe-sonda richieste» dai file HAR del 12 novembre (con e senza scorrimento) e del 16 novembre, fuori dal repository e senza valori; le risposte sono documentate dai campioni ripuliti di tests/Febe.Tests/campioni/instagram (regola 9). Solo letture: il codice rifiuta ogni «Mutation», la telemetria, la navigazione della pagina e le famiglie di chat, messaggi, presenza e promozioni, anche se una copia modificata le elencasse. Nessun doc_id né altro valore qui: la sezione «page» dice in quale modulo della pagina si trova ciascuno, e «Ho finito» li copia nella sessione salvata (tappa S4). I posti della sezione «page» vengono dal codice pubblico della pagina del HAR, solo forme e nomi: __rev da SiteData.client_revision, __hs da SiteData.haste_session, __hsi da SiteData.hsi, dpr da SiteData.pr, __comet_req da SiteData.comet_env, __ccg da WebConnectionClassServerGuess.connectionClass, x-fb-entry-nonce da BootloaderConfig.nonce, __spin_r, __spin_b e __spin_t dalle chiavi omonime di SiteData (decisione di Alberto del 18 novembre 2026: si copiano dalla pagina a «Ho finito», come gli altri; chi le aggiunge alla richiesta resta da vedere, H23), i doc_id dal modulo «<operazione>_instagramRelayOperation»; dpr e __comet_req erano costanti (1 e 7) e ora si leggono dalla pagina. Fonti dei valori: constant (dalle forme), cookie:csrftoken, session:… (copiato a «Ho finito»: user_agent, claim, doc_id e i valori della sezione «page»: lsd, fb_dtsg, app_id, account_id, rev, hs, hsi, dpr, ccg, comet_req, entry_nonce, spin_r, spin_b, spin_t), operation, variables, computed, pending (nome noto, fonte da stabilire: valori che la pagina calcola mentre gira come __req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn e __d, le intestazioni del browser come referer, priority e sec-ch-ua, e i nomi tolti dalla sonda). Un'operazione configurata con un valore session:… senza posto nella sezione «page» è rifiutata. Le forme scrivono i vero/falso del JSON come true/false, ma non distinguono un numero da un testo di cifre: i numeri delle variabili (count 12, first 3) sono scritti come numeri, da confermare. «(nome tolto)» e «(valore tolto)» sono ciò che la sonda non mostra: un'operazione che li ha nelle variabili resta non configurata. L'elenco dei seguiti manca: nessuna forma con la risposta.",
"page": {
"note": "Dove la pagina tiene i valori della sessione: «Modulo.proprietà» del require della pagina; docIdModule con {operation} per il nome dell'operazione. Solo nomi, nessun valore.",
"docIdModule": "{operation}_instagramRelayOperation",
@@ -15,7 +15,10 @@
"dpr": "SiteData.pr",
"comet_req": "SiteData.comet_env",
"ccg": "WebConnectionClassServerGuess.connectionClass",
"entry_nonce": "BootloaderConfig.nonce"
"entry_nonce": "BootloaderConfig.nonce",
"spin_r": "SiteData.__spin_r",
"spin_b": "SiteData.__spin_b",
"spin_t": "SiteData.__spin_t"
}
},
"operations": [
@@ -66,9 +69,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -148,9 +151,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -226,9 +229,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -310,9 +313,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -389,9 +392,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -465,9 +468,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -538,9 +541,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -618,9 +621,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
@@ -699,9 +702,9 @@
"__rev": "session:rev",
"__s": "pending",
"__sjsp": "pending",
"__spin_b": "pending",
"__spin_r": "pending",
"__spin_t": "pending",
"__spin_b": "session:spin_b",
"__spin_r": "session:spin_r",
"__spin_t": "session:spin_t",
"__user": "session:account_id",
"av": "session:account_id",
"doc_id": "session:doc_id",
+8 -2
View File
@@ -15,7 +15,10 @@
"dpr": "VersioneProva.dpr",
"comet_req": "VersioneProva.comet",
"ccg": "ConnessioneProva.classe",
"entry_nonce": "AvvioProva.nonce"
"entry_nonce": "AvvioProva.nonce",
"spin_r": "GiroProva.revisione",
"spin_b": "GiroProva.ramo",
"spin_t": "GiroProva.tempo"
}
},
"operations": [
@@ -104,6 +107,9 @@
"__hs": "session:hs",
"__hsi": "session:hsi",
"__rev": "session:rev",
"__spin_r": "session:spin_r",
"__spin_b": "session:spin_b",
"__spin_t": "session:spin_t",
"dpr": "session:dpr",
"fb_dtsg": "session:fb_dtsg",
"lsd": "session:lsd",
@@ -121,7 +127,7 @@
"profilo"
],
"sample": "000002-profilo-pubblico",
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
"note": "Una richiesta GraphQL del sito di prova: le stesse forme di Instagram (form con doc_id, fb_api_req_friendly_name e variables; x-csrftoken, x-fb-friendly-name, x-ig-www-claim), la risposta di /dati/profilo/{nome}. Il sito controlla doc_id, nome, gettoni e i tipi delle variabili (primi è il numero 12, raccolte un vero/falso). I campi di versione (__rev, __hs, __hsi, __ccg, dpr, __comet_req, __spin_r, __spin_b, __spin_t) e x-fb-entry-nonce vengono dalla sessione salvata, come su Instagram."
},
{
"name": "profilo-altri",
+10 -1
View File
@@ -12,6 +12,7 @@ public sealed class EngineRuntime
private readonly Lock _gate = new();
private readonly Func<bool> _userIsDriving;
private readonly Func<bool>? _isConnected;
private readonly Func<bool>? _sessionCopyMissing;
private CautionProfile _profile = CautionProfile.Prudent;
private DateTimeOffset? _rampStart;
private SessionContext? _session;
@@ -23,10 +24,15 @@ public sealed class EngineRuntime
/// <param name="userIsDriving">True while Alberto uses the browser (<see cref="IBrowserHost.UserIsDriving"/>).</param>
/// <param name="isConnected">Whether the Instagram session exists in the browser; null when unknown.</param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null)
/// <param name="sessionCopyMissing">
/// True when the browser holds the session but the saved session of the raccolta «richieste» is missing (issue #36,
/// S4b): <paramref name="isConnected"/> is then false and the monitor says «Serve «Ho finito»». Null: never.
/// </param>
public EngineRuntime(Func<bool>? userIsDriving = null, Func<bool>? isConnected = null, Func<bool>? sessionCopyMissing = null)
{
_userIsDriving = userIsDriving ?? (() => false);
_isConnected = isConnected;
_sessionCopyMissing = sessionCopyMissing;
}
/// <summary>The effective caution profile (settings applied).</summary>
@@ -56,6 +62,9 @@ public sealed class EngineRuntime
/// <summary>Whether the browser holds an Instagram session; null when the host does not say.</summary>
public bool? IsConnected => _isConnected?.Invoke();
/// <summary>True when the browser holds the session but the copy for the requests is missing (S4b).</summary>
public bool SessionCopyMissing => _sessionCopyMissing?.Invoke() == true;
/// <summary>The session in progress, if any. The Governor refuses every site action without one.</summary>
public SessionContext? CurrentSession
{
+4 -2
View File
@@ -85,6 +85,7 @@ public sealed class EngineServices
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
/// <param name="ct">Cancellation.</param>
/// <param name="sessionCopyMissing">True when the session is in the browser but its saved copy is missing (S4b).</param>
public static async Task<EngineServices> CreateAsync(
IFebeStorage storage,
IClock clock,
@@ -92,14 +93,15 @@ public sealed class EngineServices
EngineOptions? options = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null,
CancellationToken ct = default)
CancellationToken ct = default,
Func<bool>? sessionCopyMissing = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(random);
options ??= EngineOptions.Default;
var runtime = new EngineRuntime(userIsDriving, isConnected);
var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing);
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
runtime.Profile = settings.EffectiveProfile;
runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
+8 -1
View File
@@ -35,7 +35,10 @@ public sealed class EngineMonitor : IEngineMonitor
var session = runtime.CurrentSession;
var mode = ModeOf(runtime, breaker, session, window);
var resumes = ResumesAround(mode, runtime, breaker, nextWindow, now);
var (headline, details, sidebar) = Texts(mode, runtime, breaker, session, resumes, now, zone);
// Read once: the headline and the flag of the snapshot say the same thing.
var copyMissing = mode == EngineMode.NotConnected && runtime.SessionCopyMissing;
var (headline, details, sidebar) = Texts(mode, copyMissing, runtime, breaker, session, resumes, now, zone);
var budgets = _s.Governor.GetEffectiveBudgets(now);
var statuses = await _s.Governor.GetBudgetStatusAsync(ct).ConfigureAwait(false);
@@ -62,6 +65,7 @@ public sealed class EngineMonitor : IEngineMonitor
RecentActions = await RecentAsync(now, zone, ct).ConfigureAwait(false),
SuspendedRecipes = [.. _host.SuspendedRecipes.Select(r => new SuspendedRecipeView(r.Key, ItalianText.Capitalize(SessionComposer.RecipeName(r.Key)), r.Value))],
Breaker = breaker,
SessionCopyMissing = copyMissing,
};
}
@@ -136,6 +140,7 @@ public sealed class EngineMonitor : IEngineMonitor
private static (string Headline, IReadOnlyList<string> Details, string Sidebar) Texts(
EngineMode mode,
bool copyMissing,
EngineRuntime runtime,
BreakerState breaker,
SessionContext? session,
@@ -184,6 +189,8 @@ public sealed class EngineMonitor : IEngineMonitor
case EngineMode.Disconnected:
return ("Scollegato", ["La sessione di Instagram non c'è più.", "Apri il browser, accedi di nuovo, poi premi «Riprendi». Febe non prova a rientrare da solo."], "Accedi di nuovo");
case EngineMode.NotConnected when copyMissing:
return ("Serve «Ho finito»", ["Il browser è collegato, ma manca la copia della sessione per le richieste.", "Dalla pagina Collegamento apri il browser e premi «Ho finito» sulla tua pagina iniziale."], "Serve «Ho finito»");
case EngineMode.NotConnected:
return ("Non collegato", ["Il browser di Febe non ha una sessione di Instagram.", "Collegalo dalla pagina Collegamento."], "Non collegato");
case EngineMode.UserDriving:
+6
View File
@@ -190,4 +190,10 @@ public sealed record EngineSnapshot
public required IReadOnlyList<SuspendedRecipeView> SuspendedRecipes { get; init; }
public required BreakerState Breaker { get; init; }
/// <summary>
/// Not connected because the copy for the requests is missing (issue #36, S4b): the browser has the session cookie,
/// the raccolta «richieste» has no readable saved session. The headline is then «Serve «Ho finito»».
/// </summary>
public bool SessionCopyMissing { get; init; }
}
+8 -4
View File
@@ -4,6 +4,7 @@ using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;
using Febe.App;
using Febe.Desktop.Native;
namespace Febe.Desktop.Browser;
@@ -135,8 +136,11 @@ internal sealed class BrowserWindow : Window
/// <summary>Raised by «Pagina iniziale».</summary>
public event EventHandler? HomeRequested;
/// <summary>Raised when Alberto closes the window, or leaves it minimised too long: the owner puts it out of view.</summary>
public event EventHandler? DoneRequested;
/// <summary>
/// Raised when Alberto closes the window, or leaves it minimised too long (which one is the argument): the owner puts
/// it out of view.
/// </summary>
public event EventHandler<BrowserWindowLetGo>? DoneRequested;
/// <summary>Raised when the page area changed size (a new fit): the owner sizes WebView2 again.</summary>
public event EventHandler? PageAreaChanged;
@@ -253,7 +257,7 @@ internal sealed class BrowserWindow : Window
{
// The browser stays open: closing the window means «ho finito», it goes out of view.
e.Cancel = true;
DoneRequested?.Invoke(this, EventArgs.Empty);
DoneRequested?.Invoke(this, BrowserWindowLetGo.Closed);
}
base.OnClosing(e);
@@ -283,7 +287,7 @@ internal sealed class BrowserWindow : Window
if (WindowState == WindowState.Minimized)
{
// Restored out of view by the owner (MoveOffScreen), never first on screen where it was.
DoneRequested?.Invoke(this, EventArgs.Empty);
DoneRequested?.Invoke(this, BrowserWindowLetGo.MinimizedTooLong);
}
}
+1 -1
View File
@@ -52,7 +52,7 @@ internal sealed class WebView2Browser : IFebeBrowser
_options = new BrowserOptions(ProfileDirectory, settings.Width, settings.Height);
Host = new WebView2Host(
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage),
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now), context.OpenStartPage, context.CopyOnWindowClosed),
context.Log);
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
+40 -5
View File
@@ -23,7 +23,12 @@ namespace Febe.Desktop.Browser;
/// What «Pagina iniziale» does (issue #52): the connection opens the site's home when connected, the login page otherwise,
/// once the engine's session ended and with the page's turn. Null: the button does nothing.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null);
/// <param name="CopyOnClose">
/// What closing the window (or leaving it minimised too long, the argument says which) does before the page goes back
/// to the engine (issue #36, S4b): the connection copies the session, when it keeps a saved one. The window keeps the
/// engine still until the task ends. Null: nothing.
/// </param>
internal sealed record WebView2HostOptions(BrowserHosting Hosting, string AdditionalBrowserArguments, ImageSource? Icon, Action MarkUsed, Func<CancellationToken, Task>? OpenStartPage = null, Func<BrowserWindowLetGo, CancellationToken, Task>? CopyOnClose = null);
/// <summary>What the host does when a process of WebView2 fails (issue #52).</summary>
internal enum ProcessFailureResponse
@@ -349,7 +354,7 @@ internal sealed class WebView2Host : IBrowserHost
window.MoveOffScreen();
window.Show();
window.Activated += OnActivated;
window.DoneRequested += (_, _) => Done();
window.DoneRequested += (_, how) => Done(how);
window.BackRequested += (_, _) => UserNavigation(core => core.GoBack(), core => core.CanGoBack);
window.ReloadRequested += (_, _) => UserNavigation(core => core.Reload(), _ => true);
window.HomeRequested += (_, _) => OpenStartPage();
@@ -554,12 +559,42 @@ internal sealed class WebView2Host : IBrowserHost
TakeLease();
}
/// <summary>Alberto closed the window (or left it minimised too long): done, out of view.</summary>
private void Done()
/// <summary>
/// Alberto closed the window (or left it minimised too long): done, out of view at once. With a saved session
/// (S4b) the session is copied first: a hold of the driving gate keeps the page his until the copy is over, and only
/// then does it go back to the engine (rule 7).
/// </summary>
private void Done(BrowserWindowLetGo how)
{
_window?.MoveOffScreen();
ReleaseLease();
NotifyPositionChanged();
if (_lease is null || _closing || _settings.CopyOnClose is not { } copy)
{
ReleaseLease();
return;
}
var hold = UserDriving.Begin();
ReleaseLease();
_ = CopyThenLetGoAsync(copy, how, hold);
}
private async Task CopyThenLetGoAsync(Func<BrowserWindowLetGo, CancellationToken, Task> copy, BrowserWindowLetGo how, IDisposable hold)
{
try
{
await copy(how, CancellationToken.None).ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// The kind of error only: the page and the browser may hold what the session holds.
_log.Warn("browser", $"Copia della sessione alla chiusura della finestra non riuscita ({ex.GetType().Name}).");
}
finally
{
hold.Dispose();
_settings.MarkUsed();
}
}
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
+20 -5
View File
@@ -26,6 +26,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Func<CancellationToken, Task>? _openStartPage;
private readonly Action? _viewClosed;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
@@ -43,7 +44,12 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
/// What «Pagina iniziale» does (issue #52): the connection opens the start page once the engine's session ended and
/// with the page's turn; null: the button does nothing.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null)
/// <param name="viewClosed">
/// Told when a view ends from the page's side (the page left, the tab closed, the link lost), not when another view
/// takes its place or Febe stops: the connection then knows that Alberto may have left the browser (Docker, answer of
/// 25 November 2026, spec §6.0 «Quando si copia»); null: nobody is told.
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null, Func<CancellationToken, Task>? openStartPage = null, Action? viewClosed = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
@@ -51,6 +57,7 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
_openStartPage = openStartPage;
_viewClosed = viewClosed;
}
/// <summary>
@@ -104,8 +111,8 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
catch (Exception ex)
{
// Whatever went wrong (the page gone away, an unexpected frame tree), nothing of the view stays behind:
// no lease, no screencast, no subscription.
await connection.DisposeAsync().ConfigureAwait(false);
// no lease, no screencast, no subscription. Ended by the server: the page did not leave the browser.
await connection.EndAsync(RemoteViewEnd.BrowserStopped).ConfigureAwait(false);
if (ex is CdpDisconnectedException or BrowserUnavailableException or CdpCommandException or TimeoutException)
{
throw new RemoteViewUnavailableException("Il browser di Febe non risponde: riprova fra qualche secondo.", ex);
@@ -158,7 +165,9 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
}
internal void Closed(BrowserRemoteViewConnection connection)
/// <param name="connection">The view that ended.</param>
/// <param name="byPage">True when the page ended it (left, tab closed, link lost), false when the server did.</param>
internal void Closed(BrowserRemoteViewConnection connection, bool byPage)
{
lock (_gate)
{
@@ -169,6 +178,10 @@ internal sealed class BrowserRemoteViewHost : IRemoteViewHost
}
_log.Info("vista", "Vista remota chiusa.");
if (byPage)
{
_viewClosed?.Invoke();
}
}
}
@@ -445,6 +458,8 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
return;
}
// No reason given by the server (another view, Febe stopping, the browser gone): the page closed it.
var byPage = Ended is null;
Ended ??= RemoteViewEnd.BrowserStopped;
await _ended.CancelAsync().ConfigureAwait(false);
_session.Screencast.FrameReceived -= OnFrame;
@@ -462,7 +477,7 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
// The browser is gone: the lease is released anyway.
}
_owner.Closed(this);
_owner.Closed(this, byPage);
}
private void MarkUsed()
+9 -1
View File
@@ -87,7 +87,15 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log, openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask);
// A view closed by its page may be Alberto leaving the browser (answer of 25 November 2026): the connection copies
// the session and gives the page back if no other view opens within a moment (spec §6.0 «Quando si copia»).
RemoteView = new BrowserRemoteViewHost(
app.Browser!,
app.Tracker,
app.Clock,
app.Log,
openStartPage: ct => app.Connection?.OpenStartPageAsync(ct) ?? Task.CompletedTask,
viewClosed: () => app.Connection?.RemoteViewClosed());
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+45 -2
View File
@@ -1,4 +1,6 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Requests;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Native;
@@ -36,7 +38,9 @@ public static class ConnectionApi
});
// «Annulla», or a page left without either button ({ pageLeft: true }). On Windows the browser is a window of its
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52).
// own: leaving a page of Febe leaves it as it is, on screen until Alberto closes it (issue #52). In Docker leaving
// the page lets go of the browser like closing that window: the session is copied, not cancelled (answer of
// 25 November 2026). Only the button «Annulla» cancels without copying.
endpoints.MapPost("/api/connection/cancel", async (HttpContext context, IConnectionService connection, IBrowserWindow window, CancellationToken ct) =>
{
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.CancelDrivingRequest, new CancelDrivingRequest(false)).ConfigureAwait(false);
@@ -44,6 +48,10 @@ public static class ConnectionApi
{
await connection.ReleaseAsync(ct).ConfigureAwait(false);
}
else if (body.PageLeft)
{
await connection.LeavePageAsync(ct).ConfigureAwait(false);
}
else
{
await connection.CancelAsync(ct).ConfigureAwait(false);
@@ -57,19 +65,54 @@ public static class ConnectionApi
await connection.DisconnectAsync(ct).ConfigureAwait(false);
return Results.NoContent();
});
// What an incomplete copy of the session does (issue #36, S4b, answer 9): read at every copy, no restart.
endpoints.MapGet("/api/connection/settings", async (IFebeStorage storage, CancellationToken ct) =>
ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto));
endpoints.MapPut("/api/connection/settings", async (HttpContext context, IFebeStorage storage, CancellationToken ct) =>
{
var body = await ApiHttp.BodyAsync(context, FebeJsonContext.Default.ConnectionSettingsDto).ConfigureAwait(false);
var choice = SessionCopySettings.Parse(body.IncompleteCopy)
?? throw new BadRequestException($"Scelta sconosciuta per la copia incompleta: ammesse «{SessionCopySettings.ReplaceText}» e «{SessionCopySettings.KeepCompleteText}».");
await new SessionCopySettings(choice).SaveAsync(storage.Settings, ct).ConfigureAwait(false);
return ApiHttp.Json(await SettingsAsync(storage, ct).ConfigureAwait(false), FebeJsonContext.Default.ConnectionSettingsDto);
});
}
private static async Task<ConnectionSettingsDto> SettingsAsync(IFebeStorage storage, CancellationToken ct)
{
var settings = await SessionCopySettings.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
return new ConnectionSettingsDto(SessionCopySettings.ToText(settings.IncompleteCopy));
}
public static ConnectionStatusDto ToDto(ConnectionStatus status)
{
ArgumentNullException.ThrowIfNull(status);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl);
return new ConnectionStatusDto(State(status.State), status.Username, status.DisplayName, status.UserIsDriving, status.CurrentUrl, ToDto(status.SavedSession));
}
/// <summary>The saved session in counts and names; null without one.</summary>
public static SavedSessionDto? ToDto(SavedSessionStatus? saved) => saved is null
? null
: new SavedSessionDto(
saved.State,
saved.CopiedAt?.ToUnixTimeMilliseconds(),
saved.Cookies,
saved.ValuesPresent,
saved.ValuesExpected,
saved.MissingValues,
saved.DocIdsPresent,
saved.DocIdsExpected,
saved.MissingDocIds,
saved.NeededMissing);
public static string State(ConnectionState state) => state switch
{
ConnectionState.NotConnected => "notConnected",
ConnectionState.Connected => "connected",
ConnectionState.VerificationRequired => "verificationRequired",
ConnectionState.SessionCopyMissing => "copyMissing",
_ => "browserUnavailable",
};
}
+11 -4
View File
@@ -84,8 +84,9 @@ public static class EngineApi
/// <summary>
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so; when it does not run
/// (or there is none in this process) the connection is asked.
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so, and whether the copy for
/// the requests is missing too (<see cref="EngineSnapshot.SessionCopyMissing"/>, no round trip to the browser at every
/// event); only when it does not run (or there is none in this process) the connection is asked.
/// </summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
{
@@ -98,10 +99,16 @@ public static class EngineApi
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
{
EngineMode.NotConnected => "notConnected",
// The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account.
EngineMode.NotConnected => snapshot.SessionCopyMissing ? "copyMissing" : "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State == ConnectionState.Connected ? "connected" : "notConnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch
{
ConnectionState.Connected => "connected",
ConnectionState.SessionCopyMissing => "copyMissing",
_ => "notConnected",
},
_ => "connected",
};
var link = state == "notConnected"
+1
View File
@@ -48,6 +48,7 @@ namespace Febe.Web.Api;
[JsonSerializable(typeof(LoginDto))]
[JsonSerializable(typeof(Library.LibraryChange))]
[JsonSerializable(typeof(ConnectionStatusDto))]
[JsonSerializable(typeof(ConnectionSettingsDto))]
[JsonSerializable(typeof(BeginDrivingRequest))]
[JsonSerializable(typeof(CancelDrivingRequest))]
[JsonSerializable(typeof(FinishDto))]
+27 -2
View File
@@ -5,8 +5,33 @@ namespace Febe.Web.Api;
// ---------------------------------------------------------------- connection (PROTOCOLLO.md)
/// <summary><c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, verificationRequired, browserUnavailable.</summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl);
/// <summary>
/// <c>GET /api/connection</c>. <see cref="State"/>: notConnected, connected, copyMissing, verificationRequired,
/// browserUnavailable. <see cref="SavedSession"/> only with the raccolta «richieste».
/// </summary>
public sealed record ConnectionStatusDto(string State, string? Username, string? DisplayName, bool UserIsDriving, string? CurrentUrl, SavedSessionDto? SavedSession = null);
/// <summary>
/// The saved session in counts and names (issue #36, S4b): <see cref="State"/> present, none or unreadable;
/// <see cref="CopiedAt"/> Unix milliseconds. Never a value.
/// </summary>
public sealed record SavedSessionDto(
string State,
long? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing);
/// <summary>
/// <c>GET/PUT /api/connection/settings</c>: what an incomplete copy of the session does, <c>sostituisci</c> (the
/// default) or <c>tieni-completa</c>.
/// </summary>
public sealed record ConnectionSettingsDto(string IncompleteCopy);
/// <summary><c>POST /api/connection/begin</c>.</summary>
public sealed record BeginDrivingRequest(bool OpenLogin);
+54 -1
View File
@@ -14,6 +14,48 @@ public enum ConnectionState
/// <summary>The browser is not available (starting, crashed, demo without browser).</summary>
BrowserUnavailable,
/// <summary>
/// The session cookie is in the browser, but the raccolta «richieste» has no readable saved session to send it with
/// (issue #36, S4b): «Serve «Ho finito»». The engine waits until a copy is made.
/// </summary>
SessionCopyMissing,
}
/// <summary>
/// The saved session of the raccolta «richieste» as the Collegamento page shows it (issue #36, S4b): counts and names
/// only, never a value (rule 10).
/// </summary>
/// <param name="State"><see cref="Present"/>, <see cref="None"/> or <see cref="Unreadable"/>.</param>
/// <param name="CopiedAt">When the copy was made; null when there is none or it is not known.</param>
/// <param name="Cookies">How many cookies it holds.</param>
/// <param name="ValuesPresent">Values of the page it holds.</param>
/// <param name="ValuesExpected">Values of the page the copy reads.</param>
/// <param name="MissingValues">Names of the values it lacks.</param>
/// <param name="DocIdsPresent">doc_id it holds.</param>
/// <param name="DocIdsExpected">doc_id the copy reads.</param>
/// <param name="MissingDocIds">Operations whose doc_id it lacks.</param>
/// <param name="NeededMissing">How many of those a configured operation sends (its requests do not leave).</param>
public sealed record SavedSessionStatus(
string State,
DateTimeOffset? CopiedAt,
int Cookies,
int ValuesPresent,
int ValuesExpected,
IReadOnlyList<string> MissingValues,
int DocIdsPresent,
int DocIdsExpected,
IReadOnlyList<string> MissingDocIds,
int NeededMissing)
{
/// <summary>A readable saved session.</summary>
public const string Present = "present";
/// <summary>No saved session.</summary>
public const string None = "none";
/// <summary>A file that cannot be read: counts as none.</summary>
public const string Unreadable = "unreadable";
}
/// <summary>What the interface knows about the link to Instagram.</summary>
@@ -22,12 +64,14 @@ public enum ConnectionState
/// <param name="DisplayName">Display name, when known.</param>
/// <param name="UserIsDriving">True while Alberto is using the browser (login page, remote view, browser window): the engine is still.</param>
/// <param name="CurrentUrl">Address shown in the remote view's address bar, without query string.</param>
/// <param name="SavedSession">The saved session (raccolta «richieste»); null when this start keeps none.</param>
public sealed record ConnectionStatus(
ConnectionState State,
string? Username,
string? DisplayName,
bool UserIsDriving,
string? CurrentUrl);
string? CurrentUrl,
SavedSessionStatus? SavedSession = null);
/// <summary>Result of «Ho finito» on the Collegamento page.</summary>
/// <param name="Connected">True when the session cookie now exists.</param>
@@ -70,6 +114,15 @@ public interface IConnectionService
/// </summary>
Task ReleaseAsync(CancellationToken ct);
/// <summary>
/// The Febe page that took the browser was left (another page, a reload, the tab closed) while the browser is the
/// remote view (Docker, answer of Alberto of 25 November 2026, spec §6.0 «Quando si copia»): like closing the window
/// «Browser di Febe» on Windows, not like «Annulla». If within a moment no view opens again and no «Accedi» / «Usa il
/// browser» comes (a reload is not leaving), the session is copied while the page is still his, and then the page goes
/// back to the engine. By default, for a service without a saved session to copy, it is «Annulla».
/// </summary>
Task LeavePageAsync(CancellationToken ct) => CancelAsync(ct);
/// <summary>«Scollega» (after confirmation in the UI): stops the engine and deletes the browser profile.</summary>
Task DisconnectAsync(CancellationToken ct);
}
+17 -2
View File
@@ -7,11 +7,12 @@ Lo usano due parti scritte in parallelo: non cambiarlo senza aggiornare entrambe
| Endpoint | Corpo e risposta |
|---|---|
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl }` |
| `GET /api/connection` | `{ state: "notConnected"\|"connected"\|"copyMissing"\|"verificationRequired"\|"browserUnavailable", username, displayName, userIsDriving, currentUrl, savedSession }` |
| `POST /api/connection/begin` | `{ openLogin: bool }` → 204. Alberto usa il browser; con `openLogin` il browser carica la pagina di accesso vera; senza, se il browser è a riposo (`about:blank`) apre la pagina iniziale (sotto) |
| `POST /api/connection/finish` | → `{ connected: bool, message }` («Ho finito») |
| `POST /api/connection/cancel` | corpo facoltativo `{ pageLeft: bool }` → 204 («Annulla»; con `pageLeft` la pagina è stata lasciata, sotto) |
| `POST /api/connection/disconnect` | → 204 («Scollega», dopo la conferma nell'interfaccia) |
| `GET /api/connection/settings`, `PUT /api/connection/settings` | `{ incompleteCopy: "sostituisci"\|"tieni-completa" }`: che cosa fa una copia della sessione incompleta (raccolta «richieste»); un altro valore → 400 |
| `POST /api/browser/show` | corpo facoltativo `{ openLogin: bool }` → `{ message }`. Solo Windows: porta in primo piano la finestra «Browser di Febe»; come `begin` apre la pagina di accesso (`openLogin`) o, se era a riposo, la pagina iniziale |
**Pagina iniziale** (issue #52): la home del sito se Febe è collegato e non scollegato da Instagram, altrimenti la
@@ -27,9 +28,23 @@ di una disconnessione apre il browser con `openLogin: true` (in Docker la pagina
In modalità dimostrativa la scena `scollegato` dà `notConnected`, la scena `fermo` dà `verificationRequired`.
**Raccolta «richieste»** (issue #36, S4b): `savedSession` è `null` senza sessione salvata in questo avvio («pagine», o
nessuna operazione configurata); altrimenti `{ state: "present"|"none"|"unreadable", copiedAt (ms Unix o null), cookies,
valuesPresent, valuesExpected, missingValues: [nomi], docIdsPresent, docIdsExpected, missingDocIds: [operazioni],
neededMissing }`: solo conteggi e nomi, mai valori. Con il cookie di sessione nel browser ma senza una sessione salvata
leggibile lo stato è `copyMissing` («Serve «Ho finito»»): il motore aspetta, e `/api/engine` dice `copyMissing` nel
collegamento. La sessione si copia a «Ho finito», alla chiusura della finestra del browser su Windows, lasciando la
pagina del browser in Docker (sotto) e quando il permesso di guida finisce da solo, sempre prima che la pagina torni al
motore. «Annulla» non copia mai.
L'interfaccia manda `cancel` con `{ "pageLeft": true }` anche quando Alberto lascia la pagina Browser, o la pagina
Collegamento mentre accede, senza «Ho finito» né «Annulla»: un'altra pagina, la scheda chiusa o ricaricata (`fetch`
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker vale come «Annulla» (il browser torna a riposo).
con `keepalive`, che porta l'`Origin` dell'interfaccia). In Docker non è «Annulla» (`IConnectionService.LeavePageAsync`,
risposta di Alberto del 25 novembre 2026): è come chiudere la finestra del browser su Windows. Febe lo nota e aspetta
5 secondi; anche la vista remota chiusa dalla sua pagina (scheda chiusa, collegamento perso, non sostituita da un'altra
scheda) fa ricominciare l'attesa. Se in quel tempo non si apre un'altra vista e non arriva un `begin` (una pagina
ricaricata fa tutti e due), copia la sessione come alla chiusura della finestra (solo da una pagina del sito che non sia
di accesso o di verifica), poi il permesso finisce e il motore rimette il browser a riposo.
Su Windows, dove il browser è una finestra a parte, finisce solo il permesso tenuto dalla pagina: la finestra resta
com'è, sullo schermo e con la sua pagina, finché Alberto non la chiude (e finché è sullo schermo il motore resta
fermo). Dopo un «Ho finito» riuscito la pagina chiude la vista remota e non manda un nuovo `begin`.
+9
View File
@@ -802,6 +802,15 @@ input[type=range].cursore.lungo::-webkit-slider-thumb{border-color:var(--accento
.collega-destra h2.sez{margin-bottom:12px}
.collega-destra .avviso{font-size:13.5px;line-height:1.5;padding:13px 16px}
.nota-password{background:var(--accento-tinta)}
.sessione-salvata{padding:14px 16px;font-size:13.5px;line-height:1.5}
.sessione-salvata p{margin:0 0 6px}
.sessione-salvata h2.sez{margin-bottom:8px}
.sessione-salvata h3.sez{font-size:13.5px;font-weight:650;margin:12px 0 8px}
.sessione-salvata .avviso{margin:4px 0 8px}
.sessione-salvata .scelte{display:flex;flex-direction:column;gap:10px}
.sessione-salvata .scelte .voce{align-items:flex-start}
.sessione-salvata .scelte .voce .tondo{margin-top:2px}
.sessione-salvata .scelte small{display:block;color:var(--testo-2);font-size:12.5px}
.passi-collegamento{list-style:none;margin:0 0 8px;padding:0;display:flex;flex-direction:column;gap:18px}
.passi-collegamento li{display:flex;gap:14px}
.passi-collegamento .numero{width:24px;height:24px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;background:var(--accento-tinta);color:var(--accento-scuro);font-weight:650;font-size:12.5px;margin-top:1px}
+1 -1
View File
@@ -63,7 +63,7 @@ function renderStatus(state) {
const s = state.snapshot;
const meter = s.profilesOpenedToday;
const connection = state.connection;
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : 'stato.collegato');
const linkState = t(connection.state === 'verification' ? 'stato.verifica' : connection.state === 'disconnected' ? 'stato.scollegato' : connection.state === 'copyMissing' ? 'stato.copiaMancante' : 'stato.collegato');
// The own account is known only after the first sweep (a verification can come before it): no «@null».
const who = connection.state === 'notConnected'
? h('div.chi', h('span.av.segnaposto', icon('user', 's')),
+2 -2
View File
@@ -1,8 +1,8 @@
// Browser (spec §10.3 «Apri il browser»; mockup 10 without the steps column): in Docker the remote view of the
// server's browser and «Ho finito»; on Windows the browser is its own window. While Alberto uses the browser the
// engine is still; «Ho finito» lets «Riprendi» become active after a verification. Leaving the page without «Ho finito»
// (another page, a reload, closing the tab) gives the browser back, like «Annulla» (on Windows the window stays as it
// is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// (another page, a reload, closing the tab) gives the browser back, like closing the window on Windows: the server copies
// the session if no view opens again within a moment (on Windows the window stays as it is until Alberto closes it). A browser at rest opens its start page; «?accesso=1» (the red strip of a disconnection)
// opens the login page, once: the parameter leaves the address straight away.
import { api } from '../core/api.js';
+95 -10
View File
@@ -2,7 +2,9 @@
// the steps «Come collegarti», the note that the password goes only to Instagram (keys pass through the server without
// being recorded), the risk note, Annulla and «Ho finito». Windows: the browser is the separate window «Browser di
// Febe» and the large area says so, with «Portalo in primo piano». When connected: the account, «Usa il browser» and
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still.
// «Scollega» with its confirmation. While Alberto uses the browser the engine is still. With the raccolta «richieste»
// (issue #36, S4b) the page also shows the saved session in counts and names (never values), the choice for an
// incomplete copy, and «Serve «Ho finito»» when the browser is connected but the copy is missing.
import { api } from '../core/api.js';
import { caps } from '../core/context.js';
@@ -10,10 +12,10 @@ import { h, icon, fill } from '../core/dom.js';
import { engineState, refreshEngine } from '../core/engine.js';
import { navigate } from '../core/shell.js';
import { t } from '../core/text.js';
import { avatar, confirmDialog, label, showError, toast } from '../core/ui.js';
import { avatar, confirmDialog, label, radio, showError, toast } from '../core/ui.js';
import { remoteView } from './remote-view.js';
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', verificationRequired: 'rosso', browserUnavailable: '' };
const STATE_KIND = { notConnected: 'ambra', connected: 'verde', copyMissing: 'ambra', verificationRequired: 'rosso', browserUnavailable: '' };
/** True while the engine waits for «Riprendi» (the stop strip of a verification or a disconnection). */
function waitsForResume(state) {
@@ -40,9 +42,10 @@ export async function beginDriving(openLogin) {
/**
* The browser as a page uses it (spec §4.1, §10.3: the engine is still only while Alberto uses the browser). begin()
* takes it; «Ho finito», «Annulla» and «Scollega» give it back on the server, and the page calls settled(). Leaving the
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like «Annulla» (the
* browser goes back to the empty page and the engine may work again); on Windows the window «Browser di Febe» stays as
* it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
* page in any other way — another page, a reload, closing the tab — gives it back too: in Docker like closing the
* window on Windows, not like «Annulla» (answer of 25 November 2026: if no view opens again within a moment, the
* server copies the session and the engine may work again; a reload opens the view again); on Windows the window
* «Browser di Febe» stays as it is, on screen until Alberto closes it (issue #52), and only the page's hold ends.
*/
export function drivingLease(page) {
let held = false;
@@ -120,6 +123,7 @@ export async function mountConnection(page) {
fill(stateLabel, label(t(`impostazioni.collegamento.stati.${status.state}`), STATE_KIND[status.state] || ''));
if (status.state === 'connected') drawConnected();
else if (status.state === 'browserUnavailable') drawUnavailable();
else if (status.state === 'copyMissing') drawLogin({ copyMissing: true });
else drawLogin();
}
@@ -145,15 +149,17 @@ export async function mountConnection(page) {
});
// ------------------------------------------------------------------------------------------- login or verification
function drawLogin() {
function drawLogin({ copyMissing = false } = {}) {
const verification = status.state === 'verificationRequired';
// Connected but without the copy for the requests: the start page (the site's home), never the login page.
const login = !verification && !copyMissing;
waitingResume = false;
closeView();
lease.begin(!verification);
lease.begin(login);
if (windows) {
fill(left, windowPanel());
} else {
view = remoteView(page, { url: status.currentUrl, login: !verification });
view = remoteView(page, { url: status.currentUrl, login });
fill(left, view.element);
}
const steps = t(windows ? 'impostazioni.collegamento.passiWindows' : 'impostazioni.collegamento.passi');
@@ -161,6 +167,8 @@ export async function mountConnection(page) {
fill(right,
verification
? h('div.avviso.rosso', icon('octagon-alert', 's'), h('span', h('b', t('impostazioni.collegamento.verificaTitolo')), ' ', t('impostazioni.collegamento.verificaTesto')))
: copyMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', h('b', t('impostazioni.collegamento.copiaMancanteTitolo')), ' ', t('impostazioni.collegamento.copiaMancanteTesto')))
: h('div',
h('h2.sez', t('impostazioni.collegamento.come')),
h('ol.passi-collegamento', (Array.isArray(steps) ? steps : []).map((s, i) => h('li', h('span.numero', String(i + 1)), h('div', h('b', s.titolo), h('p', s.testo)))))),
@@ -168,6 +176,7 @@ export async function mountConnection(page) {
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
// Windows: one engine per account (spec §5) said before the login too; Docker keeps mockup 10 as it is.
windows ? h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))) : null,
copyMissing ? savedSessionBox(status.savedSession, page) : null,
message,
h('div.molla'),
h('div.bottoni-collegamento',
@@ -235,7 +244,8 @@ export async function mountConnection(page) {
fill(right,
passwordNote(windows),
h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('impostazioni.collegamento.rischio'))),
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))));
h('div.avviso', icon('info', 's'), h('span', t('impostazioni.collegamento.unMotore'))),
savedSessionBox(status.savedSession, page));
}
async function useBrowser() {
@@ -287,6 +297,81 @@ export async function mountConnection(page) {
await draw();
}
/**
* The saved session of the raccolta «richieste» (issue #36, S4b): when it was copied, the values and doc_id present
* and the names of the missing ones — counts and names only, the server never sends a value — and the choice for an
* incomplete copy. Nothing without a saved session in this start («pagine»).
*/
export function savedSessionBox(saved, page) {
if (!saved) return null;
const k = (key, vars) => t(`impostazioni.collegamento.salvata.${key}`, vars);
const lines = [];
if (saved.state === 'present') {
if (saved.copiedAt) {
const when = new Date(saved.copiedAt).toLocaleString('it-IT', { dateStyle: 'medium', timeStyle: 'short' });
lines.push(h('p', k('copiata', { quando: when })));
}
lines.push(h('p.muto', [
k('valori', { presenti: String(saved.valuesPresent), attesi: String(saved.valuesExpected) }),
k('docId', { presenti: String(saved.docIdsPresent), attesi: String(saved.docIdsExpected) }),
k('cookie', { n: String(saved.cookies) }),
].join(' ')));
const missing = [...(saved.missingValues || []), ...(saved.missingDocIds || [])];
if (missing.length) lines.push(h('p', k('mancano', { nomi: missing.join(', ') })));
lines.push(saved.neededMissing
? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', k('servono', { n: String(saved.neededMissing) })))
: h('p', k('completa')));
} else {
lines.push(h('p', k(saved.state === 'unreadable' ? 'illeggibile' : 'nessuna')));
}
// Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page
// never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it;
// a choice the server did not save goes back to the one before.
let stored = null;
let chosen = false;
const show = (value) => {
keep.input.checked = value === 'tieni-completa';
replace.input.checked = value === 'sostituisci';
};
const choose = async (value) => {
chosen = true;
const before = stored;
try {
const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
stored = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
unknown.hidden = true;
toast(k('salvato'));
} catch (error) {
show(before);
showError(error);
}
};
const replace = radio({ name: 'copia-incompleta', value: 'sostituisci', onchange: choose, labelNode: h('span', h('b', k('sostituisci')), h('small', k('sostituisciAiuto'))) });
const keep = radio({ name: 'copia-incompleta', value: 'tieni-completa', onchange: choose, labelNode: h('span', h('b', k('tieni')), h('small', k('tieniAiuto'))) });
const unknown = h('p.aiuto.piccolo.scelta-ignota', { hidden: true }, k('sceltaIgnota'));
for (const choice of [replace, keep]) choice.input.disabled = true;
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
if (chosen) return;
stored = settings.incompleteCopy;
show(stored);
}).catch(() => {
if (page && page.signal && page.signal.aborted) return; // the page was left
if (!chosen) unknown.hidden = false;
}).finally(() => {
if (page && page.signal && page.signal.aborted) return;
for (const choice of [replace, keep]) choice.input.disabled = false;
});
return h('div.pannello.sessione-salvata',
h('h2.sez', k('titolo')),
...lines,
h('p.aiuto.piccolo', k('nota')),
h('h3.sez', k('incompleta')),
h('div.scelte', { role: 'radiogroup', 'aria-label': k('incompleta') }, replace, keep),
unknown);
}
/** «La password va solo a Instagram», with the true wording of each shell (spec §10.3). */
export function passwordNote(windows) {
return h('div.avviso.nota-password', icon('shield-check', 's'),
+24
View File
@@ -24,6 +24,7 @@
"nessunAccount": "Nessun account",
"verifica": "Verifica richiesta",
"scollegato": "Sessione chiusa",
"copiaMancante": "Serve «Ho finito»",
"accountDaLeggere": "Nome non ancora noto",
"nonDisponibile": "Stato del motore non disponibile"
},
@@ -690,9 +691,32 @@
"stati": {
"notConnected": "Non collegato",
"connected": "Collegato",
"copyMissing": "Serve «Ho finito»",
"verificationRequired": "Verifica richiesta",
"browserUnavailable": "Browser non disponibile"
},
"copiaMancanteTitolo": "Manca la copia della sessione",
"copiaMancanteTesto": "Il browser è collegato, ma Febe non ha ancora una copia della sessione per le richieste (o non riesce a leggerla). Apri la tua pagina iniziale nel browser e premi «Ho finito»: fino ad allora il motore aspetta.",
"salvata": {
"titolo": "Sessione salvata per le richieste",
"copiata": "Copiata {quando}.",
"nessuna": "Nessuna copia: premi «Ho finito» sulla tua pagina iniziale.",
"illeggibile": "C'è un file, ma Febe non riesce a leggerlo (un'altra chiave o un file rovinato): conta come nessuna copia. Il prossimo «Ho finito» lo sostituisce.",
"valori": "Valori della pagina: {presenti} su {attesi}.",
"docId": "doc_id: {presenti} su {attesi}.",
"cookie": "Cookie: {n}.",
"mancano": "Mancano: {nomi}.",
"servono": "{n} di questi serve alle richieste configurate: le richieste che lo usano non partono e, alla prima, Febe si ferma come disconnessione.|{n} di questi servono alle richieste configurate: quelle richieste non partono e, alla prima, Febe si ferma come disconnessione.",
"completa": "Nulla di ciò che le richieste configurate mandano manca.",
"nota": "Qui ci sono solo conteggi e nomi, mai i valori.",
"incompleta": "Se una copia nuova è incompleta",
"sostituisci": "Sostituisci comunque (consigliato)",
"sostituisciAiuto": "La copia nuova prende sempre il posto di quella salvata: una copia più vecchia potrebbe avere i cookie di un altro accesso.",
"tieni": "Tieni la copia completa",
"tieniAiuto": "Se alla copia nuova manca qualcosa che le richieste usano e quella salvata è completa, Febe tiene quella salvata e te lo dice.",
"salvato": "Scelta salvata: vale dalla prossima copia.",
"sceltaIgnota": "Febe non è riuscito a leggere la scelta salvata: scegline una per salvarla di nuovo."
},
"come": "Come collegarti",
"passi": [
{
+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.
@@ -58,7 +58,9 @@ internal sealed class DesktopBed : IAsyncDisposable
/// <param name="name">Prefix of the temporary folder.</param>
/// <param name="autoLogin"><c>--accesso-di-prova</c>: the composition opens the test site once at start-up.</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct)
/// <param name="ct">Cancels the start.</param>
/// <param name="extra">More options of Febe.exe (<c>--raccolta richieste</c>).</param>
public static async Task<DesktopBed> StartAsync(string name, bool autoLogin, CancellationToken ct, string[]? extra = null)
{
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var folder = new TestFolder(name);
@@ -77,6 +79,8 @@ internal sealed class DesktopBed : IAsyncDisposable
arguments.Add("--accesso-di-prova");
}
arguments.AddRange(extra ?? []);
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
{
throw new ArgumentException(problem);
@@ -1,3 +1,4 @@
using Febe.Browser.Cdp;
using Febe.Core.Storage;
using Febe.Tests.Windows.Support;
using Febe.Web.Connection;
@@ -64,4 +65,43 @@ public sealed class WebView2ConnectionTests
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task WithRichiesteClosingTheWindowCopiesTheSessionBeforeThePageGoesBack()
{
// Issue #36, S4b (answer 5 of 18 November 2026): the window «Browser di Febe» closed with its X, without
// «Ho finito», copies the session from the site's page into the saved session, under Alberto's lease.
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("finestra-copia", autoLogin: false, ct, ["--raccolta", "richieste"]);
var app = bed.App;
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = app.Connection!;
var browser = bed.Browser;
var savedSession = app.SavedSession ?? throw new AssertFailedException("the test site's catalog has configured operations");
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
// «Accedi» (the welcome page starts the test site's session), then Alberto goes to the home of the site.
await connection.BeginUserDrivingAsync(openLogin: true, ct);
await browser.Cdp.NavigateAsync(bed.Site.Url("/"), ct);
await connection.RefreshAsync(ct);
Assert.AreEqual(ConnectionState.SessionCopyMissing, (await connection.GetStatusAsync(ct)).State, "the cookie alone is not «Collegato» with «richieste»");
await bed.Ui.InvokeAsync(() =>
{
window.Close();
return true;
});
// 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"]);
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
Assert.IsTrue(bed.Lines.Any("Finestra del browser chiusa: sessione copiata"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any(Febe.SitoDiProva.TestSite.Lsd), "no value in the log");
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
await connection.CancelAsync(ct);
}
}
+152 -1
View File
@@ -279,7 +279,7 @@ public sealed class SessionCaptureTests
.CopyAsync(() => true, CancellationToken.None);
Assert.AreEqual(1, needed.MissingValues);
Assert.AreEqual(0, needed.MissingDocIds);
StringAssert.Contains(log[^1], "mancano app_id, che servono alle operazioni configurate");
StringAssert.Contains(log[^1], "manca app_id, che serve alle operazioni configurate");
// With the shipped catalog the query is configured: its doc_id counts.
var shipped = await new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, new InMemorySiteSession(null), new VirtualClock(), log.Add)
@@ -289,6 +289,154 @@ public sealed class SessionCaptureTests
AssertNoSecret(string.Join("\n", log));
}
[TestMethod]
public async Task KeepTheCompleteCopyKeepsTheSavedOneOnlyWhenItIsCompleteAndTheNewOneLacksWhatTheRequestsNeed()
{
// Answer 9 of 18 November 2026: «tieni la completa» is a choice; «sostituisci» stays the default.
var log = new List<string>();
var store = new InMemorySiteSession(null);
var choice = IncompleteCopyChoice.KeepComplete;
BrowserSessionCopier Copier(JsonObject page) =>
new(Page($"http://{SiteHost}/", page: page), Plan, store, new VirtualClock(), log.Add) { IncompleteCopy = _ => Task.FromResult(choice) };
var lacking = PageValues();
((JsonObject)lacking["values"]!).Remove("lsd");
// Nothing saved yet: the incomplete copy is saved all the same (there is no complete one to keep).
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
var incomplete = store.Read()!;
// An incomplete saved copy is not one to keep: the next incomplete copy replaces it.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotEqual(incomplete.Capture, store.Read()!.Capture);
// A complete copy, then an incomplete one: the complete one stays, and the outcome says so.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status);
var complete = store.Read();
var kept = await Copier(lacking).CopyAsync(() => true, CancellationToken.None);
Assert.AreEqual(SessionCopyStatus.KeptComplete, kept.Status);
Assert.IsFalse(kept.Saved);
Assert.AreEqual(1, kept.MissingValues);
Assert.AreSame(complete, store.Read(), "the saved session stays as it was");
StringAssert.Contains(log[^1], "resta la copia completa salvata prima");
StringAssert.Contains(log[^1], "manca lsd, che serve alle operazioni configurate");
// A complete new copy always replaces it.
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(PageValues()).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotSame(complete, store.Read());
complete = store.Read();
// With «sostituisci» the incomplete copy replaces the complete one, as in S4.
choice = IncompleteCopyChoice.Replace;
Assert.AreEqual(SessionCopyStatus.Saved, (await Copier(lacking).CopyAsync(() => true, CancellationToken.None)).Status);
Assert.AreNotSame(complete, store.Read());
Assert.IsFalse(store.Read()!.Fields.ContainsKey("lsd"), "missing, never guessed");
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<string>();
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()
{
var store = new InMemorySiteSession(null);
var clock = new VirtualClock();
var page = PageValues();
((JsonObject)page["values"]!).Remove("hsi");
((JsonObject)page["docIds"]!).Remove("ProvaProfiloQuery");
var copier = new BrowserSessionCopier(Page($"http://{SiteHost}/", page: page), Plan, store, clock, _ => { });
var none = copier.Report();
Assert.AreEqual(SavedSessionState.None, none.State);
Assert.AreEqual(SavedSessionState.None, copier.SavedState);
Assert.IsFalse(none.Complete);
Assert.IsNull(none.CopiedAt);
Assert.AreEqual(Plan.Values.Count, none.ValuesExpected);
Assert.AreEqual(0, none.ValuesPresent);
await copier.CopyAsync(() => true, CancellationToken.None);
var report = copier.Report();
Assert.AreEqual(SavedSessionState.Present, report.State);
Assert.AreEqual(SavedSessionState.Present, copier.SavedState);
Assert.AreEqual(clock.Now, report.CopiedAt);
Assert.AreEqual(3, report.Cookies);
Assert.AreEqual(Plan.Values.Count - 1, report.ValuesPresent);
Assert.AreEqual(14, report.ValuesExpected, "the page values of the test catalog, spin_r, spin_b and spin_t among them");
CollectionAssert.AreEqual(new[] { "hsi" }, report.MissingValues.ToArray());
Assert.AreEqual(0, report.DocIdsPresent);
CollectionAssert.AreEqual(new[] { "ProvaProfiloQuery" }, report.MissingDocIds.ToArray());
Assert.AreEqual(2, report.NeededMissing, "the configured GraphQL query sends both");
Assert.IsFalse(report.Complete);
AssertNoSecret(report.ToString());
AssertNoSecret(string.Join(",", report.MissingValues.Concat(report.MissingDocIds)));
}
[TestMethod]
public async Task TheSpinValuesAreCopiedFromTheirModuleLikeTheOtherValuesOfThePage()
{
// Decision of 18 November 2026: __spin_r, __spin_b, __spin_t are a snapshot of the page at «Ho finito».
var store = new InMemorySiteSession(null);
await new BrowserSessionCopier(Page($"http://{SiteHost}/"), Plan, store, new VirtualClock(), _ => { }).CopyAsync(() => true, CancellationToken.None);
var saved = store.Read()!;
Assert.AreEqual("1001", saved.Fields["spin_r"]);
Assert.AreEqual("ramo", saved.Fields["spin_b"]);
Assert.AreEqual("1700000000", saved.Fields["spin_t"]);
var script = SessionCaptureScript.Build(Plan);
StringAssert.Contains(script, "read(\"GiroProva\", \"revisione\")");
StringAssert.Contains(script, "read(\"GiroProva\", \"tempo\")");
Assert.DoesNotContain("SiteData", script, "the test site's own module names, never Instagram's");
}
[TestMethod]
[Timeout(20_000, CooperativeCancellation = true)]
public async Task ABrowserThatDoesNotAnswerIsABrowserErrorAfterTheTimeout()
@@ -382,6 +530,9 @@ public sealed class SessionCaptureTests
["comet_req"] = "7",
["ccg"] = "BUONA",
["entry_nonce"] = "nonce-segreto",
["spin_r"] = "1001",
["spin_b"] = "ramo",
["spin_t"] = "1700000000",
["estraneo"] = "non chiesto",
},
["docIds"] = new JsonObject { ["ProvaProfiloQuery"] = "9000000000000009", ["AltraQuery"] = "1" },
@@ -65,7 +65,8 @@ public sealed class HttpSiteRequesterShapeTests
Assert.AreEqual(TestSite.ProfileQuery, request.Header("x-fb-friendly-name"));
Assert.AreEqual("0", request.Header("x-ig-www-claim"));
Assert.AreEqual(
"av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova&dpr=1"
"av=17841400000000077&__a=1&__ccg=BUONA&__comet_req=7&__hs=hs-di-prova&__hsi=hsi-di-prova&__rev=revisione-di-prova"
+ "&__spin_r=1001&__spin_b=ramo-di-prova&__spin_t=1700000000&dpr=1"
+ "&fb_dtsg=dtsg-di-prova&lsd=lsd-di-prova&fb_api_req_friendly_name=ProvaProfiloQuery"
+ "&variables=%7B%22username%22%3A%22marta.prova%22%2C%22scheda%22%3A%22post%22%2C%22primi%22%3A12%2C%22raccolte%22%3Atrue%7D"
+ "&doc_id=8000000000000001",
@@ -360,6 +361,9 @@ public sealed class HttpSiteRequesterShapeTests
[DataRow("ccg", "__ccg")]
[DataRow("comet_req", "__comet_req")]
[DataRow("entry_nonce", "x-fb-entry-nonce")]
[DataRow("spin_r", "__spin_r")]
[DataRow("spin_b", "__spin_b")]
[DataRow("spin_t", "__spin_t")]
public async Task AVersionFieldTheSessionLacksStopsTheQueryBeforeItLeaves(string field, string missing)
{
using var listener = new OneShotListener("""{"profilo":{}}""");
@@ -452,7 +452,7 @@ public sealed class HttpSiteRequesterTests
var secrets = new List<string>
{
Csrf, OtherCookie, SiteControl.InitialSession, "rinnovata-1", "claim-prova-1", TestSite.AppId, TestSite.Lsd, TestSite.Dtsg, AccountId,
TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce,
TestSite.Revision, TestSite.HasteSession, TestSite.HasteSessionId, TestSite.ConnectionClass, TestSite.EntryNonce, TestSite.SpinBranch,
TestSite.DocIds[TestSite.ProfileQuery], UserAgent, "Mozilla", "marta.prova", "luca.prova", "c12", "127.0.0.1", "scheda", "primi", "accesso", "next",
};
secrets.AddRange(cases.Values.SelectMany(c => c.Values.Values));
@@ -574,6 +574,9 @@ public sealed class HttpSiteRequesterTests
["comet_req"] = TestSite.CometReq,
["ccg"] = TestSite.ConnectionClass,
["entry_nonce"] = TestSite.EntryNonce,
["spin_r"] = TestSite.SpinRevision,
["spin_b"] = TestSite.SpinBranch,
["spin_t"] = TestSite.SpinTime,
};
/// <summary>A site client for the test site with its session, clock and log.</summary>
@@ -345,6 +345,9 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new PageValueSource("SiteData", "comet_env"), instagram.Values["comet_req"]);
Assert.AreEqual(new PageValueSource("WebConnectionClassServerGuess", "connectionClass"), instagram.Values["ccg"]);
Assert.AreEqual(new PageValueSource("BootloaderConfig", "nonce"), instagram.Values["entry_nonce"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_r"), instagram.Values["spin_r"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_b"), instagram.Values["spin_b"]);
Assert.AreEqual(new PageValueSource("SiteData", "__spin_t"), instagram.Values["spin_t"]);
CollectionAssert.AreEquivalent(SiteSessionValues.PageFields.ToArray(), instagram.Values.Keys.ToArray(), "A place for every page value.");
// The test site has its own module names, never Instagram's.
@@ -376,9 +379,10 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, "entry_nonce"), operation.Headers["x-fb-entry-nonce"], operation.Name);
Assert.AreEqual(new ValueSource(ValueSourceKind.Constant, "359341"), operation.Headers["x-asbd-id"], "The BDHeaderConfig property is not established.");
foreach (var spin in new[] { "__spin_r", "__spin_b", "__spin_t" })
// A snapshot of the page at «Ho finito» (decision of 18 November 2026); the operations stay not configured anyway.
foreach (var spin in new[] { "spin_r", "spin_b", "spin_t" })
{
Assert.AreEqual(ValueSourceKind.Pending, operation.Body[spin].Kind, $"{operation.Name} {spin}: who adds it to the request is not shown.");
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, spin), operation.Body["__" + spin], $"{operation.Name} __{spin}");
}
}
}
@@ -387,17 +391,18 @@ public sealed partial class RequestCatalogTests
public void EveryPendingLeftIsARuntimeValueABrowserHeaderOrARemovedName()
{
// A closed list: what the page computes while it runs (__req, __s, __dyn, __csr, __hblp, __hsdp, __sjsp, __crn,
// __d, __spin_*, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
// __d, x-web-session-id), headers of the browser (referer, priority, sec-ch-ua*, x-ig-max-touch-points)
// and the names the probe removed. Nothing else may stay pending without a decision.
var allowed = new HashSet<string>(StringComparer.Ordinal)
{
"__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d", "__spin_r", "__spin_b", "__spin_t",
"__req", "__s", "__dyn", "__csr", "__hblp", "__hsdp", "__sjsp", "__crn", "__d",
"x-web-session-id", "referer", "priority", "sec-ch-ua", "sec-ch-ua-mobile", "sec-ch-ua-platform", "x-ig-max-touch-points",
"fb_api_analytics_tags", "qpl_active_flow_ids", RequestCatalog.RemovedName,
};
var pending = RequestCatalog.LoadInstagram().Operations.SelectMany(o => o.PendingValues).Distinct(StringComparer.Ordinal).ToList();
CollectionAssert.AreEqual(Array.Empty<string>(), pending.Where(p => !allowed.Contains(p)).ToArray());
Assert.IsFalse(pending.Contains("__rev") || pending.Contains("x-fb-entry-nonce"), "Settled in S4.");
Assert.IsFalse(pending.Contains("__spin_r") || pending.Contains("__spin_b") || pending.Contains("__spin_t"), "Settled in S4b.");
Assert.AreEqual(0, RequestCatalog.LoadTestSite().Operations.Sum(o => o.PendingValues.Count));
}
@@ -471,7 +476,7 @@ public sealed partial class RequestCatalogTests
[TestMethod]
public void TheNewSessionFieldsAreAcceptedAndUnknownOnesStillRefused()
{
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce" })
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" })
{
var operation = Rest("post2", "/dati/post/{code}");
operation["headers"] = new JsonObject { ["user-agent"] = "session:user_agent", ["x-prova"] = "session:" + field };
@@ -480,7 +485,7 @@ public sealed partial class RequestCatalogTests
Assert.AreEqual(new ValueSource(ValueSourceKind.Session, field), Get(RequestCatalog.Parse(Alone(operation), "richieste.prova.json"), "post2").Headers["x-prova"]);
}
foreach (var field in new[] { "password", "spin_r", "cookie", "sessionid" })
foreach (var field in new[] { "password", "spin", "cookie", "sessionid" })
{
var operation = Rest("post2", "/dati/post/{code}");
operation["headers"] = new JsonObject { ["x-prova"] = "session:" + field };
@@ -91,6 +91,9 @@ public sealed class SessionCaptureIntegrationTests
Assert.IsTrue(apiCookie.HostOnly);
Assert.AreEqual(TestSite.Lsd, values.Fields["lsd"]);
Assert.AreEqual(TestSite.Dpr, values.Fields["dpr"], "a number of the page as text");
Assert.AreEqual(TestSite.SpinRevision, values.Fields["spin_r"], "S4b: __spin_r from the page, a number as text");
Assert.AreEqual(TestSite.SpinBranch, values.Fields["spin_b"]);
Assert.AreEqual(TestSite.SpinTime, values.Fields["spin_t"]);
Assert.AreEqual(TestSite.DocIds[TestSite.ProfileQuery], values.DocIds[TestSite.ProfileQuery]);
lock (site.World.Gate)
{
@@ -405,14 +405,14 @@ public sealed class SiteSessionTests
[TestMethod]
public void TheNewPageFieldsAreSessionFieldsAndTheVocabularyIsClosed()
{
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "lsd", "fb_dtsg", "app_id", "account_id" })
foreach (var field in new[] { "rev", "hs", "hsi", "dpr", "ccg", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t", "lsd", "fb_dtsg", "app_id", "account_id" })
{
Assert.IsTrue(SiteSessionValues.PageFields.Contains(field), field);
Assert.IsTrue(ValueSource.SessionFields.Contains(field), field);
}
CollectionAssert.AreEquivalent(new[] { "user_agent", "claim", "doc_id" }, ValueSource.SessionFields.Except(SiteSessionValues.PageFields).ToArray());
Assert.IsFalse(ValueSource.SessionFields.Contains("spin_r"), "__spin_* stay pending: who adds them to the request is not shown.");
Assert.IsFalse(ValueSource.SessionFields.Contains("spin"), "The vocabulary is closed.");
}
private static SiteCookie Cookie(string name, string value, DateTimeOffset? expires = null) =>
@@ -111,7 +111,7 @@ public sealed class TestSiteSessionTests
}
Assert.AreEqual(200, await StatusWith("rev", TestSite.Revision), "the right values pass");
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce" })
foreach (var field in new[] { "rev", "hs", "hsi", "ccg", "dpr", "comet_req", "entry_nonce", "spin_r", "spin_b", "spin_t" })
{
Assert.AreEqual(400, await StatusWith(field, "altro-valore"), field);
}
@@ -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();
@@ -118,17 +118,38 @@ public sealed class SavedSessionConnectionTests
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
// He closes the window without «Ho finito»: the lease ends by itself, the page is the engine's again.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
browser.FakeCdp.Navigated(Site + "/");
// He puts the window away without «Ho finito»: the lease ends by itself, after the copy of S4b (its page is still
// his until then), and the page is the engine's again.
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied once, before the lease ended");
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());
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(0, browser.FakeCdp.CaptureReads, "nothing is read from a page that is not his");
Assert.IsNull(bed.App.SavedSession!.Read());
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.AreSame(copied, bed.App.SavedSession.Read());
}
[TestMethod]
@@ -0,0 +1,601 @@
using System.Net;
using Febe.App;
using Febe.Core.Collection.Requests;
using Febe.Tests.Desktop.Support;
using Febe.Web.Connection;
namespace Febe.Tests.Desktop;
/// <summary>
/// Stage S4b of issue #36 (answers of Alberto of 18 November 2026) in the shared composition, with a fake browser and
/// the test site's catalog: the session is copied also when Alberto closes the browser window and when his driving
/// lease ends by itself — only from a page of the site, before the page goes back to the engine (rule 7) —; with the
/// raccolta «richieste» «Collegato» needs a readable saved session («Serve «Ho finito»» otherwise, the engine waits);
/// an incomplete copy can keep the complete one; the Collegamento page gets counts and names, never values. Never
/// Instagram.
/// </summary>
[TestClass]
public sealed class SessionCopyOnLetGoTests
{
private const string Site = "http://127.0.0.1:8481";
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ClosingTheWindowCopiesTheSessionBeforeThePageGoesBackToTheEngine()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// «Apri il browser»: only the window holds the engine still (no lease of «Accedi»).
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
bool? drivingWhileCopying = null;
bool? sessionWhileCopying = null;
browser.FakeCdp.OnCapture = () =>
{
drivingWhileCopying = browser.UserIsDriving;
sessionWhileCopying = bed.App.Engine!.Services.Runtime.CurrentSession is not null;
};
await browser.CloseWindowAsync(ct);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read");
Assert.IsFalse(sessionWhileCopying, "no engine session runs meanwhile");
Assert.IsFalse(browser.UserIsDriving, "then it goes back to the engine");
var saved = bed.App.SavedSession!.Read();
Assert.IsNotNull(saved);
Assert.AreEqual(Febe.SitoDiProva.TestSite.SpinBranch, saved.Fields["spin_b"]);
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task ClosingTheWindowOffTheSiteOrWithoutASessionCopiesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// Another site's page: the copier refuses before reading the modules.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated("https://altro.example.invalid/pagina");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession!.Read());
// A page of the site without the session cookie: nothing to copy.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = false;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsNull(bed.App.SavedSession.Read());
Assert.IsFalse(browser.UserIsDriving);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheEndOfTheLeaseCopiesOnceAndNotAgainAfterTheWindowCopied()
{
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», then the window is put away without «Ho finito»: the lease ends by itself after the copy.
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");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads, "copied when the lease ended");
Assert.IsNotNull(bed.App.SavedSession!.Read());
// «Usa il browser» again, the window closed (a copy), then the lease ends: no second copy for the same use.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/profilo/marta.prova/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the window's copy");
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la finestra");
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the end of the lease does not copy again");
// On the site's login page (a path of its stop rules) the end of the lease copies nothing: the copier refuses it.
var before = bed.App.SavedSession.Read();
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");
Assert.AreSame(before, bed.App.SavedSession.Read());
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 ALeaseThatCameBackDuringTheCopyIsNotEndedAfterIt()
{
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 put away: the end of the lease copies. While it copies, the remote view (or the
// window) comes back.
IDisposable? back = null;
browser.FakeCdp.OnCapture = () => back ??= browser.UserDriving.Begin();
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.HideFromUserAsync(ct);
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Fine della guida del browser: sessione copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la copia alla fine della guida");
Assert.IsNotNull(back);
// Time enough for the look after the copy: the lease of «Usa il browser» must still be there, beside the view's.
await Task.Delay(TimeSpan.FromMilliseconds(300), ct);
Assert.AreEqual(2, browser.UserDriving.Leases, "the lease of «Usa il browser» goes on while the view is back");
// The view goes away again: a new letting go, a new copy, and only then the lease ends.
browser.FakeCdp.OnCapture = null;
back.Dispose();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo la vista");
Assert.AreEqual(2, browser.FakeCdp.CaptureReads, "the second letting go copies again");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AHoFinitoAfterARefusedHoFinitoDoesNotReportTheCopyOfAnEarlierLettingGo()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// «Usa il browser», the window closed on the site's home: copied, while the lease of «Usa il browser» holds.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
await browser.CloseWindowAsync(ct);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(browser.UserIsDriving, "the lease of «Usa il browser» is still there");
// The window back, another login ending on the login page: «Ho finito» copies again and is refused.
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.Navigated(Site + "/accesso/");
var first = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
StringAssert.Contains(first, "non è stata copiata");
// A second «Ho finito» (a double click, another tab) must not say the session was already copied.
var second = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
Assert.DoesNotContain("era già stata copiata", second);
Assert.DoesNotContain("Non serve rifare l'accesso", second);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WhenTheTimeRunsOutWaitingForThePageTheLogSaysThePageWasBusy()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.LetGoWait = TimeSpan.FromMilliseconds(500);
connection.PageTurnWait = TimeSpan.FromSeconds(30);
await connection.ShowBrowserAsync(openLogin: false, ct);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A step of the profile search holds the page for longer than the window may wait.
using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct))
{
await browser.CloseWindowAsync(ct);
}
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
Assert.IsFalse(browser.UserIsDriving);
var log = ReadLog(bed);
StringAssert.Contains(log, "Finestra del browser chiusa: sessione non copiata, la pagina era occupata dalla ricerca dei profili.");
Assert.DoesNotContain("il browser non ha risposto in tempo", log, "the browser was not the cause");
}
[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 LeavingTheBrowserPageInDockerCopiesTheSessionOnceNoViewOpensAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(400);
// «Usa il browser» from the Browser page of Docker: no window, the remote view holds the engine still.
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
bool? drivingWhileCopying = null;
browser.FakeCdp.OnCapture = () => drivingWhileCopying = browser.UserIsDriving;
// The page says it is left; while its view (or another tab's) is still open nothing happens.
await connection.LeavePageAsync(ct);
await Task.Delay(TimeSpan.FromMilliseconds(900), ct);
Assert.IsTrue(browser.UserIsDriving, "a view is still open");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// Its view closes with it and no other opens: the copy while the page is still his, then it goes back to the engine.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: nessuna vista del browser riaperta, il motore può riprendere.", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina");
Assert.IsFalse(browser.UserIsDriving);
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
Assert.IsTrue(drivingWhileCopying, "the page is still Alberto's while it is read");
Assert.IsNotNull(bed.App.SavedSession!.Read());
StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione copiata");
// A late «Ho finito» from another tab reads nothing and says that the session was already copied.
var finish = (await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish")).GetProperty("message").GetString()!;
StringAssert.Contains(finish, "era già stata copiata");
Assert.AreEqual(1, browser.FakeCdp.CaptureReads);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task AReloadOfTheBrowserPageIsNotLeavingItAndAnnullaStillCopiesNothing()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromSeconds(1);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/");
// A reload: the old page says it left and its view closes, the new page takes the browser and opens its view.
await connection.LeavePageAsync(ct);
view.Dispose();
connection.RemoteViewClosed();
view = await DockerBeginAsync(bed);
await Task.Delay(TimeSpan.FromSeconds(2), ct);
Assert.IsTrue(browser.UserIsDriving, "a reload is not leaving the browser");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads);
// «Annulla» on the reloaded page: the browser goes back to rest, nothing is copied.
view.Dispose();
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
Assert.IsFalse(browser.UserIsDriving);
await Task.Delay(TimeSpan.FromSeconds(1.5), ct);
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "«Annulla» never copies");
Assert.IsNull(bed.App.SavedSession!.Read());
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300);
var view = await DockerBeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
browser.FakeCdp.Navigated(Site + "/accesso/");
// The tab closed on the site's login page (a path of its stop rules): the copier refuses it.
view.Dispose();
connection.RemoteViewClosed();
await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida lasciando la pagina di accesso");
Assert.AreEqual(0, browser.FakeCdp.CaptureReads, "refused before the modules are read");
Assert.IsNull(bed.App.SavedSession!.Read());
await DesktopTestBed.WaitUntilAsync(() => ReadLog(bed).Contains("Pagina del browser lasciata: sessione non copiata", StringComparison.Ordinal), TimeSpan.FromSeconds(10), "la riga della copia rifiutata");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithRichiesteCollegatoNeedsTheSavedSessionAndTheEngineWaitsForIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await StartAsync();
var browser = bed.Browser!;
var connection = bed.App.Connection!;
// The session in the browser, but «Annulla» instead of «Ho finito»: no copy.
await BeginAsync(bed);
browser.FakeCdp.LoggedIn = true;
using (var cancel = await bed.SendAsync(HttpMethod.Post, "/api/connection/cancel"))
{
Assert.AreEqual(HttpStatusCode.NoContent, cancel.StatusCode);
}
// As the background look would see it a moment later.
await connection.RefreshAsync(ct);
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("copyMissing", status.GetProperty("state").GetString());
var saved = status.GetProperty("savedSession");
Assert.AreEqual("none", saved.GetProperty("state").GetString());
Assert.IsTrue(connection.IsConnected);
Assert.IsTrue(connection.SessionCopyMissing);
Assert.IsFalse(connection.IsReadyToCollect, "the engine waits");
Assert.IsFalse(bed.App.Engine!.Services.Runtime.IsConnected);
Assert.IsTrue(bed.App.Engine.Services.Runtime.SessionCopyMissing);
StringAssert.Contains(ReadLog(bed), "Motore avviato: aspetta il collegamento", "at start-up nothing was connected");
StringAssert.Contains(FebeApp.StartedMessage(connection), "aspetta la copia della sessione", "the start-up line says what the engine waits for");
var engine = await bed.JsonAsync(HttpMethod.Get, "/api/engine");
Assert.AreEqual("copyMissing", engine.GetProperty("connection").GetProperty("state").GetString());
Assert.AreEqual("Serve «Ho finito»", engine.GetProperty("snapshot").GetProperty("headline").GetString());
// «Ho finito»: «Collegato», with counts and names of the copy and never a value.
await BeginAsync(bed, openLogin: false);
browser.FakeCdp.Navigated(Site + "/");
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
using (var answer = await bed.SendAsync(HttpMethod.Get, "/api/connection"))
{
var text = await answer.Content.ReadAsStringAsync(ct);
foreach (var secret in new[] { Febe.SitoDiProva.TestSite.Lsd, Febe.SitoDiProva.TestSite.Dtsg, Febe.SitoDiProva.TestSite.EntryNonce, Febe.SitoDiProva.TestSite.SpinBranch, "sessione-di-prova", "csrf-di-prova", "Finestra di prova" })
{
Assert.DoesNotContain(secret, text, "counts and names only");
}
}
status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString());
saved = status.GetProperty("savedSession");
Assert.AreEqual("present", saved.GetProperty("state").GetString());
Assert.IsTrue(saved.GetProperty("copiedAt").GetInt64() > 0);
Assert.AreEqual(saved.GetProperty("valuesExpected").GetInt32(), saved.GetProperty("valuesPresent").GetInt32());
Assert.AreEqual(0, saved.GetProperty("missingValues").GetArrayLength());
Assert.AreEqual(0, saved.GetProperty("neededMissing").GetInt32());
Assert.IsTrue(connection.IsReadyToCollect);
Assert.AreEqual("Motore avviato: il browser è collegato.", FebeApp.StartedMessage(connection));
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task WithPagineCollegatoIsTheCookieAloneAndNoSavedSessionIsShown()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), ct);
await BeginAsync(bed);
bed.Browser!.FakeCdp.LoggedIn = true;
await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString());
Assert.IsTrue(status.TryGetProperty("savedSession", out var saved) is false || saved.ValueKind == System.Text.Json.JsonValueKind.Null);
Assert.IsFalse(bed.App.Connection!.SessionCopyMissing);
Assert.AreEqual(0, bed.Browser.FakeCdp.CaptureReads);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheIncompleteCopySettingIsStoredAndHeldByTheNextHoFinito()
{
await using var bed = await StartAsync();
var browser = bed.Browser!;
// The default: «sostituisci»; an unknown choice is refused.
Assert.AreEqual(SessionCopySettings.ReplaceText, (await bed.JsonAsync(HttpMethod.Get, "/api/connection/settings")).GetProperty("incompleteCopy").GetString());
using (var wrong = await bed.SendAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"forse"}"""))
{
Assert.AreEqual(HttpStatusCode.BadRequest, wrong.StatusCode);
}
var keep = await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"tieni-completa"}""");
Assert.AreEqual(SessionCopySettings.KeepCompleteText, keep.GetProperty("incompleteCopy").GetString());
Assert.AreEqual(SessionCopySettings.KeepCompleteText, await bed.App.Database.Settings.GetAsync(SessionCopySettings.IncompleteCopyKey));
// A complete copy, then one from a page without the nonce: the complete one stays and «Ho finito» says so.
await FinishOnSiteAsync(bed, openLogin: true);
var complete = bed.App.SavedSession!.Read()!;
var page = FakeCdp.DefaultPageCapture();
((System.Text.Json.Nodes.JsonObject)page["values"]!).Remove("entry_nonce");
browser.FakeCdp.PageCapture = page;
var message = await FinishOnSiteAsync(bed, openLogin: false);
StringAssert.Contains(message, "Febe tiene la copia completa salvata prima");
StringAssert.Contains(message, "«Sostituisci comunque»");
Assert.AreSame(complete, bed.App.SavedSession.Read());
// «Sostituisci comunque»: the next incomplete copy replaces it, as in S4.
await bed.JsonAsync(HttpMethod.Put, "/api/connection/settings", """{"incompleteCopy":"sostituisci"}""");
message = await FinishOnSiteAsync(bed, openLogin: false);
StringAssert.Contains(message, "ha comunque sostituito quella salvata");
Assert.IsFalse(bed.App.SavedSession.Read()!.Fields.ContainsKey("entry_nonce"));
var status = await bed.JsonAsync(HttpMethod.Get, "/api/connection");
Assert.AreEqual("connected", status.GetProperty("state").GetString(), "an incomplete copy is still a readable session");
var saved = status.GetProperty("savedSession");
Assert.AreEqual("entry_nonce", saved.GetProperty("missingValues")[0].GetString());
Assert.AreEqual(1, saved.GetProperty("neededMissing").GetInt32());
}
[TestMethod]
public void TheMessagesOfTheNewOutcomesSayWhatHappened()
{
var kept = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 1, 0));
StringAssert.Contains(kept, "Alla pagina mancava 1 valore che serve alle richieste");
StringAssert.Contains(kept, "tiene la copia completa salvata prima");
StringAssert.Contains(kept, "Riapri il browser dalla pagina Collegamento");
Assert.AreEqual("sessione copiata", BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 0)));
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)), "(1 valore mancante), resta quella completa");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.KeptComplete, null, 3, 2, 1)), "(3 valori mancanti)");
StringAssert.Contains(BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 0, 1)), ", ma manca 1 valore che serve alle richieste");
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 mancava 1 valore che serve");
// Italian singular and plural (never «1 valori»).
var one = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0));
StringAssert.Contains(one, "Alla pagina però mancava 1 valore che serve alle richieste");
StringAssert.Contains(one, "le richieste che lo usano non partono");
var two = BrowserConnectionService.CopyMessage(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 1));
StringAssert.Contains(two, "Alla pagina però mancavano 2 valori che servono alle richieste");
StringAssert.Contains(two, "le richieste che li usano non partono");
foreach (var text in new[] { kept, one, two, before, beforeIncomplete, BrowserConnectionService.LetGoSummary(new SessionCopyOutcome(SessionCopyStatus.Saved, null, 3, 1, 0)) })
{
Assert.DoesNotContain("1 valori", text);
}
}
/// <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()
{
var bed = await DesktopTestBed.StartAsync(["--sito-di-prova", Site, "--raccolta", "richieste"]);
await bed.App.Running.WaitAsync(TimeSpan.FromSeconds(20), TestContext.CancellationToken);
return bed;
}
private static async Task BeginAsync(DesktopTestBed bed, bool openLogin = true)
{
using var begin = await bed.SendAsync(HttpMethod.Post, "/api/connection/begin", openLogin ? """{"openLogin":true}""" : """{"openLogin":false}""");
Assert.AreEqual(HttpStatusCode.NoContent, begin.StatusCode);
}
/// <summary>
/// «Usa il browser» as the Browser page of Docker takes it: the lease of the connection and the lease of its remote
/// view (returned), without the window of this composition (put away at once).
/// </summary>
private async Task<IDisposable> DockerBeginAsync(DesktopTestBed bed)
{
await BeginAsync(bed, openLogin: false);
await bed.Browser!.HideFromUserAsync(TestContext.CancellationToken);
return bed.Browser.UserDriving.Begin();
}
/// <summary>«Accedi» or «Usa il browser», the site's home with the session, «Ho finito». Returns the message.</summary>
private static async Task<string> FinishOnSiteAsync(DesktopTestBed bed, bool openLogin)
{
await BeginAsync(bed, openLogin);
bed.Browser!.FakeCdp.LoggedIn = true;
bed.Browser.FakeCdp.Navigated(Site + "/");
var finish = await bed.JsonAsync(HttpMethod.Post, "/api/connection/finish");
Assert.IsTrue(finish.GetProperty("connected").GetBoolean(), finish.GetProperty("message").GetString());
return finish.GetProperty("message").GetString()!;
}
}
@@ -196,6 +196,34 @@ internal sealed class FakeBrowser : IFebeBrowser
return Task.CompletedTask;
}
/// <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, BrowserWindowLetGo how = BrowserWindowLetGo.Closed)
{
Hidden++;
if (_lease is null || _context.CopyOnWindowClosed is not { } copy)
{
_lease?.Dispose();
_lease = null;
return;
}
var hold = UserDriving.Begin();
_lease.Dispose();
_lease = null;
try
{
await copy(how, ct);
}
finally
{
hold.Dispose();
}
}
/// <summary>The next «Scollega» finds a file held by another process (Windows) and cannot delete the profile.</summary>
public bool ProfileLocked { get; set; }
@@ -244,6 +272,9 @@ internal sealed class FakeCdp : ICdpSession
/// </summary>
public JsonObject? PageCapture { get; set; } = DefaultPageCapture();
/// <summary>Called when the copy's evaluation is asked, before it answers (what the test wants to look at then).</summary>
public Action? OnCapture { get; set; }
/// <summary>How many times the copy's evaluation (the one that reads <c>navigator.userAgent</c>) was asked.</summary>
public int CaptureReads => Volatile.Read(ref _captureReads);
@@ -267,6 +298,9 @@ internal sealed class FakeCdp : ICdpSession
["comet_req"] = Febe.SitoDiProva.TestSite.CometReq,
["ccg"] = Febe.SitoDiProva.TestSite.ConnectionClass,
["entry_nonce"] = Febe.SitoDiProva.TestSite.EntryNonce,
["spin_r"] = Febe.SitoDiProva.TestSite.SpinRevision,
["spin_b"] = Febe.SitoDiProva.TestSite.SpinBranch,
["spin_t"] = Febe.SitoDiProva.TestSite.SpinTime,
},
["docIds"] = new JsonObject { [Febe.SitoDiProva.TestSite.ProfileQuery] = Febe.SitoDiProva.TestSite.DocIds[Febe.SitoDiProva.TestSite.ProfileQuery] },
};
@@ -366,6 +400,7 @@ internal sealed class FakeCdp : ICdpSession
private JsonObject Capture()
{
Interlocked.Increment(ref _captureReads);
OnCapture?.Invoke();
return PageCapture is { } page
? new JsonObject { ["result"] = new JsonObject { ["type"] = "object", ["value"] = JsonNode.Parse(page.ToJsonString()) } }
: new JsonObject();
@@ -132,6 +132,33 @@ public sealed class RemoteViewStartTests
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task OnlyAViewClosedByItsPageIsToldToTheConnection()
{
// Docker (answer of 25 November 2026): a view closed by its page may be Alberto leaving the browser; one replaced
// by another tab, one that did not start, or one closed because Febe stops is not.
var ct = TestContext.CancellationToken;
var told = 0;
await using var bed = new Bed(attempt => attempt == 3 ? new CdpDisconnectedException("Il collegamento con il browser si è chiuso.") : null, viewClosed: () => Interlocked.Increment(ref told));
var older = await bed.Host.OpenAsync(ct);
var newer = await bed.Host.OpenAsync(ct);
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
Assert.AreEqual(0, Volatile.Read(ref told), "replaced by another tab: Alberto is still at the browser");
await newer.DisposeAsync();
Assert.AreEqual(1, Volatile.Read(ref told), "the page closed its view");
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
Assert.AreEqual(1, Volatile.Read(ref told), "a view that did not start was never the page's");
var last = await bed.Host.OpenAsync(ct);
await bed.Host.ShutdownAsync();
Assert.AreEqual(RemoteViewEnd.ShuttingDown, last.Ended);
Assert.AreEqual(1, Volatile.Read(ref told), "Febe stopping is not Alberto leaving");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task PaginaInizialeOpensTheStartPageOfTheMoment()
@@ -300,7 +327,8 @@ public sealed class RemoteViewStartTests
/// tested in BrowserStartPageTests); null: nowhere.
/// </param>
/// <param name="open">What «Pagina iniziale» does instead (it wins over <paramref name="startPage"/>).</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null)
/// <param name="viewClosed">What the connection is told when a view is closed by its page.</param>
public Bed(Func<int, Exception?> startFailure, Func<string>? startPage = null, Func<CancellationToken, Task>? open = null, Action? viewClosed = null)
{
Clock = new VirtualClock();
_start = Clock.Now;
@@ -326,7 +354,7 @@ public sealed class RemoteViewStartTests
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)))
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock, openStartPage: open ?? (startPage is null ? null : async ct => await Cdp.NavigateAsync(startPage(), ct)), viewClosed: viewClosed)
{
// The virtual clock moves only in the pauses: a watchdog on it would never wait.
Watchdog = null,
+5 -3
View File
@@ -63,19 +63,21 @@ public sealed class ConnectionApiTests
}
[TestMethod]
public async Task LeavingThePageIsAnnullaInDockerAndOnlyTheEndOfTheHoldOnWindows()
public async Task LeavingThePageLetsGoOfTheBrowserInDockerAndOnlyEndsTheHoldOnWindows()
{
// Docker: the remote view is the page, leaving it gives the browser back to rest.
// Docker: the remote view is the page; leaving it lets go of the browser like closing the window on Windows (the
// session is copied: answer of 25 November 2026), while the button «Annulla» still cancels.
var docker = new RecordingConnection();
await using (var server = await Part2.StartAsync(services: s => s.AddSingleton<IConnectionService>(docker)))
{
var (status, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel", new { pageLeft = true });
Assert.AreEqual(HttpStatusCode.NoContent, status);
await server.SendJsonAsync(HttpMethod.Post, "/api/connection/cancel");
var (showStatus, _) = await server.SendJsonAsync(HttpMethod.Post, "/api/browser/show");
Assert.AreEqual(HttpStatusCode.BadRequest, showStatus, "in Docker the browser is the Browser page");
}
CollectionAssert.AreEqual(new[] { "cancel" }, docker.Calls);
CollectionAssert.AreEqual(new[] { "leave", "cancel" }, docker.Calls);
// Windows (issue #52): the window stays as it is; «Annulla» is still «Annulla»; «Apri il browser» says which page.
var windows = new RecordingConnection();
@@ -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)
{
@@ -47,6 +47,13 @@ public sealed class HostingAndSecurityTests
// The text resource is valid JSON with the Italian texts.
using var texts = JsonDocument.Parse(files.ReadText("testi/it.json")!);
Assert.AreEqual("Libreria", texts.RootElement.GetProperty("nav").GetProperty("libreria").GetString());
// A count of one has its singular (t() picks the part before «|» when n is 1): never «1 di questi servono».
var needed = texts.RootElement.GetProperty("impostazioni").GetProperty("collegamento").GetProperty("salvata").GetProperty("servono").GetString()!;
var forms = needed.Split('|');
Assert.HasCount(2, forms, needed);
StringAssert.StartsWith(forms[0], "{n} di questi serve ");
StringAssert.StartsWith(forms[1], "{n} di questi servono ");
}
[TestMethod]
+30 -5
View File
@@ -90,12 +90,12 @@ public sealed class InterfaceTests
await ui.OpenAsync(new Uri(server.Address, "/browser"));
await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "il browser in uso con la vista aperta");
// Another page from the sidebar: the view closes and the lease of «begin» goes too (like «Annulla»).
// Another page from the sidebar: the view closes and the page lets go of the browser (not «Annulla»: the session is copied).
await ui.EvalAsync("document.querySelector('a[data-nav=libreria]').click()");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito lasciando la pagina");
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito lasciando la pagina");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
CollectionAssert.AreEqual(new[] { "begin:False", "cancel" }, connection.Snapshot());
CollectionAssert.AreEqual(new[] { "begin:False", "leave" }, connection.Snapshot());
}
[TestMethod]
@@ -111,7 +111,7 @@ public sealed class InterfaceTests
// The document goes away (tab closed, reload, another site): only the page-hide event is left to say so.
await ui.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" });
await ui.WaitForAsync(() => connection.Snapshot().Contains("cancel"), "il browser restituito chiudendo la scheda");
await ui.WaitForAsync(() => connection.Snapshot().Contains("leave"), "il browser restituito chiudendo la scheda");
}
[TestMethod]
@@ -180,6 +180,31 @@ public sealed class InterfaceTests
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name");
}
[TestMethod]
public async Task TheIncompleteCopyChoiceIsShownOnlyOnceTheServerSaysWhichOneIsStored()
{
// «Tieni la copia completa» stored; the page must not show «Sostituisci comunque» meanwhile, nor let a choice be
// made that the late answer would then undo.
var saved = new SavedSessionStatus(SavedSessionStatus.Present, null, 3, 7, 7, [], 2, 2, [], 0);
var connection = new RecordingConnection { Status = Connected with { SavedSession = saved } };
await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
await server.Db.Settings.SetAsync(Febe.Core.Collection.Requests.SessionCopySettings.IncompleteCopyKey, Febe.Core.Collection.Requests.SessionCopySettings.KeepCompleteText);
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(UiBrowser.Requests);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
await ui.EvalAsync("window.__hold('/api/connection/settings')");
await ui.NavigateAsync("/impostazioni/collegamento");
await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]') !== null", "riquadro della sessione salvata");
await ui.WaitAsync("window.__started['/api/connection/settings'] >= 1", "scelta chiesta al server");
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.checked && i.disabled)")).GetBoolean(), "neither choice shown nor pickable before the answer " + ui.Report());
await ui.EvalAsync("window.__release('/api/connection/settings')");
await ui.WaitAsync("document.querySelector('.sessione-salvata input[value=\"tieni-completa\"]').checked", "la scelta salvata mostrata");
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.sessione-salvata input[value=\"sostituisci\"]').checked")).GetBoolean());
Assert.IsTrue((await ui.EvalAsync("[...document.querySelectorAll('.sessione-salvata input[type=radio]')].every((i) => !i.disabled)")).GetBoolean(), "pickable once known");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.scelta-ignota').hidden")).GetBoolean(), "no warning when the choice was read");
}
[TestMethod]
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
{
@@ -233,7 +258,7 @@ public sealed class InterfaceTests
await ui.NavigateAsync("/libreria");
await ui.WaitAsync("location.pathname === '/libreria'", "Libreria");
await ui.WaitForQuietAsync("richieste della pagina finite");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back");
CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "leave" }, connection.Snapshot(), "leaving the page gives the browser back");
await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa");
}
@@ -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)
{
@@ -116,6 +124,14 @@ internal sealed class RecordingConnection : IConnectionService
return Task.CompletedTask;
}
/// <summary>Docker: the page of the browser left without «Ho finito» or «Annulla» (not «Annulla»: it copies).</summary>
public Task LeavePageAsync(CancellationToken ct)
{
Record("leave");
Status = Status with { UserIsDriving = false };
return Task.CompletedTask;
}
public Task ReleaseAsync(CancellationToken ct)
{
Record("release");
+110
View File
@@ -0,0 +1,110 @@
using Febe.Tests.Desktop.Support;
using Febe.Tests.Web.Support;
namespace Febe.Tests.Web;
/// <summary>
/// The modules of the interface load: a mistake that stops one module from parsing breaks every page importing it, and
/// the Chromium tests that would see it run only in the CI. <see cref="ScriptCheck"/> reads them without a browser.
/// </summary>
[TestClass]
public sealed class ScriptSyntaxTests
{
[TestMethod]
public void EveryModuleOfTheInterfaceReadsWithoutTheMistakesThatStopItLoading()
{
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
var files = Directory.GetFiles(root, "*.js", SearchOption.AllDirectories);
Assert.IsGreaterThan(30, files.Length, "the modules of the interface");
var problems = new List<string>();
foreach (var file in files)
{
var name = Path.GetRelativePath(root, file);
problems.AddRange(ScriptCheck.Problems(File.ReadAllText(file)).Select(p => $"{name}, {p}"));
}
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
}
[TestMethod]
public void EveryStaticImportNamesSomethingTheOtherModuleExports()
{
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
var problems = new List<string>();
var checkedNames = 0;
foreach (var file in Directory.GetFiles(root, "*.js", SearchOption.AllDirectories))
{
foreach (var (from, names, line) in ScriptCheck.Imports(File.ReadAllText(file)))
{
if (!from.StartsWith('.'))
{
continue;
}
var target = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, from));
var where = $"{Path.GetRelativePath(root, file)}, riga {line}";
if (!File.Exists(target))
{
problems.Add($"{where}: «{from}» non esiste");
continue;
}
var exports = ScriptCheck.Exports(File.ReadAllText(target));
foreach (var name in names)
{
checkedNames++;
if (!exports.Contains(name))
{
problems.Add($"{where}: «{from}» non esporta «{name}»");
}
}
}
}
Assert.IsGreaterThan(50, checkedNames);
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
}
[TestMethod]
[DataRow("export function box(saved, page) {\n if (!saved) return null;\n let saved = null;\n}", "«saved» dichiarato di nuovo con let (già parametro", DisplayName = "parametro ridichiarato (connection.js, b29b35a)")]
[DataRow("const show = (value) => { const value = 1; };", "«value» dichiarato di nuovo", DisplayName = "parametro di una freccia")]
[DataRow("items.map(x => { let x = 2; return x; });", "«x» dichiarato di nuovo", DisplayName = "parametro senza parentesi")]
[DataRow("function f() { let a = 1; if (a) { let b; } const a = 2; }", "«a» dichiarato di nuovo con const", DisplayName = "due volte nello stesso blocco")]
[DataRow("import { h } from './dom.js';\nconst h = 1;", "«h» dichiarato di nuovo con const (già import", DisplayName = "nome già importato")]
[DataRow("class A { m(p) { class p {} } }", "«p» dichiarato di nuovo con class", DisplayName = "classe con il nome di un parametro")]
[DataRow("function f() { if (x) { return 1; }", "mai chiusa", DisplayName = "parentesi graffa mai chiusa")]
[DataRow("const a = [1, 2);", "chiude «[»", DisplayName = "parentesi che non corrispondono")]
[DataRow("const s = 'non chiusa;\n", "stringa non chiusa", DisplayName = "stringa non chiusa")]
[DataRow("const s = `a ${b} c;\n", "modello fra apici inversi non chiuso", DisplayName = "modello non chiuso")]
public void TheCheckFindsTheMistakesThatStopAModuleLoading(string source, string expected)
{
var problems = ScriptCheck.Problems(source);
Assert.IsTrue(problems.Any(p => p.Contains(expected, StringComparison.Ordinal)), string.Join(" | ", problems.DefaultIfEmpty("(nessuno)")));
}
[TestMethod]
[DataRow("export function box(saved, page) {\n let stored = null;\n const show = (value) => { stored = value; };\n}", DisplayName = "la correzione di connection.js")]
[DataRow("for (let i = 0; i < 3; i++) { let i2 = i; }\nfor (let i = 0; i < 3; i++) { const j = i; }", DisplayName = "variabili dei cicli")]
[DataRow("const re = /a{2}[/}]\\//g; const half = 4 / 2; const t = `x ${ { a: 1 }.a } ${`y ${1}`}`;", DisplayName = "espressioni regolari, divisioni e modelli annidati")]
[DataRow("function f(a) { { let a = 1; } if (a) { const a = 2; } }", DisplayName = "lo stesso nome in un blocco interno")]
[DataRow("const o = { let: 1, const: 2 }; o.let = o.const;", DisplayName = "proprietà con nomi di parole chiave")]
[DataRow("try { x(); } catch (error) { console.log(error); }\nconst error = 1;", DisplayName = "parametro di catch e nome fuori")]
[DataRow("// a comment with ' and ` and {\n/* and } */ const a = \"}\";", DisplayName = "commenti e stringhe con parentesi")]
public void TheCheckLeavesValidCodeAlone(string source)
{
var problems = ScriptCheck.Problems(source);
Assert.IsEmpty(problems, string.Join(" | ", problems));
}
[TestMethod]
public void ImportsAndExportsAreReadByTheirNames()
{
var exports = ScriptCheck.Exports("export function a() {}\nexport async function b() {}\nexport const c = 1;\nexport class D {}\nconst e = 1, f = 2;\nexport { e, f as g };\nexport default a;");
CollectionAssert.AreEquivalent(new[] { "a", "b", "c", "D", "e", "g", "default" }, exports.ToArray());
var imports = ScriptCheck.Imports("import { a, b as c } from './x.js';\nimport * as y from './y.js';\nconst z = await import('./z.js');");
Assert.HasCount(2, imports);
Assert.AreEqual("./x.js", imports[0].From);
CollectionAssert.AreEqual(new[] { "a", "b" }, imports[0].Names);
Assert.IsEmpty(imports[1].Names);
}
}
+610
View File
@@ -0,0 +1,610 @@
using System.Text;
namespace Febe.Tests.Web.Support;
/// <summary>
/// A small check of the interface's ES modules that runs without a browser (the Chromium tests run only in the CI): it
/// reads the tokens of a module — comments, strings, template literals, regular expressions — and finds the mistakes
/// that stop a whole module from loading, so that every page importing it breaks: brackets that do not match, a
/// <c>let</c>, <c>const</c> or <c>class</c> declared twice in one block or with the name of a parameter of its function,
/// or of an import, and a static import of a name the other module does not export. Not a JavaScript parser: what it
/// does not understand (destructured bindings, <c>var</c>) it leaves alone rather than guess.
/// </summary>
internal static class ScriptCheck
{
private static readonly HashSet<string> RegexAfterWords = new(StringComparer.Ordinal)
{
"return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await",
};
private static readonly HashSet<string> NotFunctionBefore = new(StringComparer.Ordinal)
{
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
};
private static readonly HashSet<string> Reserved = new(StringComparer.Ordinal)
{
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
"function", "class", "const", "let", "var", "this", "super", "null", "true", "false", "else", "do", "try", "catch",
"finally", "throw", "case", "default", "break", "continue", "import", "export", "async", "instanceof",
};
internal enum Kind
{
Word,
Punct,
Text,
Number,
Regex,
}
internal readonly record struct Token(Kind Kind, string Value, int Line);
/// <summary>The problems found in the source of one module, each with its line; empty when it reads cleanly.</summary>
public static List<string> Problems(string source)
{
var problems = new List<string>();
List<Token> tokens;
try
{
tokens = Tokens(source);
}
catch (FormatException ex)
{
problems.Add(ex.Message);
return problems;
}
CheckScopes(tokens, problems);
return problems;
}
/// <summary>The names a module exports (<c>export function</c>, <c>const</c>, <c>let</c>, <c>class</c>, <c>{ a as b }</c>, default).</summary>
public static HashSet<string> Exports(string source)
{
var names = new HashSet<string>(StringComparer.Ordinal);
var tokens = Tokens(source);
for (var i = 0; i < tokens.Count - 1; i++)
{
if (!IsWord(tokens[i], "export"))
{
continue;
}
var j = i + 1;
if (IsWord(tokens[j], "default"))
{
names.Add("default");
continue;
}
if (IsWord(tokens[j], "async"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Word && tokens[j].Value is "function" or "const" or "let" or "var" or "class")
{
j++;
if (j < tokens.Count && IsPunct(tokens[j], "*"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Word)
{
names.Add(tokens[j].Value);
}
}
else if (j < tokens.Count && IsPunct(tokens[j], "{"))
{
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
{
if (tokens[j].Kind == Kind.Word && (j + 1 >= tokens.Count || IsPunct(tokens[j + 1], ",") || IsPunct(tokens[j + 1], "}")))
{
names.Add(tokens[j].Value);
}
}
}
}
return names;
}
/// <summary>The static imports of a module: the module named and the names taken from it (not «* as» nor default).</summary>
public static List<(string From, List<string> Names, int Line)> Imports(string source)
{
var imports = new List<(string, List<string>, int)>();
var tokens = Tokens(source);
for (var i = 0; i < tokens.Count - 1; i++)
{
if (!IsWord(tokens[i], "import") || IsPunct(tokens[i + 1], "(") || IsPunct(tokens[i + 1], "."))
{
continue;
}
var names = new List<string>();
var j = i + 1;
for (; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
{
if (IsPunct(tokens[j], "{"))
{
for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++)
{
if (tokens[j].Kind == Kind.Word && !IsWord(tokens[j], "as") && (j == 0 || !IsWord(tokens[j - 1], "as")))
{
names.Add(tokens[j].Value);
}
}
}
}
if (j < tokens.Count && IsWord(tokens[j], "from"))
{
j++;
}
if (j < tokens.Count && tokens[j].Kind == Kind.Text)
{
imports.Add((tokens[j].Value, names, tokens[i].Line));
}
}
return imports;
}
private static bool IsWord(Token token, string value) => token.Kind == Kind.Word && token.Value == value;
private static bool IsPunct(Token token, string value) => token.Kind == Kind.Punct && token.Value == value;
/// <summary>The tokens of the source; throws <see cref="FormatException"/> for an unfinished string, comment or regex.</summary>
internal static List<Token> Tokens(string s)
{
var tokens = new List<Token>();
// Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal.
var braces = new Stack<char>();
var line = 1;
var i = 0;
var inTemplate = false;
bool RegexMayStart()
{
if (tokens.Count == 0)
{
return true;
}
var last = tokens[^1];
return last.Kind switch
{
Kind.Punct => last.Value is not (")" or "]" or "}"),
Kind.Word => RegexAfterWords.Contains(last.Value),
_ => false,
};
}
void ScanTemplate()
{
// From just after a backtick or the «}» of an expression, up to the closing backtick or the next «${».
var start = line;
var text = new StringBuilder();
while (true)
{
if (i >= s.Length)
{
throw new FormatException($"riga {start}: modello fra apici inversi non chiuso");
}
var c = s[i];
if (c == '\\')
{
i += 2;
continue;
}
if (c == '\n')
{
line++;
}
if (c == '`')
{
i++;
inTemplate = false;
tokens.Add(new Token(Kind.Text, text.ToString(), start));
return;
}
if (c == '$' && i + 1 < s.Length && s[i + 1] == '{')
{
i += 2;
braces.Push('E');
inTemplate = false;
tokens.Add(new Token(Kind.Text, text.ToString(), start));
tokens.Add(new Token(Kind.Punct, "${", line));
return;
}
text.Append(c);
i++;
}
}
while (i < s.Length || inTemplate)
{
if (inTemplate)
{
ScanTemplate();
continue;
}
var c = s[i];
if (c == '\n')
{
line++;
i++;
continue;
}
if (char.IsWhiteSpace(c))
{
i++;
continue;
}
if (c == '/' && i + 1 < s.Length && s[i + 1] == '/')
{
while (i < s.Length && s[i] != '\n')
{
i++;
}
continue;
}
if (c == '/' && i + 1 < s.Length && s[i + 1] == '*')
{
var end = s.IndexOf("*/", i + 2, StringComparison.Ordinal);
if (end < 0)
{
throw new FormatException($"riga {line}: commento non chiuso");
}
line += s.AsSpan(i, end - i).Count('\n');
i = end + 2;
continue;
}
if (c is '\'' or '"')
{
i++;
var text = new StringBuilder();
while (true)
{
if (i >= s.Length || s[i] == '\n')
{
throw new FormatException($"riga {line}: stringa non chiusa");
}
if (s[i] == '\\')
{
text.Append(s[i + 1]);
i += 2;
continue;
}
if (s[i] == c)
{
i++;
break;
}
text.Append(s[i++]);
}
tokens.Add(new Token(Kind.Text, text.ToString(), line));
continue;
}
if (c == '`')
{
i++;
inTemplate = true;
continue;
}
if (c == '/' && RegexMayStart())
{
var start = i++;
var inClass = false;
while (true)
{
if (i >= s.Length || s[i] == '\n')
{
throw new FormatException($"riga {line}: espressione regolare non chiusa");
}
if (s[i] == '\\')
{
i += 2;
continue;
}
if (s[i] == '[')
{
inClass = true;
}
else if (s[i] == ']')
{
inClass = false;
}
else if (s[i] == '/' && !inClass)
{
i++;
break;
}
i++;
}
while (i < s.Length && char.IsAsciiLetter(s[i]))
{
i++;
}
tokens.Add(new Token(Kind.Regex, s[start..i], line));
continue;
}
if (char.IsLetter(c) || c is '_' or '$' or '#')
{
var start = i++;
while (i < s.Length && (char.IsLetterOrDigit(s[i]) || s[i] is '_' or '$'))
{
i++;
}
tokens.Add(new Token(Kind.Word, s[start..i], line));
continue;
}
if (char.IsAsciiDigit(c) || (c == '.' && i + 1 < s.Length && char.IsAsciiDigit(s[i + 1])))
{
var start = i++;
while (i < s.Length && (char.IsAsciiLetterOrDigit(s[i]) || s[i] is '.' or '_'))
{
i++;
}
tokens.Add(new Token(Kind.Number, s[start..i], line));
continue;
}
if (c == '{')
{
braces.Push('{');
}
else if (c == '}')
{
if (braces.Count > 0 && braces.Peek() == 'E')
{
braces.Pop();
i++;
tokens.Add(new Token(Kind.Punct, "}$", line));
inTemplate = true;
continue;
}
if (braces.Count > 0)
{
braces.Pop();
}
}
// The punctuators that matter here; any other is one character.
string[] longest = ["...", "=>", "?.", "??", "===", "!==", "==", "!=", "&&", "||", "**", "<=", ">=", "++", "--"];
var punct = longest.FirstOrDefault(p => string.CompareOrdinal(s, i, p, 0, p.Length) == 0) ?? c.ToString();
tokens.Add(new Token(Kind.Punct, punct, line));
i += punct.Length;
}
return tokens;
}
private sealed class Frame(char open, int line, int start)
{
public char Open { get; } = open;
public int Line { get; } = line;
/// <summary>Index of the opening token.</summary>
public int Start { get; } = start;
/// <summary>Names declared in this block with let, const or class, or as parameters (for a function body).</summary>
public Dictionary<string, string> Names { get; } = new(StringComparer.Ordinal);
}
private static void CheckScopes(List<Token> tokens, List<string> problems)
{
var frames = new Stack<Frame>();
frames.Push(new Frame('m', 1, -1));
List<string>? pendingParams = null;
var pendingAt = -1;
void Declare(string name, string how, int line)
{
var scope = frames.Peek();
if (scope.Names.TryGetValue(name, out var before))
{
problems.Add($"riga {line}: «{name}» dichiarato di nuovo con {how} (già {before} nello stesso blocco)");
return;
}
scope.Names[name] = how;
}
for (var i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var prev = i > 0 ? tokens[i - 1] : default;
if (token.Kind == Kind.Punct)
{
switch (token.Value)
{
case "{":
{
var frame = new Frame('{', token.Line, i);
if (pendingParams is not null && pendingAt == i)
{
foreach (var name in pendingParams)
{
frame.Names.TryAdd(name, "parametro");
}
}
frames.Push(frame);
pendingParams = null;
continue;
}
case "(" or "[" or "${":
frames.Push(new Frame(token.Value[0], token.Line, i));
continue;
case "}" or ")" or "]" or "}$":
{
var open = token.Value switch { "}" => '{', ")" => '(', "]" => '[', _ => '$' };
if (frames.Count <= 1 || frames.Peek().Open != open)
{
var top = frames.Peek();
problems.Add(top.Open == 'm'
? $"riga {token.Line}: «{token.Value[0]}» senza apertura"
: $"riga {token.Line}: «{token.Value[0]}» chiude «{top.Open}» aperta alla riga {top.Line}");
return;
}
var closed = frames.Pop();
if (open == '(')
{
OnParenClosed(tokens, closed.Start, i, ref pendingParams, ref pendingAt);
}
continue;
}
case "=>":
if (prev.Kind == Kind.Word && !Reserved.Contains(prev.Value))
{
pendingParams = [prev.Value];
pendingAt = i + 1;
}
else if (pendingParams is not null && pendingAt == i)
{
pendingAt = i + 1; // «(a, b) => {»
}
continue;
}
continue;
}
if (token.Kind != Kind.Word || i + 1 >= tokens.Count || (prev.Kind == Kind.Punct && prev.Value is "." or "?."))
{
continue;
}
var next = tokens[i + 1];
if (token.Value is "let" or "const" && next.Kind == Kind.Word && !Reserved.Contains(next.Value))
{
Declare(next.Value, token.Value, next.Line);
}
else if (token.Value == "class" && next.Kind == Kind.Word && !Reserved.Contains(next.Value) && StatementStart(tokens, i))
{
Declare(next.Value, "class", next.Line);
}
else if (token.Value == "import" && frames.Count == 1 && !IsPunct(next, "(") && !IsPunct(next, "."))
{
for (var j = i + 1; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++)
{
var t = tokens[j];
var after = j + 1 < tokens.Count ? tokens[j + 1] : default;
if (t.Kind == Kind.Word && !IsWord(t, "as") && !IsWord(after, "as") && !Reserved.Contains(t.Value))
{
Declare(t.Value, "import", t.Line);
}
}
}
}
if (frames.Count > 1)
{
var open = frames.Peek();
problems.Add($"riga {open.Line}: «{open.Open}» mai chiusa");
}
}
/// <summary>A «)» just closed: when a function body follows, the simple names of its parameters are kept for it.</summary>
private static void OnParenClosed(List<Token> tokens, int open, int close, ref List<string>? pending, ref int pendingAt)
{
var next = close + 1 < tokens.Count ? tokens[close + 1] : default;
var before = open > 0 ? tokens[open - 1] : default;
var arrow = IsPunct(next, "=>");
var body = IsPunct(next, "{") && before.Kind == Kind.Word && (!NotFunctionBefore.Contains(before.Value) || before.Value == "function");
if (!arrow && !body)
{
return;
}
var names = new List<string>();
var depth = 0;
var pieceStart = true;
for (var j = open + 1; j < close; j++)
{
var t = tokens[j];
if (t.Kind == Kind.Punct && t.Value is "(" or "[" or "{" or "${")
{
depth++;
}
else if (t.Kind == Kind.Punct && t.Value is ")" or "]" or "}" or "}$")
{
depth--;
}
if (depth == 0 && IsPunct(t, ","))
{
pieceStart = true;
continue;
}
if (pieceStart && depth == 0)
{
pieceStart = false;
var name = IsPunct(t, "...") && j + 1 < close ? tokens[j + 1] : t;
if (name.Kind == Kind.Word && !Reserved.Contains(name.Value))
{
names.Add(name.Value);
}
}
else if (pieceStart)
{
pieceStart = false; // a destructured parameter: left alone
}
}
pending = names;
pendingAt = close + 1;
}
/// <summary>True when the word at <paramref name="i"/> starts a statement (a declaration, not an expression).</summary>
private static bool StatementStart(List<Token> tokens, int i)
{
if (i == 0)
{
return true;
}
var prev = tokens[i - 1];
return (prev.Kind == Kind.Punct && prev.Value is ";" or "{" or "}") || IsWord(prev, "export") || IsWord(prev, "default");
}
}
+11 -1
View File
@@ -53,6 +53,15 @@ public sealed partial class TestSite
/// <summary>The nonce of the page load (session:entry_nonce, header <c>x-fb-entry-nonce</c>; AvvioProva.nonce).</summary>
public const string EntryNonce = "nonce-di-prova";
/// <summary>The revision of the page load (session:spin_r, field <c>__spin_r</c>; GiroProva.revisione, a number in the page).</summary>
public const string SpinRevision = "1001";
/// <summary>The branch of the page load (session:spin_b, field <c>__spin_b</c>; GiroProva.ramo).</summary>
public const string SpinBranch = "ramo-di-prova";
/// <summary>The time of the page load (session:spin_t, field <c>__spin_t</c>; GiroProva.tempo, a number in the page).</summary>
public const string SpinTime = "1700000000";
/// <summary>A cookie of the pages limited to the addresses under <see cref="ApiPath"/> (Path=/api/): the copy keeps it with its path.</summary>
public const string ApiPathCookie = "percorso_api";
@@ -258,7 +267,8 @@ public sealed partial class TestSite
// The values of the page the saved session copies (S4): a missing or different one gets the same generic 400.
if (form["__rev"].ToString() != Revision || form["__hs"].ToString() != HasteSession || form["__hsi"].ToString() != HasteSessionId
|| form["__ccg"].ToString() != ConnectionClass || form["dpr"].ToString() != Dpr || form["__comet_req"].ToString() != CometReq
|| request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce)
|| request.Headers["x-fb-entry-nonce"].ToString() != EntryNonce
|| form["__spin_r"].ToString() != SpinRevision || form["__spin_b"].ToString() != SpinBranch || form["__spin_t"].ToString() != SpinTime)
{
return ("campi", null);
}
+6
View File
@@ -83,6 +83,12 @@ public sealed partial class TestSite
});
yield return ("ConnessioneProva", new JsonObject { ["classe"] = ConnectionClass });
yield return ("AvvioProva", new JsonObject { ["nonce"] = EntryNonce });
yield return ("GiroProva", new JsonObject
{
["revisione"] = int.Parse(SpinRevision, CultureInfo.InvariantCulture),
["ramo"] = SpinBranch,
["tempo"] = int.Parse(SpinTime, CultureInfo.InvariantCulture),
});
foreach (var (operation, docId) in DocIds.OrderBy(d => d.Key, StringComparer.Ordinal))
{
yield return (operation + DocIdModuleSuffix, JsonValue.Create(docId));