Compare commits

88 Commits
Author SHA1 Message Date
Alby96 b74d2db793 Merge pull request 'CI: la pulizia toglie tutto ciò che non serve più (immagini inutilizzate, cache, resti di act_runner, vecchie :sha-), con «Solo prova»' (#9) from ci/pulizia-immagini-inutilizzate into main
verifica / controlli (push) Successful in 16s
verifica / prove (push) Successful in 17m21s
verifica / installatore (push) Successful in 5m6s
verifica / immagine (push) Successful in 20m24s
2026-10-21 14:25:03 +02:00
Alby96andClaude Opus 5.5 7d5c6505bd Novità della 0.1.2 (in preparazione): le righe di questo ramo
verifica / controlli (push) Successful in 19s
verifica / prove (push) Successful in 15m53s
verifica / installatore (push) Successful in 5m6s
verifica / immagine (push) Successful in 20m8s
La sezione 0.1.2 del CHANGELOG, sotto «Sviluppo e qualità», con ciò che questo ramo cambia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:16:29 +02:00
Alby96andClaude Opus 5.5 c5361ba8fe Documenti: tre precisazioni sulla pulizia in docs/processo.md
Il modulo delle regole di pulizia di Gitea non ha un'etichetta «nessun
limite» per lo zero: si dice «dopo lo zero». Lo store classico non è per
forza overlay2 (su Unraid docker.img è spesso btrfs): si dice solo che
è il più probabile. Un a capo rimasto a metà del paragrafo sulla prova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 12:07:18 +02:00
Alby96andClaude Opus 5.5 68100b0295 Pulizia: dice quali nomi image prune -a toglie alle immagini in uso
Docker non toglie un'immagine che un contenitore usa, ma con -a le toglie
i nomi in più: con lo store classico tutti tranne l'ultimo in ordine
alfabetico, anche quello da cui il contenitore è stato creato
(un'applicazione di Unraid creata da app:1.2 che si chiama anche
app:latest resta senza app:1.2); con containerd tutti tranne quelli dei
contenitori. La prova saltava ogni immagine in uso e i documenti la
davano per intoccata (rilievo della revisione, controllato sul codice di
moby v24, v27 e master).

La pulizia vera confronta i nomi prima e dopo la potatura e scrive, nome
per nome, quelli tolti a un'immagine che resta; la prova li stima secondo
lo store e li conta, e le prove controllano che stima e pulizia vera
coincidano con l'uno e con l'altro store. Il comando resta quello
chiesto, docker image prune -a -f --filter until=24h; docs/processo.md e
docs/docker.md dicono che cosa succede ai nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:56:41 +02:00
Alby96andClaude Opus 5.5 e24ebd24f0 Pulizia: dice quale store delle immagini usa il demone, da cui dipendono le 24 ore
I documenti dicevano che le 24 ore di «image prune --filter until»
contano sempre dalla costruzione dell'immagine. Vale solo con lo store
classico; con quello di containerd, predefinito nelle installazioni
nuove di Docker Engine dalla 29, Docker confronta il momento in cui il
nome è arrivato sul demone, che un nuovo pull dello stesso nome non
cambia. La prova invece calcola l'età dalla costruzione, quindi con
containerd prova e pulizia vera possono non coincidere, nei due sensi
(rilievo della revisione, controllato sul codice di moby).

Nei modi «settimanale» e «completa» la pulizia legge lo store con
docker info e lo scrive all'inizio; con containerd, o se docker info non
risponde, la prova avverte che le età che elenca sono solo indicative.
docs/processo.md dice come vanno le cose con l'uno e con l'altro, anche
per le immagini costruite con una data fissa. Il demone finto delle
prove sa rispondere come l'uno e come l'altro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:45:43 +02:00
Alby96andClaude Opus 5.5 483d57b89a Pulizia: dopo ogni esecuzione la cache se ne va solo se nessuno la usa da 24 ore
Alla fine di ogni lavoro «immagine», cioè a ogni push di ogni ramo,
«docker builder prune -f» senza filtro toglieva dal builder del demone
tutta la cache che nessuna immagine condivide, di qualunque età e di
tutti i progetti: gli strati intermedi e le cache montate che Encelado o
Mimante avevano usato mezz'ora prima. Alla cache di Febe non serviva
(stava nel builder dell'esecuzione, già tolto) e annullava la finestra
di 24 ore della pulizia del lunedì (rilievo della revisione).

Ora anche dopo ogni esecuzione «--filter until=24h», che BuildKit
confronta con l'ultimo uso: una costruzione che si ripete almeno una
volta al giorno ritrova la sua cache. Il compito chiedeva il comando
senza filtro; la scelta resta di Alberto, e per tornarci basta togliere
il filtro. Le immagini senza nome restano senza filtro, come prima.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:42:28 +02:00
Alby96andClaude Opus 5.5 086b603801 Immagine: un manifest semplice, così togliere una :sha- libera gli strati
Con il builder docker-container buildx aggiunge da sé l'attestazione di
provenienza, e l'immagine spinta sul registro è un indice. Gitea tiene
ogni manifest figlio come una versione a sé, sha256:… senza etichetta,
con la configurazione e gli strati: la pulizia del lunedì toglieva solo
l'indice delle :sha- vecchie e gli strati restavano per sempre, mentre i
documenti dicevano che il registro si alleggeriva (rilievo della
revisione, controllato sul codice di Gitea release/v28).

costruisci-immagine.sh costruisce con --provenance=false --sbom=false,
sia l'archivio provato sia l'immagine spinta: ogni etichetta è un
manifest semplice che tiene i suoi strati, e quando nessuna versione li
usa più li cancella la pulizia notturna dei pacchetti di Gitea. Le
versioni sha256:… lo script non le tocca mai, perché l'API non dice se
un indice le rimanda, ma ne scrive il numero, anche nella prova
(versioni-registro.js senza-etichetta); docs/processo.md dice quale
regola di pulizia di Gitea le toglie se compaiono. La CI non ha ancora
pubblicato nulla, perché manca REGISTRY_TOKEN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:38:53 +02:00
Alby96andClaude Opus 5.5 46d780c826 Pulizia: una prova scritta male non diventa mai la pulizia vera
Lo script riconosceva solo --prova esatto e ignorava ogni altro
argomento: a mano «completa --dry-run», «-n» o «prova» facevano partire
la pulizia completa vera sul demone condiviso, con codice 0. Ora ogni
argomento si controlla prima di chiamare Docker: un'opzione diversa da
--prova o un argomento in più fermano tutto con codice 2 e l'uso.

Allo stesso modo il passo di pulizia.yml accettava come prova solo il
testo «true» e trattava ogni altro valore come pulizia vera; un avvio con
l'API passa il valore così com'è («True», «1»). Ora «true» è la prova,
«false» o niente la pulizia vera, qualunque altro valore un errore senza
toccare nulla (il valore nel messaggio è ripulito, così non può
aggiungere un comando del flusso).

Le prove fanno girare il blocco del passo vero con uno script finto per
nove valori, e lo script con dieci argomenti sbagliati: codice 2 e
nessuna chiamata a Docker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:34:11 +02:00
Alby96andClaude Opus 5.5 5988c503f7 Pulizia: versioni-registro.js con codice e commenti in inglese
Lo script è nuovo e la regola del repository vuole codice e commenti in
inglese (CLAUDE.md, «Convenzioni»); i messaggi restano in italiano, come
tutti quelli della CI. Nessun cambio di comportamento: sulle pagine di
tests/Febe.Tests/Packaging/versioni-registro.json la scelta è identica
byte per byte, tenendone 0, 10 e 20, e gli errori escono ancora con 2.
Gli script di shell di .gitea, già in italiano prima di questo ramo,
restano come sono.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 11:29:38 +02:00
Alby96andClaude Opus 5.5 65988f2863 Documenti: che cosa toglie la pulizia, quando, a che prezzo, e la prova
docs/processo.md («Pulizia») dice che cosa se ne va alla fine di ogni
esecuzione e il lunedì, che cosa non se ne va mai, che cosa costa (le
immagini di base da riscaricare, la cache di costruzione da rifare, le
immagini tenute senza contenitore) e come si lancia la prova che non
toglie nulla, da fare prima della prima pulizia vera; le :sha- del
registro non si accumulano più. Lo stesso, in breve, in docs/docker.md,
nella guida (Sviluppo, «CI e rilascio») e in CLAUDE.md. In
docs/decisioni.md le scelte del 21 ottobre: la regola nuova, che per ciò
che nessuno usa sostituisce il «mai le immagini degli altri progetti» del
20 ottobre, i nomi di act_runner, l'API dei pacchetti di Gitea 28, la
casella «Solo prova», BUILDX_BUILDER=default e il controllo degli script
Node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:37:10 +02:00
Alby96andClaude Opus 5.5 016bbf73eb CI: ogni lavoro «immagine» pota ciò che nessuno usa, il lunedì tutto
Alla fine di ogni lavoro «immagine» di verifica e rilascio, dopo la
pulizia dell'esecuzione, gira pulizia-docker.sh penzolanti: le immagini
senza nome e la cache penzolante del demone se ne vanno subito invece di
aspettare il lunedì, e un errore resta un avviso, così il lavoro non
diventa rosso per la pulizia.

pulizia.yml passa al modo «completa» e, a mano, ha la casella «Solo
prova» (input booleano: Gitea 28 lo mette nell'evento come «true» o
«false»), con cui elenca che cosa toglierebbe e non tocca nulla: da
lanciare prima della prima pulizia vera. Il passo riceve REGISTRY_TOKEN,
l'indirizzo dell'API e il proprietario per le etichette del registro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:37:09 +02:00
Alby96andClaude Opus 5.5 0f11fc5220 CI: la pulizia toglie anche ciò che non serve più a nessuno
Alberto, 21/10: la pulizia della CI deve eliminare tutto quello che non
serve più, non solo ciò che la CI di Febe ha creato. pulizia-docker.sh ha
due modi nuovi. «penzolanti»: le immagini senza nome e la cache di
costruzione che nessuna immagine condivide, di tutti i progetti; un errore
è solo un avviso. «completa»: i resti della CI di Febe come prima, i resti
di act_runner (contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che
nessuno usa), le immagini che nessun contenitore usa e la cache più
vecchie di 24 ore, e con REGISTRY_TOKEN le etichette sha- del registro
oltre le 10 più recenti. Mai system, container, volume o network prune,
mai un contenitore, un volume o una rete che non sia della CI. Con
--prova ogni modo elenca che cosa toglierebbe e non tocca nulla.

Le etichette del registro le sceglie versioni-registro.js, che si prova
con un JSON e senza rete; controlli.sh ne controlla la sintassi. Le prove
girano contro un docker e un curl finti, su un demone come quello del
runner: applicazioni di Unraid ferme, un Febe vero, il lavoro della
pulizia stessa, resti veri e finti di act_runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 10:36:59 +02:00
Alby96 7a70b464f3 Merge pull request 'Rilascio 0.1.1: Febe per Windows si collega' (#7) from rilascio/0.1.1 into main
verifica / prove (push) Successful in 18m54s
verifica / controlli (push) Successful in 21s
rilascio / prove (push) Successful in 14m31s
verifica / installatore (push) Successful in 5m6s
rilascio / windows (push) Successful in 4m53s
verifica / immagine (push) Successful in 19m11s
rilascio / immagine (push) Successful in 19m41s
rilascio / release (push) Successful in 26s
2026-10-21 09:24:38 +02:00
Alby96andClaude Opus 5.5 19920dfd7e Versione 0.1.1: Febe per Windows si collega
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 19m8s
verifica / installatore (push) Successful in 5m7s
verifica / immagine (push) Successful in 24m0s
La 0.1.1 raccoglie le correzioni del 20 ottobre (il browser di Febe per Windows che non diventava mai pronto, lo storico
completato doppio o bloccato, la vista remota durante un cambio di pagina, il benvenuto del primo avvio) e il lavoro su
CI, VS Code e prove. Versione in Directory.Build.props e nel README, sezione 0.1.1 del CHANGELOG non più «in
preparazione», e in docs/stato.md l'esito della prova dal vivo C5.1: accesso a Instagram con l'account di prova riuscito.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:53:28 +02:00
Alby96 eb7db4d2bf Merge pull request 'Libreria e prove: il benvenuto del primo avvio non dipende dai tempi, la prova del pulsante Indietro non passa più per caso' (#6) from correzione/prova-pulsante-indietro into main
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 18m57s
verifica / installatore (push) Successful in 5m42s
verifica / immagine (push) Successful in 23m19s
2026-10-20 21:51:00 +02:00
Alby96andClaude Opus 5.5 b0f71936e0 Novità della 0.1.1: lo stato vuoto della Libreria e le prove stabilizzate
verifica / controlli (push) Successful in 20s
verifica / prove (push) Successful in 17m21s
verifica / installatore (push) Successful in 5m4s
verifica / immagine (push) Successful in 20m2s
Le righe per CHANGELOG.md di questo ramo: il benvenuto del primo avvio che poteva non comparire, e le due prove che la
CI con Chromium vero ha trovato instabili (#3 e #5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:05:00 +02:00
Alby96andClaude Opus 5.5 0a6dd19595 Libreria: nessuno stato vuoto finché non si sa se Febe è collegato
Con la libreria vuota e lo stato del motore ancora sconosciuto, lo stato vuoto sceglieva
«La libreria è ancora vuota». Al primo avvio, con /api/engine più lento di
/api/library/days, quel testo era falso e poi lasciava il posto al benvenuto con un salto
della pagina (rilievo R2 della revisione).

Ora, senza filtri e senza lo stato del motore, la Libreria resta bianca come il mosaico
mentre carica: un riquadro vuoto con aria-busy, che il primo stato del motore sostituisce
con il benvenuto o con «La libreria è ancora vuota». La barra laterale dice già
«Caricamento…» in quell'attesa, e il motore arriva comunque: il flusso lo manda appena si
apre e, senza flusso, l'interfaccia lo richiede a intervalli. Benvenuto e libreria vuota
non cambiano.

La prova TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate, con il motore
trattenuto, ora aspetta quel riquadro e controlla che il conteggio dica 0 e che non ci
siano né stato vuoto né mosaico; sul codice di prima fallisce («timeout: libreria vuota in
attesa del motore»).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 21:00:07 +02:00
Alby96andClaude Opus 5.5 3719adc2d9 Libreria: lo stato vuoto segue il collegamento anche quando il motore risponde dopo
La Libreria vuota sceglieva una volta sola, alla risposta di /api/library/days, fra il
benvenuto del primo avvio (§10.3: Febe non collegato, i due pulsanti) e «La libreria è
ancora vuota», guardando lo stato del motore in quel momento. Se /api/engine (o il primo
evento del flusso) arrivava dopo, lo stato era ancora sconosciuto: il primo avvio mostrava
la libreria vuota e ci restava, anche dopo che il motore aveva detto «non collegato».
Provato con Chrome trattenendo la risposta del motore.

È un difetto a sé, trovato mentre si cercava la causa dell'issue #5, e non è fra le cause
di quel fallimento: nella prova del pulsante Indietro lo stato del motore è già noto
quando la Libreria si ridisegna, e quella prova passa anche senza questa correzione.

Ora lo stato vuoto senza filtri segue il motore finché è sullo schermo: diventa il
benvenuto quando si sa che Febe non è collegato e torna «La libreria è ancora vuota»
quando si collega. Si ridisegna solo quando cambia tipo, così il fuoco su un pulsante del
benvenuto non si perde a ogni evento. Il benvenuto è lo stesso di prima: confrontato con
docs/schermate/primo-avvio.png.

Nuova prova TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate: trattiene
/api/engine fino a un segnale e toglie EventSource; sul codice di prima fallisce.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:50:23 +02:00
Alby96andClaude Opus 5.5 fbb9e602b9 Prove dell'interfaccia: il pulsante Indietro aspetta la Libreria finita, non il suo mosaico vuoto (issue #5)
TheBackButtonAsksBeforeLosingUnsavedChanges, dopo «Lascia le modifiche», aspettava
«main .vuoto-pagina, main .mosaico». Una libreria vuota con Febe non collegato (il server
di prova: motore spento, nessun account proprio) finisce però sul benvenuto del primo
avvio (.benvenuto, §10.3); .mosaico c'è solo nei millisecondi fra la costruzione del
mosaico e la risposta di /api/library/days. La prova passava quando il primo controllo
cadeva in quella finestra (circa 10 ms, misurati con Chrome) e falliva per 30 secondi
quando arrivava un poco dopo, come nella esecuzione 19 della CI. Con il primo controllo
ritardato di 5 ms o più falliva sempre; con la nuova condizione 16 su 16.

Ora aspetta il benvenuto e controlla che il dialogo e la pagina Limiti non ci siano più.
Il prodotto non c'entra: «Lascia le modifiche» torna alla Libreria anche con la pagina lenta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 20:32:37 +02:00
Alby96 1f16d29130 Merge pull request 'Integrazione 0.1.1: Febe per Windows si collega, VS Code, prove su Windows, storico e vista remota' (#4) from integrazione/0.1.1 into main
verifica / controlli (push) Successful in 17s
verifica / prove (push) Failing after 15m9s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
2026-10-20 19:05:33 +02:00
Alby96andClaude Opus 5.5 5fdbf8075a Novità e stato per la 0.1.1: Febe per Windows si collega, CI, VS Code, prove su Windows
verifica / controlli (push) Successful in 20s
verifica / prove (push) Successful in 18m18s
verifica / installatore (push) Successful in 4m35s
verifica / immagine (push) Successful in 18m57s
CHANGELOG.md ha la sezione 0.1.1 «in preparazione» con le correzioni e il lavoro sulla qualità del 20 ottobre;
docs/stato.md dice che cosa è stato provato su Windows, come gira ora la CI, che cosa resta ad Alberto (C5, S2,
REGISTRY_TOKEN, sicurezza dell'istanza) e i rilievi aperti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:07:39 +02:00
Alby96andClaude Opus 5.5 1eed504446 VS Code: attività «prove Windows», ora che il progetto delle prove Windows è in main
Il ramo strumenti/vscode non poteva citare tests/Febe.Tests.Windows, che nasceva su un altro ramo: unita la
correzione di WebView2, l'attività esiste e la guida la elenca.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 18:06:21 +02:00
Alby96 80c1345fbb Integrazione 0.1.1: unione di strumenti/vscode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-10-20 18:05:34 +02:00
Alby96 058c0e8a4d Integrazione 0.1.1: unione di correzione/vista-remota-navigazione
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-10-20 18:05:34 +02:00
Alby96 00c3d8bdf4 Integrazione 0.1.1: unione di correzione/storico-completato-una-volta
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-10-20 18:05:33 +02:00
Alby96 5dc9b4c6ae Integrazione 0.1.1: unione di correzione/prove-su-windows
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-10-20 18:05:33 +02:00
Alby96 309ace91de Integrazione 0.1.1: unione di correzione/webview2-avvio
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/decisioni.md
2026-10-20 18:05:32 +02:00
Alby96 d6df98f766 Merge pull request 'CI aziendale: prove con dati sintetici, installatore e immagine a ogni push, scansioni e pulizia' (#2) from ci/pipeline-aziendale into main
verifica / controlli (push) Successful in 21s
verifica / prove (push) Failing after 15m53s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped
2026-10-20 18:04:49 +02:00
Alby96andClaude Opus 5.5 ef23421d2d Decisioni: come si prova con Chromium vero il ritentativo della vista remota
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:39:22 +02:00
Alby96andClaude Opus 5.5 62941b104d Prova d'insieme: vista remota aperta mentre il browser naviga
Sul server vero, la vista si apre insieme alla navigazione verso una pagina del sito
(come «Accedi a Instagram» dalla pagina Collegamento) o insieme al riposo del motore:
deve aprirsi, tenere un solo permesso e ricevere i fotogrammi. È una guardia di queste
coppie, non del ritentativo: con la navigazione già partita Page.getFrameTree risponde
solo dopo il commit. Il ritentativo lo prova RemoteViewDuringNavigationTests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:39:22 +02:00
Alby96andClaude Opus 5.5 67568ae36f Prova con Chromium vero: la vista remota avviata prima del commit di una pagina
Nessuna prova con un browser vero arrivava al ritentativo di Page.startScreencast:
TwoViews… prova solo il permesso di passaggio e il ritentativo girava solo su
FakeCdpSession. Se Chromium cambiasse testo o codice del rifiuto, la CI resterebbe
verde e Alberto ritroverebbe «Il browser di Febe non risponde».

La pagina /occupata del sito locale delle prove tiene occupato il renderer per 2 s:
la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit»
e il commit, e l'avvio dei fotogrammi ci cade apposta. In ogni giro la vista deve
aprirsi e mostrare un JPEG. Se nessun giro incontra il rifiuto, la prova è
inconcludente: il ritentativo non è stato messo alla prova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 17:39:22 +02:00
Alby96andClaude Opus 5.5 1b2faa4c7a Decisioni: vista remota durante i cambi di pagina (issue #3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:55:01 +02:00
Alby96andClaude Opus 5.5 1b767d517d Prove della vista remota aperta durante un cambio di pagina
Senza browser (RemoteViewStartTests, su FakeCdpSession e VirtualClock):
un primo rifiuto «Not attached to an active page» dà comunque una vista
aperta con i suoi fotogrammi; un rifiuto che non passa finisce in «non
risponde» entro 5 s di orologio; collegamento chiuso o altri rifiuti non
si ritentano; la sostituzione di una vista non lascia mai i permessi a
zero.

Nella prova con Chromium vero (TwoViewsOpenedAtTheSameMoment...) si
controlla anche che durante la sostituzione il browser non resti mai
senza conducente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:55:01 +02:00
Alby96andClaude Opus 5.5 d07b072bf8 Vista remota: nessun istante senza conducente quando una vista sostituisce l'altra
Aprendo una vista mentre un'altra è aperta, il permesso della vecchia si
chiudeva prima che la nuova prendesse il suo: per un attimo nessuno usava
il browser, il motore si svegliava e riportava la pagina a riposo proprio
mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue
#3), e avrebbe potuto perfino cominciare una sessione. Ora OpenAsync tiene
un permesso di passaggio dalla fine della vista vecchia all'avvio della
nuova.

L'ospite della vista usa IFebeBrowser invece di ChromiumBrowser, così si
prova senza browser, e aspetta il browser sull'orologio vero (le prove
d'insieme comprimono quello del motore).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:55:00 +02:00
Alby96andClaude Opus 5.5 724c0752cf Vista remota: l'avvio dei fotogrammi si ritenta mentre la pagina cambia documento
Da ReadyToCommitNavigation al commit di una navigazione con un nuovo
RenderFrameHost (con RenderDocument: ogni navigazione, anche verso la
pagina di riposo) Chromium rifiuta Page.startScreencast con -32000
«Not attached to an active page». La vista aperta in quel momento
(insieme alla pagina di accesso, dopo un riposo del motore, durante una
sessione) finiva in «Il browser di Febe non risponde».

Ora ScreencastSession rimanda l'avvio solo su quella risposta, con pause
da 100 a 500 ms e per al più 5 s sull'orologio vero (IClock, iniettabile
nelle prove); ogni altro errore sale subito com'era. Nessun comando CDP
nuovo. Vale anche per il riavvio dei fotogrammi dopo un riavvio del browser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:54:50 +02:00
Alby96andClaude Opus 5.5 3bcbbbf7c1 Decisioni: corretto il motivo della riga doppia, aggiunte le due scelte nuove
La riga del 20 ottobre diceva che la notifica partiva col testo corto della
ricetta. Era falso: la riga della ricetta (CollectionWriter.EventAsync) va
direttamente nell'archivio, non passa da EngineEvents e AlertService non la vede;
la notifica e il messaggio Telegram avevano già il testo intero del motore. Il
doppione riguardava solo la cronologia e gli «Avvisi» (rilievo F2 della revisione).
Il messaggio del commit afbd0b4 ripete la stessa idea sbagliata: vale questa riga.

Aggiunte due righe: lo storico completato dal controllo del profilo lo chiude il
motore, anche a inizio sessione (F1); quando chiude uno storico il motore toglie
subito dalla coda il suo Storico (F3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:03:08 +02:00
Alby96andClaude Opus 5.5 9ce61d26ce Storico chiuso: la Coda non mostra più uno «Storico» da fare per quell'account
Quando lo storico si chiudeva con una corsa finita per un segnale o
un'interruzione, il compito dello Storico tornava in coda come «Fermata da un
segnale» o «Interrotta». Fino alla sessione dopo (dopo una verifica, fino a
«Riprendi») la Coda mostrava uno Storico da fare per un account già «Aggiornato» o
«In pausa». Lo stesso accadeva con lo storico chiuso dal controllo del profilo, e
per un account rimasto in pausa restavano in coda anche i suoi controlli
(rilievo F3 della revisione).

- La corsa dello Storico arrivata in fondo chiude il suo compito anche se poi si
  è fermata.
- FinishBackfillAsync toglie dalla coda lo Storico dell'account e, se l'account
  resta in pausa, tutto ciò che era pianificato per lui, come farebbe la sessione
  dopo. I comandi di Alberto restano.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:02:23 +02:00
Alby96andClaude Opus 5.5 9d959f910b Storico chiuso dal controllo del profilo: il motore lo chiude subito, con la sua riga
Se un profilo sta tutto nella prima pagina, il controllo del profilo segnava lo
storico come completato ma non cambiava lo stato e non scriveva righe. Dalla
sessione dopo l'account usciva dai candidati dello Storico, quindi nessuno lo
chiudeva più: restava «Storico in corso» per sempre, senza riga e senza avviso.
Con due account in «Storico in corso» succedeva sempre (rilievo F1 della revisione).

- Il controllo del profilo lo dice al motore con BackfillFinished, solo per un
  account «Storico in corso»: chi tiene solo i post nuovi non ha uno storico da
  annunciare.
- Il motore chiude lo storico anche dopo il controllo del profilo, con la stessa
  FinishBackfillAsync, e prosegue con l'account aggiornato.
- La fase dello Storico rilegge gli account invece di usare quelli di inizio
  sessione: altrimenti tornava a scorrere lo storico appena chiuso e scriveva una
  seconda riga.
- A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo
  storico già completato (Febe fermata a metà, o lasciati così dalla 0.1.0).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:00:04 +02:00
Alby96andClaude Opus 5.5 afbd0b4a1a Storico completato: una riga sola, quella del motore
Provando Febe per Windows contro il sito di prova, alla fine dello storico di
marta.prova la sezione «Avvisi» di Attività mostrava due righe per lo stesso
fatto, entrambe «storico-completato»: quella del motore («Storico di
@marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.»)
e una della ricetta Storico («Storico di marta.prova completato.», senza @ e
senza numeri). La notifica di Windows partiva una volta sola, ma con il
testo corto, perché la riga della ricetta arrivava prima.

Resta solo la riga del motore, che è anche quella che cambia lo stato
dell'account e che usano la dimostrazione e la simulazione. La ricetta
segna lo storico come completato e lo dice al motore, senza scrivere altro.
Prova nuova con le ricette vere sul sito finto sotto il motore vero: una
riga negli Avvisi, una notifica e un messaggio Telegram, con il testo
intero. Riga in docs/decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:30:24 +02:00
Alby96andClaude Opus 5.5 f86c794fa4 Il motore chiude lo storico anche se la corsa finisce con un segnale
Quando il cammino dello Storico arriva in fondo, la ricetta segna lo storico
come completato e lo dice al motore (BackfillFinished). Il motore però
chiudeva lo storico (stato «Aggiornato» o «In pausa» e riga «Storico
completato») solo se la corsa finiva «Completata»: un segnale o
un'interruzione arrivati subito dopo l'ultima pagina lasciavano l'account
«Storico in corso» per sempre, senza che nessuno lo riprendesse.

Ora la chiusura sta in un solo punto (FinishBackfillAsync) e scatta ogni
volta che il cammino è arrivato in fondo, comunque sia finita la corsa.
Prova nuova per il segnale e per l'interruzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:23:55 +02:00
Alby96andClaude Opus 5.5 5f968c69d9 Sito di prova: /benvenuto, la «pagina di accesso» che Febe apre, esiste
verifica / controlli (push) Successful in 22s
verifica / prove (push) Successful in 16m43s
verifica / installatore (push) Successful in 5m33s
verifica / immagine (push) Successful in 21m9s
Il Collegamento di Febe, con il sito di prova, apre /benvenuto come pagina di accesso, ma il sito rispondeva
«Pagina non trovata»: la sessione si apriva lo stesso (il cookie arriva con ogni pagina), però chi prova vedeva un
errore. Ora è una pagina di solo testo che dice di tornare a Febe e premere «Ho finito»; nessun modulo, nessuna
password. Una prova senza browser lo controlla, con qualunque seme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:53:52 +02:00
Alby96andClaude Opus 5.5 f09ce4f2d5 Collegamento: senza il nome dell'account il pannello dice «Collegato», non «Collegato come @»
Subito dopo «Ho finito» la sessione c'è ma nessun giro ha ancora letto il nome dell'account: il pannello mostrava
«Collegato come @» con il nome vuoto. Ora dice «Collegato» e sotto «Nome non ancora noto», come il riquadro di stato.
Visto provando a mano Febe per Windows contro il sito di prova; la prova d'interfaccia nuova gira dove c'è Chromium.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:52:07 +02:00
Alby96andClaude Opus 5.5 198e48d4f8 Prove: il commento dell'attesa sul database dice ciò che si è visto, non una causa
Il commento di TestLibrary.DeleteClosedFileAsync dava per certo che il file appena chiuso fosse
tenuto dall'antivirus. È solo una deduzione: su un PC il file restava in uso per pochi
millisecondi, il Restart Manager non elencava alcun processo e Defender era attivo, ma la causa
non è stata dimostrata (la revisione non ha riprodotto il caso). Il commento ora lo dice, così
nessuno smette di cercare né copia l'attesa nel prodotto per una causa mai vista. Il codice non
cambia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:39:18 +02:00
Alby96andClaude Opus 5.5 815bd44a62 Prova di costruisci.sh con Git Bash su Windows, mai col lanciatore di WSL
Dal PATH di PowerShell il primo bash è C:\Windows\System32\bash.exe, il lanciatore di WSL: senza
distribuzione fallisce («execvpe(/bin/bash) failed») e la prova falliva con lui. Su Windows ora si
cerca prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), poi un bash
sul PATH che non stia nella cartella di Windows né fra gli alias di WindowsApps; senza bash la
prova è inconcludente invece di passare in silenzio. Su Linux si usa come prima il primo bash sul
PATH.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:09:27 +02:00
Alby96andClaude Opus 5.5 f7de7f5642 Ricostruzione: la prova aspetta il database tenuto per un attimo su Windows
TestLibrary.LoseDatabaseAsync elimina febe.sqlite appena chiuso. Su Windows un file aperto da un
altro programma non si elimina, e con Defender attivo succedeva circa 3 volte su 40 esecuzioni
delle prove di libreria: il file era libero dopo 6-17 ms e nessun processo risultava tenerlo,
quindi non è un collegamento di Febe rimasto aperto. Su Windows l'eliminazione che trova il file
in uso si ripete ogni 50 ms per al più 5 s; su Linux, dove eliminare un file aperto riesce
sempre, non cambia nulla.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:09:19 +02:00
Alby96andClaude Opus 5.5 e035cfd20a Cartella dei dati in rete: la prova vale anche su Windows
La prova iniettava una tabella dei montaggi di Linux (cifs), che su Windows non esiste: lì il
controllo riconosce la rete dai percorsi UNC e dalle unità di rete, quindi il server partiva
normalmente e la prova falliva. Ora su Windows la cartella dei dati è un percorso UNC verso un
nome .invalid, riconosciuto dalla sola forma senza interrogare la rete; su Linux la prova è
quella di prima. Il prodotto era già giusto: cambia solo la prova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:09:07 +02:00
Alby96andClaude Opus 5.5 d9d8a296b1 Prove dei percorsi uguali su Linux e su Windows
Tre prove scrivevano i percorsi attesi alla Linux («/tmp/febe-profilo», «/importa», la radice
seguita da «/») e fallivano su Windows, dove il prodotto dà giustamente il percorso completo
sull'unità corrente o il percorso scritto con «/». Ora l'atteso si calcola come lo calcola il
sistema: su Linux il testo resta identico a prima, su Windows le prove passano dove gira Febe
per Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:08:58 +02:00
Alby96andClaude Opus 5.5 d9da3b07cb Prove: la struttura del rilascio vuole l'immagine dopo l'installatore
La prova sul flusso del rilascio chiedeva ancora «needs: prove» per il lavoro «immagine»: ora controlla
«needs: [prove, windows]», la regola introdotta nel commit precedente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:19:04 +02:00
Alby96andClaude Opus 5.5 010ba794be Rilascio: l'immagine si pubblica solo dopo l'installatore
Come nella verifica, il lavoro «immagine» del rilascio aspetta anche «windows»: con l'installatore rosso la release
non esce, e allora non devono uscire nemmeno :X.Y.Z e :latest. Sull'unico runner i lavori vanno comunque uno alla
volta, quindi la durata non cambia.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:10:22 +02:00
Alby96andClaude Opus 5.5 2144f755dc CI: l'immagine di main si pubblica solo dopo l'installatore
Il lavoro immagine dipendeva solo da prove: :main e :sha- uscivano anche con l'installatore rosso o non ancora finito,
mentre docs/docker.md dice che :main è l'ultimo commit di main che ha passato la verifica. Ora needs: [prove,
installatore]; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Rilievo
main-senza-installatore della revisione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:04:55 +02:00
Alby96andClaude Opus 5.5 5e7cb73a85 CI: un'esecuzione a mano non annulla più la verifica del push
Il gruppo di concorrenza dipendeva solo dal ref: una verifica lanciata a mano su un ramo (per esempio con un seme, per
rifare un errore) annullava quella del push in corso sullo stesso ramo. In Gitea un lavoro annullato lascia sul commit
lo stato «failure» e workflow_dispatch non scrive stati, quindi la richiesta di unione restava bloccata sui controlli
richiesti. Ora l'evento fa parte del gruppo. Rilievo dispatch-annulla-push della revisione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:04:55 +02:00
Alby96andClaude Opus 5.5 56fd29be80 CI: se la cima di main non si legge, avviso e pubblicazione della sola :sha-
Il passo di pubblicazione gira con bash -e -o pipefail: un errore di git ls-remote chiudeva il passo prima
dell'avviso previsto, e il lavoro immagine di main diventava rosso senza pubblicare nemmeno :sha-. Ora l'assegnazione
ha un ripiego vuoto e si arriva all'avviso, come promettono il commento e docs/decisioni.md. Rilievo ls-remote-set-e
della revisione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:04:42 +02:00
Alby96andClaude Opus 5.5 1bff405384 CI: la pulizia sceglie solo per segni che nessuna immagine porta e non tocca mai un Febe vero
Le etichette febe.ci.* stanno anche nelle immagini pubblicate (:main, :sha-, :X.Y.Z, :latest) e Docker le copia in
ogni contenitore creato da quelle: un Febe vero avviato sullo stesso demone del runner le portava, e la pulizia lo
toglieva con docker rm -f -v insieme ai suoi volumi anonimi. Con un rilascio rilanciato, che ha lo stesso numero di
esecuzione dell'immagine pubblicata, succedeva subito, e l'immagine col nome del registro spariva con docker image rm -f.

Ora le etichette dell'immagine dicono solo da dove viene. I contenitori di prova portano febe.ci.prova=<esecuzione>,
che mette solo prova-immagine.sh con docker run --label e che nessuna immagine porta, e devono chiamarsi
febe-prova-<esecuzione>; nei giri di pulizia (residui, settimanale) si tolgono solo se fermi, uno ancora acceso si
segnala con il comando per toglierlo. Le immagini si tolgono solo per il nome locale febe-ci:<esecuzione>, mai per
identificativo né con -f: un nome del registro sulla stessa immagine resta, un'immagine in uso resta. I builder si
tolgono solo se il contenitore gira l'immagine di buildkit. Le immagini senza nome restano alla pulizia oltre 72 ore.

PipelineTests fa girare la pulizia contro un client Docker finto (tests/Febe.Tests/Packaging/fake-docker.sh) con un
Febe vero acceso e uno fermo che portano le etichette delle loro immagini, e vieta i filtri sulle etichette di
provenienza e la rimozione forzata delle immagini. Rilievo bloccante della revisione (pulizia-contenitori-non-ci).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 12:04:32 +02:00
Alby96andClaude Opus 5.5 d56c24f900 Guida: che cosa fare se a fine debug compare l'elenco delle attività
«ferma il sito di prova» chiude l'attività con workbench.action.tasks.terminate;
se il sito si è già fermato da solo, VS Code non trova l'attività e apre
l'elenco di quelle da terminare, con «Termina tutte». Non c'è un modo di farlo
solo se l'attività è in corso: la guida dice di premere Esc e ricorda che
«Sito di prova + Febe per Windows» non ha il problema.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:55:06 +02:00
Alby96andClaude Opus 5.5 af5383a3ea Guida: il registro di Febe per Windows sta nella cartella dei dati
La guida diceva che i programmi scrivono nella Console di debug, ma Febe per
Windows non ha una console: lì compaiono solo i messaggi del debugger, mentre
«Interfaccia sulla porta N», lo stato del browser e gli errori finiscono in
FebeSviluppo\<checkout>\dati\registro. Chi aspettava quelle righe nella Console
di debug non le avrebbe mai viste.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:54:42 +02:00
Alby96andClaude Opus 5.5 3170fbd8b6 Febe per Windows avviato fuori da launch.json va sul sito di prova
Il pulsante ▷ «Debug project associated with this file» e «Start New Instance»
del C# Dev Kit, consigliato dal ramo, e così dotnet run --project
src/Febe.Desktop, avviavano Febe senza opzioni: Instagram vero, dati e libreria
veri, senza la conferma della configurazione ⚠. Un launchSettings.json di
Febe.Desktop con un solo profilo chiude la strada: sito di prova e dati in
%USERPROFILE%\FebeSviluppo\comune. Provato che dotnet run e il Dev Kit leggono
il profilo ed espandono %USERPROFILE%; le configurazioni coreclr di launch.json
non lo leggono, perché lo cercano nella radice. Instagram vero dal terminale
resta possibile con --no-launch-profile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:54:13 +02:00
Alby96andClaude Opus 5.5 a48899f522 Dati di sviluppo da VS Code in una cartella per checkout
Il blocco contro le istanze doppie di Febe dipende dalla cartella dei dati: con
una sola %USERPROFILE%\FebeSviluppo per tutti i checkout, F5 in un secondo
worktree trovava il Febe del primo, gli chiedeva di mostrarsi e finiva subito,
e un database migrato da un ramo più nuovo non si apriva più da main. Ora dati,
libreria e cartella temporanea della dimostrazione stanno sotto
FebeSviluppo\<nome della cartella aperta> (${workspaceFolderBasename}), e così
il server su Linux.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:46:36 +02:00
Alby96andClaude Opus 5.5 7bcb9f5f5a .vscode in JSON rigido: senza commenti, le spiegazioni nella guida
Il controllo «File JSON» della CI legge ogni *.json tracciato con JSON.parse:
con i commenti // dei quattro file di .vscode il lavoro «controlli» sarebbe
fallito a ogni push dopo l'unione con il ramo della CI, e con lui tutta la
verifica. VS Code legge anche il JSON rigido, quindi i commenti si tolgono e le
spiegazioni passano nella guida («Da VS Code»), nei campi detail delle attività
e in docs/decisioni.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:45:12 +02:00
Alby96andClaude Opus 5.5 f48b6abac4 Prove: l'errore di chi ascolta la ripartenza si prova sulla CI per Linux
La prova che un gestore di Reconnected che lancia non disfa l'Attach di
WebView2CdpSession usa solo un finto WebView2, ma stava in
tests/Febe.Tests.Windows, che la CI non esegue mai (rilievo R4 della
revisione). Ora sta in tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs,
accanto alle altre prove della sessione, e gira a ogni push. Controllata con
il vecchio Reconnected?.Invoke rimesso a mano: rossa; con il codice vero: verde.

La guida di Windows ora dice dove sta quella prova e cita, fra le prove per
Windows, «Esci» mentre l'avvio non si completa.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:29:48 +02:00
Alby96andClaude Opus 5.5 7aaa93fe3b Browser di Febe per Windows: all'uscita l'avvio non resta appeso a WebView2
Il limite di 30 s all'arresto copriva solo un «Scollega» in corso (rilievo R3
della revisione). FebeApp aspetta RunAsync prima di chiudere il browser, e
RunAsync e il ciclo di ripartenza aspettavano WebView2 senza limite: con un
WebView2 che non risponde, «Esci» restava fermo.

Ora WebView2Host.StartAsync onora il suo token. Chi chiama smette subito di
aspettare, un avvio non ancora cominciato non comincia più, uno in corso finisce
da sé e chiude ciò che ha creato se l'arresto è già passato. Il ciclo di
ripartenza usa lo stesso avvio, e WebView2Browser.DisposeAsync lo aspetta al
più 30 s. «Scollega», una volta cominciato, va invece fino in fondo: il profilo
con la sessione deve sparire e il motore deve ripartire.

Nuova prova: con il thread dell'interfaccia occupato, RunAsync torna subito
alla cancellazione e dopo l'uscita non si apre nessuna finestra. Rossa prima
della correzione (ancora in attesa dopo 10 s), verde dopo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:27:22 +02:00
Alby96andClaude Opus 5.5 a144d611ac Browser di Febe per Windows: un solo WebView nella finestra, chiunque lo avvii
Se «Scollega» faceva ripartire il browser mentre il primo avvio aspettava il
tentativo successivo, quel tentativo creava un secondo WebView nella stessa
finestra senza chiudere il primo. Il processo orfano teneva il profilo: il
«Scollega» dopo aspettava 20 s e non riusciva a cancellare la sessione di
Instagram, e l'uscita aspettava 15 s a vuoto (rilievo R2 della revisione,
riprodotto con WebView2 vero).

Ora l'avvio, dentro la sezione esclusiva di WebView2Host, non fa nulla se un
WebView è già collegato, chiude prima i resti di uno morto e, se fallisce,
chiude da sé ciò che ha creato. Il ciclo dei tentativi non chiude più niente
da fuori: poteva chiudere un browser appena fatto ripartire da «Scollega».
La ripartenza dopo un arresto del processo usa lo stesso avvio, e chiudere un
WebView ne cambia la generazione, così i suoi eventi tardivi non contano più.

Nuova prova di regressione: «Scollega» durante i tentativi lascia un solo
controllo nella finestra, il «Scollega» dopo riesce in meno di un secondo e
l'uscita non aspetta. Rossa prima della correzione (due Chrome_WidgetWin_0),
verde dopo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:23:19 +02:00
Alby96andClaude Opus 5.5 1b5a8d4dcd Decisioni sulla configurazione di VS Code
Le scelte fatte per .vscode, ognuna con il suo motivo: debug coreclr senza
launchSettings.json, dati di sviluppo fuori dal repository, registro classico
per il pannello Problemi, sito di prova in sfondo fermato a fine debug, avvio
in catena al posto di un compound, configurazioni legate a un sistema,
conferma per Instagram vero, Console di debug e attività senza shell, cartella
temporanea della dimostrazione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:12 +02:00
Alby96andClaude Opus 5.5 7a54eceaaf Guida: come si lavora con Febe da VS Code
La pagina Sviluppo ha una sezione «Da VS Code»: che cosa fa ogni
configurazione di debug, dove vanno i dati di sviluppo, perché i programmi
scrivono nella Console di debug, come si chiude Febe in debug e che cosa
resta della dimostrazione fermata dal debugger. CLAUDE.md la richiama fra i
comandi, con la cartella dei dati di sviluppo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:12 +02:00
Alby96andClaude Opus 5.5 f324105371 Configurazioni di debug di Febe per VS Code
F5 avvia Febe per Windows contro il sito di prova, che parte prima e si
ferma dopo, con dati e libreria in %USERPROFILE%\FebeSviluppo e mai nella
cartella vera. Ci sono anche il sito di prova nel debugger che avvia Febe
quando è pronto, la dimostrazione con l'interfaccia servita dai sorgenti, il
sito di prova da solo, la simulazione di 30 giorni e il server contro il sito
di prova, che serve Chromium su Xvfb e quindi gira solo su Linux: altrove si
ferma con un messaggio.

Ultima e separata, Febe per Windows con Instagram e i dati veri, per le prove
dal vivo di Alberto: prima di compilare chiede conferma, Esc annulla.

Tutte scrivono nella Console di debug e non nel terminale integrato, che
caricando il profilo di PowerShell trovava un .NET 8 e Febe non partiva.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:11 +02:00
Alby96andClaude Opus 5.5 4a4e85cc7f Attività di VS Code per compilare, provare, avviare il sito di prova e pubblicare
Da VS Code si compila con l'attività predefinita «compila» (dotnet build
Febe.slnx -warnaserror, errori nel pannello Problemi), si prova con «prove» e
«prove con filtro», si avvia il sito di prova in sfondo (pronto alla sua riga
«Sito di prova: http://…») e si pubblica Febe.exe in un file solo come fa
installer/costruisci.sh; l'immagine Docker c'è, segnata come bisognosa di
Docker Desktop.

Tutte le attività sono processi e non shell: il profilo di PowerShell di
questo PC attiva l'ambiente conda di Pinokio, che mette davanti un .NET senza
SDK. Le attività nascoste servono alle configurazioni di debug: compilare e
avviare il sito, fermarlo a fine debug, fermare con un messaggio le
configurazioni lanciate sul sistema sbagliato.

Estensioni consigliate C# Dev Kit e C#; soluzione predefinita Febe.slnx.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:10 +02:00
Alby96andClaude Opus 5.5 5397d31e13 CI: il seme delle prove si controlla prima di preparare l'ambiente
Un seme chiesto a mano e sbagliato fermava il lavoro solo dopo l'installazione
di Chromium e la compilazione; ora il passo dei semi viene subito dopo il
checkout, e i minuti del runner non si sprecano.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:04 +02:00
Alby96andClaude Opus 5.5 02e5cfe79c Un solo blocco per .vscode in .gitignore
Le regole per .vscode comparivano due volte, dal modello di Visual Studio e da
quello di VS Code. Resta il blocco di VS Code, che ora ignora anche i file
*.code-workspace: della cartella .vscode entrano nel repository solo
settings.json, tasks.json, launch.json, extensions.json e gli snippet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:10:02 +02:00
Alby96andClaude Opus 5.5 f243118f36 CI: gitleaks sulla storia del commit verificato e più memoria per Chromium
gitleaks leggeva i commit di tutti i rami scaricati: un rilievo su un ramo
avrebbe fermato anche tutti gli altri. Ora legge ogni commit da cui discende
quello verificato, e ogni ramo si controlla al suo push (main a ogni unione).
Il contenitore delle prove ha 1 GB di memoria condivisa invece dei 64 MB
predefiniti, che il Chromium senza finestra delle prove dell'interfaccia può
esaurire.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 11:08:41 +02:00
Alby96andClaude Opus 5.5 6e95aef5cc Documenti: processo, CI ed etichette dell'immagine
docs/processo.md descrive il percorso di una modifica come in un'azienda: rami,
commit, richieste di unione, controlli richiesti e protezione di main da
configurare su Gitea, che cosa garantisce ciascun lavoro della CI, etichette del
registro (:main, :sha-, :X.Y.Z, :latest), pulizia, rilievi di sicurezza,
rilasci e correzioni urgenti, e che cosa solo la prima esecuzione vera può
provare. CLAUDE.md e la guida per lo sviluppo dicevano che la verifica girava a
ogni push, e non era vero: ora descrivono la CI com'è. docs/docker.md dice quali
etichette ha l'immagine e come risalire all'esecuzione che l'ha costruita.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:57:22 +02:00
Alby96andClaude Opus 5.5 bff054dcf6 Repository: modello delle richieste di unione, segnalazioni e proprietari
Ogni richiesta di unione chiede sintesi, perché, che cosa cambia, comandi e
risultati delle prove (e che cosa non è stato provato), rischi e ritorno
indietro, e la lista delle quattordici regole di §2 della specifica. Due modelli
di segnalazione (difetto, proposta) ricordano che segreti e campioni grezzi non
vanno mai incollati. CODEOWNERS fa di Alberto il revisore di tutto (in Gitea le
regole sono espressioni regolari).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:54:26 +02:00
Alby96andClaude Opus 5.5 7fffa53c90 Prova del collegamento su Windows: Accedi, Ho finito e Scollega con WebView2 vero
Il percorso di Alberto attraverso il servizio di collegamento vero della composizione, sul sito di prova: «Accedi a Instagram» apre la pagina di accesso nella finestra «Browser di Febe», che viene in primo piano mentre il motore resta fermo; «Ho finito» trova la sessione (solo il nome del cookie) e rimette la finestra fuori vista; «Scollega» ferma il motore, chiude WebView2, cancella il profilo con la sessione, fa ripartire il browser vuoto e poi il motore. docs/windows.md elenca la prova nuova.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:53:48 +02:00
Alby96andClaude Opus 5.5 66a3fc7db6 Prove per Windows: la composizione di Febe.exe preparata in un posto solo
Sito di prova, cartelle, thread dell'interfaccia, DesktopPlatform con DesktopShell, orologio veloce e richieste all'interfaccia con il gettone passano dalla prova della sessione di raccolta a DesktopBed, così la prova del collegamento che segue usa la stessa composizione senza copiarla.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:53:48 +02:00
Alby96andClaude Opus 5.5 d1e29aa7a4 CI: verifica di ogni push con controlli, prove vere, installatore e immagine
La verifica girava solo su main e su un ramo che non esiste più, e saltava le
66 prove con browser, ffmpeg e makensis. Ora gira a ogni push su qualunque ramo
(e a mano), in quattro lavori: controlli veloci e gitleaks su tutta la storia;
compilazione di tutta la soluzione e tutte le prove di tests/Febe.Tests in un
contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri, senza prove
saltate, con il seme 13 e di nuovo con il seme dell'esecuzione per le prove del
sito di prova; installatore e zip con la versione -ci.<numero> come artefatti
per 14 giorni; immagine costruita con buildx, provata senza rete, scansionata
con Trivy e, solo dopo un push su main e con il segreto, pubblicata come :main e
:sha-<commit>. Senza il segreto un avviso e il lavoro resta verde; alla fine si
toglie sempre ciò che l'esecuzione ha creato. Niente pull_request, che rifarebbe
tutto sullo stesso commit. Le prove sui flussi tengono ferme queste regole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:52:27 +02:00
Alby96andClaude Opus 5.5 7d8ea22381 Rilascio: immagine provata senza rete e scansionata, pulizia a fine lavoro
Il lavoro «immagine» del rilascio costruisce come la verifica, con gli stessi
script: prima della pubblicazione il contenitore parte senza rete fino al
controllo di salute e Trivy ferma tutto per una CRITICAL con correzione; alla
fine, sempre, toglie immagini, contenitori, cache e builder dell'esecuzione, e
all'inizio i resti di esecuzioni interrotte. Il resto non cambia: prove, Windows,
pubblicazione con il segreto (o la release che dice che manca) e release. Ogni
lavoro ha un tempo massimo. La prova del flusso segue la pubblicazione nello
script comune.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:51:46 +02:00
Alby96andClaude Opus 5.5 f35b0a7301 CI: pulizia settimanale del demone Docker del runner
Ogni lunedì, e a mano, toglie ciò che esecuzioni annullate o scadute non hanno
potuto togliere (contenitori, immagini febe-ci e builder della CI di Febe più
vecchi di 90 minuti), l'immagine febe:ci del vecchio flusso e le immagini senza
nome più vecchie di 72 ore. Il demone è lo stesso degli altri progetti di
Alberto: niente prune generali, niente cache del demone, niente volumi con nome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:51:27 +02:00
Alby96andClaude Opus 5.5 91080a2664 CI: script comuni per strumenti verificati, prove, immagine e pulizia
Gli script di .gitea/scripts servono sia alla verifica sia al rilascio e si
lanciano anche a mano. gitleaks e Trivy si installano a versione fissa e solo se
l'impronta SHA-256 coincide; la scansione dell'immagine ferma il lavoro per una
CRITICAL con correzione e riporta le HIGH; la prova del contenitore gira sempre
senza rete, così l'immagine non può raggiungere nessun sito; la costruzione usa
sempre gli stessi argomenti, perché quella pubblicata esca dalla cache di quella
provata. La pulizia tocca solo ciò che porta i segni della CI di Febe (etichette
febe.ci.*, febe-ci:<esecuzione>, builder febe-ci-<esecuzione>) e le immagini
senza nome più vecchie di tre giorni: il demone è condiviso con gli altri
progetti. Il riepilogo delle prove conta superate, fallite e saltate e fallisce
se una prova si salta dove non dovrebbe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:51:19 +02:00
Alby96andClaude Opus 5.5 e5e2b6864f Prova di S1: il controllo sul comando rifiutato confronta letture fatte subito prima e subito dopo
Il confronto con la posizione letta prima degli altri comandi poteva cogliere la fine di uno scorrimento ancora in corso; ora si misura solo l'effetto del window.scrollBy rifiutato, che avrebbe spostato la pagina di 500 pixel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:46:58 +02:00
Alby96andClaude Opus 5.5 7b0b0339f7 Documenti: stato di Febe per Windows dopo la correzione, prove su Windows e decisioni
docs/windows.md: il riquadro «Stato» dice che cosa non andava nella 0.1.0 (il browser non
diventava mai disponibile), che ora WebView2 parte al primo tentativo su un Windows vero
(Windows 11 Pro, runtime 155.0.4283.62) e che cosa resta da provare a mano; una sezione nuova
sulle prove automatiche su Windows (come lanciarle, che cosa toccano e che cosa no, che cosa
prova ogni classe); come Febe tratta il thread dell'interfaccia e le ripartenze di WebView2; una
riga in «Problemi comuni» con l'errore che Alberto ha visto nel registro.

src/Febe.Desktop/LEGGIMI.md: le regole del thread dell'interfaccia, dei gestori di WebView2 e
dei tentativi d'avvio, scritte in modo che l'errore non si ripeta.

docs/decisioni.md: una riga datata per ogni scelta tecnica di questa correzione.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:45:13 +02:00
Alby96andClaude Opus 5.5 cf618d8986 Una sessione di raccolta vera della composizione condivisa su WebView2
L'equivalente per Windows della prova d'insieme del server su Chromium: FebeApp composto come lo
compone Febe.exe (DesktopPlatform, DesktopShell, la finestra «Browser di Febe» su un thread di
WPF), contro il sito di prova con accesso automatico, un orologio dieci volte più veloce e un
fuso in cui è mezzogiorno. Il browser parte da un thread della composizione (il percorso che
falliva sul PC di Alberto), si aggiungono marta.prova e luca.prova dall'interfaccia con il
gettone di questo avvio, «Controlla ora» su marta.prova, e una sessione del motore agisce sul
sito attraverso WebView2 con i permessi del Governatore: i file arrivano interi nella libreria
temporanea, scaricati dal CDN del sito di prova attraverso il browser. Nel registro nessun
avvio fallito e nessun indirizzo firmato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:30:51 +02:00
Alby96andClaude Opus 5.5 a305a9ed2a Prova di S1 su WebView2 vero contro il sito di prova
Quello che la parte C3 di prove-dal-vivo chiede ad Alberto di guardare a mano, ora è una prova
automatica su Windows: con la finestra «Browser di Febe» fuori vista e i comandi mandati da
thread del pool attraverso la WebView2CdpSession vera e il suo elenco, navigazione, corpi JSON
con Network.getResponseBody, Runtime.evaluate in sola lettura (la pagina si vede «visible»,
navigator.webdriver falso, 1280 punti di larghezza), cookie di sessione per nome, scorrimento
con Input.dispatchMouseEvent, fotogramma con Page.captureScreenshot, un file del CDN con
Network.loadNetworkResource e IO.read, e i comandi vietati rifiutati prima di arrivare a
WebView2. Il sito è quello in processo (TestSite.StartAsync, porte libere): mai Instagram.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:30:33 +02:00
Alby96andClaude Opus 5.5 2ef098226b Finestra di Febe: gli indirizzi esterni si aprono dopo il gestore di WebView2
La finestra dell'interfaccia apriva gli indirizzi esterni (guida, repository, «Apri su
Instagram») nel browser predefinito dentro i gestori NavigationStarting e NewWindowRequested
di WebView2. L'apertura passa dalla shell di Windows, che può far girare un ciclo di messaggi
suo, e WebView2 non regge di essere richiamato dentro i propri gestori (modello dei thread di
WebView2). Ora l'apertura si mette in coda sul thread dell'interfaccia e parte quando il
gestore è tornato.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:30:20 +02:00
Alby96andClaude Opus 5.5 3f222448ee Sessione CDP di WebView2: un errore di chi ascolta la ripartenza non disfa l'avvio
WebView2CdpSession.Attach avvisa chi ascolta Reconnected (cattura delle risposte, vista
remota) dentro l'avvio del nuovo WebView, sul thread dell'interfaccia: un'eccezione di uno di
loro usciva da Attach e trasformava un avvio riuscito in un avvio fallito, da riprovare, con lo
stesso esito ogni volta. Ora ogni gestore è chiamato da solo: il suo errore va nel registro
(tipo e prima riga) e gli altri lo ricevono comunque. L'avviso resta sincrono, come prima.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:30:11 +02:00
Alby96andClaude Opus 5.5 ccfd8b5c08 Browser di Febe per Windows: ripartenze robuste, WebView2 toccato solo dal suo thread
Dopo la correzione dell'avvio, la revisione di tutto il percorso del browser per Windows ha
trovato altri punti della stessa famiglia: lavoro che, se va storto, lascia il browser morto o
riprova per sempre.

- WebView2Host: avvio, ripartenza, chiusura dopo un avvio fallito e arresto passano uno alla
  volta (ognuno aspetta WebView2 sul thread dell'interfaccia e prima potevano intrecciarsi);
  un arresto del processo del browser durante un avvio fa fallire quell'avvio invece di
  lasciare un WebView morto dato per buono; l'arresto del processo si annuncia solo dopo che il
  gestore dell'evento di WebView2 è tornato (WebView2 non regge chiusure e ricreazioni dentro i
  suoi gestori) e solo per il WebView in uso; versione e numero del processo sono valori
  semplici letti sul thread dell'interfaccia; MoveFocus, Bounds, Indietro e Ricarica non fanno
  più cadere eccezioni nell'interfaccia se il processo è appena morto; in primo piano il
  permesso di guida si prende prima di spostare il fuoco.
- WebView2Browser: dopo un arresto del processo e dopo un «Scollega» la cui ripartenza fallisce,
  il browser riparte con gli stessi tentativi del primo avvio (prima: un tentativo solo, poi
  morto fino al riavvio di Febe; e con «Scollega» anche il motore restava fermo, perché
  l'errore non era di cartella); un solo ciclo di ripartenza alla volta, sul pool e mai dentro
  un gestore di WebView2; la cancellazione del profilo non blocca più la finestra.

Prove nuove su WebView2 vero: un avvio che fallisce davvero si riprova una volta sola e poi
va; la finestra viene in primo piano e torna fuori vista con il permesso di guida, anche
chiudendola; «Scollega» cancella profilo e sessione e il browser riparte vuoto; ucciso (per
numero di processo) il browser avviato dalla prova, Febe lo fa ripartire da solo; l'ospitalità
«composizione» di S2 parte e disegna.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:29:59 +02:00
Alby96andClaude Opus 5.5 d642b55b74 Dockerfile: file del restore trovati da soli e aggiornamenti di Debian applicati
L'elenco dei progetti scritto a mano rompeva la costruzione dell'immagine a ogni
progetto nuovo in Febe.slnx (il prossimo è tests/Febe.Tests.Windows): ora uno
stadio «progetti» copia soluzione, props e progetti trovati da soli, e il restore
resta in cache finché non cambiano. Lo stadio finale applica gli aggiornamenti
di sicurezza già pubblicati, che l'immagine di base non ha ancora, così la
scansione dell'immagine non trova correzioni disponibili e non applicate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:24:37 +02:00
Alby96andClaude Opus 5.5 f7237145aa Prove: il seme del mondo sintetico si sceglie con FEBE_SEME_PROVA
Le prove avviano il sito di prova solo da SyntheticSite, che legge il seme da
FEBE_SEME_PROVA e usa 13 quando manca: senza la variabile non cambia nulla.
Le classi che lo avviano stanno nella categoria SitoDiProva, così la CI può
rifarle con un seme diverso a ogni esecuzione senza raddoppiare tutta la suite,
e il seme finisce nell'output della prova per rifare un errore.

Nuove prove senza browser: la forma del mondo su cui contano le prove d'insieme
vale per 300 semi, i lettori leggono pagina dopo pagina ciò che il sito serve con
il seme dell'esecuzione, e nessuna prova avvia il sito per altre vie o resta
fuori dalla categoria.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:22:48 +02:00
Alby96andClaude Opus 5.5 a6623e5736 Correzione: il browser di Febe per Windows parte al primo tentativo
WebView2Host avviava WebView2 correttamente sul thread dell'interfaccia, ma WebView2Browser
aspettava l'avvio con ConfigureAwait(false) e, su un thread del pool, scriveva nel registro
«Browser di Febe pronto: WebView2 {Host.Version}»: Version leggeva BrowserVersionString
dall'ambiente di WebView2 fuori dal thread dell'interfaccia, WebView2 lanciava
InvalidOperationException, il ciclo la prendeva per un avvio fallito, chiudeva il WebView che
funzionava e riprovava per sempre (5, 15, 30, 60, 300 s). La finestra «Browser di Febe» non
diventava mai disponibile e l'accesso a Instagram non poteva nemmeno cominciare.

Ora la versione si legge sul thread dell'interfaccia durante l'avvio e Version restituisce un
valore semplice, leggibile da qualunque thread; e quello che segue un avvio riuscito (stato e
riga del registro) sta fuori dal blocco dei tentativi, così non può più disfarlo: si riprova
solo quando fallisce l'avvio stesso. La prova di regressione del commit precedente ora passa.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:10:41 +02:00
Alby96andClaude Opus 5.5 a25f60970d Prove per Windows con WebView2 vero, e la prova che riproduce l'avvio mancato
Nuovo progetto tests/Febe.Tests.Windows (net10.0-windows, WPF, solo MSTest e riferimenti ai
progetti): un thread STA con un Dispatcher di WPF vero, come il thread dell'interfaccia di
Febe.exe, e il browser di Febe costruito come lo costruisce la composizione e avviato da un
thread del pool, come fa FebeApp. Si compila anche da Linux (EnableWindowsTargeting, come
Febe.Desktop) perché la CI compila tutta la soluzione, ma gira solo su Windows; dove manca il
runtime WebView2 le prove risultano inconcludenti.

La prima prova riproduce il registro di Alberto del 14 e del 19 ottobre: «WebView2 non parte
(InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI
thread.)» a ogni tentativo. Con il codice di questo commit fallisce così; la correzione è nel
commit seguente.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:09:30 +02:00
Alby96 edade61b72 Merge pull request 'Febe 0.1.0 — prima versione completa (M0–M8)' (#1) from febe-v1 into main
verifica / prove (push) Successful in 3m59s
verifica / immagine (push) Successful in 6m46s
Reviewed-on: #1
2026-10-14 09:14:59 +02:00
96 changed files with 8412 additions and 301 deletions

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
# Proprietari del codice: Gitea chiede la loro revisione a ogni richiesta di unione che tocca i file indicati.
# In Gitea le regole sono espressioni regolari di Go, non schemi alla maniera di .gitignore (docs.gitea.com, «Code Owners»).
# Alberto è il proprietario di tutto il repository.
.* @Alby96
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Guida di Febe
url: https://gitea.encke-hake.ts.net/Alby96/Febe/wiki
about: Installazione, primo collegamento, limiti, problemi comuni e sicurezza
+36
View File
@@ -0,0 +1,36 @@
---
name: Difetto
about: Febe fa qualcosa di sbagliato, o non fa ciò che dovrebbe
title: "Difetto: "
---
<!--
Mai in una segnalazione: password, cookie, gettoni (Telegram, registro), codici di verifica, campioni grezzi della
sonda o corpi di risposta di Instagram. Il registro di Febe non li contiene: se ne incolli un pezzo, controlla
comunque prima di inviare.
-->
## Che cosa succede
<!-- Che cosa vedi, con il testo esatto dei messaggi. -->
## Che cosa ti aspettavi
## Come rifarlo
1.
2.
## Dove
- Veste: Docker (Unraid, Compose) / Windows (installato, portabile)
- Versione di Febe (Impostazioni ▸ Informazioni, o etichetta dell'immagine):
- Profilo di prudenza:
- Contro Instagram vero o contro il sito di prova:
## Registro
<!-- Le righe del registro intorno al problema (/dati/registro/febe-AAAA-MM-GG.log o %LOCALAPPDATA%\Febe\registro). -->
```text
```
+23
View File
@@ -0,0 +1,23 @@
---
name: Proposta
about: Una funzione nuova o un cambiamento di comportamento
title: "Proposta: "
---
## Il problema
<!-- Che cosa non riesci a fare oggi, o che cosa ti costa troppo. -->
## La proposta
## Regole di §2 toccate
<!-- Una proposta che chiede di contattare Instagram fuori dal browser, di cambiare il browser, di scavalcare una
verifica, di scrivere su Instagram o di aggiungere una dipendenza va discussa prima di tutto (docs/SPECIFICA.md, §2). -->
- [ ] Nessuna
- [ ] Sì, quali e perché:
## Come capiremo che è fatta
-
+67
View File
@@ -0,0 +1,67 @@
<!--
Una richiesta di unione per ramo, piccola quanto basta per leggerla tutta. Titolo in italiano: che cosa cambia.
Si unisce in main solo con la verifica verde sull'ultimo commit (docs/processo.md). Togli i commenti che non servono.
-->
## Sintesi
<!-- Che cosa fa questa richiesta, in due o tre frasi. -->
## Perché
<!-- Il problema, la richiesta di Alberto o la segnalazione (#numero) da cui nasce. -->
## Che cosa cambia
<!-- Per punti: comportamento, parti toccate, scelte nuove (con la riga in docs/decisioni.md), effetti su Docker o Windows. -->
-
## Come è stato provato
<!-- Comandi e risultati, copiati così come sono usciti. Poi, con la stessa franchezza, che cosa NON è stato provato e perché. -->
```text
dotnet build Febe.slnx -warnaserror
dotnet test tests/Febe.Tests
```
Non provato:
-
## Rischi e ritorno indietro
<!-- Che cosa può andare storto, come ce ne si accorge, come si torna indietro (di solito: annullare il commit di unione con git revert -m 1). Dati, migrazioni, impostazioni o segreti da sistemare a mano. -->
## Controlli prima di unire
Le regole di §2 della specifica (docs/SPECIFICA.md), che valgono sempre:
- [ ] 1. Verso Instagram parla solo il browser di Febe: nessuna connessione verso domini di Instagram o Meta, salvo il CDN alle condizioni di §6.5
- [ ] 2. Il browser si usa così com'è: niente stealth, user agent, impronta, fuso o lingua cambiati, headless, intestazioni riscritte, proxy, più account; comandi CDP solo dall'elenco di §6.1
- [ ] 3. Niente scavalcamenti: CAPTCHA, verifiche e codici non si risolvono in automatico, Febe si ferma e avvisa
- [ ] 4. Un account, una rete, un motore; i cookie non si copiano da una macchina all'altra
- [ ] 5. Sola lettura: niente mi piace, segui, commenti, messaggi, reazioni
- [ ] 6. Solo ciò che l'account di Alberto vede già
- [ ] 7. Ogni azione del motore verso il sito passa dal Governatore (IGovernor)
- [ ] 8. Al primo segnale di §7.6 ci si ferma, senza nuovi tentativi automatici
- [ ] 9. Nessuna prova, script o verifica contatta Instagram (solo tools/Febe.SitoDiProva) e nessuno apre i campioni grezzi della sonda (solo le copie ripulite di tests/campioni)
- [ ] 10. Nessun formato di risposta inventato: i lettori si scrivono su campioni reali ripuliti
- [ ] 11. Mai password, cookie, gettoni, tasti o corpi di risposta nei registri, nei messaggi di errore o nell'output della CI; i campioni grezzi fuori da git
- [ ] 12. La libreria non cancella e non sostituisce file da sola
- [ ] 13. Nessuna dipendenza fuori dall'elenco chiuso di §3 (Directory.Packages.props), se Alberto non l'ha approvata
- [ ] 14. Resoconto onesto: ciò che non è stato verificato è scritto qui sopra
E le convenzioni:
- [ ] La verifica è verde sull'ultimo commit: controlli, prove (nessuna saltata), installatore, immagine
- [ ] Nel motore niente DateTime.Now, Task.Delay o Random diretti (IClock, IRandomSource)
- [ ] Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano
- [ ] Ogni scelta tecnica nuova ha la sua riga in docs/decisioni.md
- [ ] Una schermata cambiata è stata confrontata con il suo mockup (§10.7)
- [ ] Le righe per CHANGELOG.md e docs/stato.md sono scritte qui sotto (le aggiunge chi integra)
### Per CHANGELOG.md e docs/stato.md
-
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché
# nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le
# sue lingue, Xvfb, ffmpeg e ffprobe, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi
# caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody
# (65534) vengono con Debian (prove dell'avvio del contenitore).
#
# .gitea/scripts/ambiente-prove.sh
set -euo pipefail
sudo=""
[[ "$(id -u)" == 0 ]] || sudo="sudo"
export DEBIAN_FRONTEND=noninteractive
$sudo apt-get update -qq
$sudo apt-get install -y -qq --no-install-recommends \
chromium chromium-l10n \
xvfb \
ffmpeg \
nsis zip \
locales tzdata libicu76 ca-certificates \
fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \
util-linux procps > /dev/null
$sudo sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen
$sudo locale-gen > /dev/null
echo "== Strumenti delle prove"
chromium --version
command -v Xvfb
ffmpeg -version | head -n 1 || true
ffprobe -version | head -n 1 || true
echo "makensis $(makensis -VERSION)"
echo "node $(node --version)"
locale -a | grep -i '^it_IT\.utf8$'
for strumento in setpriv getent stat chown sh; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done
getent passwd 65534 > /dev/null && getent group 65534 > /dev/null || { echo "Mancano l'utente o il gruppo 65534 (nobody)." >&2; exit 1; }
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env bash
# Controlli veloci prima di compilare (lavoro «controlli» della CI): pochi secondi, e fermano subito gli errori che
# altrimenti si scoprirebbero dopo mezz'ora di prove. Si lanciano anche a mano, dalla radice del repository:
#
# bash .gitea/scripts/controlli.sh
#
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
# 5. ogni progetto elencato in Febe.slnx esiste;
# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium).
set -uo pipefail
radice="$(git rev-parse --show-toplevel)" || exit 2
cd "$radice" || exit 2
errori=0
errore() {
echo "ERRORE: $*" >&2
errori=$((errori + 1))
}
echo "== Script di shell"
quanti=0
while IFS= read -r -d '' script; do
quanti=$((quanti + 1))
bash -n "$script" || errore "$script: sintassi bash non valida."
if head -n 1 "$script" | grep -Eq '^#!(/usr/bin/env )?/?(bin/)?sh( |$)'; then
sh -n "$script" || errore "$script: sintassi sh non valida."
fi
if grep -q $'\r' "$script"; then
errore "$script ha righe Windows (CR): bash non le regge (.gitattributes chiede eol=lf)."
fi
done < <(git ls-files -z -- '*.sh')
echo " $quanti script controllati"
echo "== Script Node della CI"
if command -v node > /dev/null; then
quanti=0
while IFS= read -r -d '' script; do
quanti=$((quanti + 1))
node --check "$script" || errore "$script: JavaScript non valido."
done < <(git ls-files -z -- '.gitea/scripts/*.js')
echo " $quanti script controllati"
else
errore "manca node: gli script Node della CI non si possono controllare."
fi
echo "== Flussi della CI"
while IFS= read -r -d '' flusso; do
if grep -n $'\t' "$flusso" > /dev/null; then
errore "$flusso contiene tabulazioni: in YAML il rientro si fa con gli spazi."
fi
done < <(git ls-files -z -- '.gitea/workflows/*.yml' '.gitea/workflows/*.yaml')
echo "== Segni di conflitto"
if conflitti=$(git grep -n -I -E '^(<{7}|>{7})( |$)' -- . ':!*.png' ':!*.jpg'); then
errore "segni di conflitto rimasti:"
echo "$conflitti" >&2
fi
echo "== Versione"
versione=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props)
if [[ "$(printf '%s\n' "$versione" | grep -c .)" != "1" ]]; then
errore "Directory.Build.props deve avere una sola <Version>."
elif [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then
errore "versione «$versione» non valida: serve x.y.z, eventualmente con -qualcosa."
else
echo " $versione"
fi
echo "== Progetti della soluzione"
while IFS= read -r progetto; do
[[ -f "$progetto" ]] || errore "Febe.slnx elenca $progetto, che non esiste."
done < <(sed -n 's:.*<Project Path="\([^"]*\)".*:\1:p' Febe.slnx)
echo " $(grep -c '<Project Path=' Febe.slnx) progetti"
echo "== File JSON"
if command -v node > /dev/null; then
# Un solo processo per tutti i file; stampa i file che non si leggono, uno per riga.
guasti=$(git ls-files -z -- '*.json' | node -e '
const fs = require("fs");
const files = fs.readFileSync(0, "utf8").split("\0").filter(Boolean);
for (const f of files) {
try { JSON.parse(fs.readFileSync(f, "utf8").replace(/^/, "")); } catch (e) { console.log(f + ": " + e.message); }
}
console.error(" " + files.length + " file controllati");')
if [[ -n "$guasti" ]]; then
errore "JSON non valido:"
echo "$guasti" >&2
fi
else
errore "manca node: i file JSON non si possono controllare."
fi
if ((errori > 0)); then
echo "Controlli falliti: $errori." >&2
exit 1
fi
echo "Controlli superati."
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Costruzione dell'immagine Docker di Febe con il builder buildx dell'esecuzione (docker-container), sempre con gli
# stessi argomenti e le stesse etichette: la costruzione che si pubblica esce intera dalla cache di quella che si è
# provata e scansionata, quindi gli strati sono gli stessi.
#
# costruisci-immagine.sh archivio <file.tar> <nome locale> archivio dell'immagine, per docker load e per Trivy
# costruisci-immagine.sh pubblica <nome:etichetta>... spinta sul registro da buildx: le credenziali sono
# già nella configurazione del client, il demone non
# parla mai con il registro (proverebbe HTTPS)
#
# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che
# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza
# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice.
# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero.
#
# Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id).
# Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla
# pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un
# Febe vero. Per questo qui non si mette mai febe.ci.prova, il segno dei soli contenitori di prova (prova-immagine.sh):
# lo controlla PipelineTests.
set -euo pipefail
modo="${1:?Indica il modo: archivio o pubblica.}"
shift
cd "$(git rev-parse --show-toplevel)"
comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false
--build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}"
--label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}"
--label "febe.ci.ref=${GITHUB_REF_NAME:-}" --label "febe.ci.commit=${GITHUB_SHA:-}")
case "$modo" in
archivio)
archivio="${1:?Indica il file .tar da scrivere.}"
nome="${2:?Indica il nome locale, per esempio febe-ci:123.}"
mkdir -p "$(dirname "$archivio")"
docker buildx build "${comuni[@]}" --output "type=docker,name=$nome,dest=$archivio" .
echo "Archivio dell'immagine: $archivio ($(du -h "$archivio" | cut -f1))"
;;
pubblica)
(($# > 0)) || { echo "Indica almeno un nome:etichetta da pubblicare." >&2; exit 2; }
etichette=()
for nome in "$@"; do
etichette+=(-t "$nome")
done
docker buildx build "${comuni[@]}" "${etichette[@]}" --push .
printf 'Pubblicata: %s\n' "$@"
;;
*)
echo "Modo sconosciuto: «$modo» (archivio o pubblica)." >&2
exit 2
;;
esac
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
# Prova dell'immagine appena costruita, sul demone Docker del runner. Ogni contenitore gira SENZA RETE
# (--network none): Febe non può raggiungere alcun sito, tanto meno Instagram (regola 1), e il controllo di salute
# passa dalla rete interna del contenitore.
# Ogni contenitore porta l'etichetta febe.ci.prova=<esecuzione>, messa qui con «docker run --label» e mai in
# un'immagine: è il segno con cui pulizia-docker.sh riconosce un contenitore di prova, insieme al nome
# febe-prova-<esecuzione>. Le etichette febe.ci.* dell'immagine non bastano: Docker le copia in ogni contenitore, anche
# in un Febe vero avviato da un'immagine pubblicata.
#
# .gitea/scripts/prova-immagine.sh <immagine> [esecuzione]
#
# 1. Chromium della distribuzione risponde e i criteri di Febe (niente password salvate) sono al loro posto;
# 2. la lingua it_IT.UTF-8 è generata;
# 3. il contenitore parte come dice la guida (profilo seccomp di Febe, password dell'interfaccia, PUID/PGID
# predefiniti), il controllo di salute dell'immagine diventa «healthy» e «febe --controllo-salute» risponde;
# 4. allo stop si ferma da solo, entro i 30 secondi che la guida concede.
# La password è casuale, vive solo nell'ambiente del client Docker e non si stampa mai.
set -euo pipefail
immagine="${1:?Indica quale immagine provare.}"
esecuzione="${2:-${ESECUZIONE:-locale}}"
radice="$(git rev-parse --show-toplevel)"
etichette=(--label "febe.ci.prova=$esecuzione")
nome="febe-prova-$esecuzione"
# Toglie il contenitore di prova di questa esecuzione (anche quello di un tentativo precedente), ma solo se porta il
# segno della prova: un contenitore con lo stesso nome e senza segno resta, e «docker run --name» si ferma.
togli() {
local segno
segno=$(docker container inspect -f '{{index .Config.Labels "febe.ci.prova"}}' "$nome" 2> /dev/null) || return 0
if [[ "$segno" == "$esecuzione" ]]; then
docker rm -f -v "$nome" > /dev/null 2>&1 || true
fi
}
trap togli EXIT
togli
echo "== Chromium e criteri di Febe"
docker run --rm --network none "${etichette[@]}" --entrypoint /usr/bin/chromium "$immagine" --version
docker run --rm --network none "${etichette[@]}" --entrypoint sh "$immagine" -c \
'test -s /etc/chromium/policies/managed/febe.json && test -s /usr/share/febe/seccomp.json && echo "criteri di Chromium e profilo seccomp presenti"'
echo "== Lingua italiana"
docker run --rm --network none "${etichette[@]}" --entrypoint sh "$immagine" -c 'locale -a | grep -i "^it_IT\.utf8$"'
echo "== Avvio, salute e arresto"
FEBE_PASSWORD="$(head -c 32 /dev/urandom | base64 | tr -dc 'A-Za-z0-9')"
export FEBE_PASSWORD
docker run -d --name "$nome" --network none "${etichette[@]}" \
--security-opt "seccomp=$radice/docker/chromium/seccomp.json" \
--stop-timeout 30 -e FEBE_PASSWORD "$immagine" > /dev/null
unset FEBE_PASSWORD
# Il primo controllo di salute dell'immagine arriva 30 secondi dopo l'avvio (HEALTHCHECK --interval=30s): fino a 3 minuti.
stato=""
for _ in $(seq 1 36); do
if [[ "$(docker inspect -f '{{.State.Running}}' "$nome")" != "true" ]]; then
echo "Il contenitore si è fermato da solo (codice $(docker inspect -f '{{.State.ExitCode}}' "$nome")). Registro:" >&2
docker logs --tail 80 "$nome" >&2 || true
exit 1
fi
stato="$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$nome")"
[[ "$stato" == "healthy" || "$stato" == "unhealthy" ]] && break
sleep 5
done
if [[ "$stato" != "healthy" ]]; then
echo "Il controllo di salute dice «${stato:-niente}» invece di «healthy». Registro:" >&2
docker logs --tail 80 "$nome" >&2 || true
exit 1
fi
if ! docker exec "$nome" /app/febe --controllo-salute > /dev/null; then
echo "febe --controllo-salute non risponde «ok» dentro il contenitore. Registro:" >&2
docker logs --tail 80 "$nome" >&2 || true
exit 1
fi
echo "salute: healthy, e febe --controllo-salute risponde"
inizio=$(date +%s)
docker stop -t 30 "$nome" > /dev/null
durata=$(($(date +%s) - inizio))
codice="$(docker inspect -f '{{.State.ExitCode}}' "$nome")"
echo "arresto in ${durata} s (codice di uscita $codice)"
if ((durata >= 30)); then
echo "Febe non si è fermato da solo entro 30 secondi: Docker l'ha dovuto uccidere. Registro:" >&2
docker logs --tail 80 "$nome" >&2 || true
exit 1
fi
+858
View File
@@ -0,0 +1,858 @@
#!/usr/bin/env bash
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
#
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
# anche un Febe vero. Ciò che si toglie si riconosce così:
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
# toglie da sé appena finiscono);
# - immagini provate: il nome locale febe-ci:<esecuzione>, tolto per nome, mai per identificativo e mai con -f. Se la
# stessa immagine ha anche un nome del registro, si toglie solo febe-ci:<esecuzione>; se un contenitore la usa, resta;
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
# i lavori) resta.
#
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
# lavoro «immagine», sempre)
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
# penzolante del demone (quella che nessuna immagine condivide) non usata da
# 24 ore, di tutti i progetti (alla fine di ogni lavoro «immagine», dopo
# «esecuzione»)
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
# stretta di prima del 21 ottobre 2026, ora solo a mano
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
# (flusso «pulizia», ogni lunedì e a mano)
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
# (sul registro solo GET)
#
# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o
# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto
# della prova.
#
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
# stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i
# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una
# versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
#
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
#
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
#
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
set -uo pipefail
uso() {
[[ -z "${1:-}" ]] || echo "$1" >&2
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
exit 2
}
prova=0
argomenti=()
for argomento in "$@"; do
case "$argomento" in
--prova) prova=1 ;;
-*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;;
*) argomenti+=("$argomento") ;;
esac
done
modo="${argomenti[0]:-}"
case "$modo" in
esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;;
residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;;
penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;;
*) uso ;;
esac
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
problemi=0
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
# esempio, se ne andrebbe anche lui).
previsti=()
nomi_previsti=()
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
declare -A conteggi=()
tipi=()
note=()
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
# script indicano il builder per nome.
export BUILDX_BUILDER=default
avviso() {
echo "::warning::$*"
problemi=$((problemi + 1))
}
# Un avviso che non fa diventare rosso il lavoro: per il registro.
segnala() {
echo "::warning::$*"
}
conta() {
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
}
# Vero se la prima parola è fra quelle che seguono.
fra() {
local cercata="$1" voce
shift
for voce in "$@"; do
[[ "$voce" == "$cercata" ]] && return 0
done
return 1
}
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
eta_minuti() {
local creato="${1:-}" secondi
creato="${creato//\"/}"
[[ "$creato" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$ ]] \
|| { echo 0; return; }
secondi=$(date -u -d "${BASH_REMATCH[1]}${BASH_REMATCH[3]}" +%s 2> /dev/null) || { echo 0; return; }
echo $((($(date -u +%s) - secondi) / 60))
}
durata() {
local minuti="$1"
if ((minuti >= 2 * 1440)); then
echo "$((minuti / 1440)) giorni"
elif ((minuti >= 120)); then
echo "$((minuti / 60)) ore"
else
echo "$minuti minuti"
fi
}
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
# che la pulizia vera toglierebbe.
restanti() {
local id
while read -r id; do
[[ -n "$id" ]] || continue
fra "$id" "${previsti[@]}" || echo "$id"
done <<< "${1:-}"
}
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
contenitori_di_prova() {
local run="$1"
shift
local stati=() stato elenco id nome valore
for stato in "$@"; do stati+=(--filter "status=$stato"); done
elenco=$(docker ps -a --no-trunc --filter "label=febe.ci.prova${run:+=$run}" "${stati[@]}" \
--format '{{.ID}} {{.Names}} {{.Label "febe.ci.prova"}}') || return 1
while read -r id nome valore; do
[[ -n "${id:-}" && "${valore:-}" =~ ^[0-9]+$ && "${nome:-}" == "febe-prova-$valore" ]] || continue
[[ -z "$run" || "$valore" == "$run" ]] || continue
echo "$id $nome"
done <<< "$elenco"
}
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
togli_contenitore() {
local id="$1" nome="$2" opzioni=(-v)
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
if ((prova)); then
echo " toglierei il contenitore $nome"
previsti+=("$id" "$nome")
return 0
fi
if docker rm "${opzioni[@]}" "$id" > /dev/null 2>&1; then
echo " contenitore $nome tolto"
return 0
fi
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
return 1
}
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
togli_immagine() {
local riferimento="$1" nomi
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|| { avviso "Nome di immagine inatteso: «$riferimento»."; return 1; }
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2> /dev/null) || return 1
if [[ "$nomi" == 1 && -n "$(restanti "$(docker ps -a -q --no-trunc --filter "ancestor=$riferimento")")" ]]; then
echo " immagine $riferimento in uso da un contenitore: resta"
return 1
fi
if ((prova)); then
echo " toglierei l'immagine $riferimento"
nomi_previsti+=("$riferimento")
return 0
fi
if docker image rm "$riferimento" > /dev/null 2>&1; then
echo " immagine $riferimento tolta"
return 0
fi
avviso "Non riesco a togliere l'immagine $riferimento."
return 1
}
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
# un lavoro diverso da quello che l'ha creato non ne ha la configurazione. Il contenitore si toglie solo se gira
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
togli_builder() {
local builder="$1"
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
local contenitore="buildx_buildkit_${builder}0" volume="buildx_buildkit_${builder}0_state" immagine esito=1
if ((!prova)) && docker buildx rm -f "$builder" > /dev/null 2>&1; then
echo " builder $builder tolto"
esito=0
fi
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2> /dev/null); then
if [[ "$immagine" != *moby/buildkit* ]]; then
avviso "Il contenitore $contenitore non è un builder buildx (immagine «$immagine»): resta."
return 1
fi
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
return 1
fi
fi
if docker volume inspect "$volume" > /dev/null 2>&1; then
if ((prova)); then
echo " toglierei il volume $volume"
esito=0
elif docker volume rm -f "$volume" > /dev/null 2>&1; then
echo " volume $volume tolto"
esito=0
else
avviso "Non riesco a togliere il volume $volume."
fi
fi
return "$esito"
}
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
# contenitore acceso collegato.
togli_volume() {
local nome="$1"
if ((prova)); then
echo " toglierei il volume $nome"
return 0
fi
if docker volume rm "$nome" > /dev/null 2>&1; then
echo " volume $nome tolto"
return 0
fi
docker volume inspect "$nome" > /dev/null 2>&1 && avviso "Non riesco a togliere il volume $nome."
return 1
}
togli_rete() {
local id="$1" nome="$2"
if ((prova)); then
echo " toglierei la rete $nome"
return 0
fi
if docker network rm "$id" > /dev/null 2>&1; then
echo " rete $nome tolta"
return 0
fi
docker network inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere la rete $nome."
return 1
}
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
nessuno_usa() {
local tipo="$1" nome="$2" utenti
if [[ "$tipo" == volume ]]; then
utenti=$(docker ps -a -q --no-trunc --filter "volume=$nome") || return 1
else
utenti=$(docker ps -a -q --no-trunc --filter "network=$nome") || return 1
fi
[[ -z "$(restanti "$utenti")" ]]
}
esecuzione() {
local run="${1:-}"
[[ "$run" =~ ^[0-9]+$ ]] || { echo "Indica il numero dell'esecuzione (gitea.run_id), non «$run»." >&2; exit 2; }
echo "== Pulizia dell'esecuzione $run"
local elenco id nome
if elenco=$(contenitori_di_prova "$run"); then
while read -r id nome; do
[[ -n "${id:-}" ]] && togli_contenitore "$id" "$nome" forza
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova dell'esecuzione $run."
fi
togli_immagine "febe-ci:$run"
togli_builder "febe-ci-$run"
}
residui() {
local minuti="${1:-90}"
[[ "$minuti" =~ ^[0-9]+$ ]] || { echo "I minuti devono essere un numero, non «$minuti»." >&2; exit 2; }
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
local elenco id nome eta riferimento builder
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
if elenco=$(contenitori_di_prova "" exited created dead); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori di prova della CI di Febe"
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova fermi."
fi
# Contenitori di prova ancora accesi: non si toccano, si segnalano.
if elenco=$(contenitori_di_prova "" running restarting paused); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
if ((eta >= minuti)); then
avviso "Il contenitore di prova $nome è acceso da $eta minuti: il suo lavoro si è interrotto durante la prova. La pulizia non toglie contenitori accesi; se nessuna esecuzione lo usa più, toglilo a mano: docker rm -f -v $nome"
fi
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova accesi."
fi
# Immagini provate: solo i nomi febe-ci:<esecuzione>.
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
while read -r riferimento; do
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2> /dev/null)")
((eta >= minuti)) && togli_immagine "$riferimento" && conta "immagini febe-ci"
done <<< "$elenco"
else
avviso "Non riesco a elencare le immagini febe-ci."
fi
# Builder buildx. Il filtro per nome di Docker cerca una parte del nome: il nome esatto si controlla qui.
if elenco=$(docker ps -a --no-trunc --filter "name=buildx_buildkit_febe-ci-" --format '{{.ID}} {{.Names}}'); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
nome="${nome#/}"
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
builder="${BASH_REMATCH[1]}"
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_builder "$builder" && conta "builder buildx della CI di Febe"
done <<< "$elenco"
else
avviso "Non riesco a elencare i builder buildx."
fi
}
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
resti_della_ci() {
residui 90
echo "== Immagine febe:ci del vecchio flusso di verifica"
if docker image inspect febe:ci > /dev/null 2>&1; then
togli_immagine febe:ci && conta "immagini febe-ci"
fi
}
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
resti_di_act_runner() {
local minuti="$1" elenco id nome eta
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
# -f: Docker non toglie un contenitore acceso.
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
nome="${nome#/}"
[[ "$nome" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori fermi di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di act_runner."
fi
# Volumi che nessun contenitore usa, nemmeno fermo.
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
while read -r nome; do
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker volume inspect -f '{{.CreatedAt}}' "$nome" 2> /dev/null)")
((eta >= minuti)) || continue
nessuno_usa volume "$nome" && togli_volume "$nome" && conta "volumi di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare i volumi di act_runner."
fi
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è RFC 3339.
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
while read -r id nome; do
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker network inspect -f '{{json .Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) || continue
nessuno_usa network "$nome" && togli_rete "$id" "$nome" && conta "reti di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare le reti di act_runner."
fi
}
# Le immagini dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una
# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). Solo lettura: serve all'elenco
# della prova.
immagini_in_uso() {
local elenco id nome
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
fra "$id" "${previsti[@]}" && continue
fra "${nome#/}" "${previsti[@]}" && continue
docker container inspect -f '{{.Image}} {{.Config.Image}}' "$id" 2> /dev/null
done <<< "$elenco"
return 0
}
# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di
# Docker Hub scritti senza dominio, :latest se manca l'etichetta.
nome_completo() {
local nome="$1" primo
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
if [[ "$nome" != */* ]]; then
echo "docker.io/library/$nome"
return
fi
primo="${nome%%/*}"
if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then
echo "$nome"
else
echo "docker.io/$nome"
fi
}
# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei
# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi
# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma
# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e
# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd
# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe,
# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go).
nomi_che_perde() {
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
local -A protetti=()
local -a lista=() via=()
ordinati=$(while read -r nome; do
[[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome"
done <<< "$nomi" | LC_ALL=C sort)
quanti=$(grep -c . <<< "$ordinati")
((quanti > 1)) || return 0
if [[ "$store" != containerd ]]; then
sed '$d' <<< "$ordinati" | cut -d' ' -f2-
return 0
fi
read -r -a lista <<< "$configurazioni"
for configurazione in "${lista[@]}"; do
if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then
per_id=1
elif [[ "$configurazione" == *@* ]]; then
[[ "${configurazione#*@}" == "$id" ]] && per_id=1
resto="${configurazione%%@*}"
[[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1
else
protetti[$(nome_completo "$configurazione")]=1
fi
done
while read -r completo nome; do
[[ -n "${protetti[$completo]:-}" ]] || via+=("$nome")
done <<< "$ordinati"
if ((per_id && ${#via[@]} == quanti)); then
unset "via[$((quanti - 1))]"
fi
((${#via[@]} == 0)) || printf '%s\n' "${via[@]}"
return 0
}
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. Con
# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È una stima fatta qui: nella
# pulizia vera decide Docker (image prune).
elenca_immagini() {
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
local ordine=()
if ! usate=$(immagini_in_uso) \
|| ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then
avviso "Non riesco a elencare le immagini."
return 0
fi
if [[ "$store" != classico ]] && ((minimo > 0)); then
echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)"
fi
while read -r id configurazione; do
[[ -n "${id:-}" ]] || continue
usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione"
done <<< "$usate"
while IFS='|' read -r id nome dimensione; do
[[ -n "${id:-}" ]] || continue
if [[ -z "${dimensioni[$id]+x}" ]]; then
ordine+=("$id")
dimensioni[$id]="${dimensione:-?}"
nomi[$id]=""
elenco_nomi[$id]=""
fi
[[ "$nome" == "<none>:<none>" ]] && continue
aveva_nomi[$id]=1
fra "$nome" "${nomi_previsti[@]}" && continue
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
done <<< "$elenco"
for id in "${ordine[@]}"; do
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
breve="${id#sha256:}"
if [[ -n "${usata_da[$id]+x}" ]]; then
# Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più.
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minimo)) || continue
while read -r nome; do
[[ -n "$nome" ]] || continue
echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore"
quante=$((quante + 1))
conta "nomi tolti a immagini che restano"
done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}")
continue
fi
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minimo)) || continue
nome="${nomi[$id]}"
[[ -n "$nome" ]] || nome="un'immagine senza nome"
echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa"
quante=$((quante + 1))
if [[ "$quali" == senza-nome ]]; then
conta "immagini senza nome"
else
conta "immagini che nessun contenitore usa"
fi
done
((quante > 0)) || echo " nessuna"
}
# In prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di docker system df).
elenca_cache() {
local riga tipo dimensione recuperabile
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
if [[ -z "$riga" ]]; then
echo " docker system df non dice quanta cache di costruzione c'è"
return 0
fi
IFS='|' read -r tipo dimensione recuperabile <<< "$riga"
echo " la cache di costruzione del demone occupa $dimensione; ne toglierei al più $recuperabile, la parte che nessuno sta usando"
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
}
# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove
# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore
# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione),
# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome
# non cambia).
store=""
rileva_store() {
local stato
if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then
store=sconosciuto
elif [[ "$stato" == *io.containerd.snapshotter* ]]; then
store=containerd
else
store=classico
fi
case "$store" in
containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;;
classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;;
*) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;;
esac
}
# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (<none>:<none> se non ne ha).
immagini_e_nomi() {
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
}
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «Total: 1.2GB» (buildx).
spazio_recuperato() {
local riga
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
echo "${riga:-0B}"
}
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso. I nomi si
# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta,
# e il registro del lavoro lo dice.
pota_immagini() {
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
shift
prima_nomi=$(immagini_e_nomi)
prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .)
if ! uscita=$("$@" 2>&1); then
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
return 0
fi
dopo_nomi=$(immagini_e_nomi)
dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u)
dopo=$(grep -c . <<< "$dopo_id")
while read -r id nome; do
[[ -n "${nome:-}" && "$nome" != *":<none>" ]] || continue
grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue
if grep -qxF -- "$id" <<< "$dopo_id"; then
breve="${id#sha256:}"
echo " tolto il nome $nome; l'immagine ${breve:0:12} resta"
conta "nomi tolti a immagini che restano"
else
echo " tolta $nome"
fi
done <<< "$prima_nomi"
recuperato=$(spazio_recuperato "$uscita")
if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then
echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati"
note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati")
else
echo " $cosa: $recuperato recuperati"
note+=("$cosa: $recuperato recuperati")
fi
}
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
pota_cache() {
local cosa="$1" uscita recuperato
shift
if ! uscita=$("$@" 2>&1); then
avviso "Non riesco a togliere la $cosa: $(tail -n 1 <<< "$uscita")"
return 0
fi
recuperato=$(spazio_recuperato "$uscita")
echo " $cosa: $recuperato recuperati"
note+=("$cosa: $recuperato recuperati")
}
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
chiedi() {
local metodo="$1" indirizzo="$2" uscita="$3" codice
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
-o "$uscita" -w '%{http_code}' "$indirizzo") || true
echo "${codice:-000}"
}
spiega() {
case "$1" in
000) echo "niente (Gitea non risponde)" ;;
401) echo "401: il token non vale" ;;
403) echo "403: il token non ha il permesso «package: read and write»" ;;
*) echo "$1" ;;
esac
}
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
# ne arriva una vuota (il server può darne
# meno di 50 per pagina)
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i
# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si
# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e
# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»).
registro() {
local tenere=10
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
echo " Manca il segreto REGISTRY_TOKEN: il registro non si tocca."
return 0
fi
if [[ -z "${GITEA_API:-}" || -z "${PROPRIETARIO:-}" ]]; then
segnala "Mancano GITEA_API o PROPRIETARIO: il registro non si tocca."
return 0
fi
local programma
for programma in curl node; do
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
done
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
for ((pagina = 1; ; pagina++)); do
if ((pagina > 200)); then
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
rm -rf "$cartella"
return 0
fi
if [[ "$codice" != 200 ]]; then
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
"[]" | null) break ;;
esac
done
local senza_etichetta quante
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \
|| ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
rm -rf "$cartella"
quante=$(grep -c . <<< "$senza_etichetta")
if ((quante > 0)); then
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
note+=("registro: $quante versioni sha256:… senza etichetta, che restano")
fi
if [[ -z "$scelte" ]]; then
echo " niente da togliere"
return 0
fi
local versione creata
while IFS=$'\t' read -r versione creata; do
[[ -n "${versione:-}" ]] || continue
if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
segnala "Versione inattesa «$versione» fra quelle da togliere: resta."
continue
fi
if ((prova)); then
echo " toglierei $versione (pubblicata il $creata)"
conta "etichette sha- sul registro"
continue
fi
codice=$(chiedi DELETE "$base/$versione" /dev/null)
if [[ "$codice" == 204 ]]; then
echo " $versione tolta (pubblicata il $creata)"
conta "etichette sha- sul registro"
else
segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")."
fi
done <<< "$scelte"
}
# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le
# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato.
penzolanti() {
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
if ((prova)); then
elenca_immagini 0 senza-nome
elenca_cache
return 0
fi
pota_immagini "immagini senza nome" docker image prune -f
pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h"
}
settimanale() {
resti_della_ci
echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa"
if ((prova)); then
elenca_immagini 4320 senza-nome
else
pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h"
fi
}
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
completa() {
resti_della_ci
resti_di_act_runner 90
echo "== Immagini che nessun contenitore usa, create più di 24 ore fa, di tutti i progetti"
if ((prova)); then
elenca_immagini 1440 tutte
else
pota_immagini "immagini che nessun contenitore usa" docker image prune -a -f --filter "until=24h"
fi
echo "== Cache di costruzione del demone non usata da più di 24 ore"
if ((prova)); then
elenca_cache
else
pota_cache "cache di costruzione" docker builder prune -a -f --filter "until=24h"
fi
registro
}
riepilogo() {
local tipo riga
if ((prova)); then
echo "== Riepilogo della prova (che cosa toglierei; non è stato tolto nulla)"
else
echo "== Riepilogo"
fi
for tipo in "${tipi[@]}"; do
echo " $tipo: ${conteggi[$tipo]}"
done
for riga in "${note[@]}"; do
echo " $riga"
done
((${#tipi[@]} + ${#note[@]} > 0)) || echo " niente"
}
command -v docker > /dev/null || { echo "Manca il client Docker: niente da pulire." >&2; exit 2; }
((prova)) && echo "Prova: elenco che cosa toglierei, senza togliere nulla."
case "$modo" in
esecuzione) esecuzione "${argomenti[1]:-}" ;;
penzolanti) penzolanti ;;
residui) residui "${argomenti[1]:-90}" ;;
settimanale | completa)
rileva_store
docker system df || true
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
docker system df || true
riepilogo
;;
*) uso ;;
esac
if ((problemi > 0)); then
echo "Pulizia finita con $problemi avvisi."
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
fi
exit 0
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env bash
# Riepilogo dei risultati delle prove (file .trx di «dotnet test --logger trx»): superate, fallite e saltate per ogni
# file, i nomi delle fallite e i motivi delle saltate. Lo scrive nel registro e, se il runner lo offre, nel riepilogo
# del lavoro (GITHUB_STEP_SUMMARY). Nessun corpo di risposta né dato personale: solo nomi di prove e messaggi.
#
# .gitea/scripts/riepilogo-prove.sh <cartella dei .trx> [saltate ammesse]
#
# Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono
# Chromium, Xvfb, ffmpeg, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato.
set -euo pipefail
cartella="${1:?Indica la cartella con i file .trx.}"
ammesse="${2:-${PROVE_SALTATE_AMMESSE:-0}}"
[[ "$ammesse" =~ ^[0-9]+$ ]] || { echo "Il numero di prove saltate ammesse deve essere un intero, non «$ammesse»." >&2; exit 2; }
shopt -s nullglob
file=("$cartella"/*.trx)
if (( ${#file[@]} == 0 )); then
echo "Nessun risultato delle prove in $cartella: le prove non sono partite." >&2
exit 1
fi
riepilogo="$(mktemp)"
trap 'rm -f "$riepilogo"' EXIT
fallite_totali=0
saltate_totali=0
{
echo "### Prove"
echo
echo "| Risultati | Totale | Superate | Fallite | Saltate |"
echo "|---|---:|---:|---:|---:|"
} > "$riepilogo"
for trx in "${file[@]}"; do
nome="$(basename "$trx")"
# Un risultato per riga (i .trx sono XML su più righe), poi nome, esito e primo messaggio di ciascuno.
righe="$(tr '\r\n' ' ' < "$trx" | sed 's/<UnitTestResult /\n<UnitTestResult /g' | awk '
function attributo(testo, chiave, inizio) {
if (match(testo, chiave "=\"[^\"]*\"")) {
return substr(testo, RSTART + length(chiave) + 2, RLENGTH - length(chiave) - 3)
}
return ""
}
function testo_xml(s) {
gsub(/&#xD;/, "", s); gsub(/&#xA;/, " ", s); gsub(/&apos;/, "\047", s); gsub(/&quot;/, "\"", s)
gsub(/&lt;/, "<", s); gsub(/&gt;/, ">", s); gsub(/&amp;/, "\\&", s); gsub(/[ \t]+/, " ", s)
return s
}
/^<UnitTestResult / {
testata = $0
sub(/>.*/, "", testata)
messaggio = ""
if (match($0, /<Message>[^<]*<\/Message>/)) {
messaggio = substr($0, RSTART + 9, RLENGTH - 19)
}
printf "%s\t%s\t%s\n", attributo(testata, "outcome"), testo_xml(attributo(testata, "testName")), testo_xml(messaggio)
}')"
totale=0; superate=0; fallite=0; saltate=0
if [[ -n "$righe" ]]; then
totale=$(printf '%s\n' "$righe" | wc -l)
superate=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Passed"' | wc -l)
fallite=$(printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted"' | wc -l)
fi
saltate=$((totale - superate - fallite))
fallite_totali=$((fallite_totali + fallite))
saltate_totali=$((saltate_totali + saltate))
echo "== $nome: totale $totale · superate $superate · fallite $fallite · saltate $saltate"
echo "| \`$nome\` | $totale | $superate | $fallite | $saltate |" >> "$riepilogo"
if (( fallite > 0 )); then
echo " Fallite:"
# Le righe in più si leggono e si scartano (niente «head»: con pipefail il SIGPIPE fermerebbe lo script).
printf '%s\n' "$righe" | awk -F'\t' '$1 == "Failed" || $1 == "Error" || $1 == "Timeout" || $1 == "Aborted" {
if (++n > 50) next; m = $3; if (length(m) > 300) m = substr(m, 1, 300) "…"; print " - " $2 ": " m }'
fi
if (( saltate > 0 )); then
echo " Saltate, per motivo:"
# Il motivo senza la cornice di MSTest («Il metodo … ha generato un'eccezione. Assert.Inconclusive.»).
printf '%s\n' "$righe" | awk -F'\t' '$1 != "Passed" && $1 != "Failed" && $1 != "Error" && $1 != "Timeout" && $1 != "Aborted" {
m = $3; sub(/^.*Assert\.Inconclusive\. */, "", m); if (m == "") m = "(nessun motivo)"; print m }' \
| sort | uniq -c | sort -rn | awk 'NR <= 30 { sub(/^ */, " "); print }'
fi
done
esito=0
{
echo
echo "Fallite: $fallite_totali · saltate: $saltate_totali (ammesse: $ammesse)."
} >> "$riepilogo"
if (( fallite_totali > 0 )); then
echo "Prove fallite: $fallite_totali (i file .trx sono fra gli artefatti dell'esecuzione)." >&2
esito=1
fi
if (( saltate_totali > ammesse )); then
echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, ffmpeg, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2
esito=1
fi
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
cat "$riepilogo" >> "$GITHUB_STEP_SUMMARY" || true
fi
exit "$esito"
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Scansione delle vulnerabilità dell'immagine Docker con Trivy, a versione fissa (strumento.sh), sull'archivio prodotto
# dalla costruzione (docker save o buildx --output type=docker): non serve il demone, e si scansiona proprio
# l'immagine provata. Pacchetti di Debian e dipendenze .NET di Febe (i file *.deps.json).
#
# .gitea/scripts/scansione-immagine.sh <immagine.tar> [cartella dei rapporti]
#
# La regola (docs/processo.md, «Rilievi di sicurezza»):
# - CRITICAL con una correzione disponibile: il lavoro fallisce e l'immagine non si pubblica;
# - HIGH, e CRITICAL ancora senza correzione: si riportano nel registro e in trivy.json, senza fermare nulla.
# Le eccezioni stanno solo in .trivyignore, alla radice del repository: un identificativo per riga, con la scadenza
# (exp:AAAA-MM-GG) e, sulla riga sopra, il motivo scritto e chi l'ha deciso.
set -euo pipefail
radice="$(git rev-parse --show-toplevel)"
archivio="${1:?Manca il file .tar da scansionare.}"
rapporti="${2:-$radice/out/sicurezza}"
lavoro="${RUNNER_TEMP:-/tmp}"
strumenti="$lavoro/febe-strumenti"
[[ -s "$archivio" ]] || { echo "Manca l'archivio dell'immagine: $archivio" >&2; exit 2; }
bash "$radice/.gitea/scripts/strumento.sh" trivy "$strumenti"
mkdir -p "$rapporti"
# Niente barre di avanzamento, niente controllo di versioni nuove, niente dati d'uso.
export TRIVY_NO_PROGRESS=true TRIVY_SKIP_VERSION_CHECK=true TRIVY_DISABLE_TELEMETRY=true
export TRIVY_CACHE_DIR="$lavoro/febe-trivy-cache"
comuni=(image --input "$archivio" --scanners vuln --timeout 20m)
if [[ -f "$radice/.trivyignore" ]]; then
comuni+=(--ignorefile "$radice/.trivyignore")
echo "Eccezioni in .trivyignore: $(grep -c -E '^[^#[:space:]]' "$radice/.trivyignore" || true)"
fi
echo "== Vulnerabilità HIGH e CRITICAL (rapporto: non fermano il lavoro)"
"$strumenti/trivy" "${comuni[@]}" --severity HIGH,CRITICAL --format json --output "$rapporti/trivy.json" --exit-code 0
"$strumenti/trivy" convert --format table "$rapporti/trivy.json"
if command -v jq > /dev/null; then
conteggio=$(jq -r '[.Results[]?.Vulnerabilities[]?] as $v
| "HIGH \([$v[] | select(.Severity == "HIGH")] | length) · CRITICAL \([$v[] | select(.Severity == "CRITICAL")] | length), di cui correggibili \([$v[] | select(.Severity == "CRITICAL" and ((.FixedVersion // "") != ""))] | length)"' "$rapporti/trivy.json")
echo "Trovate: $conteggio."
if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
printf "### Sicurezza dell'immagine (Trivy)\n\n%s.\n" "$conteggio" >> "$GITHUB_STEP_SUMMARY" || true
fi
fi
echo "== CRITICAL con una correzione disponibile (fermano il lavoro)"
if "$strumenti/trivy" "${comuni[@]}" --skip-db-update --skip-java-db-update --severity CRITICAL --ignore-unfixed \
--format table --exit-code 1; then
echo "Nessuna vulnerabilità CRITICAL con una correzione disponibile."
else
echo "Vulnerabilità CRITICAL con una correzione disponibile: l'immagine non passa. Aggiorna il pacchetto o la dipendenza (docs/processo.md, «Rilievi di sicurezza»)." >&2
exit 1
fi
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# Cerca segreti (gettoni, chiavi, password) con gitleaks, a versione fissa (strumento.sh), in tutta la storia del
# commit verificato: ogni commit da cui discende, non solo l'ultimo. Ogni ramo si controlla al suo push (main a ogni
# unione), così un rilievo su un ramo non blocca gli altri. Un segreto non compare mai per intero: --redact lo
# sostituisce con REDACTED nel registro e nel rapporto, e qui si stampano solo regola, file, riga, commit e impronta.
#
# .gitea/scripts/segreti.sh [cartella del rapporto]
#
# Che cosa fare con un rilievo: docs/processo.md, «Rilievi di sicurezza». In breve: un segreto vero si revoca subito
# (toglierlo dalla storia non basta); un falso allarme già controllato (un dato di prova finto) si mette in
# .gitleaksignore con la sua impronta e, sulla riga sopra, un commento che dice che cos'è e chi l'ha controllato.
set -euo pipefail
radice="$(git rev-parse --show-toplevel)"
rapporti="${1:-$radice/out/sicurezza}"
strumenti="${RUNNER_TEMP:-/tmp}/febe-strumenti"
if [[ "$(git -C "$radice" rev-parse --is-shallow-repository)" == "true" ]]; then
echo "Il clone è parziale: per cercare in tutta la storia serve actions/checkout con fetch-depth: 0." >&2
exit 2
fi
bash "$radice/.gitea/scripts/strumento.sh" gitleaks "$strumenti"
mkdir -p "$rapporti"
rapporto="$rapporti/gitleaks.json"
argomenti=(git "$radice" --log-opts="--full-history HEAD" --redact --no-banner --no-color --exit-code 1 --log-level warn
--report-format json --report-path "$rapporto")
[[ -f "$radice/.gitleaks.toml" ]] && argomenti+=(--config "$radice/.gitleaks.toml")
[[ -f "$radice/.gitleaksignore" ]] && argomenti+=(--gitleaks-ignore-path "$radice/.gitleaksignore")
commit=$(git -C "$radice" rev-list --count HEAD)
stato=0
"$strumenti/gitleaks" "${argomenti[@]}" || stato=$?
if ((stato == 0)); then
echo "Nessun segreto in $commit commit."
exit 0
fi
if [[ -s "$rapporto" ]] && command -v jq > /dev/null; then
quanti=$(jq 'length' "$rapporto")
echo "Possibili segreti: $quanti (in $commit commit). Regola, file:riga, commit, impronta per .gitleaksignore:" >&2
jq -r '.[] | " \(.RuleID) \(.File):\(.StartLine) commit \(.Commit[0:12]) impronta \(.Fingerprint)"' "$rapporto" >&2
else
echo "gitleaks è uscito con $stato: vedi il registro qui sopra e il rapporto $rapporto." >&2
fi
exit "$stato"
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env bash
# Installa uno dei due strumenti esterni della CI, gli unici approvati da Alberto e solo per la CI (20 ottobre 2026):
# gitleaks (segreti nella storia) e Trivy (vulnerabilità dell'immagine). Versione fissa, archivio scaricato dalla
# release del progetto e installato solo se la sua impronta SHA-256 coincide con quella scritta qui. Le impronte sono
# quelle dei file *_checksums.txt delle release, ricontrollate il 20 ottobre 2026 sull'archivio scaricato e
# sull'impronta che GitHub mostra per l'allegato.
#
# .gitea/scripts/strumento.sh gitleaks|trivy <cartella>
#
# Per aggiornare uno strumento si cambiano versione e impronta insieme, in un commit solo, con una riga in
# docs/decisioni.md. Mai «latest», mai le azioni di terzi (trivy-action fu compromessa a marzo 2026, CVE-2026-33634),
# mai uno script di installazione scaricato al volo.
set -euo pipefail
nome="${1:?Indica lo strumento: gitleaks o trivy.}"
cartella="${2:?Indica la cartella in cui installarlo.}"
case "$nome" in
gitleaks)
versione="8.30.1"
archivio="gitleaks_${versione}_linux_x64.tar.gz"
indirizzo="https://github.com/gitleaks/gitleaks/releases/download/v${versione}/${archivio}"
sha256="551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb"
;;
trivy)
versione="0.75.0"
archivio="trivy_${versione}_Linux-64bit.tar.gz"
indirizzo="https://github.com/aquasecurity/trivy/releases/download/v${versione}/${archivio}"
sha256="c6e65abddb348e25f10549df887045629cf28cc72453cd1c63acb717316b3f3f"
;;
*)
echo "Strumento sconosciuto: «$nome» (gitleaks o trivy)." >&2
exit 2
;;
esac
piattaforma="$(uname -s)-$(uname -m)"
if [[ "$piattaforma" != "Linux-x86_64" ]]; then
echo "Gli archivi fissati qui sono per Linux x86_64, non per $piattaforma." >&2
exit 2
fi
if [[ -x "$cartella/$nome" ]] && [[ -f "$cartella/$nome.sha256" ]] && [[ "$(cat "$cartella/$nome.sha256")" == "$sha256" ]]; then
echo "== $nome $versione già installato in $cartella"
exit 0
fi
temporanea="$(mktemp -d)"
trap 'rm -rf "$temporanea"' EXIT
echo "== $nome $versione"
curl -fsSL --retry 3 --retry-delay 5 --max-time 600 -o "$temporanea/$archivio" "$indirizzo"
if ! echo "$sha256 $temporanea/$archivio" | sha256sum -c --quiet -; then
echo "L'impronta SHA-256 di $archivio non è quella attesa: $nome non si installa." >&2
exit 1
fi
mkdir -p "$cartella"
tar -xzf "$temporanea/$archivio" -C "$cartella" "$nome"
chmod 0755 "$cartella/$nome"
echo "$sha256" > "$cartella/$nome.sha256"
"$cartella/$nome" --version | head -n 1 || true
+82
View File
@@ -0,0 +1,82 @@
"use strict";
// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the
// files it is given: no network, no writes, so it is tested with a JSON file.
//
// node versioni-registro.js <how many to keep> <page.json>...
// node versioni-registro.js senza-etichetta <page.json>...
//
// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with
// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container
// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line,
// «version<TAB>created».
//
// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always
// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag
// without a date that can be read.
//
// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index,
// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea
// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are.
//
// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed.
// Messages are in Italian, like every message of the CI.
const fs = require("fs");
const [mode, ...pages] = process.argv.slice(2);
const untagged = mode === "senza-etichetta";
if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) {
console.error("Uso: node versioni-registro.js <quante tenere> | senza-etichetta <pagina.json>...");
process.exit(2);
}
const shaTag = /^sha-[0-9a-f]{7,40}$/;
const digest = /^sha256:[0-9a-f]{64}$/;
const versions = new Map();
for (const file of pages) {
let page;
try {
page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
} catch (error) {
console.error(`${file}: ${error.message}`);
process.exit(2);
}
if (page === null) {
continue;
}
if (!Array.isArray(page)) {
console.error(`${file}: non è un elenco di versioni`);
process.exit(2);
}
for (const version of page) {
if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") {
versions.set(version.version, version);
}
}
}
const dated = (version) => ({
name: version.version,
created: String(version.created_at),
time: Date.parse(version.created_at),
id: Number(version.id) || 0,
});
let chosen;
if (untagged) {
chosen = [...versions.values()]
.filter((version) => digest.test(version.version))
.map(dated)
.sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id);
} else {
chosen = [...versions.values()]
.filter((version) => shaTag.test(version.version))
.map(dated)
.filter((version) => Number.isFinite(version.time))
.sort((a, b) => b.time - a.time || b.id - a.id)
.slice(Number(mode))
.reverse();
}
for (const version of chosen) {
process.stdout.write(`${version.name}\t${version.created}\n`);
}
+68
View File
@@ -0,0 +1,68 @@
# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del
# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie
# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script.
# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di
# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che
# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa):
# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-<esecuzione>, mai
# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:<esecuzione>, builder
# febe-ci-<esecuzione>, l'immagine febe:ci del vecchio flusso;
# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più
# vecchi di 90 minuti;
# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker
# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base
# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede;
# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z.
# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia
# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del
# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia».
name: pulizia
on:
schedule:
- cron: "17 4 * * 1"
workflow_dispatch:
inputs:
prova:
description: "Solo prova: elenca che cosa toglierebbe e non toglie nulla"
type: boolean
required: false
default: false
permissions:
contents: read
concurrency:
group: pulizia
cancel-in-progress: false
defaults:
run:
shell: bash
jobs:
docker:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
# Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e
# la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il
# lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai.
- name: Pulizia completa del demone Docker e del registro
env:
PROVA: ${{ gitea.event.inputs.prova }}
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
GITEA_API: ${{ gitea.server_url }}/api/v1
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
case "${PROVA:-}" in
true) bash .gitea/scripts/pulizia-docker.sh completa --prova ;;
"" | false) bash .gitea/scripts/pulizia-docker.sh completa ;;
*)
VALORE=$(printf '%s' "$PROVA" | tr -c 'A-Za-z0-9' '_' | cut -c 1-20)
echo "::error::La casella «prova» vale true o false, non «$VALORE»: non tolgo nulla."
exit 2
;;
esac
+59 -18
View File
@@ -3,9 +3,12 @@
# e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla;
# 2. windows: Febe.exe in un file solo, il programma di installazione NSIS e lo zip portabile (installer/costruisci.sh,
# gira su Linux);
# 3. immagine: l'immagine Docker (le prove girano anche dentro la build), pubblicata sul registro dei container di
# Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza trattino). Il lavoro dice
# se l'ha pubblicata;
# 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e
# scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro
# dei container di Gitea come <registro>/<proprietario>/febe:X.Y.Z e :latest (solo per le versioni senza
# trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder
# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i
# progetti del demone;
# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con
# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp
# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata.
@@ -29,6 +32,7 @@ on:
jobs:
prove:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
@@ -60,6 +64,7 @@ jobs:
windows:
runs-on: ubuntu-latest
needs: prove
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
@@ -89,7 +94,14 @@ jobs:
immagine:
runs-on: ubuntu-latest
needs: prove
# Dopo l'installatore: :X.Y.Z e :latest escono solo se anche la release potrà uscire.
needs: [prove, windows]
timeout-minutes: 60
env:
FLUSSO: rilascio
ESECUZIONE: ${{ gitea.run_id }}
BUILDER: febe-ci-${{ gitea.run_id }}
PROVA: febe-ci:${{ gitea.run_id }}
outputs:
immagine: ${{ steps.nome.outputs.immagine }}
pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }}
@@ -97,6 +109,12 @@ jobs:
steps:
- uses: actions/checkout@v4
# Ciò che un'esecuzione interrotta non ha potuto togliere, e un tentativo precedente di questa stessa esecuzione.
- name: Resti di esecuzioni interrotte
run: |
bash .gitea/scripts/pulizia-docker.sh residui 90
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
- name: Versione, registro e nome dell'immagine
id: nome
run: |
@@ -105,6 +123,9 @@ jobs:
[ -n "$REGISTRY" ] || REGISTRY=$(echo "${{ gitea.server_url }}" | sed -E 's#^https?://##; s#/.*$##')
OWNER=$(echo "${{ gitea.repository_owner }}" | tr '[:upper:]' '[:lower:]')
echo "VERSION=$V" >> "$GITHUB_ENV"
echo "VERSIONE=$V" >> "$GITHUB_ENV"
echo "GIT_COMMIT=${GITHUB_SHA::12}" >> "$GITHUB_ENV"
echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" >> "$GITHUB_ENV"
echo "REGISTRY=$REGISTRY" >> "$GITHUB_ENV"
echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV"
echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT"
@@ -113,19 +134,32 @@ jobs:
# Un builder buildx proprio, che sa che il registro di casa risponde in HTTP.
- uses: docker/setup-buildx-action@v3
with:
name: febe-ci-${{ gitea.run_id }}
driver: docker-container
buildkitd-config-inline: |
[registry."${{ steps.nome.outputs.registro }}"]
http = true
insecure = true
# Gli stessi argomenti ed etichette della pubblicazione (costruisci-immagine.sh): quella esce dalla cache di questa.
- name: Costruzione dell'immagine (le prove girano dentro la build)
run: |
docker buildx build -f docker/Dockerfile \
--build-arg VERSION="$VERSION" \
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
-t "$IMAGE:$VERSION" --load .
docker run --rm --entrypoint /usr/bin/chromium "$IMAGE:$VERSION" --version
bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA"
docker load -i "$ARCHIVIO"
- name: Prova del contenitore, senza rete
run: bash .gitea/scripts/prova-immagine.sh "$PROVA" "$ESECUZIONE"
- name: Vulnerabilità dell'immagine (Trivy)
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
- name: Rapporto di Trivy
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: sicurezza-immagine
path: out/sicurezza/trivy.json
if-no-files-found: ignore
- name: Segreto per il registro
id: segreto
@@ -156,16 +190,13 @@ jobs:
AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0)
jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo"
mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json"
TAGS="-t $IMAGE:$VERSION"
NOMI="$IMAGE:$VERSION"
case "$VERSION" in
*-*) echo "Versione di anteprima: :latest non si sposta." ;;
*) TAGS="$TAGS -t $IMAGE:latest" ;;
*) NOMI="$NOMI $IMAGE:latest" ;;
esac
# La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro.
docker buildx build -f docker/Dockerfile \
--build-arg VERSION="$VERSION" \
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
$TAGS --push .
# La stessa costruzione di prima (dalla cache del builder), questa volta spinta sul registro da buildx.
bash .gitea/scripts/costruisci-immagine.sh pubblica $NOMI
echo "pubblicata=si" >> "$GITHUB_OUTPUT"
- name: Credenziali tolte
@@ -176,12 +207,22 @@ jobs:
jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" && mv "$CONFIG.nuovo" "$CONFIG"
fi
- name: Pulizia (sempre)
if: always()
run: |
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
release:
runs-on: ubuntu-latest
# Le prove sono verdi, l'installatore c'è e l'immagine si è costruita: pubblicata, o non pubblicata per la sola
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione o la spinta sul
# registro falliscono, non esce nessuna release.
# mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione, la prova del
# contenitore, la scansione o la spinta sul registro falliscono, non esce nessuna release.
needs: [prove, windows, immagine]
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
+286 -28
View File
@@ -1,18 +1,155 @@
# Verifica a ogni push e a ogni pull request: compilazione con gli avvisi come errori
# (compreso Febe.Desktop, che si compila anche da Linux) e tutte le prove.
# Le prove che richiedono Chromium e Xvfb si saltano da sole se il runner non li ha.
# Verifica: a ogni push su qualunque ramo (i tag li prende rilascio.yml) e a mano (Actions ▸ verifica ▸ Esegui).
# I suoi quattro lavori sono i controlli richiesti per unire in main (docs/processo.md):
# controlli sintassi degli script, flussi senza tabulazioni, segni di conflitto, versione, progetti della
# soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate);
# prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests
# (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con
# Chromium, Xvfb, ffmpeg, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi.
# Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di
# questa esecuzione, scritto nel registro per rifare un errore;
# installatore Febe-Setup-<versione>-ci.<numero>.exe e lo zip portabile, artefatti per 14 giorni;
# immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute,
# Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push
# su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre,
# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la
# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone.
#
# Runner: act_runner con l'etichetta ubuntu-latest.
# Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo
# ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner.
# Runner: act_runner con l'etichetta ubuntu-latest, un lavoro alla volta. I lavori parlano con il demone Docker del
# server, lo stesso di Encelado, Mimante e degli altri progetti: niente montaggi della cartella del lavoro in altri
# contenitori (sul server i percorsi sono diversi); le immagini passano come archivi e contesti di costruzione.
# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre 2026) e docs/processo.md.
name: verifica
on:
push:
branches: [main, febe-v1]
pull_request:
branches: ["**"]
workflow_dispatch:
inputs:
seme:
description: "Seme del mondo sintetico per la seconda passata delle prove (vuoto: 1000 più il numero dell'esecuzione)"
required: false
default: ""
permissions:
contents: read
# Su un ramo conta l'ultimo push: l'esecuzione precedente si annulla. Su main ogni commit ha il suo gruppo, così ogni
# unione arriva fino in fondo e pubblica la sua :sha-. L'evento fa parte del gruppo: un'esecuzione a mano non annulla
# mai quella di un push, che è l'unica a scrivere gli stati del commit richiesti per unire (un lavoro annullato lascia
# lo stato «failure», e workflow_dispatch non ne scrive).
concurrency:
group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}${{ gitea.ref == 'refs/heads/main' && format('-{0}', gitea.sha) || '' }}
cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}
defaults:
run:
shell: bash
env:
DOTNET_NOLOGO: "1"
DOTNET_CLI_TELEMETRY_OPTOUT: "1"
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1"
jobs:
prove:
controlli:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
# Tutta la storia: gitleaks legge ogni commit da cui discende quello verificato.
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Script, flussi, conflitti, versione, soluzione e JSON
run: bash .gitea/scripts/controlli.sh
- name: Segreti in tutta la storia (gitleaks)
run: bash .gitea/scripts/segreti.sh out/sicurezza
- name: Rapporto di gitleaks (segreti oscurati)
if: failure()
uses: actions/upload-artifact@v3
with:
name: rapporto-gitleaks
path: out/sicurezza/gitleaks.json
retention-days: 14
if-no-files-found: ignore
prove:
needs: controlli
runs-on: ubuntu-latest
timeout-minutes: 60
# Debian 13 con Node 24: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap), e
# Node per le azioni e per la prova della pagina di accesso.
# Memoria condivisa più ampia dei 64 MB predefiniti: le prove dell'interfaccia usano un Chromium senza finestra.
container:
image: node:24-trixie
options: --shm-size=1g
env:
FEBE_CHROMIUM: /usr/bin/chromium
SEME_RICHIESTO: ${{ gitea.event.inputs.seme }}
NUMERO: ${{ gitea.run_number }}
steps:
- uses: actions/checkout@v4
# Prima di tutto, così un seme chiesto a mano e sbagliato ferma subito il lavoro.
- name: Semi del mondo sintetico
id: semi
run: |
seme="${SEME_RICHIESTO:-}"
[ -n "$seme" ] || seme=$((1000 + ${NUMERO:-0}))
if ! [[ "$seme" =~ ^-?[0-9]{1,9}$ ]]; then
echo "Seme non valido: «$seme» (serve un intero di al massimo nove cifre)." >&2
exit 1
fi
echo "seme=$seme" >> "$GITHUB_OUTPUT"
echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)."
echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\""
- name: Chromium, Xvfb, ffmpeg, NSIS e lingua italiana
run: bash .gitea/scripts/ambiente-prove.sh
- uses: actions/setup-dotnet@v4
with:
dotnet-version: "10.0.x"
- name: Compilazione di tutta la soluzione (avvisi = errori)
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
- name: Prove, seme 13
run: >-
dotnet test tests/Febe.Tests -c Release --no-build --nologo
--logger "trx;LogFileName=prove-seme-13.trx" --results-directory out/prove
- name: Prove del sito di prova, seme dell'esecuzione
if: ${{ !cancelled() && steps.semi.outputs.seme != '' }}
env:
FEBE_SEME_PROVA: ${{ steps.semi.outputs.seme }}
run: >-
dotnet test tests/Febe.Tests -c Release --no-build --nologo --filter "TestCategory=SitoDiProva"
--logger "trx;LogFileName=prove-seme-$FEBE_SEME_PROVA.trx" --results-directory out/prove
- name: Riepilogo delle prove
if: ${{ !cancelled() }}
run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0
- name: Risultati delle prove
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: risultati-prove
path: out/prove/*.trx
retention-days: 14
if-no-files-found: warn
installatore:
needs: prove
runs-on: ubuntu-latest
timeout-minutes: 30
env:
NUMERO: ${{ gitea.run_number }}
steps:
- uses: actions/checkout@v4
@@ -20,37 +157,158 @@ jobs:
with:
dotnet-version: "10.0.x"
- name: Compilazione (avvisi = errori)
run: dotnet build Febe.slnx -c Release -nologo -warnaserror
- name: NSIS e zip
run: |
SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo
$SUDO apt-get update -qq
$SUDO apt-get install -y -qq nsis zip > /dev/null
- name: Prove
run: >-
dotnet test tests/Febe.Tests -c Release --no-build --nologo
--logger "trx;LogFileName=prove.trx" --results-directory out/prove
- name: Febe.exe, programma di installazione e zip portabile (versione di prova)
run: |
V=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
echo "Versione di questa esecuzione: $V-ci.$NUMERO"
bash installer/costruisci.sh "$V-ci.$NUMERO"
- name: Risultati
if: always()
- name: Artefatti per Windows
uses: actions/upload-artifact@v3
with:
name: risultati-prove
path: out/prove/*.trx
if-no-files-found: ignore
name: windows
path: |
out/Febe-Setup-*.exe
out/Febe-*-portabile.zip
retention-days: 14
if-no-files-found: error
# Dopo l'installatore, non solo dopo le prove: :main e :sha- escono solo da un commit con tutta la verifica verde.
# Sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia.
immagine:
needs: [prove, installatore]
runs-on: ubuntu-latest
needs: prove
timeout-minutes: 60
env:
FLUSSO: verifica
ESECUZIONE: ${{ gitea.run_id }}
NUMERO: ${{ gitea.run_number }}
BUILDER: febe-ci-${{ gitea.run_id }}
PROVA: febe-ci:${{ gitea.run_id }}
steps:
- uses: actions/checkout@v4
- name: Costruzione dell'immagine Docker (senza pubblicarla; le prove girano anche dentro la build)
# Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di
# questa stessa esecuzione.
- name: Resti di esecuzioni interrotte
run: |
docker version
docker build -f docker/Dockerfile \
--build-arg VERSION=ci \
--build-arg GIT_COMMIT="${GITHUB_SHA::12}" \
-t febe:ci .
bash .gitea/scripts/pulizia-docker.sh residui 90
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
- name: L'immagine parte e mostra la pagina di errore senza password
# Registro: la variabile REGISTRY delle Actions, se c'è, altrimenti l'host dell'indirizzo del server (ROOT_URL).
- name: Versione, registro e nomi
id: nome
env:
REGISTRO_SCELTO: ${{ vars.REGISTRY }}
SERVER: ${{ gitea.server_url }}
PROPRIETARIO: ${{ gitea.repository_owner }}
run: |
docker run --rm --entrypoint /usr/bin/chromium febe:ci --version
docker run --rm --entrypoint sh febe:ci -c 'locale -a | grep -i it_IT && ls /etc/chromium/policies/managed/'
V=$(sed -n 's:.*<Version>\(.*\)</Version>.*:\1:p' Directory.Build.props | head -n 1)
REGISTRY="$REGISTRO_SCELTO"
[ -n "$REGISTRY" ] || REGISTRY=$(echo "$SERVER" | sed -E 's#^https?://##; s#/.*$##')
OWNER=$(echo "$PROPRIETARIO" | tr '[:upper:]' '[:lower:]')
{
echo "VERSIONE=$V-ci.$NUMERO"
echo "GIT_COMMIT=${GITHUB_SHA::12}"
echo "REGISTRY=$REGISTRY"
echo "IMAGE=$REGISTRY/$OWNER/febe"
echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar"
} >> "$GITHUB_ENV"
echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT"
echo "Immagine $V-ci.$NUMERO del commit ${GITHUB_SHA::12}, provata come $PROVA; registro $REGISTRY/$OWNER/febe"
# Un builder buildx di questa esecuzione (con la sua cache), che sa che il registro di casa risponde in HTTP.
- name: Builder buildx dell'esecuzione
uses: docker/setup-buildx-action@v3
with:
name: febe-ci-${{ gitea.run_id }}
driver: docker-container
buildkitd-config-inline: |
[registry."${{ steps.nome.outputs.registro }}"]
http = true
insecure = true
- name: Costruzione dell'immagine (dentro girano compilazione e prove)
run: |
bash .gitea/scripts/costruisci-immagine.sh archivio "$ARCHIVIO" "$PROVA"
docker load -i "$ARCHIVIO"
- name: Prova del contenitore, senza rete
run: bash .gitea/scripts/prova-immagine.sh "$PROVA" "$ESECUZIONE"
- name: Vulnerabilità dell'immagine (Trivy)
run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza
- name: Rapporto di Trivy
if: ${{ !cancelled() }}
uses: actions/upload-artifact@v3
with:
name: sicurezza-immagine
path: out/sicurezza/trivy.json
retention-days: 14
if-no-files-found: ignore
- name: Pubblicare?
id: segreto
env:
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
EVENTO: ${{ gitea.event_name }}
RIFERIMENTO: ${{ gitea.ref }}
run: |
if [ "$EVENTO" != push ] || [ "$RIFERIMENTO" != refs/heads/main ]; then
echo "Si pubblica solo dopo un push su main: qui l'immagine è costruita, provata e scansionata."
echo "presente=no" >> "$GITHUB_OUTPUT"
elif [ -z "$TOKEN" ]; then
echo "::warning::Manca il segreto REGISTRY_TOKEN: l'immagine di main è costruita, provata e scansionata ma non pubblicata. Aggiungilo (token con package: read and write) e rilancia la verifica di questo commit."
echo "presente=no" >> "$GITHUB_OUTPUT"
else
echo "presente=si" >> "$GITHUB_OUTPUT"
fi
- name: Pubblicazione come :main e :sha-<commit>
if: steps.segreto.outputs.presente == 'si'
env:
TOKEN: ${{ secrets.REGISTRY_TOKEN }}
UTENTE: ${{ gitea.actor }}
run: |
# Le credenziali vanno nella configurazione del client: buildx le passa al builder, il demone non c'entra (e
# proverebbe HTTPS). Non si stampano mai.
CONFIG="${DOCKER_CONFIG:-$HOME/.docker}"
mkdir -p "$CONFIG"
[ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json"
AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0)
jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo"
mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json"
NOMI=("$IMAGE:sha-${GITHUB_SHA::7}")
# :main solo se main è ancora a questo commit: un'esecuzione arrivata in ritardo non lo riporta indietro.
# Il passo gira con «bash -e -o pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo
# prima dell'avviso, e non uscirebbe nemmeno la :sha-.
CIMA=$(git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA=""
if [ "$CIMA" = "$GITHUB_SHA" ]; then
NOMI+=("$IMAGE:main")
elif [ -z "$CIMA" ]; then
echo "::warning::Non riesco a leggere la cima di main: si pubblica solo :sha-${GITHUB_SHA::7} e :main resta dov'è."
else
echo "main è già andato avanti (${CIMA::7}): si pubblica solo :sha-${GITHUB_SHA::7}."
fi
bash .gitea/scripts/costruisci-immagine.sh pubblica "${NOMI[@]}"
- name: Pulizia (sempre)
if: always()
run: |
CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json"
if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then
jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" \
&& mv "$CONFIG.nuovo" "$CONFIG" || echo "::warning::Non riesco a togliere le credenziali da $CONFIG."
fi
if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi
bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE"
# Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione
# penzolante non usata da 24 ore. Non fa mai fallire il lavoro.
bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita."
+2 -11
View File
@@ -379,17 +379,6 @@ MigrationBackup/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
@@ -401,12 +390,14 @@ FodyWeavers.xsd
*.sln.iml
# ---> VisualStudioCode
# Della cartella .vscode entra nel repository solo la configurazione condivisa (guida: Sviluppo, «Da VS Code»).
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
*.code-workspace
# Local History for Visual Studio Code
.history/
+3
View File
@@ -0,0 +1,3 @@
{
"recommendations": ["ms-dotnettools.csdevkit", "ms-dotnettools.csharp"]
}
+182
View File
@@ -0,0 +1,182 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Febe per Windows · sito di prova",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila e avvia il sito di prova",
"postDebugTask": "ferma il sito di prova",
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
"args": [
"--dati",
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
"--libreria",
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
"--sito-di-prova",
"http://127.0.0.1:8481",
"--accesso-di-prova",
"--prima-sessione",
"30",
"--sviluppo"
],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"logging": { "moduleLoad": false },
"linux": { "preLaunchTask": "solo su Windows" },
"osx": { "preLaunchTask": "solo su Windows" },
"presentation": { "group": "1-windows", "order": 1 }
},
{
"name": "Sito di prova + Febe per Windows",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila",
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
"args": ["--porta", "8481", "--porta-cdn", "8482"],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"serverReadyAction": {
"action": "startDebugging",
"pattern": "Sito di prova: http://",
"name": "Febe per Windows · contro il sito già avviato",
"killOnServerStop": true
},
"checkForDevCert": false,
"logging": { "moduleLoad": false },
"linux": { "preLaunchTask": "solo su Windows" },
"osx": { "preLaunchTask": "solo su Windows" },
"presentation": { "group": "1-windows", "order": 2 }
},
{
"name": "Febe per Windows · contro il sito già avviato",
"type": "coreclr",
"request": "launch",
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
"args": [
"--dati",
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\dati",
"--libreria",
"${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\libreria",
"--sito-di-prova",
"http://127.0.0.1:8481",
"--accesso-di-prova",
"--prima-sessione",
"30",
"--sviluppo"
],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"logging": { "moduleLoad": false },
"presentation": { "hidden": true }
},
{
"name": "Febe Server · dimostrazione (--demo)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila",
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
"args": ["--demo"],
"env": { "FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot" },
"windows": {
"env": {
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot",
"TEMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei",
"TMP": "${env:USERPROFILE}\\FebeSviluppo\\${workspaceFolderBasename}\\temporanei"
}
},
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"serverReadyAction": { "action": "openExternally", "pattern": "Apri (https?://\\S+)" },
"checkForDevCert": false,
"logging": { "moduleLoad": false },
"presentation": { "group": "2-strumenti", "order": 1 }
},
{
"name": "Sito di prova",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila",
"program": "${workspaceFolder}/tools/Febe.SitoDiProva/bin/Debug/net10.0/febe-sito-di-prova.dll",
"args": ["--porta", "8481", "--porta-cdn", "8482"],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"logging": { "moduleLoad": false },
"presentation": { "group": "2-strumenti", "order": 2 }
},
{
"name": "Simulazione 30 giorni (prudente)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila",
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
"args": ["--simula", "30g", "--profilo", "prudente"],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"logging": { "moduleLoad": false },
"presentation": { "group": "2-strumenti", "order": 3 }
},
{
"name": "Febe Server · sito di prova (solo Linux)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "compila e avvia il sito di prova",
"postDebugTask": "ferma il sito di prova",
"program": "${workspaceFolder}/src/Febe.Server/bin/Debug/net10.0/febe.dll",
"args": [
"--dati",
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/dati",
"--libreria",
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/libreria",
"--importa",
"${env:HOME}/FebeSviluppo/${workspaceFolderBasename}/importa",
"--ascolta",
"127.0.0.1",
"--sito-di-prova",
"http://127.0.0.1:8481",
"--accesso-di-prova",
"--prima-sessione",
"30"
],
"env": {
"FEBE_PASSWORD": "prova",
"FEBE_INTERFACCIA": "${workspaceFolder}/src/Febe.Web/wwwroot"
},
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"terminateChildProcesses": true,
"serverReadyAction": {
"action": "openExternally",
"pattern": "Interfaccia sulla porta (\\d+)",
"uriFormat": "http://127.0.0.1:%s/"
},
"checkForDevCert": false,
"logging": { "moduleLoad": false },
"windows": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
"osx": { "preLaunchTask": "solo su Linux", "postDebugTask": "", "args": ["--aiuto"] },
"presentation": { "group": "3-linux", "order": 1 }
},
{
"name": "⚠ Febe per Windows · Instagram vero (dati veri)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "${input:confermaInstagramVero}",
"program": "${workspaceFolder}/src/Febe.Desktop/bin/Debug/net10.0-windows/Febe.exe",
"args": [],
"cwd": "${workspaceFolder}",
"console": "internalConsole",
"logging": { "moduleLoad": false },
"linux": { "preLaunchTask": "solo su Windows" },
"osx": { "preLaunchTask": "solo su Windows" },
"presentation": { "group": "9-instagram-vero", "order": 1 }
}
],
"inputs": [
{
"id": "confermaInstagramVero",
"type": "pickString",
"description": "INSTAGRAM VERO con l'account e i dati veri di Alberto. Invio avvia, Esc annulla.",
"options": [{ "label": "Sì, avvia Febe con Instagram vero", "value": "compila" }]
}
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"dotnet.defaultSolution": "Febe.slnx"
}
+202
View File
@@ -0,0 +1,202 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "compila",
"detail": "dotnet build Febe.slnx -warnaserror: tutta la soluzione, gli avvisi sono errori; con -tl:off -clp:ForceNoAlign ogni errore sta su una riga e finisce nel pannello Problemi",
"type": "process",
"command": "dotnet",
"args": [
"build",
"${workspaceFolder}/Febe.slnx",
"-warnaserror",
"-nologo",
"-tl:off",
"-clp:ForceNoAlign"
],
"group": { "kind": "build", "isDefault": true },
"problemMatcher": "$msCompile",
"presentation": { "clear": true }
},
{
"label": "prove",
"detail": "dotnet test tests/Febe.Tests: tutte le prove (senza Chromium e Xvfb quelle con il browser vero risultano saltate)",
"type": "process",
"command": "dotnet",
"args": [
"test",
"${workspaceFolder}/tests/Febe.Tests",
"-nologo",
"-tl:off",
"-clp:ForceNoAlign"
],
"group": { "kind": "test", "isDefault": true },
"problemMatcher": "$msCompile",
"presentation": { "clear": true }
},
{
"label": "prove Windows",
"detail": "dotnet test tests/Febe.Tests.Windows: le prove con WebView2 vero e un Dispatcher di WPF, solo su Windows (aprono per qualche istante la finestra «Browser di Febe»)",
"type": "process",
"command": "dotnet",
"args": [
"test",
"${workspaceFolder}/tests/Febe.Tests.Windows",
"-nologo",
"-tl:off",
"-clp:ForceNoAlign"
],
"group": "test",
"problemMatcher": "$msCompile",
"presentation": { "clear": true }
},
{
"label": "prove con filtro",
"detail": "dotnet test tests/Febe.Tests --filter …: una prova o un gruppo, per nome",
"type": "process",
"command": "dotnet",
"args": [
"test",
"${workspaceFolder}/tests/Febe.Tests",
"--filter",
"${input:filtroDelleProve}",
"-nologo",
"-tl:off",
"-clp:ForceNoAlign"
],
"group": "test",
"problemMatcher": "$msCompile",
"presentation": { "clear": true }
},
{
"label": "sito di prova",
"detail": "dotnet run --project tools/Febe.SitoDiProva: http://127.0.0.1:8481, CDN su 127.0.0.2:8482 (dove Febe lo cerca), dati sintetici del seme 13; in sfondo, pronto alla riga «Sito di prova: http://…»",
"type": "process",
"command": "dotnet",
"args": [
"run",
"--project",
"${workspaceFolder}/tools/Febe.SitoDiProva",
"--",
"--porta",
"8481",
"--porta-cdn",
"8482"
],
"isBackground": true,
"problemMatcher": {
"base": "$msCompile",
"owner": "sito-di-prova",
"background": {
"activeOnStart": true,
"beginsPattern": "(?!)",
"endsPattern": "^Sito di prova: http://"
}
},
"presentation": { "panel": "dedicated", "clear": true }
},
{
"label": "pubblica Febe.exe",
"detail": "dotnet publish di Febe.Desktop in un file solo, come installer/costruisci.sh: out/pubblicazione/Febe.exe (Release, win-x64)",
"type": "process",
"command": "dotnet",
"args": [
"publish",
"${workspaceFolder}/src/Febe.Desktop/Febe.Desktop.csproj",
"-c",
"Release",
"-r",
"win-x64",
"--self-contained",
"true",
"-p:PublishSingleFile=true",
"-p:IncludeNativeLibrariesForSelfExtract=true",
"-p:EnableCompressionInSingleFile=true",
"-nologo",
"-o",
"${workspaceFolder}/out/pubblicazione",
"-tl:off",
"-clp:ForceNoAlign"
],
"group": "build",
"problemMatcher": "$msCompile",
"presentation": { "clear": true }
},
{
"label": "immagine Docker (serve Docker Desktop)",
"detail": "docker build -f docker/Dockerfile -t febe .: compilazione e prove dentro l'immagine; serve un demone Docker avviato",
"type": "process",
"command": "docker",
"args": ["build", "-f", "docker/Dockerfile", "-t", "febe", "."],
"group": "build",
"problemMatcher": [],
"presentation": { "clear": true }
},
{
"label": "compila e avvia il sito di prova",
"detail": "Prima del debug contro il sito di prova: compila, poi avvia il sito (se è già aperto, lo usa così com'è)",
"dependsOrder": "sequence",
"dependsOn": ["compila", "sito di prova"],
"hide": true,
"problemMatcher": []
},
{
"label": "ferma il sito di prova",
"detail": "A fine debug: chiude l'attività «sito di prova» con l'input fermaIlSitoDiProva (comando workbench.action.tasks.terminate); echo stampa solo il suo argomento",
"type": "process",
"command": "echo",
"args": ["${input:fermaIlSitoDiProva}"],
"windows": { "command": "cmd.exe", "args": ["/d", "/c", "echo", "${input:fermaIlSitoDiProva}"] },
"hide": true,
"problemMatcher": [],
"presentation": { "reveal": "never", "echo": false, "close": true }
},
{
"label": "solo su Linux",
"detail": "Ferma una configurazione che gira solo su Linux",
"type": "process",
"command": "sh",
"args": [
"-c",
"echo 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb.' >&2; exit 1"
],
"windows": {
"command": "powershell.exe",
"args": [
"-NoProfile",
"-NonInteractive",
"-Command",
"Write-Host 'Questa configurazione gira solo su Linux: il browser di Febe Server è Chromium su Xvfb. Su Windows usa «Febe per Windows · sito di prova».'; exit 1"
]
},
"hide": true,
"problemMatcher": []
},
{
"label": "solo su Windows",
"detail": "Ferma una configurazione che gira solo su Windows",
"type": "process",
"command": "sh",
"args": [
"-c",
"echo 'Questa configurazione gira solo su Windows: Febe per Windows è WPF e WebView2. Su Linux usa «Febe Server · sito di prova (solo Linux)».' >&2; exit 1"
],
"hide": true,
"problemMatcher": []
}
],
"inputs": [
{
"id": "filtroDelleProve",
"type": "promptString",
"description": "Filtro di dotnet test, per esempio FullyQualifiedName~Febe.Tests.Docs (oppure solo una parte del nome: IconTests)",
"default": "FullyQualifiedName~Febe.Tests.Docs"
},
{
"id": "fermaIlSitoDiProva",
"type": "command",
"command": "workbench.action.tasks.terminate",
"args": "sito di prova"
}
]
}
+51
View File
@@ -1,5 +1,56 @@
# Novità
## 0.1.2 (in preparazione)
Sviluppo e qualità:
- **Pulizia della CI**: oltre a ciò che crea, la CI toglie ciò che non serve più a nessuno sul demone Docker del runner.
Dopo ogni lavoro «immagine» se ne vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore.
Ogni lunedì se ne vanno le immagini che nessun contenitore usa e la cache più vecchie di 24 ore, i resti dei lavori di
act_runner e, con `REGISTRY_TOKEN`, le `:sha-` del registro oltre le 10 più recenti (mai `:main`, `:latest` o una
versione). Non tocca mai un contenitore, un volume o una rete che non sia della CI. A mano, «Solo prova» elenca che
cosa toglierebbe senza togliere nulla (`docs/processo.md`, «Pulizia»).
- Immagine Docker: si pubblica come manifest semplice, senza attestazioni, così togliere un'etichetta dal registro ne
libera davvero gli strati.
## 0.1.1
Versione correttiva: **Febe per Windows si collega**. Con la 0.1.0 il browser di Febe non diventava mai pronto e
l'accesso a Instagram non poteva cominciare.
Correzioni:
- **Febe per Windows**: il browser di Febe parte al primo tentativo. Prima WebView2 partiva, ma subito dopo veniva
toccato fuori dal suo thread; l'errore era scambiato per un avvio fallito, e il browser veniva chiuso e riavviato
per sempre.
- Febe per Windows: un «Scollega» premuto durante un nuovo tentativo di avvio poteva lasciare due browser nella finestra
e la sessione sul disco. «Esci» non resta più fermo dietro un avvio di WebView2.
- Collegamento: prima del primo giro il pannello dice «Collegato» e «Nome non ancora noto», non più «Collegato come @».
- Storico: la fine dello storico di un account dà una sola riga negli Avvisi, con il testo intero. Lo storico si chiude
anche se subito dopo l'ultima pagina arrivano un segnale, un'interruzione o il controllo del profilo: prima l'account
restava «Storico in corso» per sempre.
- Vista remota (Docker): aprirne una mentre un'altra la sostituisce, o mentre la pagina sta cambiando, non dà più «Il
browser di Febe non risponde».
- Libreria: al primo avvio poteva restare su «La libreria è ancora vuota» invece del benvenuto con «Collegati a
Instagram», se lo stato del motore arrivava dopo quello della libreria. Ora aspetta di sapere se Febe è collegato.
Sviluppo e qualità:
- **CI a ogni push e a ogni unione** (`docs/processo.md`):
- controlli e gitleaks;
- tutte le prove con Chromium vero e dati sintetici, con un seme diverso a ogni esecuzione;
- installatore per Windows;
- immagine Docker provata senza rete e scansionata con Trivy.
Dopo ogni unione in `main` l'immagine esce come `:main` e `:sha-<commit>`. Ogni esecuzione toglie ciò che ha creato,
e c'è una pulizia settimanale.
- **Sviluppo da VS Code**: attività e configurazioni di debug in `.vscode/` (guida, «Sviluppo» ▸ «Da VS Code»).
- Prove: `tests/Febe.Tests` verdi anche su Windows, e prove nuove con WebView2 vero in `tests/Febe.Tests.Windows`. Due
prove che la CI ha fatto girare per la prima volta con Chromium vero fallivano a volte, e ora sono stabili: la vista
remota durante un cambio di pagina (#3, un difetto del prodotto, corretto) e il pulsante Indietro con modifiche non
salvate (#5, la prova passava per caso).
- Sito di prova: `/benvenuto`, la pagina di accesso che Febe apre in sviluppo.
## 0.1.0
Prima versione, **anteprima**: il programma è completo e provato contro il sito di prova locale, ma non ha mai
+7 -1
View File
@@ -10,6 +10,7 @@ All'inizio di ogni sessione leggi docs/stato.md.
- Avviare in modalità dimostrativa: `dotnet run --project src/Febe.Server -- --demo`
- Simulare il motore: `dotnet run --project src/Febe.Server -- --simula 30g --profilo prudente`
- Immagine Docker: `docker build -f docker/Dockerfile -t febe .`
- Da VS Code: attività e configurazioni di debug in `.vscode/` (guida: `docs/guida/Sviluppo.md`, «Da VS Code»); Febe per Windows di sviluppo tiene i dati in `%USERPROFILE%\FebeSviluppo\<cartella del checkout>`, mai in `%LOCALAPPDATA%\Febe`.
## Regole che non si discutono (specifica §2)
1. IMPORTANTE: non contattare mai Instagram da prove, script o verifiche tue. Si usa solo tools/Febe.SitoDiProva. Le prove dal vivo le lancia Alberto.
@@ -38,6 +39,11 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande
## Repository e rilascio
- Repository: Gitea di casa, https://gitea.encke-hake.ts.net/Alby96/Febe (ramo main). Non è GitHub: niente strumenti GitHub.
- CI in `.gitea/workflows/`: `verifica.yml` a ogni push e pull request, `rilascio.yml` a ogni tag `vX.Y.Z` (immagine Docker sul registro di Gitea, installatore Windows e release).
- Processo (rami `<tipo>/<argomento>`, commit piccoli, una richiesta di unione per ramo, verifica verde per unire in main, commit di unione, rilasci, correzioni urgenti): docs/processo.md.
- CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`:
- `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.<numero>`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-<commit>` (con il segreto `REGISTRY_TOKEN`; senza, un avviso).
- `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release.
- `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore.
- Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera.
- La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
- Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`).
+1 -1
View File
@@ -1,7 +1,7 @@
<Project>
<!-- Proprietà comuni a tutti i progetti di Febe. La versione si cambia solo qui. -->
<PropertyGroup>
<Version>0.1.0</Version>
<Version>0.1.1</Version>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion>
<Nullable>enable</Nullable>
+1
View File
@@ -11,6 +11,7 @@
</Folder>
<Folder Name="/tests/">
<Project Path="tests/Febe.Tests/Febe.Tests.csproj" />
<Project Path="tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj" />
</Folder>
<Folder Name="/tools/">
<Project Path="tools/Febe.Sonda/Febe.Sonda.csproj" />
+1 -1
View File
@@ -6,7 +6,7 @@ Febe non costruisce richieste verso Instagram: usa un browser vero, in cui Alber
> Scaricare con un programma è contro le condizioni d'uso di Instagram. Febe va piano per ridurre il rischio per l'account, ma non può azzerarlo.
**Stato: versione 0.1.0, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
**Stato: versione 0.1.1, anteprima.** Il programma è completo e provato contro un sito di prova locale; prima di usarlo su Instagram serve la sonda di M0 (vedi [docs/stato.md](docs/stato.md)).
## Documenti
+20 -13
View File
@@ -7,7 +7,10 @@
# -t 192.168.30.23:3000/alby96/febe:0.1.0 .
#
# Stadi:
# build restore e compilazione di tutta la soluzione con gli avvisi come errori;
# progetti solo i file che il restore legge (soluzione, props, progetti), trovati da soli: un progetto nuovo in
# Febe.slnx non chiede di cambiare questo file;
# build restore (in cache finché quei file non cambiano) e compilazione di tutta la soluzione con gli avvisi come
# errori;
# test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove
# con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo);
# publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET;
@@ -18,24 +21,25 @@
ARG DOTNET_VERSION=10.0
# ─────────────────────────────────────────────────────────────── progetti
# I file che il restore legge, ciascuno nella sua cartella. Questo stadio rigira a ogni modifica, ma il suo risultato
# cambia solo con loro: la copia nello stadio build, e quindi il restore, restano in cache (BuildKit confronta il
# contenuto). Un progetto aggiunto a Febe.slnx (per esempio tests/Febe.Tests.Windows) arriva qui senza toccare il file.
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS progetti
WORKDIR /src
COPY . .
RUN mkdir -p /progetti \
&& find . -type f \( -name '*.slnx' -o -name '*.csproj' -o -name 'Directory.*.props' -o -name 'Directory.*.targets' \
-o -iname 'nuget.config' -o -name 'global.json' \) -exec cp --parents '{}' /progetti/ ';' \
&& test -f /progetti/Febe.slnx
# ─────────────────────────────────────────────────────────────── build
FROM mcr.microsoft.com/dotnet/sdk:${DOTNET_VERSION} AS build
WORKDIR /src
ENV DOTNET_NOLOGO=1 DOTNET_CLI_TELEMETRY_OPTOUT=1
# Prima i file di progetto: il restore resta in cache finché non cambiano.
COPY Directory.Build.props Directory.Packages.props Febe.slnx ./
COPY src/Febe.Core/Febe.Core.csproj src/Febe.Core/
COPY src/Febe.Data/Febe.Data.csproj src/Febe.Data/
COPY src/Febe.Browser/Febe.Browser.csproj src/Febe.Browser/
COPY src/Febe.Web/Febe.Web.csproj src/Febe.Web/
COPY src/Febe.App/Febe.App.csproj src/Febe.App/
COPY src/Febe.Server/Febe.Server.csproj src/Febe.Server/
COPY src/Febe.Desktop.Core/Febe.Desktop.Core.csproj src/Febe.Desktop.Core/
COPY src/Febe.Desktop/Febe.Desktop.csproj src/Febe.Desktop/
COPY tests/Febe.Tests/Febe.Tests.csproj tests/Febe.Tests/
COPY tools/Febe.Sonda/Febe.Sonda.csproj tools/Febe.Sonda/
COPY tools/Febe.SitoDiProva/Febe.SitoDiProva.csproj tools/Febe.SitoDiProva/
COPY --from=progetti /progetti/ ./
RUN dotnet restore Febe.slnx \
&& dotnet restore src/Febe.Server/Febe.Server.csproj -r linux-x64
@@ -73,8 +77,11 @@ LABEL org.opencontainers.image.title="Febe" \
# Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e
# le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua
# italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID.
# Prima gli aggiornamenti di sicurezza della distribuzione già pubblicati, anche quelli arrivati dopo l'immagine di
# base: la scansione della CI non deve trovare correzioni disponibili e non applicate.
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update \
&& apt-get upgrade -y --no-install-recommends \
&& apt-get install -y --no-install-recommends \
chromium chromium-l10n \
xvfb \
+62
View File
@@ -226,3 +226,65 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15).
| 2026-10-13 | Prove dell'interfaccia in un Chromium senza finestra guidato col protocollo DevTools diretto (`UiBrowser`, solo 127.0.0.1), inconcludenti senza Chromium | Come `tools/schermate`; il client CDP di Febe accetta solo letture |
| 2026-10-14 | Revisione avversaria di tutto il codice (7 aree, ogni rilievo verificato da un secondo revisore indipendente): 54 rilievi confermati e corretti con prove di regressione, 2 smentiti, 3 incerti corretti dove il rimedio era sicuro | §14, regola 14: resoconti onesti |
| 2026-10-14 | Restano noti e accettati: «Tieni il più grande» scrive con il proprio SafeFileWriter e non passa dal lucchetto per account di `LibraryIngest` (un'importazione e uno scaricamento con gli stessi byte nello stesso istante potrebbero entrare entrambi); le prove d'interfaccia con browser vero aspettano fino a 30 s | Finestra rarissima, nessuna perdita di dati: al più un doppione esatto da togliere a mano |
| 2026-10-20 | Il seme del mondo sintetico del sito di prova si sceglie con la variabile `FEBE_SEME_PROVA` (13 se manca), letta da `SyntheticSite` (`tests/Febe.Tests/Support`), l'unico modo in cui le prove avviano il sito; le classi che lo avviano stanno nella categoria `SitoDiProva`, e una prova controlla che nessuna lo avvii per altre vie o resti fuori dalla categoria. `SyntheticSiteSeedTests` controlla senza browser, per 300 semi, la forma del mondo su cui contano le prove d'insieme e i lettori sulle pagine servite | La CI rifà quelle prove con un seme diverso a ogni esecuzione, scritto nel registro, senza raddoppiare la durata di tutta la suite; senza la variabile non cambia nulla; un errore si rifà con lo stesso seme |
| 2026-10-20 | Dockerfile: i file che il restore legge (soluzione, `Directory.*.props`, progetti) si trovano da soli in uno stadio `progetti` invece che da un elenco scritto a mano; lo stadio finale applica gli aggiornamenti della distribuzione (`apt-get upgrade`) prima di installare i pacchetti | Un progetto nuovo in `Febe.slnx` (come `tests/Febe.Tests.Windows`) non rompe più la costruzione dell'immagine e il restore resta in cache (BuildKit confronta il contenuto copiato); la scansione Trivy della CI non deve trovare correzioni di Debian già pubblicate ma non applicate perché l'immagine di base è più vecchia |
| 2026-10-20 | Codice comune della CI in script di `.gitea/scripts/` (lanciati con `bash`), non in azioni composite locali | Uno script si prova con `bash -n` nel lavoro «controlli» e si lancia anche a mano; le azioni composite di act hanno comportamenti propri (ambiente, `if`, passi finali) che qui non si possono provare prima della prima esecuzione vera |
| 2026-10-20 | Strumenti esterni della CI: solo gitleaks 8.30.1 e Trivy 0.75.0 (approvati da Alberto il 20 ottobre, solo nella CI), scaricati dalle release come binari e installati solo se l'impronta SHA-256 scritta in `strumento.sh` coincide (verificata sull'archivio, sul file `*_checksums.txt` e sull'impronta mostrata da GitHub); nessuna azione di terzi per eseguirli | `trivy-action` e `setup-trivy` furono compromesse a marzo 2026 (CVE-2026-33634, Trivy 0.69.4–0.69.6): un'etichetta si sposta, un'impronta no. Trivy 0.75.0 e non 0.76.0: almeno due settimane di vita prima di entrare nella CI |
| 2026-10-20 | gitleaks su tutta la storia del commit verificato (`fetch-depth: 0`, ogni commit da cui discende; ogni ramo si controlla al suo push, così il rilievo di un ramo non blocca gli altri) con `--redact`; nessun `.gitleaks.toml` né elenco di eccezioni per ora: un'approssimazione locale delle 221 regole predefinite (le espressioni regolari pubblicate, applicate da uno script nostro: gitleaks non gira fuori dalla CI) non ha trovato rilievi veri, e i gettoni finti delle prove non hanno la forma completa che le regole cercano | Un falso allarme futuro si toglie con la sua impronta in `.gitleaksignore` e un commento accanto, mai disattivando una regola; un segreto vero si revoca prima di tutto (`docs/processo.md`) |
| 2026-10-20 | Trivy sull'archivio dell'immagine provata (non dal demone): una vulnerabilità CRITICAL con correzione disponibile ferma il lavoro, le HIGH (e le CRITICAL senza correzione) si riportano nel registro e in `trivy.json` (artefatto di 14 giorni); eccezioni solo in `.trivyignore`, con motivo scritto e scadenza `exp:` | La regola chiesta da Alberto; scansionare l'archivio vuol dire scansionare proprio l'immagine provata, senza dipendere dal socket del demone |
| 2026-10-20 | La prova del contenitore (`prova-immagine.sh`) gira sempre con `--network none`: Chromium, criteri, lingua, poi l'avvio come da guida (profilo seccomp, password casuale passata solo nell'ambiente del client) fino a «healthy», `febe --controllo-salute` e l'arresto entro 30 secondi | Regola 1: un'immagine appena costruita non deve poter raggiungere Instagram nemmeno per sbaglio; il controllo di salute passa dalla rete interna del contenitore |
| 2026-10-20 | Le etichette `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref`, `febe.ci.commit` dell'immagine dicono solo da dove viene; `pulizia-docker.sh` sceglie che cosa togliere da segni che nessuna immagine porta: contenitori di prova con l'etichetta `febe.ci.prova=<esecuzione>` (messa solo da `docker run --label` in `prova-immagine.sh`) e il nome esatto `febe-prova-<esecuzione>`; immagini solo per il nome locale `febe-ci:<esecuzione>`, mai per identificativo né con `-f`; builder per nome esatto e immagine `moby/buildkit`. Alla fine di ogni lavoro tutto ciò dell'esecuzione; all'inizio del lavoro successivo e ogni settimana i resti più vecchi di 90 minuti, ma dei contenitori di prova solo quelli fermi (uno acceso si segnala); più le immagini senza nome oltre 72 ore. Mai `system prune`, `builder prune`, `volume prune`. `PipelineTests` fa girare la pulizia contro un client Docker finto con un Febe vero acceso e uno fermo | Docker copia le etichette dell'immagine in ogni contenitore: un Febe vero avviato da `:main`, `:X.Y.Z` o `:latest` sullo stesso demone porta `febe.ci.run`, e un rilascio rilanciato ha lo stesso numero di esecuzione dell'immagine pubblicata (rilievo bloccante della revisione). Il demone è lo stesso di Encelado, Mimante e degli altri progetti; un lavoro dura al massimo 60 minuti, quindi un resto di 90 minuti è orfano; i builder sono sempre accesi e la loro cache se ne va solo con il contenitore |
| 2026-10-20 | `verifica` a ogni push su qualunque ramo (`branches: ["**"]`, quindi mai sui tag) e a mano (`workflow_dispatch`, con un seme facoltativo); niente `pull_request` | In Gitea i controlli di una richiesta di unione sono gli stati del suo ultimo commit, che il push del ramo ha già verificato; `pull_request` girerebbe sullo stesso commit (`refs/pull/N/head`, non un'unione di prova) e sull'unico runner raddoppierebbe tutto. Niente richieste da fork: un solo autore, rami nello stesso repository |
| 2026-10-20 | Concorrenza di `verifica`: il gruppo comprende l'evento e il ramo; su un ramo l'esecuzione nuova annulla quella in corso dello stesso evento; su main ogni commit ha il suo gruppo e nessuna si annulla; `:main` si sposta solo se main è ancora a quel commit, e se la cima di main non si legge si pubblica solo `:sha-` con un avviso | Il runner fa un lavoro alla volta; ogni unione in main deve arrivare a pubblicare la sua `:sha-`, e un'esecuzione in ritardo non deve riportare indietro `:main`. Con l'evento nel gruppo un'esecuzione a mano non annulla quella del push: in Gitea un lavoro annullato lascia lo stato «failure» e `workflow_dispatch` non scrive stati, quindi la richiesta di unione resterebbe bloccata. Gitea 28 valuta le espressioni di `concurrency.group` e `cancel-in-progress` (`services/actions/concurrency.go`) |
| 2026-10-20 | Lavoro «prove» nel contenitore `node:24-trixie` (Debian 13 con Node 24), con Chromium, Xvfb, ffmpeg, NSIS e la lingua italiana installati a ogni esecuzione; il riepilogo non ammette prove saltate; seconda passata della categoria `SitoDiProva` con il seme 1000 + numero dell'esecuzione, o quello chiesto a mano | Su Ubuntu Chromium è uno snap; le azioni JavaScript girano dentro il contenitore del lavoro e vogliono Node; un'immagine di CI costruita da noi non può fare da contenitore del lavoro, perché act_runner la scaricherebbe da un registro e quello di casa è in HTTP; nella CI una prova saltata vuol dire un ambiente rotto, non una prova superata |
| 2026-10-20 | Installatore di ogni esecuzione con versione `<Version>-ci.<numero>` e immagine con etichetta `org.opencontainers.image.version` uguale; dopo ogni unione in main l'immagine va sul registro come `:main` e `:sha-<7 caratteri>`, mai `:latest`, che resta del rilascio | Decisione di Alberto del 20 ottobre; la versione di prova non si confonde con una versione rilasciata e `installer/costruisci.sh` la accetta già |
| 2026-10-20 | Artefatti con `actions/upload-artifact@v3` e `retention-days: 14` (risultati delle prove, installatore e zip, rapporti di sicurezza) | La v4 rifiuta di girare dove il server non è github.com (prende Gitea per GHES) e la sua copia per Gitea sarebbe un'azione nuova, non approvata; il backend v3 di Gitea 28 rispetta `retentionDays` (`routers/api/actions/artifacts.go`) |
| 2026-10-20 | `permissions: contents: read` in `verifica` e `pulizia`; i riepiloghi delle prove e di Trivy vanno nel registro e anche in `GITHUB_STEP_SUMMARY` | Gitea 28 applica `permissions` al gettone del lavoro (docs.gitea.com, «Actions job token permissions»), che così non può scrivere nel repository; i riepiloghi dei lavori esistono da Gitea 1.27 ma compaiono solo se il runner li carica, quindi il registro resta la fonte |
| 2026-10-20 | Ciò che la CI usa di Gitea 28 e di act_runner: `concurrency` con espressioni, `timeout-minutes` dei lavori (lo applica il runner), `workflow_dispatch` con `inputs`, `schedule`, `defaults.run.shell`, `container` del lavoro, contesti `gitea.*`, `vars` e `secrets`; gli stati dei commit si chiamano «verifica / <lavoro> (push)» (`modules/actions/workflows.go`) e solo push, pull_request e release ne creano | Controllato sul codice di Gitea `release/v28` e su docs.gitea.com il 20 ottobre 2026; ciò che solo la prima esecuzione vera può provare è in `docs/processo.md` |
| 2026-10-20 | Processo in `docs/processo.md`: rami `<tipo>/<argomento>` da `main`, commit piccoli in italiano, una richiesta di unione per ramo con il modello di `.gitea/` (comprese le 14 regole di §2), unione con commit di unione e ramo cancellato; `main` protetto con i quattro lavori di `verifica` come controlli richiesti e «blocca se indietro»; tag `v*` protetti; Alberto proprietario di tutto (`CODEOWNERS`) | Decisione di Alberto del 20 ottobre (processo da grande azienda); con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato, quindi in `main` entra solo codice provato. Le approvazioni richieste dipendono da chi apre le richieste (Gitea non conta quella dell'autore): domanda aperta per Alberto |
| 2026-10-20 | Nella verifica il lavoro «immagine» viene dopo «prove» e «installatore» (`needs: [prove, installatore]`) | `:main` e `:sha-` devono uscire solo da un commit con tutta la verifica verde, come dice `docs/docker.md`; sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. Su un ramo, se l'installatore fallisce l'immagine si salta: la richiesta di unione è già bloccata dall'installatore |
| 2026-10-20 | Anche nel rilascio il lavoro «immagine» viene dopo «prove» e «windows» (`needs: [prove, windows]`) | Come nella verifica: `:X.Y.Z` e `:latest` si pubblicano solo se anche la release potrà uscire; prima, con l'installatore rosso, l'immagine usciva senza release |
| 2026-10-20 | Nuovo progetto di prove `tests/Febe.Tests.Windows` (`net10.0-windows`, WPF, solo MSTest e riferimenti ai progetti, nella soluzione): WebView2 vero su un thread STA con un `Dispatcher` di WPF vero, il sito di prova in processo; si compila anche da Linux (`EnableWindowsTargeting`), gira solo su Windows, senza runtime WebView2 è inconcludente | L'errore che bloccava Febe per Windows (14 e 19 ottobre) si vedeva solo con WebView2 vero e un thread dell'interfaccia vero: le prove su Linux con il finto `IWebView2DevTools` non potevano coglierlo |
| 2026-10-20 | `WebView2Host` legge sul thread dell'interfaccia, durante l'avvio, i valori che servono altrove (versione di WebView2, numero del processo del browser) e li espone come valori semplici; nessun membro di un oggetto di WebView2 si legge fuori da quel thread | Causa dell'errore: `Version` leggeva `BrowserVersionString` dell'ambiente da un thread del pool, dopo `ConfigureAwait(false)`, e WebView2 lanciava `InvalidOperationException` |
| 2026-10-20 | Nel ciclo di avvio di `WebView2Browser` si riprova solo l'eccezione dell'avvio stesso: stato e riga «Browser di Febe pronto» stanno fuori dal blocco dei tentativi | La riga del registro, dentro il `try`, trasformava ogni avvio riuscito in un avvio fallito: chiusura del WebView buono e nuovi tentativi per sempre |
| 2026-10-20 | Avvio, ripartenza e arresto di `WebView2Host` uno alla volta (un `SemaphoreSlim` preso sul thread dell'interfaccia); l'arresto aspetta al più 30 s chi è in corso, poi chiude quello che c'è | Ognuno aspetta WebView2 sul thread dell'interfaccia e fra un'attesa e l'altra potevano intrecciarsi (per esempio una ripartenza dopo un arresto del processo e «Scollega»); l'uscita da Febe non deve restare appesa a un avvio che WebView2 non completa |
| 2026-10-20 | Arresto del processo del browser: annunciato solo dopo che il gestore di `ProcessFailed` è tornato e solo per il WebView in uso (numero di generazione); se capita durante un avvio fa fallire quell'avvio; la ripartenza (e quella dopo un «Scollega» la cui ripartenza fallisce) usa gli stessi tentativi del primo avvio, un solo ciclo alla volta sul pool | Modello dei thread di WebView2: niente chiusure né ricreazioni dentro i suoi gestori. Prima: un solo tentativo, poi browser morto fino al riavvio di Febe; dopo «Scollega» restava fermo anche il motore, perché l'errore non era di cartella e `DisconnectAsync` non lo gestiva |
| 2026-10-20 | `WebView2CdpSession.Attach` chiama i gestori di `Reconnected` uno per uno: l'errore di uno va nel registro e non esce da `Attach` (l'avviso resta sincrono) | `Attach` è dentro l'avvio del nuovo WebView: un'eccezione di chi ascolta avrebbe disfatto un avvio riuscito, ancora e ancora |
| 2026-10-20 | La finestra dell'interfaccia apre gli indirizzi esterni nel browser predefinito dopo che il gestore di WebView2 è tornato (in coda sul dispatcher) | La shell di Windows può far girare un ciclo di messaggi suo e WebView2 non regge di essere richiamato dentro i propri gestori |
| 2026-10-20 | Le prove per Windows hanno un `CompressedClock` e un fuso «mezzogiorno» propri, copie di quelli della suite per Linux; `Febe.Desktop` concede gli `internal` a `Febe.Tests.Windows` e `WebView2Host` espone la sua finestra come `internal` (da leggere sul thread dell'interfaccia) | Un progetto di prove non può dipendere dall'altro; la finestra serve alle prove del primo piano e del fuori vista |
| 2026-10-20 | Un solo WebView alla volta in `WebView2Host`: l'avvio, dentro la sezione esclusiva, non fa nulla se un WebView è già collegato, chiude prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato (il ciclo dei tentativi non chiude più niente da fuori); la ripartenza dopo un arresto del processo usa lo stesso avvio; chiudere un WebView ne cambia la generazione, così i suoi eventi tardivi non contano | Revisione del ramo: un «Scollega» durante i tentativi del primo avvio faceva partire il browser, poi il tentativo in attesa ne apriva un secondo nella stessa finestra senza chiudere il primo. Il processo orfano teneva il profilo: il «Scollega» dopo aspettava 20 s e non cancellava la sessione di Instagram, l'uscita aspettava 15 s a vuoto |
| 2026-10-20 | All'uscita il primo avvio e il ciclo di ripartenza di `WebView2Browser` smettono subito di aspettare WebView2: `WebView2Host.StartAsync` onora il suo token (un avvio non ancora cominciato non comincia, uno in corso finisce da sé e l'arresto chiude ciò che lascia, anche se arriva dopo i 30 s); `WebView2Browser.DisposeAsync` aspetta il ciclo al più 30 s. «Scollega», una volta cominciato, va fino in fondo e resta coperto dai 30 s dell'arresto | Revisione del ramo: il limite di 30 s copriva solo un «Scollega» in corso. `FebeApp` aspetta `RunAsync` prima di chiudere il browser, e `RunAsync` e il ciclo aspettavano WebView2 senza limite; interrompere «Scollega» a metà lascerebbe invece fermo il motore |
| 2026-10-20 | Collegamento, pannello «collegato» senza nome dell'account (subito dopo «Ho finito», prima del primo giro): titolo «Collegato» e sotto «Nome non ancora noto», come il riquadro di stato | Provando a mano su Windows la pagina diceva «Collegato come @»; il mockup 10 mostra solo il caso con il nome |
| 2026-10-20 | Prove portabili fra Linux e Windows: i percorsi attesi si calcolano come li calcola il sistema (`Path.GetFullPath` per il profilo del browser e per `/importa`, `LibraryLayout.ToStored` per il percorso mostrato in Docker) invece di essere scritti alla Linux | Febe per Windows gira su Windows e le prove devono passare dove gira il prodotto; su Linux il testo atteso è identico a prima, quindi lì non cambia nulla |
| 2026-10-20 | Prova della cartella dei dati su una condivisione: su Linux il montaggio cifs iniettato come prima, su Windows un percorso UNC verso `febe-prova.invalid`, riconosciuto dalla sola forma; il controllo «niente scritto nella cartella dei dati» resta solo su Linux | Stesso comportamento sui due sistemi, ognuno con il suo modo di riconoscere la rete (su Windows non c'è tabella dei montaggi); guardare dentro un UNC vorrebbe dire interrogare la rete, e un nome `.invalid` (RFC 6761) non risponde mai |
| 2026-10-20 | `TestLibrary.LoseDatabaseAsync`: su Windows un'eliminazione che trova il file in uso da un altro programma (`0x80070020`) si ripete ogni 50 ms, per al più 5 s | Su Windows un file aperto da un altro programma non si elimina. Su questo PC, con Defender attivo, succedeva circa 3 volte su 40 esecuzioni di `Febe.Tests.Library`: il file era libero dopo 6–17 ms e il Restart Manager non vedeva nessun processo che lo tenesse, quindi non è un collegamento di Febe rimasto aperto. Su Linux eliminare un file aperto riesce sempre e non si ripete nulla |
| 2026-10-20 | Prova di `costruisci.sh`: su Windows prima Git Bash (accanto a git sul PATH, poi nelle cartelle del suo installatore), altrimenti un bash sul PATH che non sia il lanciatore di WSL (`System32\bash.exe`, alias in `WindowsApps`); senza bash la prova è inconcludente invece di passare in silenzio | Dal PATH di PowerShell il primo bash è il lanciatore di WSL, che senza distribuzione fallisce («execvpe(/bin/bash) failed») e non vede lo script col percorso di Windows; su Linux si usa come prima il primo bash sul PATH |
| 2026-10-20 | «Storico completato» lo scrive solo il motore (`SessionComposer.FinishBackfillAsync`: @nome, post in libreria, che cosa succede ora); la ricetta Storico non scrive più una riga sua. Il motore chiude lo storico ogni volta che il cammino è arrivato in fondo (`BackfillFinished`), anche se poi la corsa finisce con un segnale o un'interruzione | Due righe nella cronologia e in «Avvisi» per lo stesso storico (@marta.prova, 14:31): la corta della ricetta e quella del motore. La notifica era già una sola e col testo del motore, perché la riga della ricetta (`CollectionWriter.EventAsync`) non passa da `EngineEvents` e `AlertService` non la vede. Con un segnale subito dopo l'ultima pagina l'account restava «Storico in corso» per sempre |
| 2026-10-20 | Anche lo storico completato dal controllo del profilo (profilo tutto nella prima pagina) lo chiude il motore, con la sua riga (`BackfillFinished` del controllo, solo per un account «Storico in corso»). A inizio sessione il motore chiude gli account rimasti «Storico in corso» con lo storico già completato; la fase dello Storico rilegge gli account invece di usare quelli di inizio sessione | Con due account «Storico in corso» quello piccolo restava così per sempre, senza riga né avviso: dalla sessione dopo non era più candidato dello Storico. Rileggere gli account evita una seconda riga quando lo Storico della stessa sessione sceglierebbe proprio quello appena chiuso |
| 2026-10-20 | Quando chiude uno storico, il motore toglie subito dalla coda il suo «Storico» e, se l'account resta in pausa, gli altri compiti pianificati; non rimette in coda la corsa dello Storico arrivata in fondo e poi fermata da un segnale | La Coda mostrava fino alla sessione dopo (dopo una verifica, fino a «Riprendi») uno Storico da fare per un account già «Aggiornato» o «In pausa». I comandi di Alberto restano |
| 2026-10-20 | Vista remota: `Page.startScreencast` si manda di nuovo solo se Chromium risponde -32000 «Not attached to an active page», con pause da 100 a 500 ms e per al più 5 s di orologio vero (`ScreencastSession.InactivePageBudget`); collegamento chiuso, nessuna risposta o qualunque altro rifiuto danno subito «Il browser di Febe non risponde». Nessun comando CDP nuovo | Issue #3. Dal `ReadyToCommitNavigation` di una navigazione con un nuovo RenderFrameHost fino al suo commit, DevTools punta già al documento nuovo non ancora attivo e i comandi di pagina gestiti dal browser falliscono così (`page_handler.cc`, `AssureTopLevelActiveFrame`); con RenderDocument, attivo in Chromium, vale per ogni navigazione, anche verso la pagina di riposo. Ci cadevano la vista aperta insieme alla pagina di accesso, dopo un riposo del motore o durante una sessione |
| 2026-10-20 | Sostituzione di una vista remota: `BrowserRemoteViewHost.OpenAsync` tiene un permesso «Alberto usa il browser» di passaggio dalla fine della vista vecchia all'avvio della nuova; l'ospite della vista usa `IFebeBrowser` invece di `ChromiumBrowser` | Fra le due viste i permessi scendevano a zero: il motore si svegliava e riportava la pagina a riposo proprio mentre la vista nuova avviava i fotogrammi (il fallimento della CI, issue #3), e avrebbe potuto cominciare una sessione. L'interfaccia permette di provarlo senza browser |
| 2026-10-20 | Prova con Chromium vero del ritentativo della vista remota (`RemoteViewDuringNavigationTests`): una pagina del sito locale delle prove (`/occupata`) tiene occupato il renderer per 2 s, così la navigazione verso un'altra pagina dello stesso sito resta fra «ready to commit» e il commit e `Page.startScreencast` ci cade apposta; se in nessun giro Chromium rifiuta il primo avvio, la prova risulta inconcludente e non superata | Revisione dell'issue #3: TwoViews… prova solo il permesso di passaggio, e una vista aperta dall'ospite dopo l'inizio di una navigazione non incontra il rifiuto (`Page.getFrameTree` risponde solo dopo il commit). Con Chrome 155 sulla macchina di sviluppo, in un esperimento a parte con lo stesso codice di Febe, il rifiuto è arrivato in 18 giri su 18 e la vista si è aperta al sesto tentativo; con il testo atteso cambiato la stessa sequenza fallisce. Verso about:blank da una pagina del sito il commit avviene in un altro renderer: quel caso non serve allo scopo |
| 2026-10-20 | VS Code: configurazione condivisa in `.vscode/` (`launch.json`, `tasks.json`, `extensions.json`, `settings.json` con la sola `dotnet.defaultSolution`); debug con il tipo `coreclr` dell'estensione C#, che non legge `launchSettings.json` (lo cerca in `{cwd}/Properties`, e `cwd` è la radice del repository) | Il tipo `dotnet` del C# Dev Kit accetta solo il progetto e un profilo di `launchSettings.json`: niente argomenti, variabili d'ambiente, attività prima e dopo, `serverReadyAction`. Con `coreclr` tutto sta in un file solo |
| 2026-10-20 | Febe per Windows di sviluppo da VS Code con `--dati %USERPROFILE%\FebeSviluppo\<checkout>\dati` e `--libreria %USERPROFILE%\FebeSviluppo\<checkout>\libreria` (`${workspaceFolderBasename}`: una cartella per checkout); il debug avvia `Febe.exe`, non `dotnet Febe.dll` | Mai la cartella vera `%LOCALAPPDATA%\Febe`; fuori dal repository perché profilo del browser e libreria crescono e non devono finire in un commit. Una per checkout perché il blocco contro le istanze doppie dipende dalla cartella dei dati (F5 in un secondo worktree mostrava il Febe del primo e finiva subito) e un database migrato da un ramo più nuovo non si apre con una versione più vecchia. Con `Febe.exe` il percorso del processo è quello di Febe e non di `dotnet.exe` (lo usa l'avvio con il computer) |
| 2026-10-20 | Attività di compilazione, prove e pubblicazione con `-tl:off -clp:ForceNoAlign` oltre al comando della guida | Registro classico, come nella CI: ogni errore su una riga sola, senza le righe che il terminal logger ridisegna nel terminale; `$msCompile` lo porta nel pannello Problemi (provato con un errore voluto) |
| 2026-10-20 | Il sito di prova è un'attività di sfondo, pronta alla riga «Sito di prova: http://» (`activeOnStart`, con `beginsPattern` «(?!)», che non trova mai nulla); a fine debug la ferma un input che esegue `workbench.action.tasks.terminate` | VS Code legge `activeOnStart`, non `activeBegins`: senza, il debug aspettava il sito per sempre. Con «(?!)» nessuna riga successiva rimette l'attività «al lavoro». VS Code non ha un'attività che ne chiuda un'altra: un input di tipo `command` è l'unico modo per farlo da `postDebugTask`. Limite noto: se il sito non è più in corso, il comando apre l'elenco delle attività da terminare (la guida dice di premere Esc) |
| 2026-10-20 | «Sito di prova + Febe per Windows» non è un compound: la configurazione del sito avvia Febe con `serverReadyAction` (`startDebugging`, `killOnServerStop`) quando il sito scrive di essere pronto | Un compound avvia tutto insieme e senza ordine: Febe con `--accesso-di-prova` poteva cercare il sito prima che ascoltasse |
| 2026-10-20 | Le configurazioni legate a un sistema (Febe per Windows; Febe Server con il sito di prova, cioè Chromium su Xvfb) sugli altri sistemi si fermano con un messaggio (attività «solo su Windows» e «solo su Linux»; il server riceve anche solo `--aiuto`) | VS Code non sa nascondere una configurazione per sistema operativo: le proprietà `windows`, `linux` e `osx` contano solo all'avvio |
| 2026-10-20 | «⚠ Febe per Windows · Instagram vero (dati veri)» chiede conferma prima di compilare e partire (una scelta sola, Esc annulla) | Regola 1: le prove dal vivo le lancia Alberto; un F5 distratto non deve aprire Instagram con l'account e il database veri |
| 2026-10-20 | Tutte le configurazioni di debug usano la Console di debug (`internalConsole`), mai il terminale integrato (Febe per Windows non ha una console: il suo registro resta nella cartella dei dati, `registro`); le attività sono di tipo `process`, senza shell | Il terminale integrato e le attività `shell` caricano il profilo di PowerShell: su questo PC il profilo attiva l'ambiente conda di Pinokio, che mette in testa al `PATH` e in `DOTNET_ROOT` un .NET senza SDK e con il solo runtime 8. Lì `dotnet build` non trova l'SDK e Febe (net10.0) non parte («You must install or update .NET»), né come `febe.dll` né come `febe.exe`. Console di debug e attività `process` usano l'ambiente di VS Code |
| 2026-10-20 | La dimostrazione da VS Code serve l'interfaccia dai sorgenti (`FEBE_INTERFACCIA`), apre da sola il browser (`serverReadyAction`) e su Windows tiene la cartella temporanea in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei` (`TEMP`, `TMP`) | Si modifica `wwwroot` e si ricarica senza ricompilare. Fermata dal debugger, la dimostrazione non può cancellare la sua cartella (una trentina di MB): così resta fra i dati di sviluppo invece di accumularsi in `%TEMP%` |
| 2026-10-20 | I file di `.vscode/` sono JSON rigido, senza commenti: le spiegazioni stanno nella guida (pagina «Sviluppo», «Da VS Code»), nei campi `detail` delle attività e in queste righe | Il controllo «File JSON» della CI legge ogni `*.json` tracciato con `JSON.parse`, e con i commenti `//` il lavoro «controlli» falliva a ogni push dopo l'unione. VS Code legge anche il JSON rigido, così il ramo non dipende da come la CI tratta i commenti |
| 2026-10-20 | `src/Febe.Desktop/Properties/launchSettings.json` con un solo profilo, «Sito di prova»: `--dati` e `--libreria` in `%USERPROFILE%\FebeSviluppo\comune`, `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo` | `dotnet run --project src/Febe.Desktop` e i comandi del C# Dev Kit (▷ «Debug project associated with this file», «Start New Instance», «C#: …») avviavano Febe senza opzioni: Instagram vero e dati veri, senza la conferma della configurazione ⚠. `dotnet run` e il Dev Kit leggono quel profilo ed espandono `%USERPROFILE%` (provato); se un altro strumento non lo facesse, Febe rifiuta il percorso non completo e non parte. Una cartella comune perché il file non conosce il checkout. Instagram vero dal terminale: `dotnet run --project src/Febe.Desktop --no-launch-profile` |
| 2026-10-20 | Le prove dell'interfaccia aspettano lo stato finale di una pagina, mai uno di passaggio come il mosaico vuoto che la Libreria mette sullo schermo prima della risposta di `/api/library/days` | Issue #5: `TheBackButtonAsksBeforeLosingUnsavedChanges` aspettava `.vuoto-pagina` o `.mosaico`, ma una libreria vuota con Febe non collegato finisce sul benvenuto; la prova passava solo se il primo controllo cadeva nei circa 10 ms in cui c'è il mosaico vuoto (provato con Chrome: con il primo controllo ritardato di 5 ms o più falliva sempre) |
| 2026-10-20 | Lo stato vuoto della Libreria senza filtri segue il collegamento finché è sullo schermo: se il motore risponde dopo la libreria, al suo arrivo compare il benvenuto del primo avvio; quando Febe si collega, il benvenuto lascia il posto alla libreria vuota. Si ridisegna solo quando cambia tipo. La prova trattiene `/api/engine` fino a un suo segnale e toglie `EventSource` (l'interfaccia ripiega su `/api/engine`) | Prima la scelta si faceva una volta sola, alla risposta della libreria: con il motore in ritardo il primo avvio mostrava la libreria vuota invece dei due pulsanti di §10.3, e ci restava (provato con Chrome trattenendo `/api/engine`). Un segnale invece di un ritardo: l'ordine delle risposte non dipende dalla velocità della macchina |
| 2026-10-20 | Finché lo stato del motore non è noto, la Libreria vuota senza filtri non mostra nessuno stato vuoto: un riquadro vuoto con `aria-busy`, come il mosaico mentre carica, che il primo stato del motore sostituisce con il benvenuto o con «La libreria è ancora vuota». La prova aspetta quel riquadro, il conteggio «0 …» e nessuno stato vuoto | Senza il motore non si sa se è il primo avvio: «La libreria è ancora vuota» mostrata nell'attesa era falsa al primo avvio e poi lasciava il posto al benvenuto con un salto della pagina (rilievo della revisione). Il riquadro della barra laterale dice già «Caricamento…» finché il motore non risponde, e il motore arriva comunque: il flusso `/api/eventi` lo manda appena si apre e, senza flusso, l'interfaccia lo richiede a intervalli |
| 2026-10-21 | La pulizia toglie anche ciò che non serve più a nessuno, di qualunque progetto, e non più solo ciò che è della CI di Febe. Alla fine di ogni lavoro «immagine» (verifica e rilascio), dopo la pulizia dell'esecuzione, `pulizia-docker.sh penzolanti`: `docker image prune -f` e `docker builder prune -f --filter until=24h` (senza `-a`), che non fa mai fallire il lavoro. Ogni lunedì e a mano `pulizia-docker.sh completa`: i resti della CI di Febe come prima, i resti di act_runner, `docker image prune -a -f --filter until=24h`, `docker builder prune -a -f --filter until=24h`, con `REGISTRY_TOKEN` le `:sha-` del registro oltre le 10 più recenti, `docker system df` prima e dopo e un riepilogo. Mai `system prune`, `container prune`, `volume prune`, `network prune`, né un contenitore, un volume o una rete che non sia della CI. Per ciò che nessuno usa sostituisce il «mai le immagini degli altri progetti, mai la cache di costruzione del demone, mai le immagini col nome del registro» del 20 ottobre | Decisione di Alberto del 21 ottobre: «aggiungi il prune delle immagini non più utilizzate nel workflow di Actions, in modo da eliminare tutto quello che non serve più». Docker stesso non toglie mai un'immagine usata da un contenitore, acceso o fermo, quindi le applicazioni di Unraid e un Febe vero tengono le loro; le 24 ore lasciano stare ciò che un'altra costruzione ha appena prodotto (per la cache contano dall'ultimo uso; per le immagini dipende dallo store, riga sullo store più sotto). Il prezzo è scritto in `docs/processo.md` («Pulizia»): le immagini di base si riscaricano, le costruzioni ritrovano meno cache, un'immagine costruita a mano e tenuta senza contenitore va ricostruita. `docker builder prune` senza `-a` toglie ciò che nessuna immagine condivide: BuildKit salta solo i record interni, del frontend e condivisi (`cache/manager.go`), quindi senza un limite d'età a ogni push di ogni ramo se ne andrebbero anche gli strati intermedi e le cache montate che le costruzioni degli altri progetti hanno appena usato, e la finestra di 24 ore del lunedì non servirebbe. Per questo anche dopo ogni esecuzione `until=24h`, che BuildKit confronta con l'ultimo uso (rilievo della revisione: il compito chiedeva il comando senza filtro, che non è innocuo per gli altri progetti; se Alberto lo preferisce, basta togliere il filtro) |
| 2026-10-21 | Resti di act_runner: contenitori fermi (`exited`, `created`, `dead`), volumi e reti il cui nome comincia con `GITEA-ACTIONS-TASK-<numero>` seguito da `_` o `-`, più vecchi di 90 minuti; volumi e reti solo se nessun contenitore, nemmeno fermo, li usa (`docker ps -a --filter volume=…` e `network=…`). Contenitori e volumi senza `-f`; il volume `act-toolcache` resta | act_runner dà a tutto ciò che crea per un lavoro il prefisso `GITEA-ACTIONS-TASK-<id del compito>` (`internal/app/run/runner.go`); act chiama il contenitore `<prefisso>_WORKFLOW-<flusso>_JOB-<lavoro>` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-<impronta>`), i volumi `<nome>` e `<nome>-env`, la rete `<nome>-<lavoro>-network`, e monta `act-toolcache`, la cache degli strumenti di tutti i lavori (`pkg/runner/run_context.go`; controllato su gitea.com il 21 ottobre). Un lavoro vivo ha il contenitore acceso e usa volumi e rete; i 90 minuti, come per i resti della CI di Febe, coprono l'istante in cui un lavoro che parte li ha creati e non ancora usati, se un giorno il runner farà più lavori insieme. Il `Created` di una rete si legge con `{{json .Created}}`: senza, il modello lo stampa nel formato di Go e non in RFC 3339 |
| 2026-10-21 | Registro: con `REGISTRY_TOKEN` la pulizia del lunedì toglie le etichette `sha-<da 7 a 40 cifre esadecimali>` del pacchetto container `febe` oltre le 10 più recenti per data di creazione, con l'API dei pacchetti di Gitea 28: `GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50` fino alla prima pagina vuota e `DELETE /api/v1/packages/{proprietario}/container/febe/{versione}` (risponde 204). Sceglie `.gitea/scripts/versioni-registro.js` (Node, senza rete, provato con `tests/Febe.Tests/Packaging/versioni-registro.json`); lo script ricontrolla la forma prima di ogni DELETE. Mai `main`, `latest`, `X.Y.Z` (anche `-rc.N`), i digest o altro; un rifiuto dell'API è un avviso, non un lavoro rosso; il token sta solo nell'intestazione di curl e non si stampa | Percorsi controllati sul codice di Gitea `release/v28` (`routers/api/v1/api.go`: `ListPackageVersions` e `DeletePackageVersion` nel gruppo `/packages/{username}`, con token e ambito «package»; `routers/api/v1/packages/package.go`: `page` e `limit`, versioni interne escluse, DELETE con 204) e su docs.gitea.com («List package versions», «Delete a package version»). In Gitea ogni etichetta di un contenitore è una versione del pacchetto con i suoi file: togliere `sha-…` non tocca `main` o una versione che puntano allo stesso manifest, e i blob rimasti senza riferimenti li toglie la pulizia dei pacchetti di Gitea (`[cron.cleanup_packages]`), purché l'immagine sia un manifest semplice e non un indice (riga seguente sulle attestazioni). Le versioni `sha256:…` senza etichetta non si toccano mai: si contano soltanto. Node e non jq: Node c'è in ogni contenitore dei lavori (lo usano le azioni) e nelle prove, jq non c'è in `node:24-trixie` né in Git Bash. Prende il posto della regola di pulizia dei pacchetti suggerita il 20 ottobre |
| 2026-10-21 | L'immagine di Febe si costruisce e si pubblica senza attestazioni: `--provenance=false --sbom=false` fra gli argomenti comuni di `.gitea/scripts/costruisci-immagine.sh` (l'archivio provato e la spinta sul registro), così sul registro ogni etichetta è un manifest semplice | Con il builder `docker-container` buildx aggiunge da sé l'attestazione di provenienza (`mode=min`; docs.docker.com, «Build attestations») e l'immagine spinta diventa un indice con due figli spinti per digest, l'immagine e l'attestazione. Gitea tiene ogni figlio come una versione a sé, `sha256:…` senza etichetta, a cui sono legati configurazione e strati (release/v28, `routers/api/packages/container/manifest.go`: `processOciImageManifest` lega i blob alla versione del manifest stesso con `createFileFromBlobReference`, `processOciImageIndex` salva solo l'indice e le proprietà `container.manifest.reference`), e togliere un'etichetta toglie solo i file di quella versione: gli strati sarebbero rimasti per sempre (rilievo della revisione). Con un manifest semplice gli strati stanno nella versione dell'etichetta, e quando nessuna versione li usa più li cancella `[cron.cleanup_packages]` (attiva per impostazione predefinita, `@midnight`, `OLDER_THAN = 24h`: `custom/conf/app.example.ini`). Si perde l'attestazione di provenienza, che nessuno legge: da dove viene l'immagine lo dicono le etichette `febe.ci.*` e quelle OCI. Le versioni `sha256:…` (spinte a mano, o con più piattaforme; la CI non ha ancora pubblicato nulla, perché manca `REGISTRY_TOKEN`) lo script non le tocca, perché l'API dei pacchetti non dice se un indice le rimanda ancora, e ne scrive il numero; se servisse, le toglie una regola di pulizia di Gitea con schema `sha256:.+` e 7 giorni, che salta quelle rimandate e sempre `latest` (`services/packages/container/cleanup.go`, `ShouldBeSkipped`; schema confrontato con tutta la versione, `(?i)\A…\z`) |
| 2026-10-21 | Prova della pulizia: `pulizia.yml` ha l'input `prova` (`type: boolean`, `default: false`, «Solo prova») e il passo passa `gitea.event.inputs.prova` allo script, che con `--prova` elenca che cosa toglierebbe (immagini con dimensione ed età, cache di costruzione, resti della CI di Febe e di act_runner, etichette del registro) con soli comandi che leggono e, sul registro, soli GET. Nella pulizia vera le immagini le sceglie Docker; nella prova le stima lo script con la stessa regola, contando come già tolti i contenitori che la pulizia toglierebbe prima | Gitea 28 mostra un input booleano come una casella (`templates/repo/actions/workflow_dispatch_inputs.tmpl`) e nell'evento lo scrive come testo, «true» o «false» (`routers/web/repo/actions/view.go`, `Run`: `strconv.FormatBool(ctx.FormBool(name))`); il lunedì l'evento non ha input, e la stringa vuota vuol dire pulizia vera. Il passo accetta solo «true» (la prova) e «false» o niente (la pulizia vera): un avvio con l'API passa il valore così com'è (`routers/api/v1/repo/action.go`, `ActionsDispatchWorkflow`: `inputs[name] = value`, senza conversione), e qualunque altro valore («True», «1») ferma il lavoro con un errore senza toccare nulla. Allo stesso modo lo script, prima di chiamare Docker, rifiuta con codice 2 ogni opzione diversa da `--prova` e ogni argomento in più: una prova scritta in un altro modo (`--dry-run`, `-n`, `prova`) prima faceva partire la pulizia vera con codice 0 (rilievo della revisione) |
| 2026-10-21 | `pulizia-docker.sh` gira con `BUILDX_BUILDER=default`: la cache che pota è quella del builder del demone | Con il plugin buildx `docker builder` diventa `docker buildx` (`cmd/docker/builder.go` del client Docker), che lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione, che `setup-buildx-action` crea con `--use` (`src/context.ts`) e che il modo «esecuzione» ha già tolto. I comandi buildx che toccano i builder di Febe li indicano per nome |
| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì |
| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge |
| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store |
+25
View File
@@ -20,6 +20,31 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b
- L'immagine si costruisce solo con le prove verdi: la compilazione e tutte le prove girano dentro la costruzione
(quelle con il browser vero lì si saltano da sole, perché nello stadio di compilazione non ci sono Chromium e Xvfb;
girano nella CI e in sviluppo).
- I pacchetti di Debian sono aggiornati al momento della costruzione (anche le correzioni uscite dopo l'immagine di
base). Prima di ogni pubblicazione la CI fa partire il contenitore senza rete fino al controllo di salute e lo
scansiona con Trivy: una vulnerabilità CRITICAL con correzione disponibile ferma la pubblicazione
(`docs/processo.md`, «Rilievi di sicurezza»).
## Etichette dell'immagine
Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
| Etichetta | Che cos'è | Quando cambia |
|---|---|---|
| `:latest` | l'ultima versione rilasciata senza trattino: quella del modello di Unraid e di `compose.yml` | a ogni rilascio stabile |
| `:X.Y.Z` | una versione rilasciata (anche `X.Y.Z-rc.N` per un'anteprima) | mai: serve per tornare a una versione precisa |
| `:main` | l'ultimo commit di `main` che ha passato la verifica | a ogni unione in `main`: per provare, non per l'archivio vero |
| `:sha-<7 caratteri>` | un commit di `main` preciso | mai; sul registro restano le 10 più recenti |
Ogni immagine costruita dalla CI dice da dove viene, nelle etichette Docker `febe.ci.workflow`, `febe.ci.run`,
`febe.ci.ref` e `febe.ci.commit` e in `org.opencontainers.image.version` e `.revision`:
`docker inspect --format '{{json .Config.Labels}}' <immagine>`. Docker copia queste etichette anche nel contenitore di
Febe: la pulizia della CI non le usa per scegliere che cosa togliere, quindi un Febe sullo stesso Docker del runner
della CI non viene mai toccato, né la sua immagine, anche a contenitore fermo. Su quel Docker, però, la pulizia del
lunedì toglie le immagini che nessun contenitore usa e che sono state create più di 24 ore fa: un'immagine di Febe
tenuta senza contenitore (una versione precedente, per tornare indietro) se ne va, e si riscarica dal registro, dove
`:X.Y.Z` resta. E se l'immagine del Febe vero ha più nomi (`:latest` e `:0.1.0`, per esempio), resta, ma con uno solo:
gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»).
## Volumi
+79 -5
View File
@@ -46,6 +46,61 @@ dotnet test tests/Febe.Tests --filter "FullyQualifiedName~Febe.Tests.Alerts"
- La prova `Febe.Tests.Docs` controlla che questa guida dica tutto ciò che la specifica chiede (§15) e che ogni
collegamento fra le pagine porti a una pagina che esiste.
## Da VS Code
La cartella `.vscode/` prepara VS Code per Febe: estensioni consigliate (C# Dev Kit e C#), soluzione predefinita
`Febe.slnx`, attività e configurazioni di debug. Ogni configurazione compila prima con l'attività `compila`
(`dotnet build Febe.slnx -warnaserror`); gli errori del compilatore finiscono nel pannello Problemi.
| Configurazione (Esegui e debug, F5) | Che cosa fa |
|---|---|
| Febe per Windows · sito di prova | Avvia il sito di prova come attività di sfondo (porte 8481 e 8482), poi Febe per Windows con `--sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo`; a fine debug ferma il sito |
| Sito di prova + Febe per Windows | Il sito di prova nel debugger; quando è pronto parte anche Febe per Windows, che si ferma insieme al sito |
| Febe Server · dimostrazione (--demo) | La dimostrazione su `http://127.0.0.1:8480`, che si apre da sola nel browser; l'interfaccia viene da `src/Febe.Web/wwwroot` (`FEBE_INTERFACCIA`): modifichi un file e ricarichi la pagina |
| Sito di prova | Solo il sito di prova, nel debugger |
| Simulazione 30 giorni (prudente) | `--simula 30g --profilo prudente`, con il resoconto nella Console di debug |
| Febe Server · sito di prova (solo Linux) | Il server vero, con Chromium su Xvfb, contro il sito di prova: interfaccia su `127.0.0.1:8480`, password `prova` (come root serve anche `--senza-sandbox`, e `FEBE_CHROMIUM` se Chromium non è nel `PATH`). Su Windows e macOS si ferma con un messaggio; anche con «Esegui comunque il debug» stampa solo l'aiuto |
| ⚠ Febe per Windows · Instagram vero (dati veri) | Febe senza opzioni: Instagram vero, `%LOCALAPPDATA%\Febe` e `Immagini\Febe`. Solo per le prove dal vivo di Alberto: chiede conferma, e una versione di sviluppo può aggiornare il database vero. Se Febe installato è aperto, prima esci da lui (menu dell'icona ▸ Esci): un solo Febe per cartella dei dati |
- **Dati di sviluppo.** Febe per Windows di sviluppo tiene dati e libreria in
`%USERPROFILE%\FebeSviluppo\<checkout>\dati` e `%USERPROFILE%\FebeSviluppo\<checkout>\libreria`, dove `<checkout>` è
il nome della cartella aperta in VS Code (per esempio `Febe`; il server su Linux in `~/FebeSviluppo/<checkout>`):
fuori dal repository e mai nella cartella vera. Una cartella per checkout perché su una cartella dei dati gira un
Febe solo (un secondo avvio mostra il primo ed esce) e un database scritto da un ramo più nuovo non si apre con una
versione più vecchia. Con Febe chiuso si possono cancellare quando vuoi.
- Chiudendo la finestra Febe resta nell'area di notifica e il debug continua: per finire, menu dell'icona ▸ Esci oppure
Maiusc+F5. Finché Febe gira, `compila` non può sovrascrivere `Febe.exe`.
- Il sito di prova usa sempre le porte 8481 e 8482, come attività e come configurazione: uno alla volta.
- Se il sito di prova si ferma prima di Febe (terminale chiuso a mano, un guasto, oppure porta occupata e «Esegui
comunque il debug»), a fine debug VS Code apre l'elenco delle attività da terminare, con «Termina tutte»: premi Esc.
Con «Sito di prova + Febe per Windows» non succede, perché lì il sito sta nel debugger e non c'è un'attività da
chiudere.
- **Registro.** Nella Console di debug compaiono le righe del sito di prova, della dimostrazione, della simulazione e
del server. Febe per Windows non ha una console: lì mostra solo i messaggi del debugger, e il suo registro sta nella
cartella dei dati, `%USERPROFILE%\FebeSviluppo\<checkout>\dati\registro\febe-AAAA-MM-GG.log` (con il profilo di
`launchSettings.json`, in `FebeSviluppo\comune\dati\registro`). Lì si leggono «Interfaccia sulla porta N», lo stato
del browser di Febe e gli errori.
- Le configurazioni usano la Console di debug e le attività partono senza shell: il terminale integrato carica il
profilo di PowerShell, che può mettere davanti un altro .NET (per esempio quello di un ambiente conda), e allora
`dotnet` non trova l'SDK 10 o Febe non parte («You must install or update .NET»). Se nel terminale
`dotnet --list-sdks` non mostra il 10, usa le attività, Git Bash oppure `conda deactivate`.
- Fermata dal debugger, la dimostrazione non cancella la sua cartella temporanea (`febe-dimostrazione-…`, una trentina
di MB): da VS Code su Windows finisce in `%USERPROFILE%\FebeSviluppo\<checkout>\temporanei`, che si svuota quando
vuoi. Con `dotnet run --project src/Febe.Server -- --demo` in un terminale, Ctrl+C la chiude in ordine e la cancella.
- Fuori da queste configurazioni (`dotnet run --project src/Febe.Desktop`, il pulsante ▷ «Debug project associated
with this file» e «Start New Instance» del C# Dev Kit, le sue configurazioni automatiche «C#: …») Febe per Windows
prende l'unico profilo di `src/Febe.Desktop/Properties/launchSettings.json`: sito di prova su `http://127.0.0.1:8481`
(da avviare a parte, per esempio con l'attività `sito di prova`) e dati in `%USERPROFILE%\FebeSviluppo\comune`, la
stessa cartella per tutti i checkout. Instagram vero da un terminale solo con
`dotnet run --project src/Febe.Desktop --no-launch-profile`: come la configurazione ⚠, è per le prove dal vivo di
Alberto.
- Attività (Terminale ▸ Esegui attività): `compila`, `prove` (`dotnet test tests/Febe.Tests`), `prove Windows`
(`dotnet test tests/Febe.Tests.Windows`, WebView2 vero: solo su Windows), `prove con filtro`
(chiede il filtro, per esempio `FullyQualifiedName~Febe.Tests.Docs`), `sito di prova`, `pubblica Febe.exe` (un file
solo in `out/pubblicazione/`, come `installer/costruisci.sh`) e `immagine Docker (serve Docker Desktop)`.
- I file di `.vscode/` sono JSON senza commenti, così li legge anche un lettore rigido come quello dei controlli della
CI: le spiegazioni stanno in questa sezione, nei campi `detail` delle attività e in `docs/decisioni.md`.
## Dimostrazione
```sh
@@ -129,12 +184,31 @@ da sole). Vedi [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid
## CI e rilascio
Il repository è sul Gitea di casa (<https://gitea.encke-hake.ts.net/Alby96/Febe>); la CI usa Gitea Actions in
`.gitea/workflows/`:
`.gitea/workflows/`, con il codice comune in `.gitea/scripts/`. Il processo completo (nomi dei rami, commit,
richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correzioni urgenti) è in `docs/processo.md`.
- `verifica.yml`, a ogni push e pull request: compilazione con gli avvisi come errori, tutte le prove, costruzione
dell'immagine Docker (senza pubblicarla) e due controlli sull'immagine (Chromium presente, lingua italiana generata);
- `rilascio.yml`, a ogni tag `vX.Y.Z`: immagine Docker sul registro di Gitea, installatore Windows e release. Al 13
ottobre 2026 è in preparazione: se il file non c'è ancora in `.gitea/workflows/`, il rilascio non è automatico.
- `verifica.yml`, a ogni push su qualunque ramo e a mano (non sui tag, non sulle richieste di unione, che mostrano lo
stato del loro ultimo commit). Quattro lavori, che sono i controlli richiesti per unire in `main`:
- `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in
tutta la storia (gitleaks);
- `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in
un contenitore Debian con Chromium, Xvfb, ffmpeg, NSIS e Node veri: nessuna prova si salta;
- `installatore`: `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile, fra gli artefatti per 14 giorni;
- `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e
scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-<commit>`. Alla fine si toglie
tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le
immagini senza nome e la cache di costruzione che nessuno usa da 24 ore;
- `rilascio.yml`, a ogni tag `vX.Y.Z`: prove, installatore e zip, immagine provata e scansionata, pubblicata come
`:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release;
- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che
nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le
`:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo
prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»).
Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso
a ogni esecuzione, scritto nel registro del lavoro. Per rifare un errore con quel seme:
`FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoDiProva"`. I controlli veloci della
CI si lanciano anche a mano: `bash .gitea/scripts/controlli.sh`.
La versione sta solo in `Directory.Build.props` (`<Version>`); il tag deve coincidere.
+295
View File
@@ -0,0 +1,295 @@
# Processo: dal ramo al rilascio
Come una modifica arriva in `main` e da lì a una versione, con le stesse garanzie di un'azienda che non accetta codice
non verificato. Vale per Alberto e per chiunque lavori al repository, persone o agenti. Repository: il Gitea di casa,
<https://gitea.encke-hake.ts.net/Alby96/Febe> (non GitHub: niente strumenti di GitHub). Il motivo di ogni scelta è in
`docs/decisioni.md`, alle righe del 20 ottobre 2026.
## In breve
1. Un ramo per filone di lavoro, nato da `main`.
2. Commit piccoli e separati, ciascuno con un messaggio che dice che cosa cambia e perché.
3. A ogni push la verifica parte da sola: controlli, prove, installatore, immagine.
4. Una richiesta di unione per ramo, con il modello compilato, e una revisione.
5. Si unisce in `main` solo con la verifica verde sull'ultimo commit (protezione di `main`), con un commit di unione;
il ramo si cancella.
6. Dopo l'unione la verifica gira su `main` e pubblica l'immagine `:main` e `:sha-<commit>`.
7. Un rilascio è un tag `vX.Y.Z` su `main`.
## Rami
- Nome: `<tipo>/<argomento>`, in minuscolo, parole separate da trattini, in italiano. Tipi:
| Tipo | Per |
|---|---|
| `funzione/` | una funzione nuova (`funzione/esporta-csv`) |
| `correzione/` | un difetto (`correzione/webview2-avvio`) |
| `urgente/` | una correzione da rilasciare subito (vedi «Correzioni urgenti») |
| `ci/` | flussi, script e immagini della CI (`ci/pipeline-aziendale`) |
| `strumenti/` | strumenti di sviluppo (`strumenti/vscode`) |
| `documenti/` | solo documenti e guida |
| `rilascio/` | la preparazione di una versione (`rilascio/0.2.0`) |
- Si parte da `main` aggiornato e si resta brevi: giorni, non settimane. Se `main` va avanti, il ramo si aggiorna
(pulsante «Aggiorna il ramo» della richiesta di unione, o `git merge origin/main`) prima di unire.
- Su `main` non si fa push diretto: ci si arriva solo da una richiesta di unione.
## Commit
- Piccoli e logici: ogni commit compila e passa le prove da solo (così `git bisect` funziona).
- Messaggio in italiano: la prima riga (al massimo 72 caratteri) dice che cosa cambia; il corpo, dopo una riga vuota,
dice perché. Non un elenco di file.
- I commit scritti con un agente finiscono con una riga vuota e `Co-Authored-By: …` dell'agente.
- Mai nel repository: risultati di compilazione (`bin/`, `obj/`, `out/`), segreti, campioni grezzi della sonda, dati
di Alberto.
## Richieste di unione
- Una per ramo, con il modello (`.gitea/pull_request_template.md`): sintesi, perché, che cosa cambia, come è stato
provato (comandi e risultati, e che cosa non è stato provato), rischi e ritorno indietro, le quattordici regole di
§2 della specifica. Le righe per `CHANGELOG.md` e `docs/stato.md` stanno nella richiesta: le aggiunge chi integra.
- Revisione: Alberto è il proprietario di tutto (`.gitea/CODEOWNERS`). Le osservazioni si risolvono con commit nuovi
sullo stesso ramo, non riscrivendo quelli già rivisti.
- Stile di unione: **commit di unione** («Crea un commit di unione»), con il titolo della richiesta; poi il ramo si
cancella («Elimina il ramo dopo l'unione», da tenere attivo nelle impostazioni del repository).
- Tornare indietro: `git revert -m 1 <commit di unione>` in una nuova richiesta di unione.
## Controlli richiesti e protezione di main
I controlli richiesti sono i quattro lavori della verifica, come Gitea li riporta sul commit:
`verifica / controlli (push)`, `verifica / prove (push)`, `verifica / installatore (push)`,
`verifica / immagine (push)`. Una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo ha
già verificato: per questo la verifica non gira anche su `pull_request`.
Regola di protezione di `main` (Impostazioni ▸ Rami ▸ Aggiungi regola; la imposta chi integra, una volta che i
quattro controlli sono comparsi almeno una volta):
| Impostazione | Valore |
|---|---|
| Schema del ramo | `main` |
| Push | disattivato: solo da richiesta di unione |
| Push forzato | disattivato |
| Controllo di stato | attivo, con gli schemi `verifica / controlli (push)`, `verifica / prove (push)`, `verifica / installatore (push)`, `verifica / immagine (push)` |
| Blocca l'unione se la richiesta è indietro rispetto al ramo di base | attivo: con il ramo aggiornato il commit di unione ha lo stesso contenuto del commit verificato |
| Approvazioni richieste | 1 se le richieste le apre un account diverso da quello di Alberto; 0 se le apre lui (Gitea non conta l'approvazione dell'autore) |
| Annulla le approvazioni superate da nuovi commit | attivo |
| Blocca l'unione con revisioni che chiedono modifiche | attivo |
| Anche gli amministratori seguono la regola | attivo |
E nei tag protetti (Impostazioni ▸ Tag): `v*` creabili solo da Alberto.
## La CI
Gitea Actions su un solo act_runner (etichetta `ubuntu-latest`, un lavoro alla volta). I lavori parlano con il demone
Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri progetti di Alberto. I flussi stanno in
`.gitea/workflows/`, il codice comune in `.gitea/scripts/` (si lancia anche a mano).
| Lavoro | Quando | Che cosa garantisce |
|---|---|---|
| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) |
| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie`) con Chromium della distribuzione, Xvfb, ffmpeg, NSIS, Node e la lingua italiana: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi; quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) |
| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup-<versione>-ci.<numero>.exe` e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni |
| `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-<commit>` |
La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un
ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva fino in fondo. Un'esecuzione a mano non
annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit
che servono per unire, e un lavoro annullato lascerebbe lo stato «failure».
Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»).
### Il mondo sintetico e il suo seme
Le prove non contattano mai Instagram: usano il sito di prova (`tools/Febe.SitoDiProva`), con dati sintetici generati
da un seme. Nella CI le prove girano con il seme 13 e quelle della categoria `SitoDiProva` di nuovo con il seme
`1000 + numero dell'esecuzione`, scritto nel registro del passo «Semi del mondo sintetico». Per rifare un errore, in
locale o dalla CI a mano con quel seme:
```sh
FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoDiProva"
```
### Segreti e variabili
- `REGISTRY_TOKEN` (segreto del repository): token di Alberto con «package: read and write». Senza, `verifica` e
`rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi.
- `REGISTRY` (variabile, facoltativa): il registro come lo raggiunge il runner (`192.168.30.23:3000`); se manca si usa
l'host dell'indirizzo del server Gitea.
- Le credenziali vanno nella configurazione del client Docker del lavoro, mai nel demone, e si tolgono alla fine.
Nessun flusso stampa segreti; `PipelineTests` lo controlla a ogni esecuzione.
- I segreti sono leggibili da qualunque flusso di questo repository, su qualunque ramo: chi può fare push può leggerli.
Per questo il permesso di scrittura sul repository resta ad Alberto e agli account di cui si fida.
## Registro dei container: le etichette
Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`:
| Etichetta | Chi la crea | Quando cambia | Per che cosa |
|---|---|---|---|
| `:latest` | `rilascio`, solo versioni senza trattino | a ogni rilascio stabile | Unraid e Docker Compose |
| `:X.Y.Z` | `rilascio` (anche `X.Y.Z-rc.1` per un'anteprima) | mai | una versione precisa, per tornare indietro |
| `:main` | `verifica`, dopo ogni unione in `main` | a ogni unione (mai all'indietro) | provare `main` su un server di prova; non per l'archivio vero |
| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai; restano le 10 più recenti | un commit preciso di `main` |
Ogni immagine della CI porta le etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit`,
oltre a quelle OCI del Dockerfile: da un'immagine si risale all'esecuzione e al commit. Docker le copia in ogni
contenitore creato dall'immagine, anche in un Febe vero: per questo la pulizia non le usa mai per scegliere che cosa
togliere (vedi «Pulizia»). Le `:sha-` non si accumulano: con il segreto `REGISTRY_TOKEN`, la pulizia del lunedì tiene le
10 più recenti e toglie le altre; `:main`, `:latest` e le versioni restano sempre.
Perché togliere un'etichetta liberi davvero spazio, l'immagine si pubblica come un manifest semplice, senza attestazioni
(`--provenance=false --sbom=false` in `.gitea/scripts/costruisci-immagine.sh`): in Gitea ogni etichetta è una versione
del pacchetto che tiene la configurazione e gli strati, e i blob che nessuna versione usa più li cancella la pulizia dei
pacchetti di Gitea stessa, ogni notte, quando hanno più di 24 ore (`[cron.cleanup_packages]`, attiva per impostazione
predefinita). Con le attestazioni, che buildx aggiunge da sé, l'immagine sarebbe un indice: Gitea terrebbe ogni manifest
figlio come una versione a sé, `sha256:…` senza etichetta, con gli strati, e togliere l'etichetta toglierebbe solo
l'indice. La pulizia del lunedì non tocca mai le versioni `sha256:…` (l'API dei pacchetti non dice se un'etichetta le usa
ancora) e scrive quante sono. Se ce ne sono (un'immagine spinta a mano, o con più piattaforme), quelle che nessuna
etichetta usa più le toglie una regola di pulizia di Gitea, da impostare una volta sul proprietario del pacchetto
(Impostazioni ▸ Pacchetti ▸ regole di pulizia): tipo container, attiva, schema delle versioni da rimuovere `sha256:.+`,
più vecchie di 7 giorni (il valore più basso dopo lo zero, che toglierebbe anche un figlio appena spinto e non ancora
rimandato dal suo indice), nessun numero da tenere. Gitea confronta lo schema con tutta la versione, salta da sé
le versioni `sha256:` che un indice ancora rimanda e sempre `latest`, e applica la regola ogni notte; una regola non deve
mai toccare `main` e le versioni.
## Pulizia
Il demone Docker è condiviso con gli altri progetti di Alberto e, molto probabilmente, con le applicazioni di Unraid; ci
può girare anche un Febe vero, avviato da un'immagine che la CI ha pubblicato e che quindi porta le sue etichette
`febe.ci.*`. Dal 21 ottobre 2026, per decisione di Alberto, la pulizia (`.gitea/scripts/pulizia-docker.sh`) toglie due
cose: ciò che la CI di Febe può provare suo e ciò che non serve più a nessuno, di qualunque progetto. Mai un
contenitore, un volume o una rete che non sia della CI.
Ciò che è della CI di Febe si riconosce da segni che nessuna immagine porta (le etichette `febe.ci.*` no: Docker le
copia in ogni contenitore creato dall'immagine, anche in un Febe vero):
- contenitori di prova: l'etichetta `febe.ci.prova=<esecuzione>`, che mette solo `prova-immagine.sh` con
`docker run --label` e che nessuna immagine porta (lo controlla `PipelineTests`), e insieme il nome esatto
`febe-prova-<esecuzione>`;
- immagini provate: il nome locale `febe-ci:<esecuzione>`, tolto per nome, mai per identificativo e mai con `-f`. Se la
stessa immagine ha anche un nome del registro, quello resta; se un contenitore la usa, resta tutto;
- builder buildx: il contenitore `buildx_buildkit_febe-ci-<esecuzione>0` con l'immagine `moby/buildkit` e il suo volume
`…_state`.
Ciò che resta dei lavori di act_runner si riconosce dal nome che act_runner dà a tutto ciò che crea per un lavoro,
`GITEA-ACTIONS-TASK-<numero del compito>…`: il contenitore del lavoro, i suoi volumi `<nome>` e `<nome>-env`, la sua
rete `<nome>-<lavoro>-network`. Se ne vanno i contenitori fermi e i volumi e le reti che nessun contenitore usa, più
vecchi di 90 minuti. Il volume `act-toolcache`, la cache degli strumenti condivisa fra i lavori, resta.
Ciò che non serve più a nessuno lo toglie Docker stesso (`docker image prune`, `docker builder prune`), che non toglie
mai un'immagine usata da un contenitore, acceso o fermo: un'applicazione di Unraid ferma tiene la sua immagine. Se però
quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «Che cosa costa»).
| Quando | Che cosa si toglie |
|---|---|
| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso |
| all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione |
| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via |
| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` |
Che cosa costa:
- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove»,
`moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le
chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori
(`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso;
- da quando contano le 24 ore delle immagini dipende dallo store delle immagini del demone, che la pulizia scrive
all'inizio. Con lo store classico (il più probabile su Unraid) contano dalla costruzione dell'immagine: una
scaricata ieri ma costruita un mese fa se ne va, e una costruita con una data fissa (costruzioni riproducibili,
`SOURCE_DATE_EPOCH`) non è mai protetta dalla finestra. Con lo store di containerd (predefinito nelle installazioni
nuove di Docker Engine dalla 29) contano da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di
prima: un'immagine appena riscaricata con un nome che c'era già, e non ancora usata da un contenitore, se ne va. Con
tutti e due, un'immagine scaricata e non ancora usata non è al sicuro. La prova dà sempre l'età dalla costruzione, e
con containerd lo dice: lì il suo elenco è solo indicativo;
- un'immagine costruita a mano e tenuta senza contenitore (per esempio quella di `docker build -t febe .`) se ne va e va
ricostruita; una versione di Febe tenuta per tornare indietro si riscarica dal registro, dove `:X.Y.Z` resta;
- un'immagine che un contenitore usa resta, ma se ha più nomi `image prune -a` le toglie quelli in più. Con lo store
classico resta solo l'ultimo in ordine alfabetico del nome completo, anche quando il contenitore è stato creato da un
altro: un'applicazione di Unraid creata da `app:1.2`, se la stessa immagine si chiama anche `app:latest`, continua a
girare, ma in locale `app:1.2` non c'è più, e Unraid la mostra da aggiornare o la riscarica. Con lo store di
containerd restano i nomi da cui i contenitori sono stati creati. Un Febe vero avviato da `:latest`, se la stessa
immagine si chiama anche `:0.1.0`, perde `:0.1.0` e resta `:latest`. La prova elenca questi nomi e la pulizia vera li
scrive uno per uno;
- la cache di costruzione del builder del demone, con cui costruiscono gli altri progetti: resta quella usata nelle
ultime 24 ore. Dopo ogni esecuzione di Febe se ne va quella che nessuna immagine condivide (strati intermedi, cache
montate con `RUN --mount=type=cache`) e che nessuno usa da un giorno; il lunedì anche quella condivisa e quella
interna di BuildKit, con lo stesso limite. Una costruzione che si ripete almeno una volta al giorno ritrova la sua
cache; una più rara la rifà.
**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca
che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i
resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul
registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella
del repository:
`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e
`PROPRIETARIO` nell'ambiente). Una prova scritta in un altro modo non diventa la pulizia vera: un'opzione diversa da
`--prova` (`--dry-run`, `-n`, `--Prova`) o una parola in più (`prova` senza trattini) fermano lo script con codice 2
prima che tocchi Docker, e il flusso accetta per «prova» solo `true` e `false` (un avvio con l'API che passa un altro
valore, «True» o «1», si ferma con un errore). Le immagini, nella pulizia vera, le sceglie Docker; nella prova le stima
lo script con la stessa regola.
`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`), con lo store
classico e con quello di containerd, con un Febe vero acceso e uno fermo, applicazioni di Unraid accese e ferme (una con
due nomi), il lavoro della pulizia stessa, resti veri e finti di act_runner, e contro un'API dei pacchetti finta
(`fake-curl.sh`): controlla che cosa resta, che nessun comando vietato parta, che la prova non tocchi nulla e dica ciò
che la pulizia vera poi toglie, che una prova scritta male si fermi, e che il token non finisca mai nel registro del
lavoro.
## Rilievi di sicurezza
- **gitleaks** (lavoro `controlli`). Un segreto vero si **revoca subito** (gettone di Telegram da BotFather, token di
Gitea dalle impostazioni dell'utente) e se ne crea uno nuovo: toglierlo dalla storia non basta, perché qualcuno può
averlo già. Solo dopo, se serve, si riscrive la storia, d'accordo con Alberto. Un falso allarme (un dato di prova
finto, già controllato) si toglie aggiungendo la sua impronta («Fingerprint», nel registro del lavoro o nel
rapporto `rapporto-gitleaks`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha
controllato, quando. Mai disattivare una regola.
- **Trivy** (lavoro `immagine`, anche nel rilascio). Una vulnerabilità CRITICAL con correzione disponibile ferma il
lavoro e l'immagine non si pubblica. Che cosa fare: per un pacchetto di Debian di solito basta rilanciare (il
Dockerfile applica gli aggiornamenti della distribuzione); per una dipendenza .NET si aggiorna la sua versione in
`Directory.Packages.props` (una dipendenza nuova va chiesta ad Alberto); per il runtime .NET si ricostruisce con
l'SDK aggiornato. Le HIGH, e le CRITICAL ancora senza correzione, non fermano nulla ma si guardano nel rapporto
`sicurezza-immagine` (`trivy.json`) e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si
scrive solo in `.trivyignore`, alla radice: l'identificativo con una scadenza (`CVE-AAAA-NNNN exp:AAAA-MM-GG`, al
massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso.
- Strumenti: gitleaks e Trivy sono gli unici strumenti esterni della CI, approvati da Alberto, e girano solo nella
CI. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di
unione con una riga in `docs/decisioni.md`, preferendo versioni uscite da almeno due settimane.
## Rilasci
1. In un ramo `rilascio/X.Y.Z`: `<Version>` in `Directory.Build.props`, la sezione `## X.Y.Z` di `CHANGELOG.md` (è il
testo delle note della release), `docs/stato.md`. Richiesta di unione, verifica verde, unione.
2. Sul commit di unione in `main`: `git tag -a vX.Y.Z -m "Febe X.Y.Z"` e `git push origin vX.Y.Z`.
3. `rilascio.yml` controlla che il tag coincida con `<Version>`, rifà le prove, costruisce installatore e zip,
costruisce, prova e scansiona l'immagine, la pubblica come `:X.Y.Z` (e `:latest` se la versione non ha trattini) e
crea la release con installatore, zip, modello di Unraid e archivio per Compose.
4. Un'anteprima è `vX.Y.Z-rc.N`: stessa strada, `:latest` non si sposta e la release è segnata come anteprima (come
ogni versione `0.x`).
5. Se manca `REGISTRY_TOKEN` la release esce senza immagine e lo dice; aggiunto il segreto, si rilancia il flusso del
tag e le note si correggono.
## Correzioni urgenti
- Se `main` contiene solo ciò che si vuole rilasciare: ramo `urgente/<argomento>` da `main`, richiesta di unione con la
verifica verde come sempre (nessuna scorciatoia), poi un rilascio di correzione (`X.Y.Z+1`) come sopra.
- Se `main` contiene già lavoro da non rilasciare: ramo `rilascio/X.Y` dal tag della versione in uso, la correzione con
`git cherry-pick` (o scritta lì), `<Version>` a `X.Y.Z+1`, tag `vX.Y.Z+1` su quel ramo (il rilascio parte da
qualunque tag); poi la stessa correzione entra in `main` con la sua richiesta di unione.
## Che cosa solo la prima esecuzione vera può provare
Qui non ci sono runner né demone Docker: i flussi sono stati controllati come testo (struttura, espressioni, `bash -n`
di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere alla prima esecuzione: il contenitore
`node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3`
con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza
rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia;
la pubblicazione su `main` con il segreto.
Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la
casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori,
volumi e reti; che cosa la prova dice di togliere sul demone vero, da leggere prima della prima pulizia vera; poi la
pulizia vera: `docker builder prune` passato a buildx con `BUILDX_BUILDER=default`, il tempo e lo spazio recuperato,
le immagini riscaricate dopo; con il segreto, l'API dei pacchetti con `REGISTRY_TOKEN` (elenco a pagine e DELETE delle
`:sha-`), e che dopo la prima pubblicazione con `--provenance=false --sbom=false` il pacchetto non abbia versioni
`sha256:…` (la riga del registro nel lavoro della pulizia, o la pagina del pacchetto su Gitea); la pulizia di ogni
esecuzione alla fine del lavoro «immagine».
+48 -6
View File
@@ -1,10 +1,24 @@
# Stato
Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché.
Aggiornato il 13 ottobre 2026, versione 0.1.0 (anteprima).
Aggiornato il 20 ottobre 2026, versione 0.1.1 (anteprima).
## In breve
**20 ottobre 2026.** Febe per Windows non riusciva a collegarsi: il browser di Febe non diventava mai pronto (registro di
Alberto del 14 e del 19/10). Era un errore di thread, corretto. Febe per Windows ha girato per la prima volta su un
Windows vero: collegamento, account e sessioni contro il sito di prova, dall'interfaccia. Lo stesso giorno sono arrivati:
- la CI da grande azienda (`docs/processo.md`), con prove con Chromium vero, installatore e immagine a ogni push,
gitleaks, Trivy e pulizia;
- lo sviluppo da VS Code;
- le prove verdi anche su Windows;
- altre tre correzioni trovate provando: lo storico completato doppio o bloccato, la vista remota durante un cambio di
pagina, il pannello «Collegato come @».
Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI) e la PR
d'integrazione della 0.1.1.
Tutte le tappe M0–M8 sono state realizzate in una volta, su richiesta di Alberto del 13 ottobre 2026, sul ramo
`febe-v1`. Il programma è completo e provato **contro il sito di prova locale** (§14.2) con un Chromium vero su Xvfb.
**Non ha mai contattato Instagram** (regola 9): per questo le ricette, per costruzione, **si rifiutano di girare su
@@ -21,14 +35,22 @@ Instagram** finché la sonda di M0 non ha prodotto i campioni da cui compilare `
| M3 | Governatore, interruttore, fascia, sessioni, composizione, avvio graduale, cruscotto, simulazione | Prove del motore verdi; `--simula 30g` per i tre profili: **zero superamenti**, nessuna azione fuori fascia, nessuna pausa sotto il pavimento. **Arresto di M3**: Alberto legge i numeri (`docs/decisioni.md` e il resoconto della simulazione) |
| M4 | API, eventi, ossatura, tutte le schermate, tema scuro, finestra stretta, modalità dimostrativa | Schermate confrontate con i mockup (`docs/schermate/`, differenze in `docs/schermate/differenze.md`); gli originali di 02, 04–07, 09, 11–14 non sono stati forniti: confronto sui ritagli della panoramica |
| M5 | Composizione reale, vista remota, password, pagina di errore, `/salute`, Dockerfile, compose, modello Unraid | Prova d'insieme del server reale contro il sito di prova; immagine costruita dalla CI sul runner; **non provata su Unraid** |
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux; **mai eseguiti su Windows**: S1–S3 da provare (`docs/prove-dal-vivo.md`, parte C) |
| M6 | Febe per Windows (WPF, WebView2Host, area di notifica, funzioni native), installatore NSIS | `Febe.exe` (file unico) e `Febe-Setup-0.1.0.exe` costruiti su Linux. **20/10, su Windows 11 (WebView2 155)**: «Browser di Febe pronto» al primo tentativo; S1 e una sessione di raccolta nelle 11 prove di `tests/Febe.Tests.Windows`. Dall'interfaccia, contro il sito di prova: collegamento, due account, «Controlla ora», 47 file in libreria, sessioni con il browser fuori vista (S2, primo caso), sessione ritrovata dopo un riavvio (S3, primo caso). **Dal vivo, 20/10 alle 19:30** (C5.1, Alberto con l'account di prova, Febe da `main`): accesso riuscito, «Sessione presente nel browser: collegato», nessuna verifica né azione del motore su Instagram. **Da provare**: C5.2–C5.5 (Esci e riapri, riavvio di Windows, avvio con il computer, Scollega), S2 con la finestra ridotta a icona e con lo schermo bloccato, l'installatore su un Windows pulito (C2) |
| M7 | Importazione in quattro passi, riconoscitori, doppioni, copia verificata | Prove di importazione verdi; riconoscitore 4K Stogram solo come ipotesi (domanda 4 di §16) |
| M8 | Avvisi (interfaccia, notifiche di Windows, Telegram), esportazione CSV, guida | Un arresto simulato produce striscia, notifica e messaggio (prova automatica con canali finti); guida in `docs/guida/`, pubblicata nel wiki |
Revisione avversaria completata il 14 ottobre (54 rilievi confermati e corretti, vedi `docs/decisioni.md`).
Prove automatiche: `dotnet test tests/Febe.Tests` — 750 prove, tutte verdi (le prove con il browser vero si
saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI).
Prove automatiche:
- `dotnet test tests/Febe.Tests`, nella CI dal 20/10 dentro un contenitore Debian con Chromium, Xvfb, ffmpeg e NSIS:
tutte girano, **nessuna saltata** (prima, sul runner, se ne saltavano 66). Le prove del sito di prova girano una
seconda volta con il seme `1000 + numero dell'esecuzione`.
- Su Windows le prove con Chromium e Xvfb si saltano, e nessuna fallisce.
- `dotnet test tests/Febe.Tests.Windows` (solo Windows): 11 prove con WebView2 vero.
CI: ogni push su ogni ramo passa da quattro controlli (controlli, prove, installatore, immagine). Il processo e la
protezione di `main` sono in `docs/processo.md`.
## Da fare (di Alberto)
@@ -36,9 +58,29 @@ saltano da sole dove mancano Chromium e Xvfb, come sul runner della CI).
campioni **ripuliti** e le righe di `interazioni.jsonl` dei comandi dell'interfaccia: con quelli si compilano
`bersagli.instagram.json` e `lettori.instagram.json` e si portano le ipotesi H1–H11 a un esito.
2. **Prima sessione dal vivo** dopo la sonda, con il profilo Prudente su un profilo pubblico (parte B).
3. **Windows**: S1–S3 (parte C). **Docker su Unraid**: S3–S6 nel contenitore vero.
3. **Windows**: C5.2–C5.5 (C5.1, l'accesso con l'account di prova, è riuscito il 20/10), S2 con la finestra ridotta a
icona e con lo schermo bloccato, C2 (installatore della 0.1.1 su un Windows pulito). **Docker su Unraid**: S3–S6 nel contenitore
vero.
4. Le domande aperte di §16 (sono state adottate le proposte della terza colonna, vedi `docs/decisioni.md`).
5. Il segreto `REGISTRY_TOKEN` nel repository, perché il rilascio pubblichi l'immagine sul registro di Gitea.
5. Il segreto `REGISTRY_TOKEN` nel repository: senza, la CI e il rilascio costruiscono, provano e scansionano
l'immagine, ma non la pubblicano (lo dicono con un avviso). Il 20/10 mancava ancora.
6. Sicurezza dell'istanza Gitea: la registrazione è aperta, senza CAPTCHA, con quattro account creati da programmi fra
agosto e settembre. Il runner `fa94b0298b8d` è registrato per tutta l'istanza e i suoi lavori parlano con il Docker
dell'host, quindi un utente registrato potrebbe farci girare un suo flusso. Si consiglia di chiudere la registrazione
(`[service] DISABLE_REGISTRATION = true`) o di registrare il runner per il solo utente o repository.
## Rilievi aperti (20 ottobre)
- Il motore e le ricette scrivono due righe per lo stesso fatto anche per «formato-non-riconosciuto», e solo nella
cronologia per «bersaglio-non-trovato» e «ricetta-fallita». La notifica è una sola. Visto leggendo il codice, da
correggere in un cambio a parte, come «storico-completato».
- Su Windows il controllo «cartella dei dati in rete» non segue un collegamento simbolico verso una condivisione. Visto
leggendo il codice, non provato.
- Trivy, nell'immagine del 20/10: una CRITICAL (`libxml2`, CVE-2026-6653) e 246 HIGH, nessuna con una correzione di
Debian. La CI si fermerà da sola quando la correzione esisterà e non sarà ancora applicata.
- La prima sessione dopo il collegamento: se il primo giro programmato trova Febe senza account, conta come sessione
(vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha
appena collegato Febe aspetta.
## Rimandato, e perché
+58 -5
View File
@@ -8,10 +8,23 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i
> rischio per l'account (ritmo umano, tetti, fermo al primo segnale), ma non può azzerarlo. Le storie che Febe apre
> risultano viste da te.
> **Stato.** Questa versione è stata costruita e provata su Linux: tutto ciò che non dipende da Windows ha le sue prove
> automatiche, ma **nessuna parte che richiede Windows è ancora stata eseguita su un Windows vero** (finestre, WebView2,
> area di notifica, registro, programma di installazione). Le prove da fare sono in fondo a questa pagina e in
> `docs/prove-dal-vivo.md`, parte C.
> **Stato (20 ottobre 2026).** Con la 0.1.0 il browser di Febe per Windows non diventava mai disponibile, e l'accesso a
> Instagram non poteva nemmeno cominciare: WebView2 partiva, ma subito dopo Febe ne leggeva la versione da un thread
> diverso da quello dell'interfaccia, WebView2 lo rifiutava e Febe, credendo fallito l'avvio, chiudeva il browser e
> riprovava per sempre (nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException:
> CoreWebView2Environment members can only be accessed from the UI thread.)»). **È corretto**: su un Windows vero
> (Windows 11 Pro, runtime WebView2 155.0.4283.62) il browser di Febe parte al primo tentativo, in un paio di secondi.
>
> Ora ci sono anche **prove automatiche che girano su Windows**, con WebView2 vero e il sito di prova (mai Instagram):
> S1 con la finestra fuori vista (navigazione, corpi delle risposte, lettura della pagina, scorrimento con la rotella,
> fotogrammi, scaricamenti dal CDN, comandi vietati rifiutati), la finestra che viene in primo piano e torna fuori vista
> con il motore fermo nel frattempo, «Scollega», la ripartenza da sola dopo l'arresto del processo del browser, la
> «composizione» di S2 e una sessione di raccolta intera, con i file che arrivano nella libreria. Vedi «Prove
> automatiche su Windows», più sotto.
>
> **Restano da provare a mano** (parte C di `docs/prove-dal-vivo.md`): l'installazione su un Windows pulito, S2 con la
> finestra di Febe ridotta a icona e con lo schermo bloccato, S3 (il collegamento che sopravvive a «Esci» e al riavvio di
> Windows), area di notifica, notifiche, avvio con il computer, e l'accesso vero a Instagram.
## Che cosa serve
@@ -173,9 +186,18 @@ della specifica (§6.6); si sceglie con `--browser` e la scelta resta:
che lo chiude insieme a Febe.exe, anche se Febe si chiude all'improvviso o da Gestione attività: un Edge rimasto
aperto terrebbe la porta 9222 e il browser di Febe non ripartirebbe più.
Come tutti gli oggetti di WebView2, ambiente, controllo, pagina e ricevitori degli eventi DevTools vivono sul thread
dell'interfaccia: Febe li tocca solo da lì (i comandi del motore arrivano da altri thread e ci passano attraverso il
dispatcher di WPF), e il resto del programma legge solo valori semplici presi durante l'avvio, come la versione per il
registro. Se il processo del browser si chiude da solo, Febe lo fa ripartire con lo stesso profilo e con gli stessi
tentativi del primo avvio (5, 15, 30, 60 secondi, poi ogni 5 minuti), e lo stesso se dopo «Scollega» non ripartisse.
Nella finestra c'è sempre un solo browser: se «Scollega» lo fa ripartire mentre il primo avvio aspetta il prossimo
tentativo, quel tentativo lo trova già in funzione e non ne apre un secondo.
Le prove da fare su un Windows vero, con la procedura esatta, sono in `docs/prove-dal-vivo.md`, **parte C**. In breve:
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di Attività.
- **S1** — con il sito di prova: una sessione intera (gesti, corpo delle risposte, scaricamenti) e l'anteprima di
Attività. La parte che non dipende dall'installazione è già una prova automatica su Windows (sotto).
- **S2** — la stessa sessione con il browser fuori vista, con la finestra di Febe ridotta a icona e con lo schermo bloccato;
poi, se serve, `composizione` e `edge`.
- **S3** — accesso a mano, «Esci», riapertura, riavvio di Windows: il collegamento deve restare.
@@ -207,11 +229,42 @@ L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è dis
SkiaSharp e scritta a mano: per rigenerarla dopo un cambio del marchio,
`FEBE_RIGENERA_ICONA=1 dotnet test tests/Febe.Tests --filter IconTests`.
## Prove automatiche su Windows
`tests/Febe.Tests.Windows` contiene le prove che hanno bisogno di Windows e di WebView2 vero. Si compila anche da Linux
(la CI compila tutta la soluzione), ma gira solo su Windows, con il .NET SDK 10 e il runtime WebView2; dove il runtime
manca le prove risultano inconcludenti, non rosse:
```sh
dotnet test tests/Febe.Tests.Windows
dotnet test tests/Febe.Tests.Windows --filter "FullyQualifiedName~WebView2CdpTests" # una classe sola
```
Ogni prova crea un thread dell'interfaccia di WPF vero (come quello di `Febe.exe`), il proprio sito di prova su porte
libere di 127.0.0.1 (il suo «CDN» su 127.0.0.2) e cartelle temporanee in `%TEMP%`: niente tocca la cartella dei dati né
la libreria vere. La finestra «Browser di Febe» resta fuori dallo schermo, tranne in due prove che la portano in primo
piano per un attimo: una prova il primo piano da solo, l'altra il percorso intero di «Accedi a Instagram» e «Ho finito».
Una prova chiude, con il suo numero di processo, il processo del browser che lei stessa ha avviato, per vedere Febe
farlo ripartire. Tutte insieme durano due o tre minuti, quasi tutti della sessione di raccolta.
| Classe | Che cosa prova |
|---|---|
| `WebView2BrowserStartTests` | Avviato da un thread del pool, come fa la composizione, il browser è pronto al primo tentativo e il registro dice «Browser di Febe pronto: WebView2 …» (l'errore del 14 ottobre) |
| `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); «Esci» mentre l'avvio non si completa (non lo aspetta); ripartenza dopo l'arresto del processo; «composizione» di S2 |
| `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati |
| `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria |
| `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte |
Quello che di `WebView2CdpSession` non chiede Windows (per esempio: un errore di chi ascolta la ripartenza non disfa
l'avvio) si prova invece in `tests/Febe.Tests/Desktop/WebView2CdpSessionTests.cs`, con un finto WebView2: gira anche
sulla CI per Linux.
## Problemi comuni
| Che cosa vedi | Che cosa fare |
|---|---|
| All'avvio: «Manca il runtime WebView2 di Microsoft» | Installa il runtime dalla pagina ufficiale (il messaggio offre di aprirla), poi riapri Febe |
| Nel registro, a ogni tentativo: «WebView2 non parte (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)»; «Accedi a Instagram» risponde che il browser di Febe non è in funzione | È l'errore della 0.1.0: il browser di Febe non diventava mai disponibile. Installa una versione successiva alla 0.1.0 |
| «La cartella dei dati è su un disco di rete» o «non può scrivere» | Riapri Febe con una cartella dei dati su un disco locale (`--dati`), oppure libera la cartella |
| Aprendo Febe si porta solo in primo piano la finestra già aperta | È voluto: un solo Febe per cartella dei dati. Per fermarlo: menu dell'icona ▸ Esci |
| Il collegamento risulta perso dopo un riavvio | È l'ipotesi S3: riferiscilo (parte C di `docs/prove-dal-vivo.md`) con l'ora e il registro di quel giorno |
+20
View File
@@ -92,11 +92,31 @@ public sealed class CdpCommandNotAllowedException(string method, string message)
public sealed class CdpCommandException(string method, int code, string browserMessage)
: Exception($"Il comando CDP «{method}» è fallito: {browserMessage} (codice {code}).")
{
/// <summary>Chromium's generic «server error» code.</summary>
public const int ServerErrorCode = -32000;
/// <summary>
/// What Chromium answers to a browser-side page command (<c>Page.startScreencast</c>, <c>Page.captureScreenshot</c>)
/// while the page's current document is not «active»: from <c>ReadyToCommitNavigation</c> of a navigation that uses
/// a new RenderFrameHost until that navigation commits, DevTools already points at the new, still uncommitted frame
/// (content/browser/devtools/protocol/page_handler.cc, <c>AssureTopLevelActiveFrame</c>;
/// render_frame_devtools_agent_host.cc, <c>ReadyToCommitNavigation</c>). A new RenderFrameHost comes with a process
/// swap, a cross-site or back-forward-cache swap and, with RenderDocument (on by default in current Chromium), with
/// every navigation of the page to a new document — the rest page included.
/// </summary>
public const string InactivePageMessage = "Not attached to an active page";
public string Method { get; } = method;
public int Code { get; } = code;
public string BrowserMessage { get; } = browserMessage;
/// <summary>
/// The page is between two documents (see <see cref="InactivePageMessage"/>): the same command a moment later finds
/// the new document committed. A browser that is gone answers differently (closed connection, no answer).
/// </summary>
public bool IsInactivePage => Code == ServerErrorCode && string.Equals(BrowserMessage, InactivePageMessage, StringComparison.Ordinal);
}
/// <summary>The connection to the browser is closed (browser exited, crashed or is restarting).</summary>
@@ -64,12 +64,16 @@ public sealed class RemoteViewSession : IAsyncDisposable
private IDisposable? _lease;
private int _buttons;
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null)
/// <param name="cdp">The page session.</param>
/// <param name="gate">Where the «Alberto is driving» lease is taken.</param>
/// <param name="log">Where opening and closing are noted (never keys).</param>
/// <param name="clock">Wall-clock time for the screencast's start attempts; null: the system clock.</param>
public RemoteViewSession(ICdpSession cdp, UserDrivingGate gate, IBrowserLog? log = null, IClock? clock = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_gate = gate ?? throw new ArgumentNullException(nameof(gate));
_log = log ?? NullBrowserLog.Instance;
Screencast = new ScreencastSession(cdp, _log);
Screencast = new ScreencastSession(cdp, _log, clock);
}
public ScreencastSession Screencast { get; }
@@ -39,10 +39,22 @@ public sealed record ScreencastFrame(
/// <c>Page.screencastFrameAck</c>, stopped with <c>Page.stopScreencast</c>. Frames are delivered through
/// <see cref="ReadFramesAsync"/> (only the latest ones are kept when the reader is slow) and <see cref="FrameReceived"/>.
/// </summary>
/// <remarks>
/// A view opened while the page changes document (the rest page after a session, the login page opened together with
/// the view) can meet the moment in which Chromium refuses the start with «Not attached to an active page»: the start
/// is sent again, a few times, for at most <see cref="InactivePageBudget"/>. Any other failure is reported at once.
/// </remarks>
public sealed class ScreencastSession : IAsyncDisposable
{
/// <summary>How long a start refused because the page is between two documents is tried again.</summary>
public static readonly TimeSpan InactivePageBudget = TimeSpan.FromSeconds(5);
private static readonly TimeSpan FirstPause = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan LongestPause = TimeSpan.FromMilliseconds(500);
private readonly ICdpSession _cdp;
private readonly IBrowserLog _log;
private readonly IClock _clock;
private readonly Channel<ScreencastFrame> _frames = Channel.CreateBounded<ScreencastFrame>(
new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest, SingleReader = true });
@@ -54,10 +66,14 @@ public sealed class ScreencastSession : IAsyncDisposable
private int _stopped;
private long _framesReceived;
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null)
/// <param name="cdp">The page session.</param>
/// <param name="log">Where the start and stop are noted (never parameters or frames).</param>
/// <param name="clock">Wall-clock time for the pauses between start attempts; null: the system clock.</param>
public ScreencastSession(ICdpSession cdp, IBrowserLog? log = null, IClock? clock = null)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_log = log ?? NullBrowserLog.Instance;
_clock = clock ?? new SystemClock();
}
/// <summary>Raised on the browser event thread for every frame: handlers must be quick.</summary>
@@ -144,20 +160,47 @@ public sealed class ScreencastSession : IAsyncDisposable
_lifetime.Dispose();
}
private Task SendStartAsync(CancellationToken ct)
private async Task SendStartAsync(CancellationToken ct)
{
var o = _options ?? new ScreencastOptions();
return _cdp.SendAsync(
"Page.startScreencast",
new JsonObject
var deadline = _clock.Now + InactivePageBudget;
var pause = FirstPause;
for (var attempt = 1; ; attempt++)
{
try
{
["format"] = "jpeg",
["quality"] = Math.Clamp(o.Quality, 0, 100),
["maxWidth"] = o.MaxWidth,
["maxHeight"] = o.MaxHeight,
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
},
ct);
await _cdp.SendAsync(
"Page.startScreencast",
new JsonObject
{
["format"] = "jpeg",
["quality"] = Math.Clamp(o.Quality, 0, 100),
["maxWidth"] = o.MaxWidth,
["maxHeight"] = o.MaxHeight,
["everyNthFrame"] = Math.Max(1, o.EveryNthFrame),
},
ct).ConfigureAwait(false);
if (attempt > 1)
{
_log.Debug($"Vista remota: fotogrammi avviati al tentativo {attempt.ToString(System.Globalization.CultureInfo.InvariantCulture)}, dopo un cambio di pagina.");
}
return;
}
catch (CdpCommandException ex) when (ex.IsInactivePage && _clock.Now + pause <= deadline)
{
// A navigation is committing in a new frame of the page: nothing is started on the browser side, the
// same start a moment later finds the new document. Past the budget the error goes up as it is.
}
await _clock.Delay(pause, ct).ConfigureAwait(false);
if (Volatile.Read(ref _stopped) == 1)
{
return; // stopped meanwhile (a restart's start in the background): nothing left to start
}
pause = pause * 2 < LongestPause ? pause * 2 : LongestPause;
}
}
private void OnReconnected(object? sender, EventArgs e) =>
@@ -113,7 +113,7 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
_log.Write(BrowserLogLevel.Debug, "CDP: WebView2 collegato.");
if (reconnect)
{
Reconnected?.Invoke(this, EventArgs.Empty);
RaiseReconnected();
}
}
@@ -275,6 +275,31 @@ public sealed class WebView2CdpSession : ICdpSession, ICdpConnectionEvents, IAsy
return JsonElement.ParseValue(ref reader);
}
/// <summary>
/// <see cref="Reconnected"/>, on the thread of <see cref="Attach"/> (WebView2's UI thread), one handler at a time: an
/// error of a handler is logged and never reaches <see cref="Attach"/>, so it cannot undo the start of the new
/// WebView that called it. Handlers only queue their work (re-enabling a domain is a command, never sent from here).
/// </summary>
private void RaiseReconnected()
{
if (Reconnected is not { } handlers)
{
return;
}
foreach (var handler in handlers.GetInvocationList().Cast<EventHandler>())
{
try
{
handler(this, EventArgs.Empty);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Write(BrowserLogLevel.Warning, "CDP: errore in chi ascolta il nuovo collegamento con WebView2.", ex);
}
}
}
private IDisposable SubscribeNative(IWebView2DevTools devTools, string eventName) =>
devTools.Subscribe(eventName, json => _events.Writer.TryWrite(new QueuedEvent(eventName, json ?? string.Empty, null)));
@@ -184,7 +184,11 @@ public sealed partial class RecipeRunner
}
else if (page?.HasMore == false)
{
// The whole profile is on the first page, saved just now. For an account «Storico in corso» its history
// is complete: the engine closes it, with its line (RecipeOutcome.BackfillFinished). An account that
// keeps only the new posts had no history to announce.
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
run.Finished = account.State == AccountState.Backfilling;
}
}
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
@@ -394,9 +398,10 @@ public sealed partial class RecipeRunner
run.Finished = true;
if (walk.IsGrid)
{
// «Storico completato» in Attività, and the new state of the account, are the engine's: one line per
// history, with its numbers (SessionComposer, from RecipeOutcome.BackfillFinished).
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
else
{
+4 -1
View File
@@ -89,7 +89,10 @@ public sealed record RecipeOutcome(
/// <summary>Accounts where the sweep saw new posts (FollowingSweep).</summary>
public IReadOnlyList<long> AccountsWithNewPosts { get; init; } = [];
/// <summary>For Backfill: true when the beginning of the profile has been reached.</summary>
/// <summary>
/// Backfill: true when the beginning of the profile has been reached. ProfileCheck: true when the check found the
/// whole profile of an account «Storico in corso» on its first page (its history is complete as well).
/// </summary>
public bool BackfillFinished { get; init; }
}
+89 -25
View File
@@ -51,6 +51,7 @@ internal sealed class SessionComposer
public async Task<SessionSummary> RunAsync(SessionContext context, EngineTask? outsideWindowTask, CancellationToken ct)
{
var state = new SessionState(context);
await CloseCompletedHistoriesAsync(state, ct).ConfigureAwait(false);
var accounts = await SyncQueueAsync(ct).ConfigureAwait(false);
if (outsideWindowTask is not null)
@@ -145,12 +146,41 @@ internal sealed class SessionComposer
// 5. A few pages of history on one account.
if (!light && !Over(state, ct))
{
await RunBackfillAsync(accounts, state, ct).ConfigureAwait(false);
await RunBackfillAsync(state, ct).ConfigureAwait(false);
}
return state.Summary();
}
/// <summary>
/// Accounts still «Storico in corso» whose history is complete: a run closed it but its outcome was never recorded
/// (Febe stopped in between), or an earlier version left them so. Closed before the session plans anything, with
/// their line (<see cref="FinishBackfillAsync"/>); nothing towards the site.
/// </summary>
private async Task CloseCompletedHistoriesAsync(SessionState state, CancellationToken ct)
{
var complete = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is not null)
.ToList();
if (complete.Count == 0)
{
return;
}
await _queueGate.WaitAsync(ct).ConfigureAwait(false);
try
{
foreach (var account in complete)
{
await FinishBackfillAsync(account, state, Clock.Now, CancellationToken.None).ConfigureAwait(false);
}
}
finally
{
_queueGate.Release();
}
}
/// <summary>
/// Keeps the queue in step with the accounts: a profile check and a story check (as the account wants them) for
/// every contactable account, a look at each highlight collection on its profile, a backfill task for every account
@@ -568,14 +598,16 @@ internal sealed class SessionComposer
/// History advances on one account per session, alternating among the accounts «Storico in corso», each up to its
/// daily maximum; suspended while the account has too many files waiting or the data budget is reached (§6.3).
/// </summary>
private async Task RunBackfillAsync(Dictionary<long, Account> accounts, SessionState state, CancellationToken ct)
private async Task RunBackfillAsync(SessionState state, CancellationToken ct)
{
if (_health.IsSuspended(RecipeKind.Backfill) || state.Exhausted.Contains(ActionKind.BackfillPage))
{
return;
}
var candidates = accounts.Values
// Read again, not taken from the start of the session: a profile check of this session may have completed a
// history already (its line is written), and that account is not walked again.
var candidates = (await Store.Accounts.ListAsync(ct).ConfigureAwait(false))
.Where(a => a.State == AccountState.Backfilling && a.BackfillCompletedAt is null && CheckPolicy.IsContactable(a))
.ToList();
if (candidates.Count == 0)
@@ -771,6 +803,15 @@ internal sealed class SessionComposer
var now = Clock.Now;
var kind = request.Kind;
var writes = new List<Task>();
// The history reached the beginning of the profile: the walk of the Storico, however the run ended (a signal or
// a cancellation can come right after the last page was stored, and that account would not be walked again),
// or a profile check that found the whole profile on its first page. What follows sees the account as it is now.
if (kind is RecipeKind.Backfill or RecipeKind.ProfileCheck && outcome.BackfillFinished && account is not null)
{
account = await FinishBackfillAsync(account, state, now, ct).ConfigureAwait(false);
}
switch (outcome.Status)
{
case RecipeStatus.Completed:
@@ -798,7 +839,12 @@ internal sealed class SessionComposer
case RecipeStatus.StoppedBySignal:
case RecipeStatus.Cancelled:
if (task is not null)
if (task is not null && kind == RecipeKind.Backfill && outcome.BackfillFinished)
{
// The walk got to the end before the run stopped: nothing to take up again (closed above).
writes.Add(Store.Tasks.CompleteAsync(task.Id, now, ct));
}
else if (task is not null)
{
await RequeueAsync(task, outcome.Status == RecipeStatus.Cancelled ? "Interrotta" : "Fermata da un segnale", now).ConfigureAwait(false);
}
@@ -947,27 +993,8 @@ internal sealed class SessionComposer
break;
}
case RecipeKind.Backfill when outcome.BackfillFinished:
{
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
var total = await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
var tail = fresh.KeepUpdated
? " Da ora lo tengo aggiornato."
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
await _s.Events.WriteAsync(
EventSeverity.Success,
EngineEventCodes.BackfillCompleted,
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
account.Id,
state.Context.SessionId,
ct).ConfigureAwait(false);
break;
}
case RecipeKind.Backfill:
// A history completed: FinishBackfillAsync, from ApplyOutcomeAsync.
case RecipeKind.Backfill when !outcome.BackfillFinished:
if (contactable)
{
// Behind the other accounts «Storico in corso»: they alternate.
@@ -980,6 +1007,43 @@ internal sealed class SessionComposer
}
}
/// <summary>
/// The history of the account is complete: «Aggiornato» (or «In pausa» with «Tieni aggiornato» off) and the one
/// «storico completato» line of Attività, which is also the alert (spec §13.3). The recipes write no line of their
/// own for it. Called once per history: after it the account is no longer «Storico in corso». Returns the account
/// as it is now.
/// </summary>
private async Task<Account> FinishBackfillAsync(Account account, SessionState state, DateTimeOffset now, CancellationToken ct)
{
var fresh = await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? account;
await Store.Accounts.SetBackfillAsync(account.Id, fresh.BackfillCursor, now, ct).ConfigureAwait(false);
var newState = fresh.KeepUpdated ? AccountState.UpToDate : AccountState.Paused;
await Store.Accounts.SetStateAsync(account.Id, newState, now, null, ct).ConfigureAwait(false);
// The Coda follows at once, not at the next session: no «Storico» left for the account, and nothing planned
// for an account that stays paused. Commands of Alberto stay; the task in flight is settled by its outcome.
foreach (var task in await Store.Tasks.ListPendingAsync(10_000, ct).ConfigureAwait(false))
{
if (task.AccountId == account.Id && !task.IsManual && (newState == AccountState.Paused || task.Kind == EngineTaskKind.Backfill))
{
await Store.Tasks.CancelAsync(task.Id, now, ct).ConfigureAwait(false);
}
}
var total =await Store.Entries.CountDiscoveredAsync(account.Id, EntryKind.Post, DateTimeOffset.UnixEpoch, now.AddSeconds(1), ct).ConfigureAwait(false);
var tail = fresh.KeepUpdated
? " Da ora lo tengo aggiornato."
: " «Tieni aggiornato» è spento: l'account resta in pausa.";
await _s.Events.WriteAsync(
EventSeverity.Success,
EngineEventCodes.BackfillCompleted,
$"Storico di {ItalianText.Handle(account.Username)} completato: {ItalianText.Count(total, "post", "post")} in libreria.{tail}",
account.Id,
state.Context.SessionId,
ct).ConfigureAwait(false);
return await Store.Accounts.GetAsync(account.Id, ct).ConfigureAwait(false) ?? fresh;
}
private async Task PauseAfterSingleDownloadAsync(Account account, DateTimeOffset now, SessionState state, CancellationToken ct)
{
await Store.Accounts.SetStateAsync(account.Id, AccountState.Paused, now, null, ct).ConfigureAwait(false);
+203 -51
View File
@@ -12,16 +12,31 @@ namespace Febe.Desktop.Browser;
/// <summary>
/// The browser of Instagram on Windows as the shared composition sees it (<see cref="IFebeBrowser"/>): a
/// <see cref="WebView2Host"/> started with retries like <see cref="ChromiumBrowser"/> starts Chromium, started again
/// when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has closed.
/// (with the same retries) when its browser process goes away, and emptied by «Scollega» (spec §4.1) once WebView2 has
/// closed.
/// </summary>
/// <remarks>
/// Only a failed start is retried: what follows a start that worked (the log line, the state) is outside the retries,
/// and reads only plain values of the host, never WebView2 objects — this class runs on the threads of the composition,
/// while every WebView2 object lives on the UI thread (the error of 14 October 2026: the version of WebView2 read here,
/// on a thread-pool thread, threw after every successful start, and the start was undone and retried for ever).
/// </remarks>
internal sealed class WebView2Browser : IFebeBrowser
{
private static readonly TimeSpan[] Retry = [TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)];
/// <summary>How long stopping waits for the restart loop to end before closing WebView2 anyway.</summary>
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
private readonly WebView2BrowserSettings _settings;
private readonly FebePlatformContext _context;
private readonly IClock _wallClock;
private readonly BrowserOptions _options;
private readonly CancellationTokenSource _lifetime = new();
private readonly Lock _gate = new();
private Task? _restartLoop;
private bool _restartWanted;
private Exception? _restartFailure;
private volatile bool _started;
private volatile string? _lastError;
@@ -39,7 +54,7 @@ internal sealed class WebView2Browser : IFebeBrowser
ui,
new WebView2HostOptions(settings.Hosting, settings.AdditionalBrowserArguments, icon, () => context.Tracker.MarkUsed(context.Clock.Now)),
context.Log);
Host.BrowserProcessFailed += (_, _) => _ = RecoverAsync();
Host.BrowserProcessFailed += (_, _) => RequestRestart(null);
}
/// <summary>The host: window «Browser di Febe», WebView2, CDP.</summary>
@@ -63,35 +78,10 @@ internal sealed class WebView2Browser : IFebeBrowser
public async Task RunAsync(CancellationToken ct)
{
for (var attempt = 0; !ct.IsCancellationRequested; attempt++)
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct, _lifetime.Token);
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), stop.Token).ConfigureAwait(false))
{
try
{
await Host.StartAsync(_options, ct).ConfigureAwait(false);
_started = true;
_lastError = null;
_context.Log.Info("browser", $"Browser di Febe pronto: WebView2 {Host.Version}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.");
return;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_lastError = $"WebView2 non parte ({ex.GetType().Name}: {FirstLine(ex.Message)}).";
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
await Host.ResetAsync().ConfigureAwait(false);
try
{
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
_context.Log.Info("browser", ReadyMessage("Browser di Febe pronto"));
}
}
@@ -101,56 +91,218 @@ internal sealed class WebView2Browser : IFebeBrowser
public Task HideFromUserAsync(CancellationToken ct) => Host.HideFromUserAsync();
/// <summary>«Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty.</summary>
/// <summary>
/// «Scollega»: WebView2 closes and its process exits, <c>Dati\browser</c> is deleted, the browser starts empty. When
/// the profile cannot be deleted completely an <see cref="IOException"/> says so (the browser starts again anyway);
/// when WebView2 does not start again, the same retries as at start-up bring it back in the background, and
/// «Scollega» has still done its part (the connection service starts the engine again either way).
/// </summary>
public async Task RestartWithEmptyProfileAsync(CancellationToken ct)
{
Exception? deletion = null;
async Task DeleteProfileQuietlyAsync()
{
try
{
await DeleteProfileAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
deletion = ex;
}
}
var restarted = false;
try
{
await Host.RestartAsync(DeleteProfileAsync, ct).ConfigureAwait(false);
await Host.RestartAsync(DeleteProfileQuietlyAsync, ct).ConfigureAwait(false);
MarkStarted();
restarted = true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
catch (Exception ex) when (ex is not (OutOfMemoryException or ObjectDisposedException))
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", ex);
// The start that follows the deletion failed: never a dead browser after «Scollega».
RequestRestart(ex);
}
_context.Log.Info("browser", "Profilo del browser cancellato; il browser è ripartito vuoto.");
if (deletion is not null)
{
throw new IOException($"La cartella del browser ({ProfileDirectory}) non si è potuta cancellare del tutto: esci da Febe e cancellala tu, contiene la sessione di Instagram.", deletion);
}
_context.Log.Info("browser", restarted
? "Profilo del browser cancellato; il browser è ripartito vuoto."
: "Profilo del browser cancellato; il browser ripartirà vuoto.");
}
public ValueTask DisposeAsync() => Host.DisposeAsync();
/// <summary>The browser process of WebView2 went away by itself: it starts again with the same profile.</summary>
private async Task RecoverAsync()
/// <summary>
/// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as
/// <c>_lifetime</c> is cancelled; at most <see cref="StopWait"/> in any case), then closes WebView2 and its window.
/// <c>_lifetime</c> stays undisposed on purpose: a late caller may still read its (cancelled) token.
/// </summary>
public async ValueTask DisposeAsync()
{
await _lifetime.CancelAsync().ConfigureAwait(false);
Task? restarting;
lock (_gate)
{
restarting = _restartLoop;
}
if (restarting is not null)
{
try
{
await restarting.WaitAsync(StopWait).ConfigureAwait(false);
}
catch (TimeoutException)
{
_context.Log.Warn("browser", "WebView2: la ripartenza del browser non si è fermata in tempo; Febe si chiude lo stesso.");
}
}
await Host.DisposeAsync().ConfigureAwait(false);
}
/// <summary>
/// Runs <paramref name="start"/> until it works (true) or <paramref name="ct"/> is cancelled (false), waiting
/// <see cref="Retry"/> between attempts. With <paramref name="failedFirst"/> the first attempt already failed with it.
/// Only an exception of the start itself is a failed start; this method never throws.
/// </summary>
private async Task<bool> StartWithRetriesAsync(Func<CancellationToken, Task> start, CancellationToken ct, Exception? failedFirst = null)
{
var attempt = 0;
if (failedFirst is not null && !await AfterFailedStartAsync(failedFirst, attempt++, ct).ConfigureAwait(false))
{
return false;
}
while (!ct.IsCancellationRequested)
{
try
{
await start(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ct.IsCancellationRequested && ex is (OperationCanceledException or ObjectDisposedException))
{
return false;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
if (!await AfterFailedStartAsync(ex, attempt++, ct).ConfigureAwait(false))
{
return false;
}
continue;
}
MarkStarted();
return true;
}
return false;
}
/// <summary>
/// A start failed: it is said, and the next attempt waits. False when cancelled. What the failed start created it
/// closed itself, inside the host: a close from here could catch a browser that «Scollega» started meanwhile.
/// </summary>
private async Task<bool> AfterFailedStartAsync(Exception error, int attempt, CancellationToken ct)
{
var wait = Retry[Math.Min(attempt, Retry.Length - 1)];
_lastError = $"WebView2 non parte ({error.GetType().Name}: {FirstLine(error.Message)}).";
_context.Log.Error("browser", $"{_lastError} Nuovo tentativo fra {wait.TotalSeconds.ToString("0", CultureInfo.InvariantCulture)} s.");
try
{
await Host.RestartAsync(null, CancellationToken.None).ConfigureAwait(false);
_context.Log.Info("browser", "Browser di Febe ripartito dopo l'arresto del suo processo.");
await _wallClock.Delay(wait, ct).ConfigureAwait(false);
return true;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
catch (OperationCanceledException)
{
_started = false;
_lastError = $"WebView2 non riparte ({ex.GetType().Name}).";
_context.Log.Error("browser", _lastError);
return false;
}
}
/// <summary>Deletes the profile; a process of WebView2 may still hold a file for a moment.</summary>
private void MarkStarted()
{
_started = true;
_lastError = null;
}
/// <summary>
/// The browser must start again (its process went away by itself, or the start after «Scollega» failed with
/// <paramref name="failure"/>): one loop at a time starts it, with the retries of the first start, on the thread
/// pool — never inside an event handler of WebView2. A request that comes while the loop runs makes it go round
/// again. The loop only starts what is not running: when another way in (the first start, «Scollega») brought the
/// browser back first, its attempt finds it running and is done.
/// </summary>
private void RequestRestart(Exception? failure)
{
lock (_gate)
{
if (_lifetime.IsCancellationRequested)
{
return;
}
_restartWanted = true;
_restartFailure ??= failure;
_restartLoop ??= Task.Run(RestartLoopAsync);
}
}
private async Task RestartLoopAsync()
{
while (true)
{
Exception? failure;
lock (_gate)
{
if (!_restartWanted || _lifetime.IsCancellationRequested)
{
_restartLoop = null;
return;
}
_restartWanted = false;
failure = _restartFailure;
_restartFailure = null;
}
if (await StartWithRetriesAsync(token => Host.StartAsync(_options, token), _lifetime.Token, failure).ConfigureAwait(false))
{
_context.Log.Info("browser", ReadyMessage("Browser di Febe ripartito"));
}
}
}
/// <summary>Plain values only (the version was read on the UI thread during the start).</summary>
private string ReadyMessage(string what) =>
$"{what}: WebView2 {Host.Version ?? "di versione sconosciuta"}, pagina {WindowWidth.ToString(CultureInfo.InvariantCulture)}×{WindowHeight.ToString(CultureInfo.InvariantCulture)}, {BrowserHostingNames.Name(_settings.Hosting)}, fuori vista.";
/// <summary>
/// Deletes the profile — off the UI thread, it can be large — retrying while a process of WebView2 still holds a
/// file for a moment.
/// </summary>
private async Task DeleteProfileAsync()
{
for (var attempt = 0; ; attempt++)
{
try
{
if (Directory.Exists(ProfileDirectory))
await Task.Run(() =>
{
Directory.Delete(ProfileDirectory, recursive: true);
}
if (Directory.Exists(ProfileDirectory))
{
Directory.Delete(ProfileDirectory, recursive: true);
}
}).ConfigureAwait(true);
return;
}
catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 10)
{
await Task.Delay(500).ConfigureAwait(true);
await _wallClock.Delay(TimeSpan.FromMilliseconds(500), CancellationToken.None).ConfigureAwait(true);
}
}
}
+314 -63
View File
@@ -1,3 +1,4 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Threading;
@@ -35,27 +36,49 @@ internal sealed record WebView2HostOptions(BrowserHosting Hosting, string Additi
/// «Ho finito»; using and closing it marks the browser as used for «Riprendi».</item>
/// <item>Stopping closes the WebView and waits for its browser process to exit, so the session is on disk (S3);
/// <see cref="RestartAsync"/> («Scollega») does the same before deleting the profile.</item>
/// <item>Every WebView2 call runs on the UI thread through its dispatcher.</item>
/// <item>Threads: every WebView2 object (environment, controller, <c>CoreWebView2</c>, its settings and DevTools
/// receivers) and the window are touched only on the UI thread, through its dispatcher; WebView2 throws on any other
/// thread. Callers on other threads (the composition, the engine) get only plain values captured on the UI thread
/// during the start (<see cref="Version"/>, <see cref="BrowserProcessId"/>), the CDP session, and tasks. Start,
/// restart and stop run one at a time.</item>
/// <item>One WebView at a time, whoever starts it (the first start and its retries, «Scollega», the start after a
/// crash): a start finds the WebView running and does nothing, closes what a dead one left before creating a new one,
/// and when it fails it closes what it created itself. Events of a closed WebView never count.</item>
/// </list>
/// </remarks>
internal sealed class WebView2Host : IBrowserHost
{
private static readonly TimeSpan ExitWait = TimeSpan.FromSeconds(15);
/// <summary>How long stopping waits for a start or restart in progress before closing what there is.</summary>
private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30);
private readonly Dispatcher _ui;
private readonly WebView2HostOptions _settings;
private readonly FebeLog _log;
private readonly WebView2CdpSession _session;
// Start, restart and dispose each await WebView2 on the UI thread: without this they could interleave there.
private readonly SemaphoreSlim _lifecycle = new(1, 1);
// The fields below are touched on the UI thread only.
private BrowserOptions? _options;
private BrowserWindow? _window;
private CoreWebView2Environment? _environment;
private CoreWebView2Controller? _controller;
private CoreWebView2? _core;
private CompositionHost? _composition;
private CoreWebView2DevTools? _devTools;
private TaskCompletionSource? _exited;
private IDisposable? _lease;
private int _generation;
private bool _starting;
private bool _crashedWhileStarting;
private bool _closing;
private bool _restarting;
// Plain values read on the UI thread during the start: any thread may read them.
private volatile string? _version;
private int _browserProcessId;
public WebView2Host(Dispatcher ui, WebView2HostOptions settings, FebeLog log)
{
@@ -79,18 +102,41 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>True while a WebView is attached (commands can be sent).</summary>
public bool IsAttached => _session.IsAttached;
/// <summary>The version of the WebView2 runtime in use (for the log).</summary>
public string? Version => _environment?.BrowserVersionString;
/// <summary>
/// The version of the WebView2 runtime of the browser in use (for the log), read on the UI thread when it started;
/// null before the first start. Any thread: it is a plain value, never a member of a WebView2 object.
/// </summary>
public string? Version => _version;
/// <summary>Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts).</summary>
/// <summary>The browser process of WebView2 when it last started (0 before the first start). Any thread.</summary>
public int BrowserProcessId => Volatile.Read(ref _browserProcessId);
/// <summary>The window «Browser di Febe» (null before the first start). UI thread only, like every WPF object.</summary>
internal BrowserWindow? Window => _window;
/// <summary>
/// Raised on the UI thread when the browser process of WebView2 went away by itself (the owner restarts), after the
/// handler of WebView2's own event has returned: WebView2 does not support closing and recreating inside it.
/// </summary>
public event EventHandler? BrowserProcessFailed;
/// <summary>Creates the window (once), the environment and the controller, and attaches the CDP session.</summary>
/// <summary>
/// Creates the window (once), the environment and the controller, and attaches the CDP session — unless a WebView
/// is already running, because another way in started it («Scollega», the start after a crash): then it does nothing
/// and the start counts as done. A failed start leaves nothing open. When <paramref name="ct"/> is cancelled (Febe
/// is exiting) the caller stops waiting at once, even while WebView2 has not answered: a start not yet begun does not
/// begin, one under way on the UI thread ends by itself, and stopping closes what it leaves.
/// </summary>
public Task StartAsync(BrowserOptions options, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
return OnUiAsync(StartCoreAsync);
var start = OnUiAsync(() => ExclusiveAsync(() =>
{
ct.ThrowIfCancellationRequested();
return StartCoreAsync();
}));
return UntilCancelledAsync(start, ct);
}
public Task ShowToUserAsync() => OnUiAsync(() =>
@@ -104,8 +150,18 @@ internal sealed class WebView2Host : IBrowserHost
window.Activate();
window.Topmost = true;
window.Topmost = false;
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
// The lease first: once the window is on screen the engine must be still, whatever happens to the focus.
TakeLease();
try
{
_controller?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is gone (it is starting again): the window is on screen anyway.
}
return Task.CompletedTask;
});
@@ -119,55 +175,50 @@ internal sealed class WebView2Host : IBrowserHost
/// <summary>
/// Closes the WebView, waits for its browser process to exit (the profile is free and written), runs
/// <paramref name="whileStopped"/> — «Scollega» deletes the profile there — and starts it again. <see cref="Cdp"/>
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails; its error is
/// thrown afterwards.
/// stays the same object. The browser starts again even when <paramref name="whileStopped"/> fails with an
/// <see cref="IOException"/> or <see cref="UnauthorizedAccessException"/>; that error is thrown afterwards. A failed
/// start throws its own error and, like a failed <see cref="StartAsync"/>, leaves nothing open. Once begun it goes
/// to the end whatever <paramref name="ct"/> says (the profile with the Instagram session must go, and the engine
/// starts again after it); stopping waits for it at most <see cref="StopWait"/>.
/// </summary>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(async () =>
public Task RestartAsync(Func<Task>? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () =>
{
_restarting = true;
try
ObjectDisposedException.ThrowIf(_closing, this);
Exception? failure = null;
await CloseWebViewAsync().ConfigureAwait(true);
if (whileStopped is not null)
{
await CloseWebViewAsync().ConfigureAwait(true);
Exception? failure = null;
try
{
if (whileStopped is not null)
{
await whileStopped().ConfigureAwait(true);
}
await whileStopped().ConfigureAwait(true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
failure = ex;
}
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
throw failure;
}
}
finally
await StartCoreAsync().ConfigureAwait(true);
if (failure is not null)
{
_restarting = false;
ExceptionDispatchInfo.Throw(failure);
}
});
/// <summary>Closes what a failed start left, so that the next start begins clean.</summary>
public Task ResetAsync() => OnUiAsync(CloseWebViewAsync);
}));
public async ValueTask DisposeAsync()
{
try
{
await OnUiAsync(async () =>
{
_closing = true;
ReleaseLease();
await CloseWebViewAsync().ConfigureAwait(true);
_window?.CloseForGood();
_window = null;
}).ConfigureAwait(false);
await OnUiAsync(() => ExclusiveAsync(
async () =>
{
_closing = true;
ReleaseLease();
await CloseWebViewAsync().ConfigureAwait(true);
_window?.CloseForGood();
_window = null;
},
StopWait)).ConfigureAwait(false);
}
catch (Exception ex) when (ex is InvalidOperationException or TaskCanceledException)
{
@@ -177,9 +228,71 @@ internal sealed class WebView2Host : IBrowserHost
await _session.DisposeAsync().ConfigureAwait(false);
}
/// <summary>True while a WebView is in the window and attached to the session (its browser process did not die).</summary>
private bool IsRunning => _controller is not null && _session.IsAttached;
/// <summary>
/// UI thread, one at a time (<see cref="ExclusiveAsync"/>): the only place a WebView is created, so the window never
/// holds two. A WebView already running stays (the start is done); what a dead one left is closed first; a failed
/// start closes what it created.
/// </summary>
private async Task StartCoreAsync()
{
_ui.VerifyAccess();
ObjectDisposedException.ThrowIf(_closing, this);
var options = _options ?? throw new InvalidOperationException("Opzioni del browser mancanti.");
// Started already, by «Scollega» or by the start after a crash, while this start waited for its turn or for its
// next attempt: a second WebView would orphan the first, whose browser process then holds the profile.
if (IsRunning)
{
return;
}
// A WebView whose browser process died (the session is detached) is closed before the new one exists.
await CloseWebViewAsync().ConfigureAwait(true);
_starting = true;
_crashedWhileStarting = false;
try
{
await CreateWebViewAsync(options).ConfigureAwait(true);
// The browser process went away while the start awaited WebView2: this start failed, the caller retries.
if (_crashedWhileStarting)
{
throw new InvalidOperationException("Il processo del browser WebView2 si è chiuso durante l'avvio.");
}
// Stopping gave up waiting for this start (WebView2 took longer than StopWait) and closed what there was:
// what this start created goes too.
ObjectDisposedException.ThrowIf(_closing, this);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// Nothing stays open after a failed start, whoever retries it and whenever: here, inside the same step.
await CloseAfterFailedStartAsync().ConfigureAwait(true);
throw;
}
finally
{
_starting = false;
}
}
private async Task CloseAfterFailedStartAsync()
{
try
{
await CloseWebViewAsync().ConfigureAwait(true);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
_log.Warn("browser", "WebView2: quello che l'avvio non riuscito ha lasciato aperto non si è chiuso del tutto.", ex);
}
}
private async Task CreateWebViewAsync(BrowserOptions options)
{
if (_window is null)
{
var window = new BrowserWindow(options.WindowWidth, options.WindowHeight, _settings.Icon);
@@ -196,24 +309,31 @@ internal sealed class WebView2Host : IBrowserHost
var profile = Path.GetFullPath(options.ProfileDirectory);
Directory.CreateDirectory(profile);
var environmentOptions = new CoreWebView2EnvironmentOptions { AdditionalBrowserArguments = _settings.AdditionalBrowserArguments };
_environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
var environment = await CoreWebView2Environment.CreateAsync(null, profile, environmentOptions).ConfigureAwait(true);
_environment = environment;
_exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_environment.BrowserProcessExited += OnBrowserProcessExited;
environment.BrowserProcessExited += OnBrowserProcessExited;
// Read here, on the UI thread, for the log line the composition writes from another thread: a member of the
// environment read there throws «CoreWebView2Environment members can only be accessed from the UI thread».
_version = environment.BrowserVersionString;
var hwnd = _window.Handle;
CoreWebView2Controller controller;
if (_settings.Hosting == BrowserHosting.Composition)
{
var composition = await _environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
var composition = await environment.CreateCoreWebView2CompositionControllerAsync(hwnd).ConfigureAwait(true);
controller = composition;
_controller = controller;
_composition = new CompositionHost(hwnd, () => _window?.PageBounds ?? default);
_composition.Attach(composition);
_controller = composition;
}
else
{
_controller = await _environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
controller = await environment.CreateCoreWebView2ControllerAsync(hwnd).ConfigureAwait(true);
_controller = controller;
}
var controller = _controller;
controller.BoundsMode = CoreWebView2BoundsMode.UseRawPixels;
controller.Bounds = _window.PageBounds;
@@ -221,6 +341,8 @@ internal sealed class WebView2Host : IBrowserHost
controller.IsVisible = true;
var core = controller.CoreWebView2;
_core = core;
Volatile.Write(ref _browserProcessId, unchecked((int)core.BrowserProcessId));
var s = core.Settings;
s.IsPasswordAutosaveEnabled = false;
s.IsGeneralAutofillEnabled = false;
@@ -228,11 +350,14 @@ internal sealed class WebView2Host : IBrowserHost
s.IsZoomControlEnabled = false;
s.IsPinchZoomEnabled = false;
s.IsSwipeNavigationEnabled = false;
// Events of an earlier WebView (closed, or crashed) must not act on this one.
var generation = ++_generation;
core.NewWindowRequested += OnNewWindowRequested;
core.DownloadStarting += (_, e) => e.Cancel = true;
core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny;
core.SourceChanged += (_, _) => _window?.ShowAddress(Addresses.WithoutQuery(core.Source));
core.ProcessFailed += OnProcessFailed;
core.ProcessFailed += (sender, e) => OnProcessFailed(generation, sender, e);
core.Navigate(CdpPageExtensions.RestUrl);
_devTools = new CoreWebView2DevTools(_ui, core);
@@ -240,19 +365,37 @@ internal sealed class WebView2Host : IBrowserHost
await _session.SendAsync("Page.enable", null, CancellationToken.None).ConfigureAwait(true);
}
/// <summary>Closes the controller and waits for the browser process to exit (the profile is written). UI thread.</summary>
/// <summary>
/// Closes the controller and waits for the browser process to exit (the profile is written). UI thread. From here on
/// the events of the WebView being closed belong to an old generation: they change nothing.
/// </summary>
private async Task CloseWebViewAsync()
{
_ui.VerifyAccess();
_generation++;
_session.Detach();
_devTools?.Close();
_devTools = null;
_core = null;
var exited = _exited;
if (_composition is { } composition)
{
_composition = null;
try
{
composition.Dispose();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The visual tree goes with the window.
}
}
if (_controller is { } controller)
{
_controller = null;
try
{
_composition?.Dispose();
controller.Close();
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
@@ -260,7 +403,6 @@ internal sealed class WebView2Host : IBrowserHost
// The browser process is already gone (it crashed): nothing left to close.
}
_composition = null;
if (exited is not null)
{
await Task.WhenAny(exited.Task, Task.Delay(ExitWait)).ConfigureAwait(true);
@@ -276,24 +418,42 @@ internal sealed class WebView2Host : IBrowserHost
private void OnBrowserProcessExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs e) => _exited?.TrySetResult();
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
private void OnProcessFailed(int generation, object? sender, CoreWebView2ProcessFailedEventArgs e)
{
_log.Warn("browser", $"WebView2: processo terminato ({e.ProcessFailedKind}).");
if (_closing || _restarting)
var kind = e.ProcessFailedKind;
_log.Warn("browser", $"WebView2: processo terminato ({kind}).");
// A WebView that is closing, closed or replaced is not ours any more (a restart, «Scollega», a failed start).
if (_closing || generation != _generation)
{
return;
}
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
// During a start the failure is the start's own error: the start closes what it created and the caller retries.
if (_starting)
{
// The whole browser is gone: the owner starts it again (same profile), as the supervisor does with Chromium.
_session.Detach();
BrowserProcessFailed?.Invoke(this, EventArgs.Empty);
_crashedWhileStarting |= kind == CoreWebView2ProcessFailedKind.BrowserProcessExited;
return;
}
else if (e.ProcessFailedKind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
{
// The whole browser is gone: commands fail from now on, and the owner starts it again (same profile), as
// the supervisor does with Chromium — once this handler has returned (threading model of WebView2).
_session.Detach();
_ = _ui.InvokeAsync(() => BrowserProcessFailed?.Invoke(this, EventArgs.Empty), DispatcherPriority.Background);
}
else if (kind is CoreWebView2ProcessFailedKind.RenderProcessExited or CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
{
// The page crashed: back to the rest page (spec §6.1); a running recipe ends on its own errors.
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
try
{
(sender as CoreWebView2)?.Navigate(CdpPageExtensions.RestUrl);
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser went with the page: its own ProcessFailed follows.
}
}
}
@@ -331,19 +491,40 @@ internal sealed class WebView2Host : IBrowserHost
private void UserNavigation(Action<CoreWebView2> action, Func<CoreWebView2, bool> allowed)
{
// «Indietro» and «Ricarica» of the bar are Alberto's own navigation (rule 7): never an engine action.
if (_controller?.CoreWebView2 is { } core && allowed(core))
if (_core is not { } core)
{
TakeLease();
action(core);
return;
}
try
{
if (allowed(core))
{
TakeLease();
action(core);
}
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is gone (it is starting again): the button does nothing.
}
}
private void UpdateBounds()
{
if (_controller is { } controller && _window is { } window)
if (_controller is not { } controller || _window is not { } window)
{
return;
}
try
{
controller.Bounds = window.PageBounds;
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
// The browser process is gone: the next start sizes the new WebView.
}
}
private void TakeLease()
@@ -368,5 +549,75 @@ internal sealed class WebView2Host : IBrowserHost
}
}
private Task OnUiAsync(Func<Task> action) => _ui.CheckAccess() ? action() : _ui.InvokeAsync(action).Task.Unwrap();
/// <summary>
/// Runs one step of the life of the WebView (start, restart, stop) after the others. UI thread. With
/// <paramref name="wait"/> the step runs anyway once that time has passed (stopping must not hang behind a start
/// that WebView2 never completes).
/// </summary>
private async Task ExclusiveAsync(Func<Task> step, TimeSpan? wait = null)
{
var entered = true;
if (wait is { } limit)
{
entered = await _lifecycle.WaitAsync(limit).ConfigureAwait(true);
}
else
{
await _lifecycle.WaitAsync().ConfigureAwait(true);
}
try
{
await step().ConfigureAwait(true);
}
finally
{
if (entered)
{
_lifecycle.Release();
}
}
}
/// <summary>
/// Waits for <paramref name="work"/> until <paramref name="ct"/> is cancelled. Then the caller goes on and the work
/// is left to end by itself; its outcome is observed here, so a late error is never an unobserved task.
/// </summary>
private static async Task UntilCancelledAsync(Task work, CancellationToken ct)
{
try
{
await work.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
_ = work.ContinueWith(
static done => _ = done.Exception,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
throw;
}
}
/// <summary>
/// Runs <paramref name="action"/> on the UI thread — at once when already there — and returns its task: an exception
/// is always in the task, never thrown to the caller.
/// </summary>
private Task OnUiAsync(Func<Task> action)
{
if (!_ui.CheckAccess())
{
return _ui.InvokeAsync(action).Task.Unwrap();
}
try
{
return action();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
return Task.FromException(ex);
}
}
}
+4
View File
@@ -38,6 +38,10 @@
<ProjectReference Include="..\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
<PackageReference Include="Microsoft.Web.WebView2" />
</ItemGroup>
<ItemGroup>
<!-- Le prove che girano solo su Windows (WebView2 vero sul thread dell'interfaccia). -->
<InternalsVisibleTo Include="Febe.Tests.Windows" />
</ItemGroup>
<ItemGroup>
<!-- L'icona del marchio (appendice C), generata da BrandMark e IcoWriter: finestre e area di notifica la leggono da qui. -->
<EmbeddedResource Include="Febe.ico" LogicalName="Febe.ico" />
+18 -4
View File
@@ -2,7 +2,8 @@
L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compila anche da Linux
(`EnableWindowsTargeting`), ma gira solo su Windows: tutto ciò che si può provare altrove sta in
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`). Guida per l'uso: `docs/windows.md`.
`src/Febe.Desktop.Core` (`net10.0`, prove in `tests/Febe.Tests/Desktop`); il resto si prova su Windows, con WebView2
vero, in `tests/Febe.Tests.Windows` (`dotnet test tests/Febe.Tests.Windows`). Guida per l'uso: `docs/windows.md`.
## Come è fatto
@@ -23,9 +24,22 @@ L'eseguibile per Windows (WPF, `net10.0-windows`; specifica §5, §12). Si compi
| `Native/Win32.cs` | Le poche chiamate Win32 e le interfacce di DirectComposition |
| `Febe.ico` | Il marchio (appendice C) a 16–256 pixel, generato da `BrandMark`/`IcoWriter` (`FEBE_RIGENERA_ICONA=1 dotnet test --filter IconTests`) |
Regole che valgono anche qui: le chiamate a WebView2 solo sul thread dell'interfaccia; il browser di Febe non si nasconde
e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie o tasti; nessun pacchetto oltre a
`Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
Regole che valgono anche qui:
- Ogni oggetto di WebView2 (ambiente, controllo, `CoreWebView2`, impostazioni, ricevitori DevTools) e ogni finestra si
tocca solo sul thread dell'interfaccia, anche solo per leggere una proprietà: WebView2 lancia
`InvalidOperationException` su ogni altro thread. Chi sta su un altro thread (composizione, motore) passa dal
dispatcher o legge valori semplici presi durante l'avvio (`WebView2Host.Version`, `BrowserProcessId`). Attenzione a
`ConfigureAwait(false)`: dopo, si è su un thread del pool. È l'errore del 14 ottobre 2026 (il browser non partiva mai).
- Dentro un gestore di un evento di WebView2 niente chiusure, ricreazioni, cicli di messaggi o shell: si mette in coda
sul dispatcher e si fa dopo (modello dei thread di WebView2).
- Si riprova solo un avvio fallito: ciò che segue un avvio riuscito (registro, stato) non lo disfa mai.
- Un solo WebView alla volta, chiunque lo avvii (primo avvio e suoi tentativi, «Scollega», ripartenza dopo un arresto
del processo): l'avvio, dentro la sezione esclusiva di `WebView2Host`, trova quello in funzione e non fa nulla, chiude
prima i resti di uno morto, e se fallisce chiude da sé ciò che ha creato. Un WebView orfano terrebbe vivo il processo
del browser sul profilo, e «Scollega» non potrebbe più cancellarlo.
- Il browser di Febe non si nasconde e non si riduce mai a icona (S2); nel registro mai indirizzi con il gettone, cookie
o tasti; nessun pacchetto oltre a `Microsoft.Web.WebView2` (WPF e Windows Forms vengono con il .NET per Windows).
## Pubblicazione
+9 -2
View File
@@ -1,6 +1,7 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
@@ -120,7 +121,7 @@ internal sealed class MainWindow : Window
e.Cancel = true;
if (uri.Scheme is "http" or "https")
{
_ = _openOutside(uri);
OpenOutsideLater(uri);
}
}
@@ -138,7 +139,13 @@ internal sealed class MainWindow : Window
}
else if (uri.Scheme is "http" or "https")
{
_ = _openOutside(uri);
OpenOutsideLater(uri);
}
}
/// <summary>
/// Opens <paramref name="uri"/> in Alberto's browser once the handler of WebView2's event has returned: the shell
/// may run a message loop of its own, and WebView2 does not support re-entering its handlers (threading model).
/// </summary>
private void OpenOutsideLater(Uri uri) => Dispatcher.InvokeAsync(() => _openOutside(uri), DispatcherPriority.Background);
}
@@ -0,0 +1,8 @@
{
"profiles": {
"Sito di prova": {
"commandName": "Project",
"commandLineArgs": "--dati \"%USERPROFILE%\\FebeSviluppo\\comune\\dati\" --libreria \"%USERPROFILE%\\FebeSviluppo\\comune\\libreria\" --sito-di-prova http://127.0.0.1:8481 --accesso-di-prova --prima-sessione 30 --sviluppo"
}
}
}
+40 -11
View File
@@ -17,18 +17,40 @@ namespace Febe.Server;
/// the older view is always ended — and its screencast stopped — before the newer one starts). Keys go to the browser
/// and nowhere else.
/// </summary>
internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log) : IRemoteViewHost
internal sealed class BrowserRemoteViewHost : IRemoteViewHost
{
private readonly IFebeBrowser _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly IClock _browserClock;
private readonly FebeLog _log;
private readonly Lock _gate = new();
private readonly SemaphoreSlim _opening = new(1, 1);
private BrowserRemoteViewConnection? _current;
private bool _shuttingDown;
/// <param name="browser">The browser shown.</param>
/// <param name="tracker">Notes when Alberto last used the browser.</param>
/// <param name="clock">The composition's clock (the time of that note).</param>
/// <param name="log">Febe's log.</param>
/// <param name="browserClock">
/// Time for the waits on the browser itself; null: the wall clock, because the browser commits a navigation in real
/// time whatever clock the engine runs on (the tests compress it).
/// </param>
public BrowserRemoteViewHost(IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, FebeLog log, IClock? browserClock = null)
{
_browser = browser ?? throw new ArgumentNullException(nameof(browser));
_tracker = tracker ?? throw new ArgumentNullException(nameof(tracker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_log = log ?? throw new ArgumentNullException(nameof(log));
_browserClock = browserClock ?? new SystemClock(clock.LocalZone);
}
public async Task<IRemoteViewConnection> OpenAsync(CancellationToken ct)
{
if (!browser.IsAvailable)
if (!_browser.IsAvailable)
{
throw new RemoteViewUnavailableException(browser.LastError is { } error
throw new RemoteViewUnavailableException(_browser.LastError is { } error
? "Il browser di Febe non è in funzione: " + error
: "Il browser di Febe si sta avviando: riprova fra qualche secondo.");
}
@@ -37,6 +59,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
// would both start and the later assignment would orphan the other (still holding its lease, and stopping the
// shared screencast when it closes).
await _opening.WaitAsync(ct).ConfigureAwait(false);
IDisposable? handover = null;
try
{
BrowserRemoteViewConnection? previous;
@@ -53,13 +76,17 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
if (previous is not null)
{
// Alberto is still at the browser while one view takes the place of the other: without this lease the
// engine would see nobody driving for a moment and put the page back to rest (a navigation under the new
// view's start) or even begin a session.
handover = _browser.UserDriving.Begin();
await previous.EndAsync(RemoteViewEnd.Replaced).ConfigureAwait(false);
}
var connection = new BrowserRemoteViewConnection(this, browser, tracker, clock);
var connection = new BrowserRemoteViewConnection(this, _browser, _tracker, _clock, _browserClock);
try
{
await connection.StartAsync(browser.BrowserOptions.WindowWidth, browser.BrowserOptions.WindowHeight, ct).ConfigureAwait(false);
await connection.StartAsync(_browser.WindowWidth, _browser.WindowHeight, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -90,11 +117,13 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
throw new RemoteViewUnavailableException("Febe si sta fermando.");
}
log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
_log.Info("vista", "Vista remota aperta: il motore resta fermo finché è aperta.");
return connection;
}
finally
{
// The new view holds its own lease by now; if it did not start, nobody is at the browser any more.
handover?.Dispose();
_opening.Release();
}
}
@@ -126,7 +155,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
}
}
log.Info("vista", "Vista remota chiusa.");
_log.Info("vista", "Vista remota chiusa.");
}
}
@@ -134,7 +163,7 @@ internal sealed class BrowserRemoteViewHost(ChromiumBrowser browser, BrowserUseT
internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
{
private readonly BrowserRemoteViewHost _owner;
private readonly ChromiumBrowser _browser;
private readonly IFebeBrowser _browser;
private readonly BrowserUseTracker _tracker;
private readonly IClock _clock;
private readonly RemoteViewSession _session;
@@ -155,18 +184,18 @@ internal sealed class BrowserRemoteViewConnection : IRemoteViewConnection
private int _disposed;
private bool _used;
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, ChromiumBrowser browser, BrowserUseTracker tracker, IClock clock)
public BrowserRemoteViewConnection(BrowserRemoteViewHost owner, IFebeBrowser browser, BrowserUseTracker tracker, IClock clock, IClock browserClock)
{
_owner = owner;
_browser = browser;
_tracker = tracker;
_clock = clock;
_session = new RemoteViewSession(browser.Host.Cdp, browser.Host.UserDriving);
_session = new RemoteViewSession(browser.Cdp, browser.UserDriving, clock: browserClock);
}
public RemoteViewEnd? Ended { get; private set; }
private ICdpSession Cdp => _browser.Host.Cdp;
private ICdpSession Cdp => _browser.Cdp;
public async Task StartAsync(int width, int height, CancellationToken ct)
{
+1 -1
View File
@@ -53,7 +53,7 @@ internal sealed class DockerPlatform(ServerOptions options) : IFebePlatform
{
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(app);
RemoteView = new BrowserRemoteViewHost((ChromiumBrowser)app.Browser!, app.Tracker, app.Clock, app.Log);
RemoteView = new BrowserRemoteViewHost(app.Browser!, app.Tracker, app.Clock, app.Log);
services.AddSingleton<IRemoteViewHost>(RemoteView);
}
+5 -2
View File
@@ -220,9 +220,12 @@ export async function mountConnection(page) {
function drawConnected() {
waitingResume = false;
closeView();
// Before the first round the name of the account is not known yet: «Collegato» and «Nome non ancora noto», never «@».
const nome = status.username || '';
const sotto = nome ? status.displayName : t('stato.accountDaLeggere');
fill(left, h('div.pannello.collegato',
h('div.chi-collegato', avatar(status.username || '', 'g'),
h('div', h('h2', t('impostazioni.collegamento.collegatoCome', { nome: status.username || '' })), status.displayName ? h('span.muto', status.displayName) : null)),
h('div.chi-collegato', avatar(nome, 'g'),
h('div', h('h2', nome ? t('impostazioni.collegamento.collegatoCome', { nome }) : t('stato.collegato')), sotto ? h('span.muto', sotto) : null)),
h('p', t('impostazioni.collegamento.collegatoTesto')),
h('div.azioni-collegato',
h('button.btn', { type: 'button', onclick: useBrowser }, icon('app-window', 's'), t('impostazioni.collegamento.usaBrowser')),
+27 -6
View File
@@ -323,6 +323,32 @@ export default {
}
}
// The empty state: no results of a filter, the first start (spec §10.3: not connected, the two ways to begin) or an
// empty library. Whether Febe is connected comes with the engine, which may answer after the library: until then
// the page stays blank, as the mosaic does while it loads, rather than guess. The empty state follows the engine
// while it is on screen, and is drawn again only when it changes kind.
let empty = null;
function drawEmpty() {
const kind = filtersActive() ? 'filtro' : !engineState() ? 'attesa' : notConnected() ? 'benvenuto' : 'vuota';
if (empty && empty.kind === kind && empty.node.isConnected) return;
let node;
if (kind === 'attesa') {
node = h('div', { 'aria-busy': 'true' });
} else if (kind === 'filtro') {
node = h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')));
} else if (kind === 'benvenuto') {
node = welcome();
} else {
node = h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')));
}
fill(host, node);
empty = { kind, node };
}
page.onEngine(() => {
if (empty && empty.node.isConnected) drawEmpty();
});
// The mosaic.
async function apply() {
setQuery({
@@ -347,12 +373,7 @@ export default {
onOpen: (tile) => openViewer({ tile, source: mosaic, origin: t('libreria.titolo'), onDeleted: (ids) => mosaic.removeTiles(ids) }),
onSelection: drawSelection,
onTotals: ({ entries, accounts: n }) => page.count(t('libreria.quanti', { elementi: t('comune.elementi', { n: entries }), account: t('comune.account', { n }) })),
onEmpty: () => fill(host, filtersActive()
? h('div.vuoto-pagina', icon('list-filter'), h('h2', t('libreria.nessuno')), h('p', t('libreria.nessunoTesto')),
h('button.btn', { type: 'button', onclick: () => { Object.assign(state, readState(new URLSearchParams())); search.value = ''; apply(); } }, t('libreria.togliFiltri')))
: notConnected()
? welcome()
: h('div.vuoto-pagina', icon('image'), h('h2', t('libreria.vuota')), h('p', t('libreria.vuotaTesto')))),
onEmpty: drawEmpty,
});
try {
await mosaic.start();
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Prove che girano solo su Windows, con il WebView2 vero: il thread dell'interfaccia di WPF, il browser di Febe,
il protocollo DevTools sul sito di prova locale e una sessione di raccolta della composizione condivisa.
Si compila anche da Linux (EnableWindowsTargeting, come Febe.Desktop: la CI compila tutta la soluzione), ma si
esegue solo su Windows (dotnet test tests/Febe.Tests.Windows); dove manca il runtime WebView2 le prove risultano
inconcludenti. Mai Instagram: il browser vede solo 127.0.0.1. -->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<EnableWindowsTargeting>true</EnableWindowsTargeting>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<!-- Con WPF l'SDK toglie System.IO dagli using impliciti (Path di System.Windows.Shapes): qui serve. -->
<Using Include="System.IO" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="MSTest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Febe.Core\Febe.Core.csproj" />
<ProjectReference Include="..\..\src\Febe.Data\Febe.Data.csproj" />
<ProjectReference Include="..\..\src\Febe.Browser\Febe.Browser.csproj" />
<ProjectReference Include="..\..\src\Febe.Web\Febe.Web.csproj" />
<ProjectReference Include="..\..\src\Febe.App\Febe.App.csproj" />
<ProjectReference Include="..\..\src\Febe.Desktop.Core\Febe.Desktop.Core.csproj" />
<ProjectReference Include="..\..\src\Febe.Desktop\Febe.Desktop.csproj" />
<ProjectReference Include="..\..\tools\Febe.SitoDiProva\Febe.SitoDiProva.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,2 @@
// One WebView2 at a time: every test starts its own browser process, window and UI thread.
[assembly: DoNotParallelize]
@@ -0,0 +1,127 @@
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Core.Library;
using Febe.Data;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.Web.Engine;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// The browser of Febe for Windows on its own, as the composition builds it (<see cref="DesktopPlatform"/> through
/// <c>DesktopShell</c>): a <see cref="WebView2Browser"/> with its window «Browser di Febe» and WebView2 on a real UI
/// thread, a profile in a temporary Data folder, the switches of S2 and the log of Febe captured.
/// </summary>
internal sealed class BrowserBed : IAsyncDisposable
{
private BrowserBed(TestFolder folder, UiThread ui, LogLines lines, FebeLog log, FebeDatabase database, BrowserUseTracker tracker, WebView2Browser browser)
{
Folder = folder;
Ui = ui;
Lines = lines;
Log = log;
Database = database;
Tracker = tracker;
Browser = browser;
}
public TestFolder Folder { get; }
public UiThread Ui { get; }
/// <summary>What Febe wrote in its log.</summary>
public LogLines Lines { get; }
public FebeLog Log { get; }
public FebeDatabase Database { get; }
/// <summary>When Alberto last used the browser («Riprendi» after a verification).</summary>
public BrowserUseTracker Tracker { get; }
public WebView2Browser Browser { get; }
public static async Task<BrowserBed> CreateAsync(string name, BrowserHosting hosting = BrowserHosting.Window)
{
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
var lines = new LogLines();
var clock = new SystemClock();
var log = new FebeLog(null, lines, clock);
var data = new DataFolderLayout(folder.Combine("dati"));
var database = await FebeDatabase.OpenAsync(data.Root);
var options = new FebeAppOptions { DataFolder = data.Root, LibraryFolder = folder.Combine("libreria") };
var tracker = new BrowserUseTracker();
var context = new FebePlatformContext(options, data, database, clock, log, tracker);
var settings = new WebView2BrowserSettings(data.BrowserProfile, 1280, 900, hosting, BrowserArguments.ForWebView2());
// Built off the UI thread, as DesktopPlatform.CreateBrowserAsync does after its awaits.
var browser = new WebView2Browser(ui.Dispatcher, settings, context, icon: null);
return new BrowserBed(folder, ui, lines, log, database, tracker, browser);
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
public async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
}
await Task.Delay(50, ct);
}
}
/// <summary>Reads a value of the UI thread (the window, its position) through the dispatcher.</summary>
public Task<T> OnUiAsync<T>(Func<T> read) => Ui.InvokeAsync(read);
/// <summary>The class names of the child windows of «Browser di Febe»: one per WebView hosted in it.</summary>
public Task<IReadOnlyList<string>> ChildWindowsAsync() =>
OnUiAsync(() => Browser.Host.Window is { } window ? ChildWindows.Of(window.Handle) : (IReadOnlyList<string>)[]);
/// <summary>
/// Starts the browser from a thread-pool thread, like <c>FebeApp.BringUpBrowserAsync</c>, and waits until
/// <see cref="WebView2Browser.RunAsync"/> returns. Fails at once when the log reports a failed start: the loop of
/// retries would otherwise go on for ever.
/// </summary>
public async Task StartAsync(CancellationToken ct, TimeSpan? timeout = null)
{
var run = Task.Run(() => Browser.RunAsync(ct), ct);
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(60));
while (!run.IsCompleted)
{
if (Lines.Any("non parte"))
{
Assert.Fail("Il browser di Febe non è partito al primo tentativo:\n" + Lines.Text);
}
if (DateTime.UtcNow > deadline)
{
Assert.Fail("Il browser di Febe non è diventato disponibile in tempo:\n" + Lines.Text);
}
await Task.Delay(50, ct);
}
await run;
}
public async ValueTask DisposeAsync()
{
try
{
await Browser.DisposeAsync();
}
finally
{
await Ui.DisposeAsync();
await Database.DisposeAsync();
Log.Dispose();
Folder.Dispose();
}
}
}
@@ -0,0 +1,31 @@
using System.Runtime.InteropServices;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// The direct child windows of a window, by class name. WebView2 hosted in a window («finestra») puts one child window
/// per controller into its parent: two of them in «Browser di Febe» mean two WebViews, one of them orphaned.
/// </summary>
internal static class ChildWindows
{
/// <summary>The class names of the direct children of <paramref name="parent"/>, in Z order.</summary>
public static IReadOnlyList<string> Of(IntPtr parent)
{
var names = new List<string>();
var buffer = new char[256];
var child = IntPtr.Zero;
while ((child = FindWindowEx(parent, child, null, null)) != IntPtr.Zero)
{
var length = GetClassName(child, buffer, buffer.Length);
names.Add(new string(buffer, 0, Math.Max(length, 0)));
}
return names;
}
[DllImport("user32.dll", EntryPoint = "FindWindowExW", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childAfter, string? className, string? windowName);
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr window, [Out] char[] className, int maxCount);
}
@@ -0,0 +1,78 @@
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A clock that compresses time, like the one of the Linux suite: <see cref="Delay"/> waits for real only a fraction
/// of the requested time and <see cref="Now"/> moves on by the whole of it, so the engine keeps its order of events
/// while a session lasts minutes instead of hours.
/// </summary>
internal sealed class CompressedClock(double factor, TimeZoneInfo zone) : IClock
{
private readonly Lock _gate = new();
private TimeSpan _offset;
public TimeZoneInfo LocalZone { get; } = zone;
public DateTimeOffset Now
{
get
{
lock (_gate)
{
return DateTimeOffset.UtcNow + _offset;
}
}
}
public async Task Delay(TimeSpan time, CancellationToken ct)
{
if (time <= TimeSpan.Zero)
{
ct.ThrowIfCancellationRequested();
return;
}
var real = TimeSpan.FromTicks((long)(time.Ticks / factor));
if (real >= TimeSpan.FromMilliseconds(1))
{
await Task.Delay(real, ct).ConfigureAwait(false);
}
else
{
ct.ThrowIfCancellationRequested();
await Task.Yield();
}
lock (_gate)
{
_offset += time - real;
}
}
}
internal static class TestZones
{
/// <summary>
/// A fixed-offset zone where it is between 12:00 and 13:00 now: inside the active window of every caution profile,
/// whatever the hour of the test.
/// </summary>
public static TimeZoneInfo Noon()
{
var offset = 12 - DateTimeOffset.UtcNow.Hour;
return TimeZoneInfo.CreateCustomTimeZone("Febe/Mezzogiorno", TimeSpan.FromHours(offset), "Mezzogiorno di prova", "Mezzogiorno di prova");
}
}
/// <summary>The registry values «CartellaDati» and «NuovaCartellaDati», in memory.</summary>
internal sealed class MemoryLocations : IDataFolderLocationStore
{
public string? Current { get; private set; }
public string? Pending { get; private set; }
public void SetCurrent(string? folder) => Current = folder;
public void SetPending(string? folder) => Pending = folder;
}
@@ -0,0 +1,150 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Febe.App;
using Febe.Core.Abstractions;
using Febe.Desktop;
using Febe.Desktop.Browser;
using Febe.Desktop.Core;
using Febe.SitoDiProva;
using Febe.Web.Native;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// The shared composition (<see cref="FebeApp"/>) as Febe.exe composes it — <see cref="DesktopPlatform"/>,
/// <c>DesktopShell</c>, the window «Browser di Febe» on a WPF UI thread — against its own test site, in temporary
/// folders, on a clock ten times faster and in a zone where it is noon. The interface is asked like the main window asks
/// it: with the token of this start and the Origin of the interface.
/// </summary>
internal sealed class DesktopBed : IAsyncDisposable
{
private readonly HttpClient _client;
private DesktopBed(TestSite site, TestFolder folder, UiThread ui, LogLines lines, CompressedClock clock, DesktopPlatform platform, FebeApp app)
{
Site = site;
Folder = folder;
Ui = ui;
Lines = lines;
Clock = clock;
Platform = platform;
App = app;
_client = new HttpClient(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false, UseProxy = false })
{
BaseAddress = app.Address,
Timeout = TimeSpan.FromSeconds(30),
};
}
public TestSite Site { get; }
public TestFolder Folder { get; }
public UiThread Ui { get; }
/// <summary>What Febe wrote in its log.</summary>
public LogLines Lines { get; }
public CompressedClock Clock { get; }
public DesktopPlatform Platform { get; }
public FebeApp App { get; }
/// <summary>The browser of Febe: WebView2 (Febe.exe never uses another one unless asked with <c>--browser edge</c>).</summary>
public WebView2Browser Browser => App.Browser as WebView2Browser ?? throw new AssertFailedException("Il browser della composizione non è WebView2.");
/// <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)
{
var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
var folder = new TestFolder(name);
var ui = await UiThread.StartAsync();
try
{
var lines = new LogLines();
var data = folder.Combine("dati");
List<string> arguments =
[
"--dati", data, "--libreria", folder.Combine("libreria"),
"--sito-di-prova", site.SiteUrl, "--cdn-di-prova", site.CdnUrl, "--prima-sessione", "1",
];
if (autoLogin)
{
arguments.Add("--accesso-di-prova");
}
if (!DesktopCommandLine.TryParse([.. arguments], out var options, out var problem))
{
throw new ArgumentException(problem);
}
var zone = TestZones.Noon();
var clock = new CompressedClock(10, zone);
var shell = new DesktopShell(ui.Dispatcher, null, BrowserShell.Instance);
var platform = new DesktopPlatform(options, shell, new MemoryLocations(), dataFolderFixed: true);
var appOptions = options.AppOptions(data, new DesktopFolders(folder.Combine("AppData"), folder.Combine("Immagini"))) with { Zone = zone, ZoneId = zone.Id };
var hooks = new FebeAppHooks { Clock = clock, Random = new SeededRandom(20261020), Console = lines, ShutdownTimeout = TimeSpan.FromSeconds(1) };
var app = await FebeApp.StartAsync(appOptions, platform, hooks, ct);
return new DesktopBed(site, folder, ui, lines, clock, platform, app);
}
catch
{
await ui.DisposeAsync();
folder.Dispose();
await site.DisposeAsync();
throw;
}
}
/// <summary>A request as the main window sends it; the answer must be 200 with JSON.</summary>
public async Task<JsonElement> JsonAsync(HttpMethod method, string path, string? json, CancellationToken ct)
{
using var request = new HttpRequestMessage(method, path);
request.Headers.TryAddWithoutValidation(Febe.Web.Security.AccessToken.HeaderName, Platform.AccessToken);
request.Headers.TryAddWithoutValidation("Origin", $"{App.Address.Scheme}://{App.Address.Authority}");
if (json is not null)
{
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
}
using var response = await _client.SendAsync(request, ct);
var text = await response.Content.ReadAsStringAsync(ct);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, $"{path}: {text}");
return JsonDocument.Parse(text).RootElement.Clone();
}
/// <summary>Waits (real time) until <paramref name="condition"/> holds; fails with <paramref name="what"/> and the log otherwise.</summary>
public async Task WaitUntilAsync(Func<Task<bool>> condition, TimeSpan timeout, string what, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!await condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.\n{Lines.Text}");
}
await Task.Delay(250, ct);
}
}
/// <summary>Stops the composition (the browser of Febe closes on its UI thread), then the UI thread, folders, site.</summary>
public async ValueTask DisposeAsync()
{
_client.Dispose();
try
{
await App.DisposeAsync();
}
finally
{
await Ui.DisposeAsync();
Folder.Dispose();
await Site.DisposeAsync();
}
}
}
@@ -0,0 +1,54 @@
using System.Text;
namespace Febe.Tests.Windows.Support;
/// <summary>The «console» of <see cref="Febe.App.FebeLog"/> in a test: the lines Alberto would find in his log.</summary>
internal sealed class LogLines : TextWriter
{
private readonly Lock _gate = new();
private readonly List<string> _lines = [];
private readonly StringBuilder _current = new();
public override Encoding Encoding => Encoding.UTF8;
public IReadOnlyList<string> Lines
{
get
{
lock (_gate)
{
return [.. _lines];
}
}
}
public string Text => string.Join('\n', Lines);
public bool Any(string fragment) => Lines.Any(l => l.Contains(fragment, StringComparison.Ordinal));
public override void Write(char value)
{
lock (_gate)
{
if (value == '\n')
{
_lines.Add(_current.ToString().TrimEnd('\r'));
_current.Clear();
}
else
{
_current.Append(value);
}
}
}
public override void WriteLine(string? value)
{
lock (_gate)
{
_current.Append(value);
_lines.Add(_current.ToString());
_current.Clear();
}
}
}
@@ -0,0 +1,39 @@
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A temporary folder under <see cref="Path.GetTempPath"/> (TEMP: on Alberto's PC a work folder outside drive C:),
/// removed at the end of the test. WebView2 may hold a file of its profile for a moment after it closed: removal is
/// retried and a leftover folder is not an error.
/// </summary>
internal sealed class TestFolder : IDisposable
{
public TestFolder(string prefix)
{
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "febe-prove-windows", prefix + "-" + Guid.NewGuid().ToString("N")[..10]);
Directory.CreateDirectory(Path);
}
public string Path { get; }
public string Combine(params string[] parts) => System.IO.Path.Combine([Path, .. parts]);
public void Dispose()
{
for (var attempt = 0; attempt < 10; attempt++)
{
try
{
if (Directory.Exists(Path))
{
Directory.Delete(Path, recursive: true);
}
return;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Thread.Sleep(300);
}
}
}
}
@@ -0,0 +1,55 @@
using System.Windows.Threading;
namespace Febe.Tests.Windows.Support;
/// <summary>
/// A UI thread like the one of Febe.exe: an STA thread running a WPF <see cref="System.Windows.Threading.Dispatcher"/>
/// (its message pump and its <see cref="DispatcherSynchronizationContext"/>). The browser of Febe is created on it,
/// while the test itself — like the engine of Febe — runs on thread-pool threads.
/// </summary>
internal sealed class UiThread : IAsyncDisposable
{
private readonly Thread _thread;
private UiThread(Thread thread, Dispatcher dispatcher)
{
_thread = thread;
Dispatcher = dispatcher;
}
public Dispatcher Dispatcher { get; }
/// <summary>The managed id of the UI thread (to tell where code ran).</summary>
public int ThreadId => _thread.ManagedThreadId;
public static async Task<UiThread> StartAsync()
{
var ready = new TaskCompletionSource<Dispatcher>(TaskCreationOptions.RunContinuationsAsynchronously);
var thread = new Thread(() =>
{
ready.SetResult(Dispatcher.CurrentDispatcher);
Dispatcher.Run();
})
{
IsBackground = true,
Name = "Febe: thread dell'interfaccia (prove)",
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
var dispatcher = await ready.Task.WaitAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
return new UiThread(thread, dispatcher);
}
/// <summary>Runs <paramref name="action"/> on the UI thread and waits for it.</summary>
public Task<T> InvokeAsync<T>(Func<T> action) => Dispatcher.InvokeAsync(action).Task;
public async ValueTask DisposeAsync()
{
if (!Dispatcher.HasShutdownStarted)
{
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
}
await Task.Run(() => _thread.Join(TimeSpan.FromSeconds(15))).ConfigureAwait(false);
}
}
@@ -0,0 +1,39 @@
using System.Runtime.CompilerServices;
using Microsoft.Web.WebView2.Core;
namespace Febe.Tests.Windows.Support;
/// <summary>Whether these tests can run here: Windows with the WebView2 runtime (the tests are inconclusive otherwise).</summary>
internal static class WebView2Runtime
{
/// <summary>Null when WebView2 can run; otherwise why not, in Italian (the text of the inconclusive result).</summary>
public static string? UnavailableReason()
{
if (!OperatingSystem.IsWindows())
{
return "Prova solo per Windows: qui non c'è WebView2.";
}
try
{
return InstalledVersion() is null ? "Runtime WebView2 non installato su questo Windows." : null;
}
catch (Exception ex) when (ex is WebView2RuntimeNotFoundException or DllNotFoundException or BadImageFormatException)
{
return $"Runtime WebView2 non disponibile ({ex.GetType().Name}).";
}
}
/// <summary>The version of the installed WebView2 runtime, e.g. «141.0.3537.71».</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static string? InstalledVersion() => CoreWebView2Environment.GetAvailableBrowserVersionString();
/// <summary>Marks the test inconclusive where WebView2 cannot run.</summary>
public static void Require()
{
if (UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
}
@@ -0,0 +1,50 @@
using System.Text.RegularExpressions;
using Febe.Browser.Cdp;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// The start of the browser of Febe on a real Windows (regression of 14 and 19 October 2026: «WebView2 non parte
/// (InvalidOperationException: CoreWebView2Environment members can only be accessed from the UI thread.)» at every
/// attempt, for ever). The composition starts the browser from a thread-pool thread; every WebView2 object lives on the
/// UI thread of WPF.
/// </summary>
[TestClass]
public sealed partial class WebView2BrowserStartTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task StartedFromAThreadPoolThreadTheBrowserIsReadyAtTheFirstAttempt()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("avvio");
await bed.StartAsync(ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Browser.IsAvailable, "the browser is available once RunAsync returned");
Assert.IsNull(bed.Browser.LastError);
var ready = bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)).ToList();
Assert.HasCount(1, ready, "one «ready» line: " + bed.Lines.Text);
Assert.MatchesRegex(ReadyLine(), ready[0]);
Assert.IsFalse(bed.Lines.Any("non parte"), "no failed attempt: " + bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("ERRORE"), "no error at all: " + bed.Lines.Text);
// The version is a plain value now: it can be read from any thread.
var version = await Task.Run(() => bed.Browser.Host.Version, ct);
Assert.IsNotNull(version);
StringAssert.Contains(ready[0], version);
// The engine's threads use the page through the session: the command hops to the UI thread and back.
Assert.AreEqual("about:blank", await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
}
[GeneratedRegex(@"\[browser\] Browser di Febe pronto: WebView2 \d+\.\d+\.\d+\.\d+, pagina 1280×900, finestra, fuori vista\.$")]
private static partial Regex ReadyLine();
}
@@ -0,0 +1,200 @@
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Browser.Capture;
using Febe.Browser.Cdp;
using Febe.Browser.Download;
using Febe.Browser.Gestures;
using Febe.Browser.Hosting;
using Febe.Browser.RemoteView;
using Febe.Browser.WebView2;
using Febe.Browser.Recipes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// S1 on a real Windows (docs/prove-dal-vivo.md, C3): the DevTools protocol of WebView2 through the real
/// <see cref="WebView2CdpSession"/> and its allowlist, against the local test site (never Instagram), from thread-pool
/// threads as the engine sends it, with the window «Browser di Febe» out of view as it always is.
/// </summary>
[TestClass]
public sealed class WebView2CdpTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task S1TheProtocolWorksOnTheTestSiteWithTheWindowOutOfView()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("s1");
await bed.StartAsync(ct);
var cdp = bed.Browser.Cdp;
Assert.IsInstanceOfType<WebView2CdpSession>(cdp, "the real session of WebView2, with its allowlist");
var clock = new SystemClock();
var testSite = CollectionSite.TestSite(site.SiteHost, site.CdnHost);
await Task.Run(
async () =>
{
// Response bodies: Network.enable and the events are subscribed from this thread, the bodies come
// through Network.getResponseBody.
var bodies = new BodyCollector();
await using var tap = new ResponseTap(cdp, testSite.Hosts, clock);
tap.AddConsumer(bodies);
await tap.StartAsync(ct);
// Navigation.
var navigation = await cdp.NavigateAsync(site.Url("/profilo/luca.prova/"), ct);
Assert.IsTrue(navigation.Succeeded, navigation.ErrorText);
Assert.IsTrue(await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(20), ct), "the profile page loaded");
await WaitUntilAsync(() => bodies.Paths.Contains("/dati/profilo/luca.prova"), TimeSpan.FromSeconds(20), "il corpo JSON del profilo", ct);
var profile = bodies.Json("/dati/profilo/luca.prova");
Assert.AreEqual("luca.prova", profile.GetProperty("profilo").GetProperty("nome").GetString());
Assert.IsTrue(tap.Stats.JsonBodies >= 1);
// Read-only Runtime.evaluate: what the page sees, out of view (S2: visible, never «hidden»).
var seen = await cdp.EvaluateAsync(
"({ visibility: document.visibilityState, hidden: document.hidden, webdriver: navigator.webdriver, width: innerWidth, height: innerHeight, path: location.pathname, tiles: document.querySelectorAll('#griglia a').length })",
ct);
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
Assert.AreEqual("/profilo/luca.prova/", seen.GetProperty("path").GetString());
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString(), "out of view the page stays visible (S2)");
Assert.IsFalse(seen.GetProperty("hidden").GetBoolean());
Assert.IsFalse(seen.GetProperty("webdriver").GetBoolean(), "an ordinary browser: navigator.webdriver is false");
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32(), "the page has its fixed width");
Assert.IsGreaterThan(0, seen.GetProperty("tiles").GetInt32(), "the page drew the grid from the JSON");
// The session cookie of the site exists (only its name is looked at).
Assert.IsTrue(await SessionCookieProbe.HasSessionCookieAsync(cdp, testSite.SessionCookie, ct));
// Scrolling with Input.dispatchMouseEvent (mouseWheel), as the recipes do.
var height = (await cdp.EvaluateAsync("document.documentElement.scrollHeight", ct)).GetDouble();
Assert.IsGreaterThan(seen.GetProperty("height").GetInt32() + 400.0, height, "a page long enough to scroll");
Assert.AreEqual(0, (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble());
var gestures = new HumanGestures(cdp, clock, new SeededRandom(20261020));
await gestures.MoveToAsync(new PagePoint(640, 450), ct);
var requested = await gestures.ScrollBurstAsync(ct: ct);
await Task.Delay(800, ct);
var scrolled = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
TestContext.WriteLine($"Scorrimento: chiesti {requested} pixel, pagina scesa di {scrolled}.");
Assert.IsGreaterThan(100.0, scrolled, "the wheel really scrolled the page out of view");
// Page.captureScreenshot: a JPEG of the page, out of view (the preview of Attività).
var jpeg = await PagePreview.CaptureAsync(cdp, 60, ct);
TestContext.WriteLine($"Fotogramma: {jpeg.Length} byte.");
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame, not an empty one");
Assert.AreEqual(0xFF, jpeg[0]);
Assert.AreEqual(0xD8, jpeg[1]);
// A file of the CDN through the browser (Network.loadNetworkResource, IO.read, IO.close).
var media = FirstCdnAddress(profile, site.CdnUrl) ?? throw new AssertFailedException("nessun indirizzo del CDN nel JSON del profilo");
var fetcher = new BrowserFileFetcher(cdp, testSite.Hosts);
using var file = new MemoryStream();
var fetched = await fetcher.FetchAsync(new Uri(media), file, null, ct);
Assert.AreEqual(FetchOutcome.Completed, fetched.Outcome, fetched.Error);
Assert.IsGreaterThan(1_000L, fetched.Bytes);
Assert.AreEqual(0xFF, file.GetBuffer()[0], "a JPEG of the CDN");
var refused = await fetcher.FetchAsync(new Uri(site.Url("/dati/inizio")), Stream.Null, null, ct);
Assert.AreEqual(FetchOutcome.HostNotAllowed, refused.Outcome, "only the CDN is downloaded");
// Forbidden commands are refused before WebView2, and change nothing.
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Emulation.setTimezoneOverride", new JsonObject { ["timezoneId"] = "America/New_York" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Network.setUserAgentOverride", new JsonObject { ["userAgent"] = "Febe" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = "1" }, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Fetch.enable", null, ct));
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.SendAsync("Target.createTarget", new JsonObject { ["url"] = "about:blank" }, ct));
var before = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => cdp.EvaluateAsync("window.scrollBy(0, 500)", ct));
await Task.Delay(300, ct);
var after = (await cdp.EvaluateAsync("window.scrollY", ct)).GetDouble();
Assert.IsLessThan(100.0, Math.Abs(after - before), "the refused script did not run (it would have scrolled 500 px)");
var zone = (await cdp.EvaluateAsync("Intl.DateTimeFormat().resolvedOptions().timeZone", ct)).GetString();
Assert.AreNotEqual("America/New_York", zone);
// Back to the rest page.
await bed.Browser.RestAsync(ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(10), ct);
Assert.AreEqual(CdpPageExtensions.RestUrl, await cdp.GetMainFrameUrlAsync(ct));
},
ct);
// The log has actions and outcomes only: no signed address of the CDN, no error.
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
private static string? FirstCdnAddress(JsonElement element, string cdnUrl)
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
{
if (property.Name == "indirizzo" && property.Value.ValueKind == JsonValueKind.String
&& property.Value.GetString() is { } address && address.StartsWith(cdnUrl, StringComparison.Ordinal) && address.Contains(".jpg", StringComparison.Ordinal))
{
return address;
}
if (FirstCdnAddress(property.Value, cdnUrl) is { } found)
{
return found;
}
}
return null;
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray())
{
if (FirstCdnAddress(item, cdnUrl) is { } found)
{
return found;
}
}
return null;
default:
return null;
}
}
private static async Task WaitUntilAsync(Func<bool> condition, TimeSpan timeout, string what, CancellationToken ct)
{
var deadline = DateTime.UtcNow + timeout;
while (!condition())
{
if (DateTime.UtcNow > deadline)
{
Assert.Fail($"Tempo scaduto: {what}.");
}
await Task.Delay(50, ct);
}
}
/// <summary>The JSON bodies the page received, by path.</summary>
private sealed class BodyCollector : IResponseConsumer
{
private readonly ConcurrentDictionary<string, string> _bodies = new(StringComparer.Ordinal);
public ICollection<string> Paths => _bodies.Keys;
public JsonElement Json(string path) => JsonDocument.Parse(_bodies[path]).RootElement.Clone();
public ValueTask ConsumeAsync(ResponseDescriptor response, JsonDocument body, CancellationToken ct)
{
_bodies.TryAdd(response.Path, body.RootElement.GetRawText());
return ValueTask.CompletedTask;
}
}
}
@@ -0,0 +1,102 @@
using System.Net.Http;
using Febe.App;
using Febe.Core.Domain;
using Febe.Desktop.Browser;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// One real collection session of the shared composition (<see cref="FebeApp"/>) running on WebView2, as Febe.exe
/// composes it, against the local test site, with files arriving in a temporary library. The Linux suite has the
/// equivalent with Chromium (ServerEndToEndTests). Never Instagram: the browser only sees 127.0.0.1.
/// </summary>
[TestClass]
public sealed class WebView2CollectionTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(420_000, CooperativeCancellation = true)]
public async Task ARealSessionOfTheCompositionRunsOnWebView2AndTheFilesArriveInTheLibrary()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("raccolta", autoLogin: true, ct);
var app = bed.App;
Assert.IsEmpty(app.Problems, string.Join("; ", app.Problems.Select(p => p.Title)));
// The browser starts from a thread of the composition (the path that failed on Alberto's PC), the pipeline and
// the engine follow.
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
Assert.IsInstanceOfType<WebView2Browser>(app.Browser);
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
Assert.AreEqual(Febe.Web.Connection.ConnectionState.Connected, (await app.Connection!.GetStatusAsync(ct)).State, "the test site's automatic login");
// Accounts and «Controlla ora» through the interface, as from the main window.
var added = await bed.JsonAsync(HttpMethod.Post, "/api/accounts", """{"usernames":["marta.prova","luca.prova"],"start":"everything"}""", ct);
Assert.AreEqual(2, added.GetProperty("added").GetInt32());
var marta = await app.Database.Accounts.FindByUsernameAsync("marta.prova", ct) ?? throw new AssertFailedException("marta.prova manca");
var check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", null, ct);
if (check.GetProperty("status").GetString() == "needsConfirmation")
{
check = await bed.JsonAsync(HttpMethod.Post, $"/api/accounts/{marta.Id}/check-now", $$"""{"token":"{{check.GetProperty("token").GetString()}}"}""", ct);
}
Assert.AreEqual("queued", check.GetProperty("status").GetString(), check.GetProperty("message").GetString());
// A session of the engine acts on the site through WebView2: every action has its Governor's permit.
await bed.WaitUntilAsync(
async () => (await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct)).Any(a => a.AccountId == marta.Id),
TimeSpan.FromSeconds(120),
"un'azione del motore su marta.prova nel registro delle azioni",
ct);
// Files arrive in the library, complete, downloaded through the browser from the test site's CDN.
var library = app.Library ?? throw new AssertFailedException("nessuna libreria");
List<Media> stored = [];
await bed.WaitUntilAsync(
async () =>
{
stored = await StoredAsync(app, marta.Id, ct);
return stored.Count >= 3;
},
TimeSpan.FromSeconds(180),
"tre file di marta.prova nella libreria",
ct);
foreach (var media in stored)
{
var path = library.FullPath(marta, media.RelativePath!);
Assert.IsTrue(File.Exists(path), path);
Assert.AreEqual(media.Bytes, new FileInfo(path).Length, path);
StringAssert.StartsWith(path, bed.Folder.Path, "inside the temporary library");
}
var actions = await app.Database.ActionLog.ListAsync(DateTimeOffset.UnixEpoch, bed.Clock.Now.AddDays(1), ct);
Assert.IsTrue(actions.All(a => a.SessionId is not null), "every counted action belongs to a session");
TestContext.WriteLine($"File di marta.prova: {stored.Count}; azioni: {actions.Count}; CDN: {bed.Site.Control.CdnFilesServed} file serviti.");
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("non parte"), "the browser never failed to start");
Assert.IsFalse(bed.Lines.Any("firma="), "no signed address in the log");
}
private static async Task<List<Media>> StoredAsync(FebeApp app, long accountId, CancellationToken ct)
{
var list = new List<Media>();
foreach (var entry in await app.Database.Entries.ListByAccountAsync(accountId, null, ct))
{
foreach (var media in await app.Database.Media.ListByEntryAsync(entry.Id, ct))
{
if (media.State == MediaState.Downloaded && media.RelativePath is not null && media.Sha256 is not null && entry.Kind != EntryKind.ProfilePicture)
{
list.Add(media);
}
}
}
return list;
}
}
@@ -0,0 +1,67 @@
using Febe.Core.Storage;
using Febe.Tests.Windows.Support;
using Febe.Web.Connection;
namespace Febe.Tests.Windows;
/// <summary>
/// The login on Windows through the real connection service of the composition (spec §4.1, docs/windows.md «Il primo
/// collegamento a Instagram»), on WebView2 and the test site: «Accedi a Instagram» opens the login page in the window
/// «Browser di Febe», which comes on screen while the engine is still; «Ho finito» checks the session (the cookie's name
/// only) and puts the window back out of view; «Scollega» deletes the profile with the session and the browser comes
/// back empty. The window comes on screen for a moment, as for Alberto.
/// </summary>
[TestClass]
public sealed class WebView2ConnectionTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(240_000, CooperativeCancellation = true)]
public async Task TheLoginBringsTheWindowAndScollegaEmptiesTheProfile()
{
var ct = TestContext.CancellationToken;
await using var bed = await DesktopBed.StartAsync("collegamento", autoLogin: false, ct);
var app = bed.App;
await app.Running.WaitAsync(TimeSpan.FromSeconds(120), ct);
var connection = app.Connection!;
var browser = bed.Browser;
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State, "a new profile is not connected");
var window = await bed.Ui.InvokeAsync(() => browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen));
// «Accedi a Instagram» (here the test site's welcome page, whose first visit starts its session).
await connection.BeginUserDrivingAsync(openLogin: true, ct);
var driving = await connection.GetStatusAsync(ct);
Assert.IsTrue(driving.UserIsDriving);
Assert.IsTrue(browser.UserIsDriving, "the engine is still while Alberto is at the browser");
Assert.IsTrue(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "the window «Browser di Febe» came on screen");
StringAssert.StartsWith(driving.CurrentUrl, bed.Site.SiteUrl, "the login page of the configured site, never Instagram in tests");
// «Ho finito».
var finish = await connection.FinishAsync(ct);
Assert.IsTrue(finish.Connected, finish.Message);
Assert.IsFalse(browser.UserIsDriving, "«Ho finito» ends the driving");
Assert.IsFalse(await bed.Ui.InvokeAsync(() => window.IsOnScreen), "and puts the window back out of view");
Assert.AreEqual(ConnectionState.Connected, (await connection.GetStatusAsync(ct)).State);
Assert.IsNotNull(await app.Database.Settings.GetInt64Async(Febe.App.BrowserConnectionService.FirstConnectionKey, ct), "first connection recorded");
// «Scollega»: engine stopped, WebView2 closed, profile deleted, browser started again empty, engine started again.
var marker = Path.Combine(browser.ProfileDirectory, "segno-della-prova");
await File.WriteAllTextAsync(marker, "x", ct);
await connection.DisconnectAsync(ct);
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
Assert.IsTrue(browser.IsAvailable, "the browser runs again, with an empty profile");
Assert.AreEqual(ConnectionState.NotConnected, (await connection.GetStatusAsync(ct)).State);
Assert.IsFalse(browser.UserIsDriving);
await bed.WaitUntilAsync(() => Task.FromResult(app.Engine!.Services.Runtime.IsRunning), TimeSpan.FromSeconds(10), "il motore di nuovo in funzione", ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Lines.Any("«Scollega»: motore fermo, profilo del browser cancellato, browser ripartito vuoto."), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("non parte"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
}
@@ -0,0 +1,299 @@
using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Browser.Recipes;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Desktop.Core;
using Febe.SitoDiProva;
using Febe.Tests.Windows.Support;
namespace Febe.Tests.Windows;
/// <summary>
/// The life of the browser of Febe on a real Windows, driven from thread-pool threads as the composition and the
/// connection service drive it: a start that really fails is retried (and only that), the window comes on screen and
/// goes away with the «driving» lease (the login), «Scollega» empties the profile and the browser comes back, a browser
/// process that dies is started again, and the second hosting of S2 (composition) starts and draws.
/// </summary>
/// <remarks>Two tests bring the window «Browser di Febe» on screen for a moment, as «Accedi a Instagram» does.</remarks>
[TestClass]
public sealed class WebView2LifecycleTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireWebView2() => WebView2Runtime.Require();
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AStartThatReallyFailsIsRetriedAndThenTheBrowserIsReady()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("tentativi");
// A file where the profile folder must go: WebView2 cannot start.
var profile = bed.Browser.ProfileDirectory;
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
await bed.WaitUntilAsync(() => bed.Lines.Any("non parte"), TimeSpan.FromSeconds(30), "il primo avvio non riuscito", ct);
Assert.IsFalse(bed.Browser.IsAvailable);
StringAssert.StartsWith(bed.Browser.LastError, "WebView2 non parte (IOException:");
StringAssert.EndsWith(bed.Lines.Lines.Single(l => l.Contains("non parte", StringComparison.Ordinal)), "Nuovo tentativo fra 5 s.");
// The obstacle goes away: the next attempt, 5 s later, works.
File.Delete(profile);
await run.WaitAsync(TimeSpan.FromSeconds(60), ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Browser.IsAvailable);
Assert.IsNull(bed.Browser.LastError);
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("non parte", StringComparison.Ordinal)), "one failed attempt only");
Assert.HasCount(1, bed.Lines.Lines.Where(l => l.Contains("Browser di Febe pronto: WebView2 ", StringComparison.Ordinal)));
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheWindowComesOnScreenWithTheLeaseAndGoesAwayWithIt()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("finestra");
await bed.StartAsync(ct);
var window = await bed.OnUiAsync(() => bed.Browser.Host.Window) ?? throw new AssertFailedException("nessuna finestra");
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "the window is open");
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen), "after the start it is parked out of view");
Assert.IsFalse(bed.Browser.UserIsDriving);
// «Accedi a Instagram» / «Portalo in primo piano», from the connection service's thread.
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsOnScreen), "the window came on screen");
Assert.IsTrue(bed.Browser.UserIsDriving, "while it is in front the engine is still");
Assert.IsNotNull(bed.Tracker.LastUsedAt, "using it counts for «Riprendi»");
// «Ho finito».
await Task.Run(() => bed.Browser.HideFromUserAsync(ct), ct);
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
Assert.IsFalse(bed.Browser.UserIsDriving);
// Closing the window is «ho finito» too: out of view, still open, still painting.
await Task.Run(() => bed.Browser.ShowToUserAsync(ct), ct);
Assert.IsTrue(bed.Browser.UserIsDriving);
await bed.OnUiAsync(() =>
{
window.Close();
return true;
});
Assert.IsFalse(bed.Browser.UserIsDriving);
Assert.IsTrue(await bed.OnUiAsync(() => window.IsVisible), "closing it never closes it");
Assert.IsFalse(await bed.OnUiAsync(() => window.IsOnScreen));
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(bed.Browser.Cdp, 50, ct), ct);
Assert.AreEqual(0xFF, jpeg[0], "the page still draws out of view");
Assert.IsTrue(bed.Browser.IsAvailable);
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task ScollegaDeletesTheProfileWithTheSessionAndTheBrowserComesBackEmpty()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("scollega");
await bed.StartAsync(ct);
var cdp = bed.Browser.Cdp;
var cookie = CollectionSite.TestSite(site.SiteHost, site.CdnHost).SessionCookie;
var clock = new SystemClock();
// «Collegato»: the site's session cookie is in the profile.
await Task.Run(
async () =>
{
await cdp.NavigateAsync(site.Url("/"), ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
},
ct);
Assert.IsTrue(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "connected to the test site");
var marker = Path.Combine(bed.Browser.ProfileDirectory, "segno-della-prova");
await File.WriteAllTextAsync(marker, "x", ct);
var before = bed.Browser.Host.BrowserProcessId;
// «Scollega», from the connection service's thread.
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsFalse(File.Exists(marker), "the profile folder was deleted");
Assert.IsTrue(bed.Browser.IsAvailable, "the browser runs again");
Assert.AreNotEqual(before, bed.Browser.Host.BrowserProcessId, "with a new browser process");
Assert.IsFalse(await Task.Run(() => SessionCookieProbe.HasSessionCookieAsync(cdp, cookie, ct), ct), "the session went with the profile");
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => cdp.GetMainFrameUrlAsync(ct), ct));
Assert.IsTrue(bed.Lines.Any("Profilo del browser cancellato; il browser è ripartito vuoto."));
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
}
/// <summary>
/// Regression (review of 20 October 2026): «Scollega» while the first start waits for its next attempt started the
/// browser, then the waiting attempt started a second WebView in the same window without closing the first. The
/// orphan kept its browser process alive on the profile: the next «Scollega» waited 15 s for nothing and could not
/// delete the profile (the Instagram session stayed on disk), and exiting waited 15 s more.
/// </summary>
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task ScollegaWhileTheFirstStartWaitsToRetryLeavesOneWebViewAndTheNextScollegaWorks()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("scollega-nei-tentativi");
// A file where the profile folder must go: the first start fails, and fails again 5 s later.
var profile = bed.Browser.ProfileDirectory;
Directory.CreateDirectory(Path.GetDirectoryName(profile)!);
await File.WriteAllTextAsync(profile, "occupa il posto della cartella del profilo", ct);
var run = Task.Run(() => bed.Browser.RunAsync(ct), ct);
await bed.WaitUntilAsync(() => bed.Lines.Any("Nuovo tentativo fra 15 s."), TimeSpan.FromSeconds(40), "il secondo avvio non riuscito", ct);
File.Delete(profile);
// «Scollega» while RunAsync waits 15 s for its third attempt: the browser starts with it.
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
Assert.IsTrue(bed.Browser.IsAvailable, bed.Lines.Text);
var pid = bed.Browser.Host.BrowserProcessId;
// The waiting attempt finds the browser running: no second WebView, the one of «Scollega» untouched.
await run.WaitAsync(TimeSpan.FromSeconds(40), ct);
var children = await bed.ChildWindowsAsync();
Assert.HasCount(1, children, "one WebView in the window: " + string.Join(", ", children));
Assert.AreEqual(pid, bed.Browser.Host.BrowserProcessId, "the browser process of «Scollega» is still the one in use");
Assert.IsTrue(bed.Lines.Any("Browser di Febe pronto: WebView2 "), bed.Lines.Text);
Assert.IsTrue(bed.Browser.IsAvailable);
// The next «Scollega»: the only browser process exits at once, the profile goes, the browser comes back.
var marker = Path.Combine(profile, "segno-della-prova");
await File.WriteAllTextAsync(marker, "x", ct);
var watch = Stopwatch.StartNew();
await Task.Run(() => bed.Browser.RestartWithEmptyProfileAsync(ct), ct);
TestContext.WriteLine($"Secondo «Scollega»: {watch.Elapsed.TotalSeconds:0.0} s.");
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "no wait for a browser process that never exits");
Assert.IsFalse(File.Exists(marker), "the profile with the session was deleted");
Assert.HasCount(1, await bed.ChildWindowsAsync());
Assert.IsTrue(bed.Browser.IsAvailable);
// Exiting closes the only WebView and its process exits: no wait in vain.
watch.Restart();
await bed.Browser.DisposeAsync();
TestContext.WriteLine($"Arresto: {watch.Elapsed.TotalSeconds:0.0} s.");
TestContext.WriteLine(bed.Lines.Text);
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds, "exiting waits for nothing");
Assert.HasCount(2, bed.Lines.Lines.Where(l => l.Contains("ERRORE", StringComparison.Ordinal)), "only the two failed starts: " + bed.Lines.Text);
}
/// <summary>
/// «Esci» while the start does not complete (review of 20 October 2026): the composition awaits
/// <see cref="Febe.Desktop.Browser.WebView2Browser.RunAsync"/> before it closes the browser, so RunAsync must stop
/// waiting as soon as it is cancelled. Here the UI thread is kept busy, as when WebView2 does not answer.
/// </summary>
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task OnExitTheStartStopsWaitingForAUiThreadThatDoesNotAnswer()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("uscita");
var released = false;
var busy = bed.Ui.Dispatcher.InvokeAsync(() =>
{
// Thread.Sleep does not pump: nothing else runs on the UI thread meanwhile.
var until = DateTime.UtcNow.AddSeconds(60);
while (!Volatile.Read(ref released) && DateTime.UtcNow < until)
{
Thread.Sleep(20);
}
});
using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(ct);
var run = Task.Run(() => bed.Browser.RunAsync(lifetime.Token), ct);
await Task.Delay(500, ct);
Assert.IsFalse(run.IsCompleted, "the start waits for the UI thread");
// «Esci»: FebeApp cancels its lifetime, then waits for RunAsync.
var watch = Stopwatch.StartNew();
await lifetime.CancelAsync();
try
{
await run.WaitAsync(TimeSpan.FromSeconds(10), ct);
}
finally
{
Volatile.Write(ref released, true);
await busy.Task;
}
TestContext.WriteLine($"RunAsync è tornato {watch.Elapsed.TotalSeconds:0.0} s dopo la cancellazione.");
Assert.IsLessThan(3, watch.Elapsed.TotalSeconds, "RunAsync stops waiting at once");
Assert.IsFalse(bed.Browser.IsAvailable);
// The start that was waiting for the UI thread does not begin after the exit, and stopping is quick.
watch.Restart();
await bed.Browser.DisposeAsync();
Assert.IsLessThan(10, watch.Elapsed.TotalSeconds);
Assert.IsNull(await bed.OnUiAsync(() => bed.Browser.Host.Window), "no window was created after the exit");
Assert.AreEqual(0, bed.Browser.Host.BrowserProcessId, "no browser process was started after the exit");
Assert.IsFalse(bed.Lines.Any("ERRORE"), bed.Lines.Text);
Assert.IsFalse(bed.Lines.Any("Browser di Febe pronto"), bed.Lines.Text);
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task WhenItsBrowserProcessDiesTheBrowserStartsAgainByItself()
{
var ct = TestContext.CancellationToken;
await using var bed = await BrowserBed.CreateAsync("arresto");
await bed.StartAsync(ct);
var reconnected = 0;
bed.Browser.Host.Connection.Reconnected += (_, _) => Interlocked.Increment(ref reconnected);
// The browser process this test started — by its id, never by name.
var pid = bed.Browser.Host.BrowserProcessId;
Assert.AreNotEqual(0, pid);
using (var process = Process.GetProcessById(pid))
{
Assert.AreEqual("msedgewebview2", process.ProcessName, "the browser process of WebView2");
process.Kill();
}
await bed.WaitUntilAsync(() => bed.Lines.Any("Browser di Febe ripartito: WebView2 "), TimeSpan.FromSeconds(90), "la ripartenza del browser", ct);
TestContext.WriteLine(bed.Lines.Text);
Assert.IsTrue(bed.Lines.Any("WebView2: processo terminato (BrowserProcessExited)."));
Assert.IsTrue(bed.Browser.IsAvailable);
Assert.AreNotEqual(pid, bed.Browser.Host.BrowserProcessId, "a new browser process");
Assert.AreEqual(1, Volatile.Read(ref reconnected), "the subscriptions of the session moved to the new WebView once");
Assert.AreEqual(CdpPageExtensions.RestUrl, await Task.Run(() => bed.Browser.Cdp.GetMainFrameUrlAsync(ct), ct));
Assert.IsFalse(bed.Lines.Any("non parte"), "the new start worked at once");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheCompositionHostingOfS2StartsAndDrawsThePage()
{
var ct = TestContext.CancellationToken;
await using var site = await TestSite.StartAsync(new TestSiteOptions(), ct);
await using var bed = await BrowserBed.CreateAsync("composizione", BrowserHosting.Composition);
await bed.StartAsync(ct);
Assert.IsTrue(bed.Lines.Any(", composizione, fuori vista."), bed.Lines.Text);
var cdp = bed.Browser.Cdp;
var clock = new SystemClock();
var seen = await Task.Run(
async () =>
{
await cdp.NavigateAsync(site.Url("/profilo/marta.prova/"), ct);
await cdp.WaitForLoadAsync(clock, TimeSpan.FromSeconds(15), ct);
return await cdp.EvaluateAsync("({ visibility: document.visibilityState, width: innerWidth, height: innerHeight })", ct);
},
ct);
TestContext.WriteLine("La pagina vede: " + seen.GetRawText());
Assert.AreEqual("visible", seen.GetProperty("visibility").GetString());
Assert.AreEqual(1280, seen.GetProperty("width").GetInt32());
var jpeg = await Task.Run(() => PagePreview.CaptureAsync(cdp, 60, ct), ct);
Assert.IsGreaterThan(5_000, jpeg.Length, "a real frame");
}
}
+3 -1
View File
@@ -15,7 +15,9 @@ public sealed class HostingTests
var args = ChromiumCommandLine.Build(Options, new ChromiumLaunchOptions());
CollectionAssert.Contains(args.ToList(), "--remote-debugging-port=9333");
CollectionAssert.Contains(args.ToList(), "--user-data-dir=/tmp/febe-profilo");
// The profile reaches Chromium as a full path: «/tmp/febe-profilo» on Linux, rooted on the current drive on Windows.
CollectionAssert.Contains(args.ToList(), $"--user-data-dir={Path.GetFullPath(Options.ProfileDirectory)}");
CollectionAssert.Contains(args.ToList(), "--no-first-run");
CollectionAssert.Contains(args.ToList(), "--no-default-browser-check");
CollectionAssert.Contains(args.ToList(), "--window-size=1280,900");
@@ -0,0 +1,129 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using Febe.Browser.Cdp;
using Febe.Browser.Diagnostics;
using Febe.Browser.RemoteView;
using Febe.Tests.Browser.TestSupport;
namespace Febe.Tests.Browser;
/// <summary>
/// The remote view started while the page is between two documents (Gitea issue #3), on a real Chromium on Xvfb and the
/// local test site. From <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until its commit,
/// DevTools points at the new, not yet active document and Chromium refuses <c>Page.startScreencast</c> with -32000
/// «Not attached to an active page». That moment lasts milliseconds in real use; here a page keeps its renderer busy, so
/// a navigation away from it to a page of the same site waits to commit for over a second and the start lands in it on
/// purpose. The view must open once the new document has committed and show its frames. If Chromium ever answers that
/// moment with another text or code, the start fails here, on the CI, and not in Alberto's hands.
/// </summary>
/// <remarks>
/// Seen with Chrome 155 on the development machine (a standalone CDP experiment, same pages): the start was refused in
/// every round to a page of the same site and went through once the new document had committed. A navigation to
/// about:blank from a site page commits in another renderer, which is not busy, so it is not used here. And a view opened
/// through the host after a navigation has begun does not meet the refusal at all: its <c>Page.getFrameTree</c> is answered
/// only once that navigation has committed (see ServerEndToEndTests.AViewOpenedWhileThePageIsNavigating…).
/// </remarks>
[TestClass]
[DoNotParallelize]
public sealed class RemoteViewDuringNavigationTests
{
public TestContext TestContext { get; set; } = null!;
[TestInitialize]
public void RequireBrowser()
{
if (RealBrowser.UnavailableReason() is { } reason)
{
Assert.Inconclusive(reason);
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task AViewStartedBeforeTheNewDocumentCommitsOpensOnceItHasCommitted()
{
var ct = TestContext.CancellationToken;
await using var browser = await RealBrowser.StartAsync();
var cdp = browser.Cdp;
const int rounds = 6;
var refusedRounds = 0;
for (var round = 0; round < rounds; round++)
{
// Page.navigate answers once the new document is ready to commit; the busy page commits a moment later and its
// script holds the renderer from 0.1 s after that, for 2 s.
var busy = await cdp.NavigateAsync(browser.Site.Url("/occupata"), ct);
Assert.IsTrue(busy.Succeeded, busy.ErrorText);
await Task.Delay(TimeSpan.FromMilliseconds(500), ct);
// The login page of the site, as «Accedi a Instagram» opens it: ready to commit at once, committed only when
// the busy script lets go.
var navigation = cdp.NavigateAsync(browser.Site.Url($"/accesso?giro={round}"), ct);
await Task.Delay(TimeSpan.FromMilliseconds(150), ct);
var notes = new ConcurrentQueue<string>();
var log = new DelegateBrowserLog((level, message, _) =>
{
if (level == BrowserLogLevel.Debug)
{
notes.Enqueue(message);
}
});
var view = new RemoteViewSession(cdp, browser.Host.UserDriving, log);
try
{
var watch = Stopwatch.StartNew();
await view.StartAsync(new ScreencastOptions(Quality: 60, MaxWidth: 1280, MaxHeight: 900), ct);
watch.Stop();
var navigated = await navigation;
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
Assert.IsTrue(browser.Host.UserIsDriving, $"Round {round}: the open view holds the browser.");
// Only the attempt number is in the note (ScreencastSession): «… al tentativo N, dopo un cambio di pagina.»
var retry = notes.FirstOrDefault(n => n.Contains("tentativo", StringComparison.Ordinal));
if (retry is not null)
{
refusedRounds++;
}
TestContext.WriteLine($"Giro {round}: vista aperta in {watch.ElapsedMilliseconds} ms; {retry ?? "fotogrammi avviati al primo tentativo."}");
// The frames of the new document: an animated page repaints all the time.
var animated = await cdp.NavigateAsync(browser.Site.Url("/animata"), ct);
Assert.IsTrue(animated.Succeeded, animated.ErrorText);
Assert.IsTrue(await JpegArrivesAsync(view.Screencast, ct), $"Round {round}: frames after the view opened.");
}
finally
{
await view.DisposeAsync();
}
Assert.IsFalse(browser.Host.UserIsDriving, $"Round {round}: the closed view released the browser.");
}
TestContext.WriteLine($"Giri in cui Chromium ha rifiutato il primo avvio con «{CdpCommandException.InactivePageMessage}»: {refusedRounds} su {rounds}.");
if (refusedRounds == 0)
{
// Every view opened: the product is fine, but the start never met the refusal, so the retry was not exercised.
Assert.Inconclusive("La vista si è aperta in ogni giro, ma Chromium non ha mai rifiutato il primo avvio: la prova non ha raggiunto il momento fra «ready to commit» e il commit (pagina /occupata, versione di Chromium) e il ritentativo non è stato messo alla prova.");
}
}
private static async Task<bool> JpegArrivesAsync(ScreencastSession screencast, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
try
{
await foreach (var frame in screencast.ReadFramesAsync(timeout.Token))
{
return frame.Jpeg is [0xFF, 0xD8, ..];
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
}
return false;
}
}
@@ -202,6 +202,10 @@ public sealed class LocalTestSite : IDisposable
"/spa" => "<p>Applicazione</p><script>addEventListener('load', () => setTimeout(() => history.pushState({}, '', '/verifica/interna?x=1'), 300));</script>",
"/verifica" => "<h1>Verifica</h1>",
"/accesso" => "<h1>Accesso</h1>",
// Keeps its renderer busy for 2 s, from 0.1 s after it has committed: a navigation away from it to a page of the
// same site (same renderer) reaches «ready to commit» at once but commits only when the script lets go.
"/occupata" => "<p>Occupata</p><script>setTimeout(() => { const end = performance.now() + 2000; while (performance.now() < end) { } }, 100);</script>",
_ => "<p>Pagina di prova</p>",
};
@@ -4,7 +4,6 @@ using Febe.Browser.Cdp;
using Febe.Browser.Gestures;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.SitoDiProva;
using Febe.Sonda;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
@@ -16,6 +15,7 @@ namespace Febe.Tests.Collection;
/// the probe only listens. Then the whole M0 path: raw samples, cleaning, verification.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class ProbeIntegrationTests
{
@@ -53,7 +53,7 @@ public sealed class ProbeIntegrationTests
Assert.Inconclusive(s_unavailable);
}
await using var site = await TestSite.StartAsync();
await using var site = await SyntheticSite.StartAsync();
using var temp = new TempFolder("sonda");
var raw = temp.Combine("grezzi");
var hosts = new HostClassifier([site.SiteHost], [site.CdnHost]);
@@ -5,6 +5,7 @@ using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
@@ -13,6 +14,7 @@ namespace Febe.Tests.Collection;
/// Instagram. Time is compressed (a 2.2 s wait lasts about 0.2 s); the browser is shared and the tests run one at a time.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class RecipeIntegrationTests
{
@@ -7,6 +7,7 @@ using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
@@ -14,6 +15,7 @@ namespace Febe.Tests.Collection;
/// Stop signals (spec §7.6) and the download queue (spec §6.5) against the local test site with a real Chromium.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed class StopAndDownloadIntegrationTests
{
@@ -129,7 +129,7 @@ internal sealed class CollectionHarness : IAsyncDisposable
public static async Task<CollectionHarness> CreateAsync(SharedChromium chromium, RecipeOptions? options = null, double factor = 10)
{
var site = await TestSite.StartAsync(new TestSiteOptions());
var site = await SyntheticSite.StartAsync();
var temp = new TempFolder("raccolta");
var library = await TestLibrary.CreateAsync(temp);
var clock = new CompressedClock(factor, TestZones.Rome);
@@ -0,0 +1,262 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Febe.Core.Collection.Readers;
using Febe.Core.Domain;
using Febe.SitoDiProva;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The synthetic world of the test site and its seed (<see cref="SyntheticSite"/>), without a browser, so they run
/// everywhere: what the integration tests take for granted holds for every seed, and the readers of
/// <c>lettori.prova.json</c> read what the site serves with the seed of this run, page after page. Never Instagram:
/// the site is on 127.0.0.1.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
public sealed partial class SyntheticSiteSeedTests
{
private static readonly ShapeReader Reader = new(ReaderVocabulary.LoadTestSite());
private static readonly string[] StoryBarOrder = ["marta.prova", "nadia.prova", "luca.prova", "giulia.prova"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void TheSeedComesFromTheVariableAndIsThirteenWithoutIt()
{
Assert.AreEqual(13, SyntheticSite.ParseSeed(null));
Assert.AreEqual(13, SyntheticSite.ParseSeed(" "));
Assert.AreEqual(4242, SyntheticSite.ParseSeed("4242"));
Assert.AreEqual(-7, SyntheticSite.ParseSeed(" -7 "));
Assert.ThrowsExactly<InvalidOperationException>(() => SyntheticSite.ParseSeed("tredici"));
Assert.ThrowsExactly<InvalidOperationException>(() => SyntheticSite.ParseSeed("99999999999"));
}
[TestMethod]
public void EveryTestThatStartsTheSiteTakesTheSeedOfTheRunAndIsInItsCategory()
{
var tests = Repository.PathOf("tests", "Febe.Tests");
var direct = new List<string>();
var outside = new List<string>();
foreach (var file in Directory.EnumerateFiles(tests, "*.cs", SearchOption.AllDirectories))
{
var name = Path.GetRelativePath(tests, file).Replace('\\', '/');
if (name.StartsWith("bin/", StringComparison.Ordinal) || name.StartsWith("obj/", StringComparison.Ordinal))
{
continue;
}
var text = File.ReadAllText(file);
if (name != "Support/SyntheticSite.cs" && DirectStart().IsMatch(text))
{
direct.Add(name);
}
if (SiteStart().IsMatch(text) && text.Contains("[TestClass]", StringComparison.Ordinal)
&& !text.Contains("[TestCategory(SyntheticSite.Category)]", StringComparison.Ordinal))
{
outside.Add(name);
}
}
Assert.IsEmpty(direct, "The site starts through SyntheticSite.StartAsync, which reads FEBE_SEME_PROVA: " + string.Join(", ", direct));
Assert.IsEmpty(outside, "The CI runs these tests again with the seed of the run only through their category: " + string.Join(", ", outside));
}
[TestMethod]
public void EverySeedGivesTheWorldTheIntegrationTestsRelyOn()
{
var now = new DateTimeOffset(2026, 10, 20, 9, 30, 0, TimeSpan.Zero);
int[] extremes = [SyntheticSite.Seed, int.MinValue, -1, 0, int.MaxValue];
foreach (var seed in extremes.Concat(Enumerable.Range(1, 300)).Distinct())
{
var world = World.Generate(seed, now);
var context = "seme " + seed.ToString(CultureInfo.InvariantCulture);
Assert.AreEqual(seed, world.Seed, context);
Assert.AreEqual("alberto.prova", world.Viewer.Username, context);
Assert.HasCount(31, world.Accounts, context);
Assert.HasCount(28, world.Following, context);
var counts = new Dictionary<string, int>
{
["alberto.prova"] = 4,
["marta.prova"] = 18,
["luca.prova"] = 40,
["giulia.prova"] = 6,
["nadia.prova"] = 3,
["paolo.prova"] = 8,
["riservato.prova"] = 5,
};
foreach (var (username, count) in counts)
{
Assert.HasCount(count, world.FindByUsername(username)!.Posts, $"{context}: {username}");
}
foreach (var account in world.Accounts)
{
if (account.Username.StartsWith("amico", StringComparison.Ordinal))
{
Assert.IsTrue(account.Posts.Count is 1 or 2, $"{context}: {account.Username}");
}
// Newest first, strictly: «known content at the top» and the cursors rely on it.
for (var i = 1; i < account.Posts.Count; i++)
{
Assert.IsTrue(account.Posts[i - 1].PublishedAt > account.Posts[i].PublishedAt, $"{context}: {account.Username} #{i}");
}
}
var posts = world.Accounts.SelectMany(a => a.Posts).ToList();
Assert.HasCount(posts.Count, posts.Select(p => p.Code).Distinct(StringComparer.Ordinal), $"{context}: codes are unique");
Assert.HasCount(posts.Count, posts.Select(p => p.Id).Distinct(StringComparer.Ordinal), $"{context}: identifiers are unique");
Assert.IsTrue(posts.All(p => p.Code.Length == 7 && p.PublishedAt <= now), context);
var feed = world.Feed();
for (var i = 1; i < feed.Count; i++)
{
Assert.IsTrue(feed[i - 1].PublishedAt >= feed[i].PublishedAt, $"{context}: feed #{i}");
}
CollectionAssert.AreEqual(StoryBarOrder, world.StoryBar(now).Select(a => a.Username).ToArray(), context);
var marta = world.FindByUsername("marta.prova")!;
var active = marta.Stories.Where(s => s.ExpiresAt > now).ToList();
Assert.HasCount(4, active, context);
Assert.AreEqual(1, active.Count(s => s.File.IsVideo), context);
Assert.HasCount(3, world.FindByUsername("nadia.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
Assert.HasCount(2, world.FindByUsername("luca.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
Assert.HasCount(5, world.FindByUsername("giulia.prova")!.Stories.Where(s => s.ExpiresAt > now), context);
var grid = world.Grid(marta, ProfileTab.Posts);
Assert.IsTrue(grid.Take(2).All(p => p.Pinned) && grid.Count(p => p.Pinned) == 2, $"{context}: two pinned posts on top");
Assert.IsTrue(grid.Take(DataApi.GridPageSize).Any(p => p.Files.Count == 3), $"{context}: a series on the first page");
Assert.HasCount(3, world.Grid(marta, ProfileTab.Tagged), context);
CollectionAssert.AreEqual(new[] { "Estate", "Viaggi" }, marta.Highlights.Select(h => h.Title).ToArray(), context);
Assert.IsTrue(marta.Highlights[0].Items.Any(i => i.Id == marta.Stories[1].Id), $"{context}: a story also in «Estate» (H9)");
}
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task TheLoginAddressOfTheTestSiteIsAWelcomePageThatOpensTheSession()
{
// Febe opens /benvenuto as the «pagina di accesso» of the test site (LoginUrl of DesktopOptions and ServerOptions).
await using var site = await SyntheticSite.StartAsync();
using var client = new HttpClient(new SocketsHttpHandler { UseProxy = false, UseCookies = false });
using var response = await client.GetAsync(new Uri(site.Url("/benvenuto")), TestContext.CancellationToken);
Assert.AreEqual(System.Net.HttpStatusCode.OK, response.StatusCode);
var html = await response.Content.ReadAsStringAsync(TestContext.CancellationToken);
StringAssert.Contains(html, "Ho finito");
Assert.DoesNotContain("<form", html, "No login form: the test site never asks for a password.");
Assert.IsTrue(
response.Headers.TryGetValues("Set-Cookie", out var cookies) && cookies.Any(c => c.StartsWith(TestSite.SessionCookie + "=", StringComparison.Ordinal)),
"The visit opens the session of the site.");
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheReadersReadWhatTheSiteServesWithTheSeedOfThisRun()
{
await using var site = await SyntheticSite.StartAsync();
TestContext.WriteLine($"Seme del mondo sintetico: {site.World.Seed.ToString(CultureInfo.InvariantCulture)}");
Assert.AreEqual(SyntheticSite.Seed, site.World.Seed);
string[] feed, firstFeedPageSeries, martaFirstPage, lucaGrid, martaStories, following;
string seriesCode, sharedStory, summerId;
lock (site.World.Gate)
{
var world = site.World;
var marta = world.FindByUsername("marta.prova")!;
feed = [.. world.Feed().Select(p => p.Id)];
firstFeedPageSeries = [.. world.Feed().Take(DataApi.FeedPageSize).Where(p => p.Files.Count > 1).Select(p => p.Id)];
martaFirstPage = [.. world.Grid(marta, ProfileTab.Posts).Take(DataApi.GridPageSize).Select(p => p.Id)];
seriesCode = world.Grid(marta, ProfileTab.Posts).First(p => p.Files.Count == 3).Code;
lucaGrid = [.. world.Grid(world.FindByUsername("luca.prova")!, ProfileTab.Posts).Select(p => p.Id)];
martaStories = [.. marta.Stories.Select(s => s.Id)];
sharedStory = marta.Stories[1].Id;
summerId = marta.Highlights[0].Id;
following = [.. world.Following.Select(a => a.Username)];
}
// The home: the connected account, the stories bar, then the whole feed page by page, as the recipe scrolls it.
var home = await ReadAsync(site, "/dati/inizio");
Assert.AreEqual(ReadShape.Recognized, home.Shape);
Assert.AreEqual("alberto.prova", home.Viewer?.Username);
CollectionAssert.AreEqual(StoryBarOrder, home.Profiles.Where(p => p.LatestStoryAt is not null).Select(p => p.Username).ToArray());
CollectionAssert.AreEqual(firstFeedPageSeries, home.Contents.Where(c => !c.IsComplete).Select(c => c.Id).ToArray(), "A series arrives incomplete in the feed.");
Assert.IsTrue(home.Contents.Where(c => !c.IsComplete).All(c => c.Files.Count == 1));
CollectionAssert.AreEqual(feed, await AllPagesAsync(site, home, "/dati/inizio/altri?dopo="));
// Marta's grid: two pinned posts on top, her highlights, her post count.
var profile = await ReadAsync(site, "/dati/profilo/marta.prova?scheda=post");
CollectionAssert.AreEqual(martaFirstPage, profile.Contents.Select(c => c.Id).ToArray());
Assert.IsTrue(profile.Contents.Take(2).All(c => c.Pinned) && profile.Contents.Count(c => c.Pinned) == 2);
CollectionAssert.AreEqual(new[] { "Estate", "Viaggi" }, profile.Highlights.Select(h => h.Title).ToArray());
Assert.AreEqual(18, profile.Profiles.Single(p => p.PostCount is not null).PostCount);
// Luca's history, page after page (the backfill): every post once, in order.
var luca = await ReadAsync(site, "/dati/profilo/luca.prova?scheda=post");
CollectionAssert.AreEqual(lucaGrid, await AllPagesAsync(site, luca, "/dati/profilo/luca.prova/altri?scheda=post&dopo="));
// A series on its own page: complete, in order, a video in the middle.
var series = (await ReadAsync(site, "/dati/post/" + seriesCode)).Contents.Single();
Assert.AreEqual(seriesCode, series.Code);
Assert.IsTrue(series.IsComplete);
CollectionAssert.AreEqual(new[] { MediaKind.Photo, MediaKind.Video, MediaKind.Photo }, series.Files.Select(f => f.Kind).ToArray());
// Stories and a highlight that shares one of them (H9).
var stories = await ReadAsync(site, "/dati/storie/marta.prova");
CollectionAssert.AreEqual(martaStories, stories.Contents.Select(c => c.Id).ToArray());
Assert.AreEqual(1, stories.Contents.Count(c => c.Files[0].Kind == MediaKind.Video));
var summer = (await ReadAsync(site, "/dati/evidenza/" + summerId)).Highlights.Single();
Assert.HasCount(3, summer.Items);
Assert.IsTrue(summer.Items.Any(i => i.Id == sharedStory));
// The following list, page after page, and a private profile Alberto does not follow.
var first = await ReadAsync(site, "/dati/seguiti");
var names = first.Profiles.Select(p => p.Username).ToList();
var page = first.Page;
while (page?.HasMore == true)
{
var next = await ReadAsync(site, "/dati/seguiti?dopo=" + Uri.EscapeDataString(page.Cursor!));
names.AddRange(next.Profiles.Select(p => p.Username));
page = next.Page;
}
CollectionAssert.AreEqual(following, names);
var hidden = await ReadAsync(site, "/dati/profilo/riservato.prova?scheda=post");
Assert.AreEqual(true, hidden.Profiles.Single().IsPrivate);
Assert.AreEqual(false, hidden.Profiles.Single().IsFollowed);
Assert.IsEmpty(hidden.Contents);
}
private async Task<ReadResult> ReadAsync(TestSite site, string pathAndQuery)
{
var result = Reader.Read(await site.GetDataAsync(pathAndQuery, TestContext.CancellationToken));
Assert.AreEqual(ReadShape.Recognized, result.Shape, pathAndQuery);
return result;
}
/// <summary>The identifiers of a first page and of every page after it, following the cursors.</summary>
private async Task<string[]> AllPagesAsync(TestSite site, ReadResult first, string nextPath)
{
var ids = first.Contents.Select(c => c.Id).ToList();
var page = first.Page;
while (page?.HasMore == true)
{
var next = await ReadAsync(site, nextPath + Uri.EscapeDataString(page.Cursor!));
ids.AddRange(next.Contents.Select(c => c.Id));
page = next.Page;
}
return [.. ids];
}
[GeneratedRegex(@"\bTestSite\.StartAsync\(")]
private static partial Regex DirectStart();
[GeneratedRegex(@"\b(?:SyntheticSite\.StartAsync|CollectionHarness\.CreateAsync|ServerTestBed\.StartAsync)\(")]
private static partial Regex SiteStart();
}
+55 -7
View File
@@ -112,10 +112,10 @@ public sealed partial class InstallerTests
StringAssert.Contains(text, "100 * 1024 * 1024");
Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR");
var bash = FindOnPath("bash");
var bash = FindBash();
if (bash is null)
{
return;
Assert.Inconclusive("Manca bash (su Windows: Git Bash): la prova della sintassi di costruisci.sh si salta.");
}
using var process = Process.Start(new ProcessStartInfo(bash, ["-n", script]) { RedirectStandardError = true })!;
@@ -124,21 +124,69 @@ public sealed partial class InstallerTests
Assert.AreEqual(0, process.ExitCode, errors);
}
private static string? FindOnPath(string name)
private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault();
/// <summary>
/// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash
/// first (next to git on PATH, then where its installer puts it), else any bash on PATH except the WSL launcher:
/// <c>System32\bash.exe</c> and the <c>WindowsApps</c> alias start a Linux distribution, which may be missing
/// («execvpe(/bin/bash) failed») and does not see the script by its Windows path.
/// </summary>
private static string? FindBash()
{
if (!OperatingSystem.IsWindows())
{
return FindOnPath("bash");
}
var roots = new List<string>();
if (FindOnPath("git") is { } git)
{
// git.exe sits in <Git>\cmd, <Git>\bin or <Git>\mingw64\bin.
for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder))
{
roots.Add(folder);
}
}
foreach (var variable in new[] { "ProgramW6432", "ProgramFiles", "ProgramFiles(x86)" })
{
if (Environment.GetEnvironmentVariable(variable) is { Length: > 0 } programs)
{
roots.Add(Path.Combine(programs, "Git"));
}
}
roots.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs", "Git"));
var gitBash = roots
.SelectMany(root => new[] { Path.Combine(root, "bin", "bash.exe"), Path.Combine(root, "usr", "bin", "bash.exe") })
.FirstOrDefault(path => File.Exists(path) && !IsWslLauncher(path));
return gitBash ?? OnPath("bash").FirstOrDefault(path => !IsWslLauncher(path));
}
private static bool IsWslLauncher(string path)
{
var full = Path.GetFullPath(path);
var windows = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
return (windows.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(windows) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
|| full.Contains(@"\Microsoft\WindowsApps\", StringComparison.OrdinalIgnoreCase);
}
/// <summary>Every file called <paramref name="name"/> on PATH, in order (on Windows only <c>.exe</c>: the others do not start).</summary>
private static IEnumerable<string> OnPath(string name)
{
var candidates = OperatingSystem.IsWindows() ? new[] { name + ".exe" } : new[] { name, name + ".exe" };
foreach (var folder in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
foreach (var candidate in new[] { name, name + ".exe" })
foreach (var candidate in candidates)
{
var path = Path.Combine(folder, candidate);
if (File.Exists(path))
{
return path;
yield return path;
}
}
}
return null;
}
[GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?<target>[^""]+)""", RegexOptions.Multiline)]
@@ -286,6 +286,26 @@ public sealed class WebView2CdpSessionTests
CollectionAssert.AreEqual(new[] { "uno", "due" }, received.ToArray());
}
[TestMethod]
public async Task AFailingReconnectionHandlerDoesNotUndoTheAttach()
{
// Attach runs inside the start of the new WebView: an error of whoever listens must not turn a start that worked
// into a failed one, retried with the same outcome for ever.
var log = new RecordingBrowserLog();
await using var session = new WebView2CdpSession(log);
var later = 0;
session.Reconnected += (_, _) => throw new InvalidOperationException("guasto di chi ascolta");
session.Reconnected += (_, _) => later++;
session.Attach(new FakeDevTools());
session.Attach(new FakeDevTools());
Assert.IsTrue(session.IsAttached, "the new WebView stays attached");
Assert.AreEqual(1, later, "the other handlers still hear of it");
Assert.IsTrue(log.Lines.Any(l => l.StartsWith("Warning ", StringComparison.Ordinal) && l.Contains("InvalidOperationException", StringComparison.Ordinal)), log.All);
Assert.AreEqual("{}", (await session.SendAsync("Page.enable", ct: TestContext.CancellationToken)).GetRawText());
}
[TestMethod]
public void ProtocolErrorsAreReadFromTheMessageOfWebView2()
{
@@ -0,0 +1,254 @@
using Febe.Core.Abstractions;
using Febe.Core.Alerts;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Alerts.Support;
using Febe.Tests.Collection.Support;
using Febe.Tests.Engine.Support;
using Febe.Web.Api;
namespace Febe.Tests.Engine;
/// <summary>
/// «Storico completato» is one line of Attività and one alert per history, written by the engine with its numbers:
/// the real recipes on the scripted site (no browser) under the real engine, and the runs that end otherwise right
/// after the last page.
/// </summary>
[TestClass]
public sealed class BackfillCompletedTests
{
private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0);
/// <summary>Found testing Febe for Windows on the test site: two lines in «Avvisi» for one history, at 14:31.</summary>
[TestMethod]
public async Task AHistoryCompletedByTheRecipesIsOneLineOfAvvisiWithItsNumbersAndOneNotification()
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var (runner, site) = RealRecipes(engine);
var marta = site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
marta.Posts.AddRange(ScriptedBed.Posts(0, 18, Morning.AddDays(-30)));
var account = await AddBackfillingAsync(engine, marta, postCount: 18);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(2));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
const string Expected = "Storico di @marta.prova completato: 18 post in libreria. Da ora lo tengo aggiornato.";
var done = await engine.Db.Accounts.GetAsync(account.Id);
Assert.IsNotNull(done!.BackfillCompletedAt, "The history reached the beginning of the profile.");
Assert.AreEqual(AccountState.UpToDate, done.State);
Assert.HasCount(18, await engine.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Post, Limit = 100 }));
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines, "One line for one history: " + string.Join(" | ", lines.Select(e => e.Message)));
Assert.AreEqual(Expected, lines[0].Message);
Assert.AreEqual(EventSeverity.Success, lines[0].Severity);
Assert.AreEqual(account.Id, lines[0].AccountId);
Assert.IsNotNull(lines[0].SessionId);
// The «Avvisi» list of Attività.
var alerts = (await ActivityApi.AlertsAsync(engine.Db, engine.Clock, CancellationToken.None)).Items.Where(i => i.Kind == "backfillDone").ToList();
Assert.HasCount(1, alerts);
Assert.AreEqual(Expected, alerts[0].Message);
// One Windows notification and one Telegram message, with the same full text.
var notification = bed.Shell.Notifications.Single(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone));
Assert.AreEqual(Expected, notification.Message);
var telegram = bed.Telegram.Requests.Where(r => r.Text.StartsWith("Febe · Storico completato\n", StringComparison.Ordinal)).ToList();
Assert.HasCount(1, telegram);
Assert.AreEqual("Febe · Storico completato\n" + Expected, telegram[0].Text);
Assert.HasCount(1, bed.Outcomes.Where(o => o.Alert.Kind == AlertKind.BackfillDone), "Nothing held back as a repeat either.");
}
/// <summary>
/// A run that completes the history: the walk reached the beginning of the profile and stored it, then a signal or
/// a cancellation changed how the run ended; or a profile check found the whole profile on its first page. The
/// history is closed with its line (it would never be walked again), and right after that run the Coda shows
/// nothing planned for the account, now paused: no «Storico» put back in the queue (review F3).
/// </summary>
[TestMethod]
[DataRow(RecipeKind.Backfill, RecipeStatus.StoppedBySignal)]
[DataRow(RecipeKind.Backfill, RecipeStatus.Cancelled)]
[DataRow(RecipeKind.ProfileCheck, RecipeStatus.Completed)]
public async Task AHistoryCompletedByARunIsClosedWithItsLineAndLeavesNothingInTheQueue(RecipeKind kind, RecipeStatus status)
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var account = await engine.AddAccountAsync("luca.prova", followed: true, state: AccountState.Backfilling, postCount: 30);
await engine.Db.Accounts.UpdateAsync((await engine.Db.Accounts.GetAsync(account.Id))! with { KeepUpdated = false });
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
RecipeRequest? closing = null;
var walksAfter = 0;
runner.Before = async r =>
{
if (r.AccountId != account.Id)
{
return;
}
if (closing is not null)
{
walksAfter += r.Kind == RecipeKind.Backfill ? 1 : 0;
}
else if (r.Kind == kind)
{
// What the recipe stores: the walk met the end of the list, or the whole profile is on its first page.
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
closing = r;
}
};
runner.Script = r => ReferenceEquals(r, closing) ? new RecipeOutcome(status, 1, 6) { BackfillFinished = true } : null;
engine.Start(runner);
var end = Morning.AddDays(2);
while (closing is null && engine.Clock.Now < end)
{
await engine.RunForAsync(TimeSpan.FromMinutes(1));
}
// Right after that run, before the next session tidies the queue.
Assert.IsNotNull(closing);
var queued = (await engine.Db.Tasks.ListPendingAsync(1000)).Where(t => t.AccountId == account.Id).ToList();
Assert.HasCount(0, queued, "Planned for a paused account: " + string.Join(", ", queued.Select(t => $"{t.Kind} «{t.LastError}»")));
await engine.RunUntilAsync(end);
await engine.StopAsync();
await bed.Alerts.FlushAsync();
Assert.AreEqual(0, walksAfter, "Never walked again.");
var finished = await engine.Db.Accounts.GetAsync(account.Id);
Assert.AreEqual(AccountState.Paused, finished!.State, "«Tieni aggiornato» off: one download, then paused.");
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines);
Assert.AreEqual("Storico di @luca.prova completato: 0 post in libreria. «Tieni aggiornato» è spento: l'account resta in pausa.", lines[0].Message);
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
}
/// <summary>
/// A profile that fits on its first page: the profile check completes its history. When the walk of the session
/// went to another account «Storico in corso», the small one stayed so for ever, with no line and no alert (review
/// F1). Added first, the small one is the walk's next pick in that very session: it must not get a second line.
/// An account that keeps only the new posts has no history to announce.
/// </summary>
[TestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task AHistoryCompletedByTheProfileCheckIsClosedAtOnceWithOneLine(bool smallFirst)
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var (runner, site) = RealRecipes(engine);
var big = site.Add(new ScriptedAccount("3003", "grande.prova") { Followed = false });
big.Posts.AddRange(ScriptedBed.Posts(0, 400, Morning.AddDays(-30), prefix: "g"));
var small = site.Add(new ScriptedAccount("4004", "piccolo.prova") { Followed = false });
small.Posts.AddRange(ScriptedBed.Posts(0, 5, Morning.AddDays(-30), prefix: "s"));
var news = site.Add(new ScriptedAccount("5005", "nuovi.prova") { Followed = false });
news.Posts.AddRange(ScriptedBed.Posts(0, 3, Morning.AddDays(-30), prefix: "n"));
// Among the accounts «Storico in corso» the walk takes the lowest id first.
Account smallAccount;
if (smallFirst)
{
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
await AddBackfillingAsync(engine, big, postCount: 400);
}
else
{
await AddBackfillingAsync(engine, big, postCount: 400);
smallAccount = await AddBackfillingAsync(engine, small, postCount: 5);
}
var newsAccount = await engine.Db.Accounts.AddAsync(Account.Create(news.Username, StartingPoint.OnlyNewFromToday, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
{
InstagramId = news.Id,
IsFollowed = news.Followed,
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
PostCount = 3,
});
Assert.AreEqual(AccountState.UpToDate, newsAccount.State);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(4));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
var all = string.Join(" | ", lines.Select(e => e.Message));
var done = await engine.Db.Accounts.GetAsync(smallAccount.Id);
Assert.IsNotNull(done!.BackfillCompletedAt, "The whole profile is on its first page.");
Assert.AreEqual(AccountState.UpToDate, done.State, all);
const string Expected = "Storico di @piccolo.prova completato: 5 post in libreria. Da ora lo tengo aggiornato.";
Assert.HasCount(1, lines.Where(e => e.AccountId == smallAccount.Id).ToList(), all);
Assert.AreEqual(Expected, lines.Single(e => e.AccountId == smallAccount.Id).Message);
Assert.AreEqual(1, bed.Shell.Notifications.Count(n => n.Message == Expected));
Assert.IsFalse(lines.Any(e => e.AccountId == newsAccount.Id), "«Solo i nuovi»: no history. " + all);
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(newsAccount.Id))!.State);
Assert.IsTrue(lines.GroupBy(e => e.AccountId).All(g => g.Count() == 1), "One line per history: " + all);
}
/// <summary>
/// An account «Storico in corso» whose history is already complete (a profile check closed it and Febe stopped
/// before recording the outcome, or a version that left it so): closed when the next session starts, with its
/// line, without walking anything.
/// </summary>
[TestMethod]
public async Task AnAccountLeftStoricoInCorsoWithItsHistoryCompleteIsClosedWhenASessionStarts()
{
await using var bed = await AlertBed.CreateAsync(start: Morning);
var engine = bed.Engine;
var account = await engine.AddAccountAsync("anna.prova", followed: true, state: AccountState.Backfilling, postCount: 7);
await engine.Db.Accounts.SetBackfillAsync(account.Id, null, engine.Clock.Now);
var runner = new ScriptedRunner(engine.Governor, engine.Clock);
engine.Start(runner);
await engine.RunUntilAsync(Morning.AddDays(1));
await engine.StopAsync();
await bed.Alerts.FlushAsync();
Assert.AreEqual(AccountState.UpToDate, (await engine.Db.Accounts.GetAsync(account.Id))!.State);
var lines = await engine.Db.Events.ListAsync(new EventQuery { Codes = [EngineEventCodes.BackfillCompleted] });
Assert.HasCount(1, lines);
Assert.AreEqual("Storico di @anna.prova completato: 0 post in libreria. Da ora lo tengo aggiornato.", lines[0].Message);
Assert.IsNotNull(lines[0].SessionId);
Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Backfill), "Nothing left to walk.");
Assert.HasCount(1, bed.Shell.Notifications.Where(n => n.Title == AlertCatalog.Title(AlertKind.BackfillDone)));
}
/// <summary>The real recipes over the scripted site, on the engine's database, clock, Governor and breaker.</summary>
private static (RecipeRunner Runner, ScriptedSite Site) RealRecipes(EngineTestBed engine)
{
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), engine.Clock);
var site = new ScriptedSite(capture, engine.Clock);
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = site,
Capture = capture,
Governor = engine.Governor,
Budget = engine.Governor,
DataBudget = engine.Governor,
Signals = new SignalDetector(SignalRules.LoadTestSite(), engine.Breaker, engine.Clock),
Storage = engine.Db,
SiteMap = SiteMap.LoadTestSite(),
Clock = engine.Clock,
Random = new SeededRandom(7),
Breaker = engine.Breaker,
});
return (runner, site);
}
/// <summary>An account «Storico in corso» for a scripted account: posts only, so that a visit is the profile check.</summary>
private static Task<Account> AddBackfillingAsync(EngineTestBed engine, ScriptedAccount scripted, int postCount) =>
engine.Db.Accounts.AddAsync(Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, engine.Clock.Now, EngineTestBed.Zone, engine.Runtime.Profile) with
{
InstagramId = scripted.Id,
IsFollowed = scripted.Followed,
State = AccountState.Backfilling,
ContentTypes = ContentTypes.PostPhotos | ContentTypes.PostVideos,
PostCount = postCount,
});
}
@@ -27,7 +27,8 @@ public sealed class ImportSourcesTests
Assert.AreEqual(Path.Combine(root, "4K Stogram"), info.FullPath);
Assert.IsTrue(info.ReadOnly, "Il volume /importa è in sola lettura.");
Assert.IsFalse(info.CanMove);
Assert.AreEqual(root + "/4K Stogram", info.DisplayPath);
// Shown as in the container, with «/»: the same text as the root on Linux; on Windows the separators change too.
Assert.AreEqual(LibraryLayout.ToStored(root) + "/4K Stogram", info.DisplayPath);
var outside = Assert.ThrowsExactly<ImportSourceException>(() => sources.Inspect(temp.Combine("fuori")));
StringAssert.Contains(outside.Message, "sottocartella");
+18 -5
View File
@@ -128,8 +128,9 @@ public sealed partial class PackagingTests
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
StringAssert.Contains(prove, "dotnet test tests/Febe.Tests -c Release --no-build");
StringAssert.Contains(Job(workflow, "windows"), "needs: prove");
// The image waits for the installer too: :X.Y.Z and :latest are published only when the release can follow.
var image = Job(workflow, "immagine");
StringAssert.Contains(image, "needs: prove");
StringAssert.Contains(image, "needs: [prove, windows]");
// pkg-3: the release needs the tests, the installer and the image job, which says whether it published.
var release = Job(workflow, "release");
@@ -145,13 +146,25 @@ public sealed partial class PackagingTests
StringAssert.Contains(secret, "presente=no");
StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "if: steps.segreto.outputs.presente == 'si'");
// The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login».
// The registry at home answers in HTTP: buildx with its own builder, told so, and no «docker login». The push is
// the same build as the tested one (.gitea/scripts/costruisci-immagine.sh, shared with the verification).
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
StringAssert.Contains(image, "--push");
Assert.DoesNotContain("docker login", image);
Assert.DoesNotContain("docker push", image);
StringAssert.Contains(Step(image, "Pubblicazione sul registro di Gitea"), "bash .gitea/scripts/costruisci-immagine.sh pubblica");
var build = File.ReadAllText(Repository.PathOf(".gitea", "scripts", "costruisci-immagine.sh"));
StringAssert.Contains(build, "docker buildx build \"${comuni[@]}\" \"${etichette[@]}\" --push .");
foreach (var text in new[] { image, build })
{
Assert.DoesNotContain("docker login", text);
Assert.DoesNotContain("docker push", text);
}
// Before publishing, the image is started without a network and scanned (Trivy); at the end everything of the
// run goes away, whatever happened.
StringAssert.Contains(image, "bash .gitea/scripts/prova-immagine.sh");
StringAssert.Contains(image, "bash .gitea/scripts/scansione-immagine.sh");
StringAssert.Contains(Step(image, "Pulizia (sempre)"), "if: always()");
// pkg-4: compose.yml goes out with chromium/seccomp.json next to it, never alone.
StringAssert.Contains(release, "cp docker/compose.yml \"$COMPOSE/compose.yml\"");
@@ -0,0 +1,977 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
/// a fake docker client (fake-docker.sh) and a fake curl (fake-curl.sh): no daemon, no network.
/// </summary>
public sealed partial class PipelineTests
{
private const string RegistryApi = "http://gitea.invalid/api/v1";
private const string WeeklyStep = "Pulizia completa del demone Docker e del registro";
// Low entropy on purpose: gitleaks reads every commit, and a fake value shaped like a token would look like one.
private const string RegistryToken = "gettone-finto-gettone-finto";
/// <summary>The tags versioni-registro.json leaves to the cleanup once the ten newest sha- are kept, oldest first.</summary>
private static readonly string[] OldShaTags = ["sha-0a1b2c3", "sha-1b2c3d4", "sha-2c3d4e5", "sha-4e5f6a7"];
/// <summary>The untagged versions of the container febe in versioni-registro.json (manifests of an index), oldest first.</summary>
private static readonly string[] UntaggedDigests =
[
"sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b",
"sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c",
"sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647",
];
[TestMethod]
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
{
var cleanup = Code(Script("pulizia-docker.sh"));
foreach (var forbidden in new[] { "system prune", "container prune", "volume prune", "network prune", "prune --all", "image prune -f -a", "builder prune -f -a" })
{
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects and his Unraid apps");
}
// Only these prunes: what nothing uses after every run, the narrow weekly of before, and in the complete
// cleanup every unused image and all the cache. The cache always with the filter of 24 hours, after every run
// too: other projects build with the daemon's builder, and what they used today stays.
string[] allowed =
[
"image prune -f",
"image prune -f --filter \"until=72h\"",
"image prune -a -f --filter \"until=24h\"",
"builder prune -f --filter \"until=24h\"",
"builder prune -a -f --filter \"until=24h\"",
];
CollectionAssert.AreEquivalent(allowed, Prune().Matches(cleanup).Select(m => $"{m.Groups["what"].Value} prune{m.Groups["args"].Value.TrimEnd()}").Distinct().ToList());
StringAssert.Contains(cleanup, "export BUILDX_BUILDER=default", "the cache pruned is the daemon's, not the builder of the run, which is gone by then");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are listed for removal only by a mark of the CI (the label of the tried
// containers with their exact name, the name of Febe's builders, the name act_runner gives its jobs); who uses
// an image, a volume or a network is asked only to keep it; the one listing of every container reads.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
var readsOnly = Function(cleanup, "immagini_in_uso");
Assert.IsFalse(Removal().IsMatch(readsOnly), "immagini_in_uso only reads");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
var marked = new[] { "--filter \"label=febe.ci.prova", "--filter \"name=buildx_buildkit_febe-ci-\"", "--filter \"name=GITEA-ACTIONS-TASK-\"", "--filter \"ancestor=", "--filter \"volume=", "--filter \"network=" }
.Any(filter => line.Contains(filter, StringComparison.Ordinal));
Assert.IsTrue(marked || readsOnly.Contains(line, StringComparison.Ordinal), $"«{line.Trim()}» lists containers without a mark of the CI");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
StringAssert.Contains(cleanup, "nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'", "act_runner's objects start with the task");
StringAssert.Contains(cleanup, "togli_contenitore \"$id\" \"$nome\" && conta \"contenitori fermi di act_runner\"", "act_runner's containers go without -f: Docker keeps a running one");
StringAssert.Contains(cleanup, "docker volume rm \"$nome\"", "act_runner's volumes go without -f");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
}
[TestMethod]
public void EveryImageJobEndsByPruningWhatNobodyUsesAndThatNeverFailsTheJob()
{
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
{
var cleanup = Step(Job(Workflow(name), "immagine"), "Pulizia (sempre)");
StringAssert.Contains(cleanup, "if: always()", name);
var own = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"", StringComparison.Ordinal);
var everyone = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh penzolanti || echo \"::warning::", StringComparison.Ordinal);
Assert.IsTrue(own >= 0 && everyone > own, $"{name}: after the cleanup of the run, and a failure is only a warning");
}
}
[TestMethod]
public void TheWeeklyCleanupIsCompleteAndCanBeTriedFirstWithoutRemovingAnything()
{
var weekly = Workflow("pulizia.yml");
StringAssert.Contains(weekly, "schedule:\n - cron: \"17 4 * * 1\"");
StringAssert.Contains(weekly, " workflow_dispatch:\n inputs:\n prova:\n");
var input = weekly[weekly.IndexOf(" prova:\n", StringComparison.Ordinal)..weekly.IndexOf("\npermissions:", StringComparison.Ordinal)];
StringAssert.Contains(input, "type: boolean", "Gitea 28 shows a checkbox and puts \"true\" or \"false\" in the event");
StringAssert.Contains(input, "default: false", "by hand the cleanup is real unless the box is ticked");
var step = Step(Job(weekly, "docker"), WeeklyStep);
StringAssert.Contains(step, "PROVA: ${{ gitea.event.inputs.prova }}");
StringAssert.Contains(step, "REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}");
StringAssert.Contains(step, "GITEA_API: ${{ gitea.server_url }}/api/v1");
StringAssert.Contains(step, "PROPRIETARIO: ${{ gitea.repository_owner }}");
Assert.DoesNotContain("settimanale", Code(weekly), "the weekly cleanup is the complete one");
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task TheWeeklyStepTriesOnlyForTrueCleansForFalseOrNothingAndStopsOnAnyOtherValue()
{
// The run block of the step, as the runner executes it, with a cleanup script that only records how it is
// called. The box of the form gives "true" or "false" and Monday no value at all; a dispatch through the API
// passes any text as it is, and anything else must not become the real cleanup.
var bash = RequireBash();
var block = RunBlock(Step(Job(Workflow("pulizia.yml"), "docker"), WeeklyStep));
using var folder = new TempFolder("febe-passo-pulizia");
Directory.CreateDirectory(folder.Combine(".gitea", "scripts"));
await File.WriteAllTextAsync(folder.Combine(".gitea", "scripts", "pulizia-docker.sh"), "printf '%s\\n' \"$*\" >> chiamate\n", TestContext.CancellationToken);
await File.WriteAllTextAsync(folder.Combine("passo.sh"), block, TestContext.CancellationToken);
(string? Value, string? Called)[] cases =
[
("true", "completa --prova"),
("false", "completa"),
(string.Empty, "completa"),
(null, "completa"),
("True", null),
("1", null),
("yes", null),
("true ", null),
("x\n::add-mask::y", null),
];
foreach (var (value, called) in cases)
{
File.Delete(folder.Combine("chiamate"));
var step = await RunProcessAsync(bash, ["--noprofile", "--norc", "-eo", "pipefail", "passo.sh"], start =>
{
start.WorkingDirectory = folder.Path;
start.Environment.Remove("PROVA");
if (value is not null)
{
start.Environment["PROVA"] = value;
}
});
var calls = await ReadLinesAsync(folder.Combine("chiamate"));
var report = $"PROVA=«{value}»: codice {step.Code}\n{step.Output}\n{step.Errors}";
if (called is not null)
{
Assert.AreEqual(0, step.Code, report);
CollectionAssert.AreEqual(new[] { called }, calls, report);
}
else
{
Assert.AreEqual(2, step.Code, report);
Assert.IsEmpty(calls, report);
StringAssert.StartsWith(step.Output, "::error::", report);
Assert.HasCount(1, Lines(step.Output), "a value cannot add a workflow command of its own");
}
}
}
[TestMethod]
[Timeout(120_000, CooperativeCancellation = true)]
public async Task AWrongOptionOrAWordTooManyStopsTheCleanupBeforeItTouchesDocker()
{
// By hand on the server a dry run spelt another way must not become the real cleanup.
var bash = RequireBash();
string[][] wrong =
[
["completa", "--dry-run"],
["completa", "--Prova"],
["completa", "-n"],
["completa", "prova"],
["--prova"],
[],
["penzolanti", "--forza"],
["settimanale", "-f"],
["esecuzione", "777", "778"],
["residui", "90", "10"],
];
foreach (var arguments in wrong)
{
var run = await RunCleanupAsync(bash, SharedDaemon.World, touchesDocker: false, arguments);
var report = $"«{string.Join(' ', arguments)}»\n{run.Report}";
Assert.AreEqual(2, run.Code, report);
Assert.IsEmpty(run.Calls, report);
StringAssert.Contains(run.Errors, "Uso: ", report);
Assert.IsEmpty(run.Output, report);
}
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
{
var bash = RequireBash();
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// The narrow weekly cleanup of before, on a daemon without anything odd: the same, the old febe:ci and the
// dangling images older than 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Clean), "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
{
var bash = RequireBash();
var run = await RunCleanupAsync(bash, SharedDaemon.World, "penzolanti");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
// Images without a name that no container uses, of any age; never one with a name, never one a stopped
// container uses. Containers, volumes and networks stay as they are.
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds.Except(["img-plex-precedente", "img-penzolante-giovane"]).ToList(), run.ImageIds, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), run.Containers, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, run.Volumes, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, run.Networks, run.Report);
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker image prune -f");
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker builder prune -f --filter until=24h", "the dangling cache of the daemon's builder, without -a, unused for a day");
// A daemon that refuses: two warnings, and the job of the run stays green.
var refused = await RunCleanupAsync(bash, SharedDaemon.World with { Broken = ["image prune", "builder prune"] }, "penzolanti");
Assert.AreEqual(0, refused.Code, refused.Report);
Assert.HasCount(2, WarningLine().Matches(refused.Output), refused.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, refused.ImageIds, refused.Report);
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
{
var bash = RequireBash();
var run = await RunCleanupAsync(bash, SharedDaemon.World, "completa");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ContainersLeft, run.Containers, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, run.ImageIds, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumesLeft, run.Volumes, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworksLeft, run.Networks, run.Report);
// An image a container uses stays, but «image prune -a» takes its extra names: with the classic store all but
// the last in the order of their full names, even the one the container was made from (Jellyfin, from :10.9).
// The log says so, name by name.
StringAssert.Contains(run.Output, "== Store delle immagini del demone: classico", run.Report);
CollectionAssert.Contains(run.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", run.Report);
CollectionAssert.Contains(run.Images, "img-jellyfin|jellyfin/jellyfin:latest", run.Report);
StringAssert.Contains(run.Output, " tolto il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta\n", run.Report);
StringAssert.Contains(run.Output, " tolto il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta\n", run.Report);
Assert.AreEqual("2", SummaryCount(run.Output, "nomi tolti a immagini che restano"), run.Report);
// Not even an attempt on what is not the CI's (Docker would refuse some of it: the script must not ask), and
// the prunes of everyone only with their filter, once.
foreach (var call in run.Calls)
{
var target = RemovalTarget().Match(call);
if (target.Success)
{
CollectionAssert.Contains(SharedDaemon.Removed, target.Groups["target"].Value, call);
}
}
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker image prune -a -f --filter until=24h"), run.Report);
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker builder prune -a -f --filter until=24h"), run.Report);
Assert.HasCount(2, run.Calls.Where(c => c.EndsWith("docker system df", StringComparison.Ordinal)), "before and after");
// Without the secret the registry is not touched, and the summary says what went.
StringAssert.Contains(run.Output, " Manca il segreto REGISTRY_TOKEN: il registro non si tocca.");
Assert.IsEmpty(run.RegistryCalls, run.Report);
StringAssert.Contains(run.Output, "== Riepilogo\n");
Assert.AreEqual("2", SummaryCount(run.Output, "contenitori fermi di act_runner"), run.Report);
Assert.AreEqual("4", SummaryCount(run.Output, "volumi di act_runner"), run.Report);
Assert.AreEqual("2", SummaryCount(run.Output, "reti di act_runner"), run.Report);
Assert.AreEqual("4", SummaryCount(run.Output, "immagini che nessun contenitore usa"), run.Report);
// Something left for a person to look at (a tried container still running) turns it red, as before.
var noticed = await RunCleanupAsync(bash, SharedDaemon.World with { Containers = [.. SharedDaemon.Containers, "c-prova-556|febe-prova-556|running|300|febe-ci:556|img-rilascio|febe.ci.prova=556"] }, "completa");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
{
var bash = RequireBash();
RequireNode();
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
Assert.AreEqual(0, tried.Code, tried.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), tried.Containers, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, tried.ImageIds, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, tried.Volumes, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, tried.Networks, tried.Report);
foreach (var call in tried.Calls)
{
Assert.IsFalse(Destructive().IsMatch(call), $"the dry run called «{call}»");
}
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
Assert.IsEmpty(tried.Deleted, tried.Report);
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
Assert.DoesNotContain("solo indicativo", tried.Output, "with the classic store the ages are those «until» uses");
foreach (var expected in new[]
{
"Prova: elenco che cosa toglierei, senza togliere nulla.",
"== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)\n",
" toglierei il contenitore febe-prova-555\n",
" toglierei il contenitore GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove\n",
" toglierei il volume GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-env\n",
" toglierei la rete GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-prove-network\n",
" toglierei 192.168.30.23:3000/alby96/febe:0.0.9 (img-febe-vec) · 400MB · creata 34 giorni fa\n",
" toglierei node:24-trixie (img-node) · 410MB · creata 13 giorni fa\n",
" toglierei un'immagine senza nome (img-plex-pre) · 300MB · creata 69 giorni fa\n",
" toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n",
" toglierei il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta, perché la usa un contenitore\n",
"la cache di costruzione del demone occupa 5.3GB",
" toglierei sha-4e5f6a7 (pubblicata il 2026-10-05T01:00:00+02:00)\n",
$" {UntaggedDigests.Length} versioni senza etichetta (sha256:…",
"== Riepilogo della prova",
})
{
StringAssert.Contains(tried.Output, expected, tried.Report);
}
foreach (var kept in new[] { "plexinc/pms-docker", "encelado:latest", "mimante:latest", "runner-images", "moby/buildkit", "act-toolcache", "encelado-dati", "febe:latest", "jellyfin/jellyfin:latest", "toglierei main", "toglierei latest", "toglierei 0.1.", "GITEA-ACTIONS-TASK-90", "GITEA-ACTIONS-TASK-60", "GITEA-ACTIONS-TASK-88", "GITEA-ACTIONS-TASK-89", "GITEA-ACTIONS-TASK-77" })
{
Assert.DoesNotContain(kept, tried.Output, tried.Report);
}
// And it counts what the real cleanup then takes.
var real = await RunCleanupAsync(bash, world, "completa");
Assert.AreEqual(0, real.Code, real.Report);
foreach (var kind in new[] { "contenitori di prova della CI di Febe", "immagini febe-ci", "builder buildx della CI di Febe", "contenitori fermi di act_runner", "volumi di act_runner", "reti di act_runner", "immagini che nessun contenitore usa", "nomi tolti a immagini che restano", "etichette sha- sul registro" })
{
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
}
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task OnTheContainerdStoreTheCleanupSaysSoAndTheAgesOfTheDryRunAreOnlyIndicative()
{
// With the containerd image store «until» counts from when a name reached the daemon, which no command shows;
// the dry run can only give the age of the image and must say so.
var bash = RequireBash();
var world = SharedDaemon.World with { Store = "containerd" };
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
Assert.AreEqual(0, tried.Code, tried.Report);
StringAssert.Contains(tried.Output, "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)\n", tried.Report);
StringAssert.Contains(tried.Output, "l'elenco è solo indicativo)", tried.Report);
CollectionAssert.Contains(tried.Calls, "BUILDX_BUILDER=default docker info --format {{json .DriverStatus}}", "the store is read, never changed");
// Of an image a container uses, containerd keeps the names the containers were made from and takes the others:
// Jellyfin keeps :10.9 and loses :latest, the other way round from the classic store. The dry run says so, and
// the real cleanup does it.
StringAssert.Contains(tried.Output, " toglierei il nome jellyfin/jellyfin:latest; l'immagine img-jellyfin resta, perché la usa un contenitore\n", tried.Report);
StringAssert.Contains(tried.Output, " toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n", tried.Report);
Assert.DoesNotContain("jellyfin/jellyfin:10.9", tried.Output, tried.Report);
var real = await RunCleanupAsync(bash, world, "completa");
Assert.AreEqual(0, real.Code, real.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, real.ImageIds, real.Report);
CollectionAssert.Contains(real.Images, "img-jellyfin|jellyfin/jellyfin:10.9", real.Report);
CollectionAssert.Contains(real.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", real.Report);
foreach (var kind in new[] { "immagini che nessun contenitore usa", "nomi tolti a immagini che restano" })
{
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
}
}
[TestMethod]
public void TheImageIsAPlainManifestSoRemovingATagFromTheRegistryFreesItsLayers()
{
// With attestations, which buildx adds by itself, the image is an index: Gitea keeps each child manifest as an
// untagged sha256: version holding the configuration and the layers, and deleting the tag deletes only the
// index. Both builds (the tried archive and the push) share these arguments, so they stay the same image.
var build = Code(Script("costruisci-immagine.sh"));
var start = build.IndexOf("comuni=(", StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, "costruisci-immagine.sh has no common arguments");
var common = build[start..build.IndexOf(')', start)];
StringAssert.Contains(common, "--provenance=false");
StringAssert.Contains(common, "--sbom=false");
Assert.AreEqual(2, Regex.Count(build, @"docker buildx build ""\$\{comuni\[@\]\}"""), "every build uses the common arguments");
Assert.DoesNotContain("--platform", build, "more platforms would make an index again");
Assert.DoesNotContain("--attest", build);
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
{
var node = RequireNode();
var script = CiPath("scripts", "versioni-registro.js");
using var folder = new TempFolder("febe-registro");
var pages = await WriteRegistryPagesAsync(folder.Path);
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
// other packages stay, though they are older; a tag in two pages counts once.
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
Assert.AreEqual(0, chosen.Code, chosen.Errors);
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
var all = await RunProcessAsync(node, [script, "0", .. pages]);
Assert.HasCount(14, Lines(all.Output), all.Output);
foreach (var line in Lines(all.Output))
{
Assert.IsTrue(ShaTagLine().IsMatch(line), line);
}
// The untagged versions, the manifests of an index with their layers: listed only to be counted, oldest first,
// those of the container febe and no other package.
var untagged = await RunProcessAsync(node, [script, "senza-etichetta", .. pages]);
Assert.AreEqual(0, untagged.Code, untagged.Errors);
CollectionAssert.AreEqual(UntaggedDigests, Lines(untagged.Output).Select(l => l.Split('\t')[0]).ToList(), untagged.Output);
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
// everything, so in doubt nothing goes.
var empty = Path.Combine(folder.Path, "vuota.json");
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
var broken = Path.Combine(folder.Path, "rotta.json");
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
{
var bash = RequireBash();
RequireNode();
// A daemon with almost nothing on it: here only the registry counts.
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
Assert.AreEqual(0, run.Code, run.Report);
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
var package = $"{RegistryApi}/packages/Alby96/container/febe";
CollectionAssert.AreEqual(
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
run.RegistryCalls,
run.Report);
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
// The untagged versions stay, and the log says how many there are: their layers are freed only by a cleanup
// rule of Gitea, which knows whether a tag still uses them.
Assert.IsFalse(run.RegistryCalls.Any(c => c.Contains("sha256:", StringComparison.Ordinal)), run.Report);
StringAssert.Contains(run.Output, $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano", run.Report);
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
// and the weekly job stays green.
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
{
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
Assert.AreEqual(0, refused.Code, refused.Report);
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
Assert.IsEmpty(refused.Deleted, refused.Report);
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
}
}
/// <summary>
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
/// as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado||buildx_buildkit_febe-ci-4570_state",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7890_state",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7770_state",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static World WorldOf(string[] containers) => new(containers, Images, Volumes, []);
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
/// <summary>
/// A daemon as the runner's is likely to be (format in fake-docker.sh): a real Febe and Unraid apps, running and
/// stopped; the job container of the cleanup itself; leftovers of act_runner, with the names of today's act_runner
/// («_WORKFLOW-…») and of older ones («-WORKFLOW-…» with a hash), and look-alikes; leftovers of the CI of Febe;
/// images used and unused, named and dangling, old and young; volumes and networks of every kind. The images of the
/// real Febe and of Jellyfin have two names each, and Jellyfin was created from the one that is not the last.
/// </summary>
private static class SharedDaemon
{
private const string Job53 = "GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove";
private const string Job41 = "GITEA-ACTIONS-TASK-41-WORKFLOW-verifica-JOB-prove-9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
private const string Job90 = "GITEA-ACTIONS-TASK-90_WORKFLOW-pulizia_JOB-docker";
public static readonly string[] Containers =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0|febe-dati|bridge",
"c-plex|plex|exited|90000|plexinc/pms-docker:latest|img-plex||plex-config|br0",
"c-jellyfin|jellyfin|running|90000|jellyfin/jellyfin:10.9|img-jellyfin||",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|||encelado_default",
$"c-lavoro|{Job90}|running|5|docker.gitea.com/runner-images:ubuntu-latest|img-runner||{Job90},{Job90}-env,act-toolcache|{Job90}-docker-network",
$"c-act-fermo|{Job53}|exited|3000|node:24-trixie|img-node||{Job53},{Job53}-env,act-toolcache|{Job53}-prove-network",
$"c-act-antico|{Job41}|dead|20000|node:24-trixie|img-node||{Job41}-env|",
"c-act-giovane|GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|exited|30|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|",
"c-act-acceso|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|running|3000|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network",
"c-quasi-act|mio-GITEA-ACTIONS-TASK-7_WORKFLOW-x|exited|3000|encelado:latest|img-encelado||GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|",
"c-senza-numero|GITEA-ACTIONS-TASK-x_WORKFLOW-y|exited|3000|encelado:latest|img-encelado|",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state|",
"b-altro|buildx_buildkit_encelado0|running|3000|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_encelado0_state|",
];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0|43200|febe.ci.run=777|412MB",
"img-febe-vecchia|192.168.30.23:3000/alby96/febe:0.0.9|50000||400MB",
"img-plex|plexinc/pms-docker:latest|100000||300MB",
"img-plex-precedente||100000||300MB",
"img-jellyfin|jellyfin/jellyfin:10.9,jellyfin/jellyfin:latest|100000||900MB",
"img-encelado|encelado:latest|5000||250MB",
"img-encelado-dev|encelado:dev|3000||250MB",
"img-mimante-nuova|mimante:latest|60||180MB",
"img-runner|docker.gitea.com/runner-images:ubuntu-latest|20000||1.2GB",
"img-node|node:24-trixie|20000||410MB",
"img-buildkit|moby/buildkit:buildx-stable-1|50000||210MB",
"img-penzolante-giovane||30||40MB",
"img-penzolante-in-uso||20000|febe.ci.run=111|400MB",
"img-ci555|febe-ci:555|300|febe.ci.run=555|412MB",
"img-legacy|febe:ci|6000||400MB",
];
public static readonly string[] Volumes =
[
$"{Job53}|3000",
$"{Job53}-env|3000",
$"{Job41}-env|20000",
$"{Job90}|5",
$"{Job90}-env|5",
"GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|30",
"GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|3000",
"GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x|50000",
"GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y|30",
"GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|50000",
"act-toolcache|50000",
"encelado-dati|50000",
"febe-dati|43200",
"plex-config|100000",
"3f9a2b7c1d0e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a|50000",
"mio-GITEA-ACTIONS-TASK-3_WORKFLOW-x|50000",
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_encelado0_state",
];
public static readonly string[] Networks =
[
"net-bridge|bridge|100000",
"net-host|host|100000",
"net-none|none|100000",
"net-br0|br0|100000",
"net-encelado|encelado_default|5000",
$"net-act-53|{Job53}-prove-network|3000",
$"net-act-90|{Job90}-docker-network|5",
"net-act-60|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network|3000",
"net-act-12|GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x-x-network|50000",
"net-act-88|GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y-y-network|30",
"net-quasi|altro-GITEA-ACTIONS-TASK-5_WORKFLOW-x-network|50000",
];
public static readonly World World = new(Containers, Images, Volumes, Networks);
public static readonly List<string> ImageIds = [.. Images.Select(First)];
public static readonly List<string> VolumeNames = [.. Volumes.Select(First)];
public static readonly List<string> NetworkNames = [.. Networks.Select(n => n.Split('|')[1])];
/// <summary>
/// What the complete cleanup takes: stopped act_runner containers older than 90 minutes, a stopped tried
/// container and a builder of Febe; the volumes and networks of act_runner nothing else uses; the images no
/// container uses created more than a day ago (node:24-trixie only once its stopped containers are gone).
/// </summary>
public static readonly string[] Removed =
[
"c-act-fermo", "c-act-antico", "c-prova-555", "b-vecchio",
"img-febe-vecchia", "img-plex-precedente", "img-encelado-dev", "img-node", "img-ci555", "img-legacy",
$"{Job53}", $"{Job53}-env", $"{Job41}-env", "GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x", "buildx_buildkit_febe-ci-4560_state",
"net-act-53", "net-act-12",
// How the cleanup names what it removes: by id or by name, and the local names of the images.
"buildx_buildkit_febe-ci-4560", "febe-ci:555", "febe:ci", "febe-ci-4560",
];
public static readonly List<string> ContainersLeft = [.. FakeDaemon.ContainersOf(Containers).Except(Removed)];
public static readonly List<string> ImagesLeft = [.. ImageIds.Except(Removed)];
public static readonly List<string> VolumesLeft = [.. VolumeNames.Except(Removed)];
public static readonly List<string> NetworksLeft = [.. Networks.Where(n => !Removed.Contains(First(n))).Select(n => n.Split('|')[1])];
private static string First(string line) => line.Split('|')[0];
}
/// <summary>A fake daemon (format in fake-docker.sh) and, for the registry, a fake Gitea (fake-curl.sh).</summary>
private sealed record World(string[] Containers, string[] Images, string[] Volumes, string[] Networks)
{
/// <summary>Docker commands that fail as if the daemon refused them («image prune», «builder prune»).</summary>
public string[] Broken { get; init; } = [];
/// <summary>The registry; without it the cleanup runs with no REGISTRY_TOKEN.</summary>
public FakeRegistry? Registry { get; init; }
/// <summary>«containerd» for the containerd image store; null for the classic one.</summary>
public string? Store { get; init; }
}
/// <summary>
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
/// </summary>
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
private sealed record CleanupRun(int Code, string Output, string Errors)
{
/// <summary>The ids of the containers left.</summary>
public List<string> Containers { get; init; } = [];
/// <summary>«id|names» of the images left.</summary>
public List<string> Images { get; init; } = [];
public List<string> Volumes { get; init; } = [];
public List<string> Networks { get; init; } = [];
/// <summary>Every docker call, as fake-docker.sh writes it.</summary>
public List<string> Calls { get; init; } = [];
/// <summary>Every call to the API of the registry, «METHOD URL».</summary>
public List<string> RegistryCalls { get; init; } = [];
/// <summary>The versions deleted from the registry.</summary>
public List<string> Deleted { get; init; } = [];
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon and, with a registry, the fake curl. DOCKER_HOST points nowhere and the
/// API is on a domain that cannot exist (.invalid): even if a real docker or curl came first on the PATH they could
/// reach nothing, and the test fails because the fakes recorded no call or curl complained on stderr.
/// </summary>
private Task<CleanupRun> RunCleanupAsync(string bash, World world, params string[] arguments) =>
RunCleanupAsync(bash, world, touchesDocker: true, arguments);
/// <summary>
/// As <see cref="RunCleanupAsync(string, World, string[])"/>; with <paramref name="touchesDocker"/> false the run
/// may call no docker at all (wrong arguments stop before it).
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, World world, bool touchesDocker, string[] arguments)
{
using var folder = new TempFolder("febe-pulizia");
var bin = folder.Combine("bin");
var registry = folder.Combine("registro");
var temporary = folder.Combine("tmp");
foreach (var directory in new[] { bin, registry, temporary })
{
Directory.CreateDirectory(directory);
}
InstallFake("fake-docker.sh", Path.Combine(bin, "docker"));
await WriteLinesAsync(folder.Combine("containers"), world.Containers);
await WriteLinesAsync(folder.Combine("images"), world.Images);
await WriteLinesAsync(folder.Combine("volumes"), world.Volumes);
await WriteLinesAsync(folder.Combine("networks"), world.Networks);
if (world.Broken.Length > 0)
{
await WriteLinesAsync(folder.Combine("broken"), world.Broken);
}
if (world.Store is { } store)
{
await WriteLinesAsync(folder.Combine("store"), [store]);
}
if (world.Registry is { } fake)
{
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
await File.WriteAllTextAsync(Path.Combine(registry, "token"), fake.Token, TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(registry, "base"), $"{RegistryApi}/packages/Alby96/container/febe", TestContext.CancellationToken);
if (fake.Refuse)
{
await File.WriteAllTextAsync(Path.Combine(registry, "refuse"), string.Empty, TestContext.CancellationToken);
}
await WriteRegistryPagesAsync(registry);
}
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
// PATH it is given.
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/pulizia-docker.sh"];
var result = await RunProcessAsync(bash, [.. script, .. arguments], start =>
{
start.Environment["FAKE_BIN"] = bin;
start.Environment["FAKE_DOCKER_WORLD"] = folder.Path.Replace('\\', '/');
start.Environment["FAKE_CURL_WORLD"] = registry.Replace('\\', '/');
start.Environment["TMPDIR"] = temporary.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
start.Environment.Remove("BUILDX_BUILDER");
start.Environment.Remove("REGISTRY_TOKEN");
start.Environment["GITEA_API"] = RegistryApi;
start.Environment["PROPRIETARIO"] = "Alby96";
if (world.Registry is { } sent)
{
start.Environment["REGISTRY_TOKEN"] = sent.Sent ?? sent.Token;
}
});
var run = new CleanupRun(result.Code, result.Output, result.Errors)
{
Containers = FakeDaemon.ContainersOf([.. await ReadLinesAsync(folder.Combine("containers"))]),
Images = [.. (await ReadLinesAsync(folder.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
Volumes = [.. (await ReadLinesAsync(folder.Combine("volumes"))).Select(v => v.Split('|')[0])],
Networks = [.. (await ReadLinesAsync(folder.Combine("networks"))).Select(n => n.Split('|')[1])],
Calls = await ReadLinesAsync(folder.Combine("calls")),
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
};
if (touchesDocker)
{
Assert.IsNotEmpty(run.Calls, $"the fake docker client was not the one called\n{run.Report}");
}
Assert.DoesNotContain("unexpected call", run.Errors, run.Report);
Assert.DoesNotContain("fake curl:", run.Errors, run.Report);
Assert.DoesNotContain("curl: (", run.Errors, $"a real curl was called\n{run.Report}");
Assert.IsEmpty(Directory.EnumerateFileSystemEntries(temporary), $"the cleanup leaves no temporary files\n{run.Report}");
return run;
}
/// <summary>A program with its arguments, from the root of the repository; its output with Unix lines.</summary>
private async Task<(int Code, string Output, string Errors)> RunProcessAsync(string program, IEnumerable<string> arguments, Action<ProcessStartInfo>? configure = null)
{
var start = new ProcessStartInfo(program)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
configure?.Invoke(start);
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
return (process.ExitCode, (await output).Replace("\r\n", "\n", StringComparison.Ordinal), (await errors).Replace("\r\n", "\n", StringComparison.Ordinal));
}
/// <summary>The pages of versioni-registro.json as Gitea would answer them, one file each.</summary>
private async Task<List<string>> WriteRegistryPagesAsync(string folder)
{
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "versioni-registro.json"), TestContext.CancellationToken);
using var pages = JsonDocument.Parse(fixture);
var files = new List<string>();
foreach (var page in pages.RootElement.EnumerateArray())
{
var file = Path.Combine(folder, $"page-{files.Count + 1}.json");
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
files.Add(file);
}
return files;
}
private static void InstallFake(string name, string path)
{
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
File.Exists(path) ? Lines(await File.ReadAllTextAsync(path, TestContext.CancellationToken)) : [];
private static List<string> Lines(string text) => [.. text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>The number the summary of the cleanup gives for a kind of object, or null when it does not list it.</summary>
private static string? SummaryCount(string output, string kind)
{
var match = Regex.Match(output, $@"^ {Regex.Escape(kind)}: (?<count>[0-9]+)", RegexOptions.Multiline);
return match.Success ? match.Groups["count"].Value : null;
}
/// <summary>The «run: |» block of a step without its indentation, as the runner writes it to a script.</summary>
private static string RunBlock(string step)
{
const string start = "run: |\n";
var at = step.IndexOf(start, StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, at, $"the step has no «{start.Trim()}» block");
var lines = step[(at + start.Length)..].Split('\n');
var indent = new string(' ', lines.First(l => l.Trim().Length > 0).TakeWhile(c => c == ' ').Count());
var body = lines.TakeWhile(l => l.Trim().Length == 0 || l.StartsWith(indent, StringComparison.Ordinal));
return string.Concat(body.Select(l => (l.Length >= indent.Length ? l[indent.Length..] : string.Empty) + "\n"));
}
/// <summary>The body of a shell function of a script, from «name() {» to the closing brace at the start of a line.</summary>
private static string Function(string script, string name)
{
var match = Regex.Match(script, $@"^{Regex.Escape(name)}\(\) \{{\n(?<body>.*?)^\}}", RegexOptions.Multiline | RegexOptions.Singleline);
Assert.IsTrue(match.Success, $"manca la funzione {name}");
return match.Groups["body"].Value;
}
private static string RequireBash()
{
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(CiPath("scripts", "pulizia-docker.sh")));
return bash;
}
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
private static string RequireNode()
{
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
.FirstOrDefault(File.Exists);
if (node is null)
{
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
}
return node;
}
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
private static partial Regex Prune();
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
private static partial Regex ProvenanceLabelFilter();
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
private static partial Regex ForcedImageRemoval();
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm|buildx rm)\b|prune")]
private static partial Regex Removal();
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm)(?: -[a-z]+)* (?<target>\S+)$")]
private static partial Regex RemovalTarget();
[GeneratedRegex(@"docker (?:rm|kill|stop|image rm|rmi|image prune|builder prune|buildx rm|buildx prune|volume rm|volume prune|network rm|network prune|container prune|system prune)\b")]
private static partial Regex Destructive();
[GeneratedRegex(@"^::warning::", RegexOptions.Multiline)]
private static partial Regex WarningLine();
[GeneratedRegex(@"^sha-[0-9a-f]{7,40}\t")]
private static partial Regex ShaTagLine();
}
+262
View File
@@ -0,0 +1,262 @@
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The CI of the repository (.gitea/workflows/verifica.yml, pulizia.yml and the scripts of .gitea/scripts), read as
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
/// clients, is in PipelineTests.Pulizia.cs.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
{
private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease()
{
var workflow = Workflow("verifica.yml");
StringAssert.Contains(workflow, "on:\n push:\n branches: [\"**\"]\n workflow_dispatch:");
var code = Code(workflow);
Assert.DoesNotContain("pull_request", code, "a PR shows the status of its head commit, already verified by the push");
Assert.DoesNotContain("tags:", code, "tags belong to rilascio.yml");
StringAssert.Contains(code, "cancel-in-progress: ${{ gitea.ref != 'refs/heads/main' }}", "every merge into main runs to the end");
// A run started by hand never cancels the run of a push: only that one writes the statuses a merge needs.
StringAssert.Contains(code, "group: verifica-${{ gitea.event_name }}-${{ gitea.ref }}");
}
[TestMethod]
public void TheJobsFollowOneAnotherAndEachHasATimeout()
{
var workflow = Workflow("verifica.yml");
foreach (var job in Jobs)
{
StringAssert.Contains(Job(workflow, job), "timeout-minutes:", job);
}
StringAssert.Contains(Job(workflow, "prove"), "needs: controlli");
StringAssert.Contains(Job(workflow, "installatore"), "needs: prove");
StringAssert.Contains(Job(workflow, "immagine"), "needs: [prove, installatore]", ":main comes only from a commit whose whole verification is green");
foreach (var other in new[] { "rilascio.yml", "pulizia.yml" })
{
var text = Workflow(other);
foreach (Match job in JobHeader().Matches(text))
{
StringAssert.Contains(Job(text, job.Groups["name"].Value), "timeout-minutes:", $"{other}: {job.Groups["name"].Value}");
}
}
}
[TestMethod]
public void TheWholeSolutionIsBuiltAndTheTestsRunOnlyThroughTheTestProjectWithTheBrowser()
{
var prove = Job(Workflow("verifica.yml"), "prove");
StringAssert.Contains(prove, "container:\n image: node:24-trixie", "Debian: Chromium is a real package there, a snap on Ubuntu");
StringAssert.Contains(prove, "bash .gitea/scripts/ambiente-prove.sh");
StringAssert.Contains(prove, "dotnet build Febe.slnx -c Release -nologo -warnaserror");
StringAssert.Contains(prove, "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", "no test may skip itself in the CI");
// The second pass: the tests of the synthetic world again, with the seed of the run in the variable the helper reads.
StringAssert.Contains(prove, $"{SyntheticSite.Variable}: ${{{{ steps.semi.outputs.seme }}}}");
StringAssert.Contains(prove, $"--filter \"TestCategory={SyntheticSite.Category}\"");
var environment = Script("ambiente-prove.sh");
foreach (var package in new[] { "chromium", "xvfb", "ffmpeg", "nsis", "locales" })
{
StringAssert.Contains(environment, package);
}
// tests/Febe.Tests.Windows runs only on Windows: never «dotnet test» on the solution or without a project.
foreach (var name in new[] { "verifica.yml", "rilascio.yml" })
{
foreach (Match test in DotnetTest().Matches(Code(Workflow(name))))
{
Assert.AreEqual("tests/Febe.Tests", test.Groups["target"].Value, $"{name}: {test.Value}");
}
}
}
[TestMethod]
public void TheImageIsPublishedOnlyAfterAPushToMainAsMainAndShaNeverAsLatest()
{
var image = Job(Workflow("verifica.yml"), "immagine");
var decision = Step(image, "Pubblicare?");
StringAssert.Contains(decision, "[ \"$EVENTO\" != push ] || [ \"$RIFERIMENTO\" != refs/heads/main ]");
StringAssert.Contains(decision, "::warning::Manca il segreto REGISTRY_TOKEN");
Assert.DoesNotContain("exit 1", decision, "without the secret the job stays green");
var publish = Step(image, "Pubblicazione come :main e :sha-<commit>");
StringAssert.Contains(publish, "if: steps.segreto.outputs.presente == 'si'");
StringAssert.Contains(publish, "\"$IMAGE:sha-${GITHUB_SHA::7}\"");
StringAssert.Contains(publish, "\"$IMAGE:main\"");
StringAssert.Contains(publish, "bash .gitea/scripts/costruisci-immagine.sh pubblica");
StringAssert.Contains(publish, "| cut -f1) || CIMA=\"\"", "under bash -e an unreadable main must reach the warning and still publish :sha-");
Assert.DoesNotContain(":latest", Code(Workflow("verifica.yml")), ":latest belongs to the release");
// Built with buildx, tried without a network and scanned before anything is published; always cleaned up.
StringAssert.Contains(image, "uses: docker/setup-buildx-action@v3");
StringAssert.Contains(image, "http = true");
StringAssert.Contains(image, "insecure = true");
var decide = image.IndexOf("- name: Pubblicare?", StringComparison.Ordinal);
foreach (var gate in new[] { "bash .gitea/scripts/costruisci-immagine.sh archivio", "bash .gitea/scripts/prova-immagine.sh", "bash .gitea/scripts/scansione-immagine.sh" })
{
var at = image.IndexOf(gate, StringComparison.Ordinal);
Assert.IsTrue(at >= 0 && at < decide, $"«{gate}» comes before the publication");
}
var cleanup = Step(image, "Pulizia (sempre)");
StringAssert.Contains(cleanup, "if: always()");
StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"");
StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration");
}
[TestMethod]
public void SecretsAreNeverPrintedNorTheDaemonUsedForTheRegistry()
{
foreach (var (name, text) in AllCiFiles())
{
var code = Code(text);
Assert.DoesNotContain("docker login", code, name);
Assert.DoesNotContain("docker push", code, name);
Assert.IsFalse(Trace().IsMatch(code), $"{name}: no shell tracing (it would print secrets)");
// A secret goes into echo or printf only to be piped or redirected, never to the log.
foreach (var line in code.Split('\n').Where(l => Printing().IsMatch(l)))
{
var secret = SecretReference().Match(line);
if (secret.Success)
{
var after = line[secret.Index..];
Assert.IsTrue(after.Contains('|', StringComparison.Ordinal) || after.Contains('>', StringComparison.Ordinal), $"{name}: «{line.Trim()}» would print a secret");
}
}
}
}
[TestMethod]
public void TheExternalToolsArePinnedAndCheckedAndNoThirdPartyActionRunsThem()
{
var tool = Script("strumento.sh");
StringAssert.Contains(tool, "versione=\"8.30.1\"");
StringAssert.Contains(tool, "versione=\"0.75.0\"");
Assert.HasCount(2, Sha256().Matches(tool), "one SHA-256 per tool");
StringAssert.Contains(tool, "sha256sum -c");
Assert.DoesNotContain("latest", Code(tool));
foreach (var (name, text) in AllCiFiles())
{
Assert.DoesNotContain("trivy-action", Code(text), name);
Assert.DoesNotContain("gitleaks-action", Code(text), name);
}
var secrets = Script("segreti.sh");
StringAssert.Contains(secrets, "--redact");
StringAssert.Contains(Job(Workflow("verifica.yml"), "controlli"), "fetch-depth: 0");
var scan = Script("scansione-immagine.sh");
StringAssert.Contains(scan, "--severity CRITICAL --ignore-unfixed");
StringAssert.Contains(scan, "--exit-code 1");
}
[TestMethod]
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
var smoke = Code(Script("prova-immagine.sh"));
var runs = DockerRun().Matches(smoke);
Assert.IsGreaterThanOrEqualTo(4, runs.Count);
foreach (Match run in runs)
{
StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site");
StringAssert.Contains(run.Value, "\"${etichette[@]}\"", "every tried container carries the mark the cleanup looks for");
}
StringAssert.Contains(smoke, "etichette=(--label \"febe.ci.prova=$esecuzione\")");
StringAssert.Contains(smoke, "nome=\"febe-prova-$esecuzione\"");
// Docker copies the labels of an image into every container made from it: the mark must never be in an image.
Assert.DoesNotContain("febe.ci.prova", Code(Script("costruisci-immagine.sh")));
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
if (OperatingSystem.IsWindows())
{
var git = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Git", "bin", "bash.exe");
return File.Exists(git) ? git : null;
}
return new[] { "/bin/bash", "/usr/bin/bash" }.FirstOrDefault(File.Exists);
}
/// <summary>The workflows and the scripts of the CI, by name.</summary>
private static List<(string Name, string Text)> AllCiFiles() =>
[.. Directory.EnumerateFiles(CiPath("workflows")).Concat(Directory.EnumerateFiles(CiPath("scripts")))
.Select(file => (Path.GetFileName(file), Read(file)))];
private static string Workflow(string name) => Read(CiPath("workflows", name));
private static string Script(string name) => Read(CiPath("scripts", name));
private static string Read(string path) => File.ReadAllText(path).Replace("\r\n", "\n", StringComparison.Ordinal);
/// <summary>A path under .gitea; inconclusive in the build of the image, whose context leaves .gitea out.</summary>
private static string CiPath(params string[] parts)
{
var path = Repository.PathOf([".gitea", .. parts]);
var root = Repository.Root()!;
if (!File.Exists(path) && !Directory.Exists(path) && !Directory.Exists(Path.Combine(root, ".git")) && !File.Exists(Path.Combine(root, ".git")))
{
Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker).");
}
return path;
}
/// <summary>The text without comment lines (YAML and shell): what runs, not what the comments say.</summary>
private static string Code(string text) =>
string.Join('\n', text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Where(line => !line.TrimStart().StartsWith('#')));
/// <summary>The block of a job: from « name:» to the next job.</summary>
private static string Job(string workflow, string name)
{
var match = Regex.Match(workflow, $@"^ {Regex.Escape(name)}:\n(?<body>(?:(?: .*|\s*)\n)*)", RegexOptions.Multiline);
Assert.IsTrue(match.Success, $"manca il lavoro {name}");
return match.Groups["body"].Value;
}
/// <summary>The block of a step, from its «- name:» to the next step.</summary>
private static string Step(string job, string name)
{
var start = job.IndexOf("- name: " + name, StringComparison.Ordinal);
Assert.IsGreaterThanOrEqualTo(0, start, $"manca il passo «{name}»");
var next = job.IndexOf("\n - ", start + 1, StringComparison.Ordinal);
return next < 0 ? job[start..] : job[start..next];
}
[GeneratedRegex(@"(?<=^jobs:\n(?:.*\n)*?)^ (?<name>[a-z][\w-]*):$", RegexOptions.Multiline)]
private static partial Regex JobHeader();
[GeneratedRegex(@"dotnet test(?:\s+(?<target>[^\s-][^\s]*))?")]
private static partial Regex DotnetTest();
[GeneratedRegex(@"(?m)^\s*set\s+-[a-wyz]*x|\bbash\s+-x\b")]
private static partial Regex Trace();
[GeneratedRegex(@"\b(?:echo|printf)\b")]
private static partial Regex Printing();
[GeneratedRegex(@"\$\{?(?:TOKEN|FEBE_PASSWORD|AUTH|REGISTRY_TOKEN|PASSWORD)\b")]
private static partial Regex SecretReference();
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
private static partial Regex Sha256();
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
private static partial Regex DockerRun();
}
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
# its headers. Any other option is an error (exit 3).
set -uo pipefail
world="${FAKE_CURL_WORLD:?}"
token="$(cat "$world/token" 2> /dev/null)"
method=GET output="" write="" url="" authorized=0
while (($#)); do
case "$1" in
-s | -S | -sS) ;;
--max-time) shift ;;
-X) method="$2"; shift ;;
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
-o) output="$2"; shift ;;
-w) write="$2"; shift ;;
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
*)
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
url="$1"
;;
esac
shift
done
printf '%s %s\n' "$method" "$url" >> "$world/calls"
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
answer() {
local code="$1" body="${2:-}"
if [[ -n "$output" ]]; then
printf '%s' "$body" > "$output"
else
printf '%s' "$body"
fi
[[ -z "$write" ]] || printf '%s' "$code"
exit 0
}
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
((authorized)) || answer 401 '{"message":"token is required"}'
base="$(cat "$world/base")"
case "$method $url" in
"GET $base?page="*"&limit=50")
page="${url#"$base?page="}"
page="${page%%&*}"
if [[ -f "$world/page-$page.json" ]]; then
answer 200 "$(cat "$world/page-$page.json")"
fi
answer 200 "[]"
;;
"DELETE $base/"*)
echo "${url#"$base/"}" >> "$world/deleted"
answer 204
;;
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
esac
+586
View File
@@ -0,0 +1,586 @@
#!/usr/bin/env bash
# A fake docker client for PipelineTests: .gitea/scripts/pulizia-docker.sh runs against a small daemon written in text
# files, and the test reads what is left. No daemon, no network. It models only what the cleanup relies on, the way
# Docker does it:
# - filters of «ps»: label filters must all match, the values of any other key are alternatives (status, name as a
# regular expression, ancestor by name or id, volume and network by name; stopped containers too);
# - «rm» refuses a running container without -f;
# - «image rm <name>» only untags when the image has other names, and refuses an image a container uses (always if the
# container runs, without -f if it is stopped);
# - «image prune» takes only images no container uses, running or stopped: without -a only those without a name, with
# -a any; «until» keeps those created in the last 72 or 24 hours. With -a an image a container uses stays but loses
# its extra names, as moby does it with the classic store or, with $FAKE_DOCKER_WORLD/store, with containerd;
# - «builder prune» only answers (the cache is not modelled);
# - «volume rm» refuses a volume a container mounts, running or stopped, even with -f;
# - «network rm» refuses the predefined networks and a network a running container is attached to;
# - creation times: containers and images in UTC with nanoseconds, volumes and networks two hours ahead with the
# offset (+02:00), as a daemon in Italy writes them; the Created of a network is a time of Go, which the template
# prints as «2026-10-21 06:17:03.123456789 +0200 CEST» and {{json .Created}} as RFC 3339 between quotes.
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use. That includes any prune
# other than those the cleanup may run: image prune -f [--filter until=72h], image prune -a -f --filter until=24h,
# builder prune [-a] -f --filter until=24h.
#
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels|volumes|networks
# (labels as Docker gives them to the container: those of the image plus those of «run»;
# volumes and networks by name, comma separated; the last fields may be missing)
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels|size
# $FAKE_DOCKER_WORLD/volumes name|minutes ago (missing: just created)
# $FAKE_DOCKER_WORLD/networks id|name|minutes ago
# $FAKE_DOCKER_WORLD/store optional: «containerd» for the containerd image store (what «docker info» says);
# otherwise the classic store of overlay2
# $FAKE_DOCKER_WORLD/broken optional: commands («image prune», «builder prune») that fail as if the daemon refused
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here), after BUILDX_BUILDER=<value> when it is set
set -uo pipefail
world="${FAKE_DOCKER_WORLD:?}"
printf '%sdocker %s\n' "${BUILDX_BUILDER:+BUILDX_BUILDER=$BUILDX_BUILDER }" "$*" >> "$world/calls"
now=$(date -u +%s)
touch "$world/containers" "$world/images" "$world/volumes" "$world/networks"
unexpected() {
echo "fake docker: unexpected call: $*" >&2
exit 3
}
broken() {
[[ -f "$world/broken" ]] && grep -qxF -- "$1" "$world/broken"
}
created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; }
created_in_italy() { date -u -d "@$((now - ${1:-0} * 60 + 7200))" "+%Y-%m-%dT%H:%M:%S${2:-}+02:00"; }
# The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints <no value>).
label_value() {
local labels=",$1," key="$2" rest
[[ "$labels" == *",$key="* ]] || { echo "${3:-}"; return; }
rest="${labels#*,"$key"=}"
echo "${rest%%,*}"
}
has_label() {
local labels=",$1," want="$2"
if [[ "$want" == *=* ]]; then
[[ "$labels" == *",$want,"* ]]
else
[[ "$labels" == *",$want="* ]]
fi
}
# Image id for a name or an id; empty when there is none.
resolve_image() {
local ref="$1" id names rest
while IFS='|' read -r id names rest; do
[[ -n "$id" ]] || continue
if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then
echo "$id"
return
fi
done < "$world/images"
}
# The line of a world file whose first field (or, with $3, whose field number $3) is $2; empty when there is none.
line_of() {
local file="$1" wanted="$2" field="${3:-1}" line fields
while IFS= read -r line; do
[[ -n "$line" ]] || continue
IFS='|' read -r -a fields <<< "$line"
if [[ "${fields[0]}" == "$wanted" || "${fields[field - 1]:-}" == "$wanted" ]]; then
echo "$line"
return
fi
done < "$file"
}
image_line() { line_of "$world/images" "$1"; }
# The container line for an id or a name; empty when there is none.
find_container() { line_of "$world/containers" "$1" 2; }
volume_line() { line_of "$world/volumes" "$1"; }
# The network line for an id or a name; empty when there is none.
network_line() { line_of "$world/networks" "$1" 2; }
# Rewrites a world file without the lines whose first field is $2.
drop() {
local file="$1" id="$2" line
: > "$file.new"
while IFS= read -r line; do
[[ "${line%%|*}" == "$id" ]] || printf '%s\n' "$line" >> "$file.new"
done < "$file"
mv "$file.new" "$file"
}
# True when a container uses the image (any: in any state; running: only a running one).
used_by() {
local image="$1" want="$2" id name state age config image_id labels volumes networks
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" && "$image_id" == "$image" ]] || continue
[[ "$want" == any || "$state" == running ]] && return 0
done < "$world/containers"
return 1
}
# True when a container (any: in any state; running: only a running one) has the volume or the network.
uses() {
local field="$1" wanted="$2" want="$3" id name state age config image_id labels volumes networks list
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" ]] || continue
if [[ "$field" == volume ]]; then list="$volumes"; else list="$networks"; fi
[[ ",$list," == *",$wanted,"* ]] || continue
[[ "$want" == any || "$state" == running ]] && return 0
done < "$world/containers"
return 1
}
matches() {
local name="$1" state="$2" image_id="$3" labels="$4" volumes="$5" networks="$6"
shift 6
local -A seen=() ok=()
local filter key value
for filter in "$@"; do
key="${filter%%=*}"
value="${filter#*=}"
case "$key" in
label) has_label "$labels" "$value" || return 1 ;;
status) seen[$key]=1; [[ "$state" == "$value" ]] && ok[$key]=1 ;;
name) seen[$key]=1; [[ "$name" =~ $value ]] && ok[$key]=1 ;;
ancestor) seen[$key]=1; [[ -n "$image_id" && "$(resolve_image "$value")" == "$image_id" ]] && ok[$key]=1 ;;
volume) seen[$key]=1; [[ ",$volumes," == *",$value,"* ]] && ok[$key]=1 ;;
network) seen[$key]=1; [[ ",$networks," == *",$value,"* ]] && ok[$key]=1 ;;
*) unexpected "filter $filter" ;;
esac
done
for key in "${!seen[@]}"; do
[[ -n "${ok[$key]:-}" ]] || return 1
done
return 0
}
ps_command() {
local quiet=0 format='{{.ID}} {{.Names}}' filters=()
while (($#)); do
case "$1" in
-a | --no-trunc) ;;
-q) quiet=1 ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "ps $1" ;;
esac
shift
done
local id name state age config image_id labels volumes networks out key
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" ]] || continue
matches "$name" "$state" "$image_id" "$labels" "$volumes" "$networks" "${filters[@]}" || continue
if ((quiet)); then
echo "$id"
continue
fi
out="${format//"{{.ID}}"/$id}"
out="${out//"{{.Names}}"/$name}"
while [[ "$out" =~ \{\{\.Label\ \"([^\"]+)\"\}\} ]]; do
key="${BASH_REMATCH[1]}"
out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}"
done
[[ "$out" == *"{{"* ]] && unexpected "ps --format $format"
printf '%s\n' "$out"
done < "$world/containers"
return 0
}
container_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
(($#)) || unexpected "container inspect without a container"
local ref line id name state age config image_id labels volumes networks status=0
for ref in "$@"; do
line=$(find_container "$ref")
if [[ -z "$line" ]]; then
echo "Error: No such container: $ref" >&2
status=1
continue
fi
IFS='|' read -r id name state age config image_id labels volumes networks <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{.Config.Image}}") echo "$config" ;;
"{{.Image}}") echo "$image_id" ;;
"{{.Image}} {{.Config.Image}}") echo "$image_id $config" ;;
"{{.Name}}") echo "/$name" ;;
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
*) unexpected "container inspect -f $format" ;;
esac
done
return "$status"
}
rm_command() {
local force=0
while [[ "${1:-}" == -* ]]; do
case "$1" in
-f) force=1 ;;
-v) ;;
*) unexpected "rm $1" ;;
esac
shift
done
local line id name state rest
line=$(find_container "${1:?}")
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
IFS='|' read -r id name state rest <<< "$line"
if [[ "$state" == running && "$force" == 0 ]]; then
echo "Error: cannot remove container \"/$name\": container is running: stop the container before removing or force remove" >&2
exit 1
fi
drop "$world/containers" "$id"
}
image_ls() {
local format="" reference=""
while (($#)); do
case "$1" in
--no-trunc) ;;
--filter) [[ "$2" == reference=* ]] || unexpected "image ls --filter $2"; reference="${2#reference=}"; shift ;;
--format) format="$2"; shift ;;
*) unexpected "image ls $1" ;;
esac
shift
done
[[ -n "$format" ]] || unexpected "image ls without --format"
local id names age labels size tag out
while IFS='|' read -r id names age labels size; do
[[ -n "$id" ]] || continue
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
if ((${#tags[@]} == 0)); then
[[ -z "$reference" ]] || continue
tags=("<none>:<none>")
fi
for tag in "${tags[@]}"; do
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] || continue
out="${format//"{{.ID}}"/$id}"
out="${out//"{{.Repository}}"/${tag%:*}}"
out="${out//"{{.Tag}}"/${tag##*:}}"
out="${out//"{{.Size}}"/${size:-100MB}}"
[[ "$out" == *"{{"* ]] && unexpected "image ls --format $format"
printf '%s\n' "$out"
done
done < "$world/images"
return 0
}
image_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local wanted id names age labels size
wanted=$(resolve_image "${1:?}")
[[ -n "$wanted" ]] || { echo "Error: No such image: $1" >&2; exit 1; }
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
*) unexpected "image inspect -f $format" ;;
esac
}
image_rm() {
local force=0
[[ "${1:-}" == -f ]] && { force=1; shift; }
local ref="${1:?}" wanted id names age labels size left="" tag
wanted=$(resolve_image "$ref")
[[ -n "$wanted" ]] || { echo "Error: No such image: $ref" >&2; exit 1; }
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
if [[ "$ref" != "$id" && ${#tags[@]} -gt 1 ]]; then
for tag in "${tags[@]}"; do [[ "$tag" == "$ref" ]] || left="${left:+$left,}$tag"; done
drop "$world/images" "$id"
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
echo "Untagged: $ref"
return 0
fi
if [[ "$ref" == "$id" && ${#tags[@]} -gt 1 && "$force" == 0 ]]; then
echo "Error: conflict: unable to delete $id (must be forced) - image is referenced in multiple repositories" >&2
exit 1
fi
if used_by "$id" running || { [[ "$force" == 0 ]] && used_by "$id" any; }; then
echo "Error: conflict: unable to remove repository reference \"$ref\" - container is using its referenced image" >&2
exit 1
fi
drop "$world/images" "$id"
echo "Deleted: $id"
}
# The full name of an image name, the way Docker sorts references: docker.io/library/ or docker.io/ before the names
# of Docker Hub written without a domain, :latest when the tag is missing.
full_name() {
local name="$1" first
[[ "${name##*/}" == *:* ]] || name="$name:latest"
if [[ "$name" != */* ]]; then
echo "docker.io/library/$name"
return
fi
first="${name%%/*}"
if [[ "$first" == *.* || "$first" == *:* || "$first" == localhost ]]; then echo "$name"; else echo "docker.io/$name"; fi
}
# The names «image prune -a» leaves to an image a container uses, comma separated, the way moby does it. With the
# classic store it removes the references in lexical order of their full names and only the last one is refused
# (ImageDelete keeps the single reference of an image in use); with containerd it keeps the names the containers were
# created from and, when a container uses the image by id and no name would be left, the last one in lexical order.
names_kept() {
local image="$1" names="$2" sorted name full cid cname state age config image_id rest by_id=0
local -A from=()
local kept=()
sorted=$(IFS=','; for name in $names; do printf '%s %s\n' "$(full_name "$name")" "$name"; done | LC_ALL=C sort)
if [[ "$(store)" == classic ]]; then
tail -n 1 <<< "$sorted" | cut -d' ' -f2-
return
fi
while IFS='|' read -r cid cname state age config image_id rest; do
[[ -n "$cid" && "$image_id" == "$image" ]] || continue
if [[ "$config" == "$image" ]]; then by_id=1; else from[$(full_name "$config")]=1; fi
done < "$world/containers"
while read -r full name; do
[[ -n "${from[$full]:-}" ]] && kept+=("$name")
done <<< "$sorted"
((${#kept[@]} > 0 || !by_id)) || kept=("$(tail -n 1 <<< "$sorted" | cut -d' ' -f2-)")
(IFS=','; echo "${kept[*]}")
}
image_prune() {
local all=0 hours=0
case "$*" in
"-f") ;;
"-f --filter until=72h") hours=72 ;;
"-a -f --filter until=24h") all=1; hours=24 ;;
*) unexpected "image prune $*" ;;
esac
broken "image prune" && { echo "Error response from daemon: a prune operation is already running" >&2; exit 1; }
local id names age labels size gone=() untag=() tag left
while IFS='|' read -r id names age labels size; do
[[ -n "$id" ]] || continue
((all)) || [[ -z "$names" ]] || continue
((age >= hours * 60)) || continue
if used_by "$id" any; then
[[ "$names" == *,* ]] && untag+=("$id")
else
gone+=("$id")
fi
done < "$world/images"
((${#gone[@]} + ${#untag[@]} == 0)) || echo "Deleted Images:"
for id in "${untag[@]}"; do
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
left=$(names_kept "$id" "$names")
IFS=',' read -r -a tags <<< "$names"
for tag in "${tags[@]}"; do
[[ ",$left," == *",$tag,"* ]] || echo "untagged: $tag"
done
drop "$world/images" "$id"
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
done
for id in "${gone[@]}"; do
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
for tag in "${tags[@]}"; do
echo "untagged: $tag"
echo "untagged: ${tag%:*}@sha256:0123456789abcdef"
done
drop "$world/images" "$id"
echo "deleted: sha256:$id"
done
echo
if ((${#gone[@]} > 0)); then
echo "Total reclaimed space: ${#gone[@]}00MB"
else
echo "Total reclaimed space: 0B"
fi
}
builder_prune() {
case "$*" in
"-f --filter until=24h" | "-a -f --filter until=24h") ;;
*) unexpected "builder prune $*" ;;
esac
broken "builder prune" && { echo "ERROR: failed to prune build cache: a prune operation is already running" >&2; exit 1; }
printf 'Total:\t1.5GB\n'
}
volume_ls() {
local filters=() format='{{.Name}}' filter name age
while (($#)); do
case "$1" in
-q) ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "volume ls $1" ;;
esac
shift
done
[[ "$format" == '{{.Name}}' ]] || unexpected "volume ls --format $format"
while IFS='|' read -r name age; do
[[ -n "$name" ]] || continue
for filter in "${filters[@]}"; do
case "$filter" in
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
dangling=true) uses volume "$name" any && continue 2 ;;
*) unexpected "volume ls --filter $filter" ;;
esac
done
echo "$name"
done < "$world/volumes"
return 0
}
volume_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line name age
line=$(volume_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: get $1: no such volume" >&2; exit 1; }
IFS='|' read -r name age <<< "$line"
case "$format" in
"") echo "[{\"Name\": \"$name\"}]" ;;
"{{.CreatedAt}}") created_in_italy "$age" ;;
*) unexpected "volume inspect -f $format" ;;
esac
}
volume_rm() {
[[ "${1:-}" == -f ]] && shift
local name="${1:?}"
[[ -n "$(volume_line "$name")" ]] || { echo "Error response from daemon: get $name: no such volume" >&2; exit 1; }
if uses volume "$name" any; then
echo "Error response from daemon: remove $name: volume is in use" >&2
exit 1
fi
drop "$world/volumes" "$name"
}
network_ls() {
local filters=() format='{{.ID}} {{.Name}}' filter id name age
while (($#)); do
case "$1" in
--no-trunc) ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "network ls $1" ;;
esac
shift
done
[[ "$format" == '{{.ID}} {{.Name}}' ]] || unexpected "network ls --format $format"
while IFS='|' read -r id name age; do
[[ -n "$id" ]] || continue
for filter in "${filters[@]}"; do
case "$filter" in
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
*) unexpected "network ls --filter $filter" ;;
esac
done
echo "$id $name"
done < "$world/networks"
return 0
}
network_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line id name age
line=$(network_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
IFS='|' read -r id name age <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\", \"Name\": \"$name\"}]" ;;
"{{json .Created}}") echo "\"$(created_in_italy "$age" .123456789)\"" ;;
# Created of a network is a time.Time: the template prints it the way Go does, not as RFC 3339.
"{{.Created}}") date -u -d "@$((now - ${age:-0} * 60 + 7200))" "+%Y-%m-%d %H:%M:%S.123456789 +0200 CEST" ;;
*) unexpected "network inspect -f $format" ;;
esac
}
network_rm() {
local line id name age
line=$(network_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
IFS='|' read -r id name age <<< "$line"
case "$name" in
bridge | host | none) echo "Error response from daemon: $name is a pre-defined network and cannot be removed" >&2; exit 1 ;;
esac
if uses network "$name" running; then
echo "Error response from daemon: error while removing network: network $name id $id has active endpoints" >&2
exit 1
fi
drop "$world/networks" "$id"
}
store() {
if [[ "$(cat "$world/store" 2> /dev/null)" == containerd ]]; then echo containerd; else echo classic; fi
}
# The DriverStatus of «docker info» as Docker prints it: with the containerd image store the snapshotter, with the
# classic one the details of overlay2.
info_command() {
[[ "$*" == "--format {{json .DriverStatus}}" ]] || unexpected "info $*"
if [[ "$(store)" == containerd ]]; then
echo '[["driver-type","io.containerd.snapshotter.v1"]]'
else
echo '[["Backing Filesystem","extfs"],["Supports d_type","true"],["Using metacopy","false"],["Native Overlay Diff","true"],["userxattr","false"]]'
fi
}
system_df() {
case "$*" in
"") echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
"--format {{.Type}}|{{.Size}}|{{.Reclaimable}}")
printf '%s\n' "Images|9.1GB|6.2GB (68%)" "Containers|120MB|80MB (66%)" "Local Volumes|3.4GB|1.1GB (32%)" "Build Cache|5.3GB|4.8GB"
;;
*) unexpected "system df $*" ;;
esac
}
case "${1:-}" in
ps) shift; ps_command "$@" ;;
container) [[ "${2:-}" == inspect ]] || unexpected "$*"; shift 2; container_inspect "$@" ;;
rm) shift; rm_command "$@" ;;
image)
sub="${2:-}"
shift 2
case "$sub" in
ls) image_ls "$@" ;;
inspect) image_inspect "$@" ;;
rm) image_rm "$@" ;;
prune) image_prune "$@" ;;
*) unexpected "image $sub" ;;
esac
;;
builder) [[ "${2:-}" == prune ]] || unexpected "$*"; shift 2; builder_prune "$@" ;;
buildx) [[ "${2:-}" == rm ]] || unexpected "$*"; echo "ERROR: no builder \"${4:-}\" found" >&2; exit 1 ;;
volume)
sub="${2:-}"
shift 2
case "$sub" in
ls) volume_ls "$@" ;;
inspect) volume_inspect "$@" ;;
rm) volume_rm "$@" ;;
*) unexpected "volume $sub" ;;
esac
;;
network)
sub="${2:-}"
shift 2
case "$sub" in
ls) network_ls "$@" ;;
inspect) network_inspect "$@" ;;
rm) network_rm "$@" ;;
*) unexpected "network $sub" ;;
esac
;;
system) [[ "${2:-}" == df ]] || unexpected "$*"; shift 2; system_df "$@" ;;
info) shift; info_command "$@" ;;
*) unexpected "$*" ;;
esac
@@ -0,0 +1,36 @@
[
[
{"id": 140, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "main", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/main", "created_at": "2026-10-20T19:42:15+02:00"},
{"id": 142, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "created_at": "2026-10-20T19:42:09+02:00"},
{"id": 141, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "created_at": "2026-10-20T19:42:09+02:00"},
{"id": 139, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "created_at": "2026-10-20T19:42:11+02:00"},
{"id": 138, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.1", "created_at": "2026-10-20T18:05:00+02:00"},
{"id": 137, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "latest", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/latest", "created_at": "2026-10-14T10:00:00+02:00"},
{"id": 136, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.0", "created_at": "2026-10-14T10:00:00+02:00"},
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
{"id": 101, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-0a1b2c3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-0a1b2c3", "created_at": "2026-10-01T09:00:00+02:00"},
{"id": 112, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-be1f2a3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-be1f2a3", "created_at": "2026-10-12T09:00:00+02:00"},
{"id": 111, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ad0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ad0e1f2", "created_at": "2026-10-11T09:00:00+02:00"},
{"id": 110, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-9d0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-9d0e1f2", "created_at": "2026-10-10T09:00:00+02:00"},
{"id": 99, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "created_at": "2026-09-20T09:00:00+02:00"},
{"id": 109, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-8c9d0e1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-8c9d0e1", "created_at": "2026-10-09T09:00:00+02:00"}
],
[
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
{"id": 108, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-7b8c9d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-7b8c9d0", "created_at": "2026-10-08T09:00:00+02:00"},
{"id": 107, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-6a7b8c9", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-6a7b8c9", "created_at": "2026-10-07T09:00:00+02:00"},
{"id": 106, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-5f6a7b8", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-5f6a7b8", "created_at": "2026-10-06T09:00:00+02:00"},
{"id": 105, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-4e5f6a7", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-4e5f6a7", "created_at": "2026-10-05T01:00:00+02:00"},
{"id": 104, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-3d4e5f6", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-3d4e5f6", "created_at": "2026-10-04T23:30:00Z"},
{"id": 103, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-2c3d4e5", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-2c3d4e5", "created_at": "2026-10-03T07:00:00Z"},
{"id": 102, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1b2c3d4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1b2c3d4", "created_at": "2026-10-02T09:00:00+02:00"},
{"id": 100, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.2.0-rc.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.2.0-rc.1", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 97, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-zzzzzzz", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-zzzzzzz", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 96, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1a2b3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1a2b3c", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 95, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ABCDEF0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ABCDEF0", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 94, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-e1f2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-e1f2a3b4"},
{"id": 93, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha-0000000", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha-0000000", "created_at": "2026-08-01T09:00:00+02:00"},
{"id": 91, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "created_at": "2026-08-01T09:00:00+02:00"},
{"id": 92, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe", "version": "sha-1111111", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe/sha-1111111", "created_at": "2026-08-01T09:00:00+02:00"}
]
]
@@ -0,0 +1,253 @@
using System.Diagnostics;
using System.Text.Json.Nodes;
using Febe.App;
using Febe.Browser.Cdp;
using Febe.Browser.Hosting;
using Febe.Browser.RemoteView;
using Febe.Core.Abstractions;
using Febe.Server;
using Febe.Tests.Browser.TestSupport;
using Febe.Web.Connection;
using Febe.Web.Engine;
namespace Febe.Tests.Server;
/// <summary>
/// Opening the remote view while the page changes document (Gitea issue #3), without a browser. From
/// <c>ReadyToCommitNavigation</c> of a navigation in a new RenderFrameHost until it commits, Chromium answers
/// <c>Page.startScreencast</c> with -32000 «Not attached to an active page»: the view must open once the new document is
/// there, a page that never gets there must still end in «non risponde» within a few seconds, and a browser that is gone
/// must say so at once.
/// </summary>
[TestClass]
public sealed class RemoteViewStartTests
{
public TestContext TestContext { get; set; } = null!;
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task AViewOpenedWhileThePageChangesDocumentOpensOnceTheNewDocumentIsThere()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(attempt => attempt == 1 ? InactivePage() : null);
var view = await bed.Host.OpenAsync(ct);
Assert.IsNull(view.Ended, "the view is open");
Assert.AreEqual(2, bed.Starts, "the start refused while the page changed document was sent again");
Assert.AreEqual(1, bed.Browser.UserDriving.Leases, "the open view holds the browser");
Assert.IsLessThan(TimeSpan.FromSeconds(1), bed.Elapsed, "a short pause, not the whole budget");
// Frames flow to the view: meta first, then the JPEG.
bed.Cdp.Raise("Page.screencastFrame", Frame());
var outputs = await ReadUntilFrameAsync(view, ct);
Assert.IsInstanceOfType<RemoteViewMeta>(outputs[0]);
Assert.IsInstanceOfType<RemoteViewFrame>(outputs[^1]);
await view.DisposeAsync();
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "no view, no lease");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task APageThatStaysBetweenTwoDocumentsStillEndsInNonRispondeWithinTheBudget()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => InactivePage());
var watch = Stopwatch.StartNew();
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
StringAssert.Contains(error.Message, "non risponde");
Assert.IsTrue(error.InnerException is CdpCommandException { IsInactivePage: true }, "the browser's answer stays the cause");
Assert.IsLessThanOrEqualTo(ScreencastSession.InactivePageBudget, bed.Elapsed, "never longer than the budget");
Assert.IsGreaterThan(TimeSpan.FromSeconds(4), bed.Elapsed, "tried for the whole budget");
Assert.IsInRange(5, 15, bed.Starts, "a few attempts, spaced out");
Assert.IsLessThan(TimeSpan.FromSeconds(10), watch.Elapsed, "the pauses are the clock's, not a hang");
Assert.AreEqual(0, bed.Browser.UserDriving.Leases, "nothing of the view stays behind");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ABrowserThatIsGoneIsNotTriedAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => new CdpDisconnectedException("Il collegamento con il browser si è chiuso."));
var error = await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
StringAssert.Contains(error.Message, "non risponde");
Assert.AreEqual(1, bed.Starts);
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed, "no pause at all");
Assert.AreEqual(0, bed.Browser.UserDriving.Leases);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task AnotherRefusalOfTheBrowserIsNotTriedAgain()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => new CdpCommandException("Page.startScreencast", CdpCommandException.ServerErrorCode, "Not attached to a page"));
await Assert.ThrowsExactlyAsync<RemoteViewUnavailableException>(() => bed.Host.OpenAsync(ct));
Assert.AreEqual(1, bed.Starts, "only «Not attached to an active page» is the moment of a navigation");
Assert.AreEqual(TimeSpan.Zero, bed.Elapsed);
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ReplacingAViewKeepsAlbertoAtTheBrowserThroughout()
{
var ct = TestContext.CancellationToken;
await using var bed = new Bed(_ => null);
var gate = bed.Browser.UserDriving;
var older = await bed.Host.OpenAsync(ct);
var released = 0;
void OnChanged(object? sender, bool driving)
{
if (!driving)
{
Interlocked.Increment(ref released);
}
}
gate.Changed += OnChanged;
try
{
var newer = await bed.Host.OpenAsync(ct);
Assert.AreEqual(RemoteViewEnd.Replaced, older.Ended);
Assert.IsNull(newer.Ended);
Assert.AreEqual(0, released, "the engine never sees nobody at the browser between the two views (it would rest the page under the new one)");
Assert.AreEqual(1, gate.Leases);
await newer.DisposeAsync();
Assert.AreEqual(1, released, "closing the last view lets the engine go on");
Assert.AreEqual(0, gate.Leases);
}
finally
{
gate.Changed -= OnChanged;
}
}
private static CdpCommandException InactivePage() =>
new("Page.startScreencast", CdpCommandException.ServerErrorCode, CdpCommandException.InactivePageMessage);
private static JsonObject Frame() => new()
{
["sessionId"] = 1,
["data"] = Convert.ToBase64String([0xFF, 0xD8, 0xFF, 0xD9]),
["metadata"] = new JsonObject { ["deviceWidth"] = Bed.Width, ["deviceHeight"] = Bed.Height, ["pageScaleFactor"] = 1 },
};
private static async Task<List<RemoteViewOutput>> ReadUntilFrameAsync(IRemoteViewConnection view, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(TimeSpan.FromSeconds(10));
var outputs = new List<RemoteViewOutput>();
await foreach (var output in view.ReadAsync(timeout.Token))
{
outputs.Add(output);
if (output is RemoteViewFrame)
{
break;
}
}
return outputs;
}
/// <summary>The host over a fake page whose answer to each <c>Page.startScreencast</c> is chosen by the test.</summary>
private sealed class Bed : IAsyncDisposable
{
public const int Width = 1280;
public const int Height = 900;
private readonly FebeLog _log;
private readonly DateTimeOffset _start;
private int _starts;
/// <param name="startFailure">For the n-th start (from 1), the exception the browser answers with; null: started.</param>
public Bed(Func<int, Exception?> startFailure)
{
Clock = new VirtualClock();
_start = Clock.Now;
Cdp = new FakeCdpSession(Clock)
{
Responder = (method, _) =>
{
switch (method)
{
case "Page.getFrameTree":
return new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1", ["url"] = "about:blank" } } };
case "Page.startScreencast":
if (startFailure(Interlocked.Increment(ref _starts)) is { } failure)
{
throw failure;
}
return null;
default:
return null;
}
},
};
Browser = new PageBrowser(Cdp);
_log = new FebeLog(null, null, Clock);
Host = new BrowserRemoteViewHost(Browser, new BrowserUseTracker(), Clock, _log, browserClock: Clock);
}
public VirtualClock Clock { get; }
public FakeCdpSession Cdp { get; }
public PageBrowser Browser { get; }
public BrowserRemoteViewHost Host { get; }
public int Starts => Volatile.Read(ref _starts);
/// <summary>Time spent in the host's pauses (the virtual clock moves only there).</summary>
public TimeSpan Elapsed => Clock.Now - _start;
public async ValueTask DisposeAsync()
{
await Host.ShutdownAsync();
_log.Dispose();
}
}
/// <summary>A running browser on one page, as the remote view host sees it.</summary>
private sealed class PageBrowser(ICdpSession cdp) : IFebeBrowser
{
public ICdpSession Cdp { get; } = cdp;
public UserDrivingGate UserDriving { get; } = new();
public bool UserIsDriving => UserDriving.IsDriving;
public bool IsAvailable => true;
public string? LastError => null;
public string ProfileDirectory => "browser";
public int WindowWidth => Bed.Width;
public int WindowHeight => Bed.Height;
public Task RunAsync(CancellationToken ct) => Task.CompletedTask;
public Task<NavigationResult> RestAsync(CancellationToken ct) => Cdp.RestAsync(ct);
public Task ShowToUserAsync(CancellationToken ct) => Task.CompletedTask;
public Task HideFromUserAsync(CancellationToken ct) => Task.CompletedTask;
public Task RestartWithEmptyProfileAsync(CancellationToken ct) => Task.CompletedTask;
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
}
+77 -2
View File
@@ -9,6 +9,7 @@ using Febe.Core.Storage;
using Febe.SitoDiProva;
using Febe.Tests.Alerts.Support;
using Febe.Tests.Server.Support;
using Febe.Tests.Support;
using Febe.Web.Connection;
namespace Febe.Tests.Server;
@@ -20,6 +21,7 @@ namespace Febe.Tests.Server;
/// the remote view. Never Instagram: the browser only sees 127.0.0.1.
/// </summary>
[TestClass]
[TestCategory(SyntheticSite.Category)]
[DoNotParallelize]
public sealed partial class ServerEndToEndTests
{
@@ -250,20 +252,44 @@ public sealed partial class ServerEndToEndTests
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
var host = server.RemoteView!;
var gate = server.Browser!.UserDriving;
var released = 0;
void OnChanged(object? sender, bool driving)
{
if (!driving)
{
Interlocked.Increment(ref released);
}
}
for (var round = 0; round < 5; round++)
{
// From the rest page: where the browser starts, and where the engine puts it once nobody is at the browser.
// Page.getFrameTree is answered by the page itself, which DevTools holds back while a navigation is pending:
// «about:blank» here means the engine's rest has committed.
await ServerTestBed.WaitUntilAsync(
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(server.Browser.Cdp, ct) == "about:blank",
TimeSpan.FromSeconds(20),
"la pagina di riposo");
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended.
var views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
// Two tabs restored together, or the phone and the PC at once: the newest wins, the other is ended — and the
// engine never sees nobody at the browser in between (it would put the page to rest under the newer view).
Volatile.Write(ref released, 0);
gate.Changed += OnChanged;
IRemoteViewConnection[] views;
try
{
views = await Task.WhenAll(Task.Run(() => host.OpenAsync(ct), ct), Task.Run(() => host.OpenAsync(ct), ct));
}
finally
{
gate.Changed -= OnChanged;
}
var open = views.Where(v => v.Ended is null).ToList();
Assert.HasCount(1, open, $"Round {round}: one view stays open.");
Assert.AreEqual(RemoteViewEnd.Replaced, views.Single(v => v.Ended is not null).Ended);
Assert.AreEqual(1, gate.Leases, $"Round {round}: only the open view holds the browser.");
Assert.AreEqual(0, Volatile.Read(ref released), $"Round {round}: the browser was never left without a driver while one view replaced the other.");
// The page of the replaced view closes its socket: the open view still gets its frames.
await views.Single(v => v.Ended is not null).DisposeAsync();
@@ -275,6 +301,55 @@ public sealed partial class ServerEndToEndTests
}
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task AViewOpenedWhileThePageIsNavigatingOpensAndShowsItsFrames()
{
var ct = TestContext.CancellationToken;
await using var bed = await ServerTestBed.StartAsync();
var server = bed.Server;
await server.Running.WaitAsync(TimeSpan.FromSeconds(60), ct);
var host = server.RemoteView!;
var browser = server.Browser!;
for (var round = 0; round < 6; round++)
{
// From the rest page, as in TwoViews…: the previous round ends on a site page, so «about:blank» here means the
// engine's rest after the last view has committed and nothing else navigates.
await ServerTestBed.WaitUntilAsync(
async () => await Febe.Browser.Cdp.CdpPageExtensions.GetMainFrameUrlAsync(browser.Cdp, ct) == "about:blank",
TimeSpan.FromSeconds(20),
"la pagina di riposo");
// Even rounds: «Accedi a Instagram» on the Collegamento page navigates to the login page while the same page
// opens the view. Odd rounds: the rest page, as the engine puts it after a session or after the last view.
// A guard of these pairs, not of the retry: with the navigation already sent, the view's first look at the
// page (Page.getFrameTree) is answered only once it has committed, so the start comes after the commit (seen
// with Chrome 155). RemoteViewDuringNavigationTests makes the start meet the refusal on purpose.
var navigation = round % 2 == 0
? Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?vista={round}", ct)
: browser.RestAsync(ct);
var view = await host.OpenAsync(ct);
try
{
var navigated = await navigation;
Assert.IsTrue(navigated.Succeeded, $"Round {round}: {navigated.ErrorText}");
Assert.IsNull(view.Ended, $"Round {round}: the view is open.");
Assert.AreEqual(1, browser.UserDriving.Leases, $"Round {round}: only the view holds the browser.");
// A new page paints: its frames reach the view.
await Febe.Browser.Cdp.CdpPageExtensions.NavigateAsync(browser.Cdp, $"{bed.Site.SiteUrl}/?giro={round}", ct);
Assert.IsTrue(await FrameArrivesAsync(view, ct), $"Round {round}: frames of the page.");
}
finally
{
await view.DisposeAsync();
}
Assert.AreEqual(0, browser.UserDriving.Leases, $"Round {round}: no view, no lease.");
}
}
private static async Task<bool> FrameArrivesAsync(IRemoteViewConnection view, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
+13 -4
View File
@@ -99,14 +99,23 @@ public sealed class StartupProblemTests
[TestMethod]
public async Task ADataFolderOnANetworkShareIsRefused()
{
// A share shows itself differently on the two systems: on Linux as a cifs mount in the mount table (injected
// here), on Windows as a UNC path, recognised from its form before anything touches it. The Windows server name
// ends in .invalid (RFC 6761): no machine answers to it, and nothing here looks it up.
using var temp = new TempFolder("server-problemi");
var data = temp.Combine("dati");
var windows = OperatingSystem.IsWindows();
var data = windows ? @"\\febe-prova.invalid\condivisa\dati" : temp.Combine("dati");
var mounts = $"/dev/sda1 / ext4 rw 0 0\n//nas/condivisa {temp.Path} cifs rw 0 0\n";
await using var server = await FebeServer.StartAsync(Options(temp), Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
await using var server = await FebeServer.StartAsync(Options(temp) with { DataFolder = data }, Hooks() with { DataFolderCheck = new DataFolderCheck(() => mounts) });
var problem = server.Problems.Single();
Assert.AreEqual(StartupChecks.DataOnNetwork, problem.Code);
StringAssert.Contains(problem.Message, "cifs");
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
StringAssert.Contains(problem.Message, windows ? "condivisione di rete" : "cifs");
if (!windows)
{
// Nothing written in the Data folder (on Windows the share does not exist: looking would mean asking the network).
Assert.IsFalse(Directory.Exists(Path.Combine(data, "registro")));
}
using var client = Client(server);
await AssertHealthAsync(client, HttpStatusCode.ServiceUnavailable, """{"stato":"problema"}""");
}
@@ -60,7 +60,7 @@ internal sealed class ServerTestBed : IAsyncDisposable
public static async Task<ServerTestBed> StartAsync(bool autoLogin = false, double factor = 10, HttpMessageHandler? telegram = null, IFreeSpaceProbe? freeSpace = null)
{
var temp = new TempFolder("server");
var site = await TestSite.StartAsync(new TestSiteOptions());
var site = await SyntheticSite.StartAsync();
var zone = NoonZone();
var clock = new CompressedClock(factor, zone);
var options = new ServerOptions
+46
View File
@@ -0,0 +1,46 @@
using System.Globalization;
using Febe.SitoDiProva;
namespace Febe.Tests.Support;
/// <summary>
/// The one way the tests start the local test site (spec §14.2), so that a run can choose the seed of its synthetic
/// world: <see cref="Variable"/> when it is set, <see cref="DefaultSeed"/> otherwise (nothing changes when it is unset).
/// The CI runs the whole suite with the default seed, then the tests of <see cref="Category"/> again with a seed of
/// its own that it prints in the log: a failure is reproduced by setting the same variable.
/// </summary>
internal static class SyntheticSite
{
/// <summary>Environment variable with the seed of the synthetic world.</summary>
public const string Variable = "FEBE_SEME_PROVA";
/// <summary>The seed when the variable is not set: the one of the command-line site and of the cleaned samples.</summary>
public const int DefaultSeed = 13;
/// <summary>Test category of the tests whose world comes from the seed (the CI runs them with a second seed).</summary>
public const string Category = "SitoDiProva";
/// <summary>The seed of this run.</summary>
public static int Seed => ParseSeed(Environment.GetEnvironmentVariable(Variable));
/// <summary>Starts the test site with the seed of this run, and says which one in the output of the test.</summary>
public static Task<TestSite> StartAsync()
{
var seed = Seed;
Console.WriteLine($"Sito di prova con il seme {seed.ToString(CultureInfo.InvariantCulture)} (si cambia con {Variable}).");
return TestSite.StartAsync(new TestSiteOptions { Seed = seed });
}
/// <summary>The seed written in <paramref name="value"/>: the default when it is empty, an error when it is not a number.</summary>
public static int ParseSeed(string? value)
{
if (string.IsNullOrWhiteSpace(value))
{
return DefaultSeed;
}
return int.TryParse(value.Trim(), NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seed)
? seed
: throw new InvalidOperationException($"{Variable} deve essere un numero intero (fra -2147483648 e 2147483647), non «{value}».");
}
}
+24 -1
View File
@@ -63,13 +63,36 @@ internal sealed class TestLibrary : IAsyncDisposable
await Db.DisposeAsync();
foreach (var suffix in new[] { string.Empty, "-wal", "-shm" })
{
File.Delete(Data.Database + suffix);
await DeleteClosedFileAsync(Data.Database + suffix);
}
Db = await FebeDatabase.OpenAsync(Data.Root);
Ingest = new LibraryIngest(Db, Layout, LibraryNaming.Default, Journal, Clock, Thumbnails, Index);
}
/// <summary>
/// Deletes a file Febe has already closed. On Windows a file still held open elsewhere cannot be deleted, and on one PC a
/// database just closed was now and then held for a few milliseconds by something outside Febe (Restart Manager listed
/// no process; probably the real-time antivirus, which was active, but the cause was never shown): that sharing
/// violation is waited out (at most 5 s). On Linux a delete never meets one, so the first attempt is the only one.
/// </summary>
private static async Task DeleteClosedFileAsync(string path)
{
const int SharingViolation = unchecked((int)0x80070020);
for (var attempt = 1; ; attempt++)
{
try
{
File.Delete(path);
return;
}
catch (IOException ex) when (OperatingSystem.IsWindows() && ex.HResult == SharingViolation && attempt < 100)
{
await Task.Delay(50);
}
}
}
public ValueTask DisposeAsync() => Db.DisposeAsync();
}
+4 -2
View File
@@ -163,10 +163,12 @@ public sealed class ImportApiTests
Assert.AreEqual(HttpStatusCode.BadRequest, sources, "desktop: the native picker, no listing");
}
// Docker: the sources live under /importa (absent on this machine: the listing says so).
// Docker: the sources live under /importa (absent on this machine: the listing says so). The root is reported as
// a full path: «/importa» in the container, rooted on the current drive where the edition runs for development
// on Windows.
await using var docker = await Part2.StartAsync();
var overview = await docker.GetJsonAsync("/api/import");
Assert.AreEqual("/importa", overview.Str("sourceRoot"));
Assert.AreEqual(Path.GetFullPath("/importa"), overview.Str("sourceRoot"));
Assert.IsFalse(overview.Bool("pickFolder"));
var (pick, _) = await docker.SendJsonAsync(HttpMethod.Post, "/api/import/pick-folder");
Assert.AreEqual(HttpStatusCode.BadRequest, pick);
+67 -2
View File
@@ -20,7 +20,8 @@ namespace Febe.Tests.Web;
/// The interface itself in a real (headless) Chromium against a test server: what only shows when the scripts run.
/// The «driving» lease of the Browser and Collegamento pages (spec §4.1, §10.3: the engine is still only while Alberto
/// uses the browser), the remote view's keyboard and mouse, the mosaic and the account card when filters change,
/// the unsaved-changes guard on the browser's Back button, the window bar of Limiti, the sidebar status box.
/// the empty library that follows the connection, the unsaved-changes guard on the browser's Back button, the window
/// bar of Limiti, the sidebar status box.
/// </summary>
[TestClass]
[DoNotParallelize]
@@ -30,6 +31,25 @@ public sealed class InterfaceTests
private static readonly ConnectionStatus Verification = new(ConnectionState.VerificationRequired, "tuo.profilo", "Il tuo profilo", false, "https://www.instagram.com/challenge/");
/// <summary>
/// Installed before the page scripts: the answer of <c>/api/engine</c> waits until <c>window.__releaseEngine()</c>,
/// and without the event stream (the interface then asks <c>/api/engine</c>) nothing brings the engine sooner.
/// </summary>
private const string HoldEngine = """
(() => {
const original = window.fetch.bind(window);
let release;
const gate = new Promise((resolve) => { release = resolve; });
window.__releaseEngine = () => { release(); return true; };
window.fetch = async (input, init) => {
const url = typeof input === 'string' ? input : input.url;
if (url.includes('/api/engine')) await gate;
return original(input, init);
};
delete window.EventSource;
})();
""";
// ------------------------------------------------------------------------------------------ the driving lease
[TestMethod]
@@ -112,6 +132,21 @@ public sealed class InterfaceTests
CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back");
}
[TestMethod]
public async Task ConnectedBeforeTheFirstRoundSaysTheNameIsNotKnownYet()
{
// Right after «Ho finito» the session exists but no round has read the name of the account yet.
var connection = new RecordingConnection { Status = new ConnectionStatus(ConnectionState.Connected, null, null, false, null) };
await using var server = await DockerAsync(connection, new FakeRemoteViewHost());
await using var ui = await UiBrowser.StartAsync();
await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento"));
await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato");
Assert.AreEqual("Collegato", (await ui.EvalAsync("document.querySelector('.chi-collegato h2').textContent")).GetString());
Assert.AreEqual("Nome non ancora noto", (await ui.EvalAsync("document.querySelector('.chi-collegato .muto').textContent")).GetString());
Assert.IsFalse((await ui.EvalAsync("document.querySelector('.chi-collegato').textContent.includes('@')")).GetBoolean(), "no «@» without a name");
}
[TestMethod]
public async Task HoFinitoOnCollegamentoClosesTheRemoteView()
{
@@ -347,6 +382,32 @@ public sealed class InterfaceTests
await ui.WaitAsync("document.querySelector('main .mosaico .tess') !== null", "tessere disegnate");
}
[TestMethod]
public async Task TheEmptyLibraryFollowsTheConnectionAlsoWhenTheEngineAnswersLate()
{
await using var server = await WebTestServer.StartAsync();
await using var ui = await UiBrowser.StartAsync();
await ui.AddInitScriptAsync(HoldEngine);
await ui.OpenAsync(new Uri(server.Address, "/libreria"));
// The library answered first (empty: its count and its empty state come together) and nothing says yet whether
// Febe is connected: the page waits blank, neither the empty library nor the welcome, and not the mosaic.
await ui.WaitAsync("document.querySelector('main [aria-busy=true]') !== null", "libreria vuota in attesa del motore");
Assert.IsTrue((await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.engineState() === null)")).GetBoolean(), "the engine has not answered yet");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina, main .benvenuto, main .mosaico') === null")).GetBoolean(), "no empty state is guessed " + ui.Report());
StringAssert.StartsWith((await ui.EvalAsync("document.querySelector('.testa .quanti').textContent")).GetString(), "0 ");
// Not connected (no own account): the first start with its two ways to begin (spec §10.3).
await ui.EvalAsync("window.__releaseEngine()");
await ui.WaitAsync("document.querySelector('main .benvenuto') !== null && document.querySelector('main [aria-busy=true]') === null", "primo avvio dopo la risposta del motore");
// Connected now (the own account is known): the welcome gives way to the empty library.
await server.Db.Accounts.AddAsync(Make.Account("tuo.profilo", mine: true));
await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)");
await ui.WaitAsync("document.querySelector('main .benvenuto') === null && document.querySelector('main .vuoto-pagina h2') !== null", "libreria vuota da collegato");
Assert.AreEqual("La libreria è ancora vuota", (await ui.EvalAsync("document.querySelector('main .vuoto-pagina h2').textContent")).GetString());
}
[TestMethod]
public async Task TheAccountHeaderFollowsEveryMenuAction()
{
@@ -407,7 +468,11 @@ public sealed class InterfaceTests
await ui.EvalAsync("history.back()");
await ui.WaitAsync("document.querySelector('.dialogo') !== null", "di nuovo il dialogo");
await ui.EvalAsync("[...document.querySelectorAll('.dialogo footer button')].find((b) => b.textContent === 'Lascia le modifiche').click()");
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .vuoto-pagina, main .mosaico') !== null", "Libreria");
// The Libreria drawn to its end, not its empty mosaic of the first milliseconds: this library is empty and Febe
// is not connected, so it ends on the welcome of the first start (spec §10.3).
await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)");
Assert.IsTrue((await ui.EvalAsync("document.querySelector('.dialogo') === null && document.querySelector('.cerchio-giorno') === null && document.querySelector('.salva').hidden")).GetBoolean(), "Limiti and its edits are gone");
}
[TestMethod]
+6 -1
View File
@@ -15,7 +15,11 @@ dotnet run --project tools/Febe.SitoDiProva -- [--porta 8481] [--porta-cdn 8482]
del sito non gli arrivano.
- I dati sono **sintetici** e si generano da un seme: stesso seme, stessi account, post, codici e didascalie. Le date
sono relative al momento dell'avvio (le storie sono attive per 24 ore da lì).
- Le prove automatiche lo avviano dentro il processo con `TestSite.StartAsync(...)` (porte libere scelte da sole).
- Le prove automatiche lo avviano dentro il processo con `SyntheticSite.StartAsync()` (`tests/Febe.Tests/Support`), che
chiama `TestSite.StartAsync(...)` con porte libere scelte da sole e il seme della variabile `FEBE_SEME_PROVA` (13 se
manca). La CI fa girare tutte le prove con il seme 13 e quelle della categoria `SitoDiProva` anche con un seme
diverso a ogni esecuzione, scritto nel registro; per rifare una prova fallita con quel seme:
`FEBE_SEME_PROVA=<seme> dotnet test tests/Febe.Tests --filter "TestCategory=SitoDiProva"`.
- Campioni grezzi per le prove dei lettori: `dotnet run --project tools/Febe.SitoDiProva -- campioni --cartella <fuori dal repository>`
(poi `febe-sonda ripulisci`, vedi `tests/Febe.Tests/campioni/prova/LEGGIMI.md`).
@@ -49,6 +53,7 @@ storie attive di Marta è anche nella raccolta «Estate», con lo **stesso ident
| `/post/{codice}/` | pagina di un post, con tutti i file |
| `/verifica` | pagina di verifica, semplice testo |
| `/sessione-scaduta` | pagina di sessione terminata, semplice testo (non è un modulo di accesso) |
| `/benvenuto` | quella che Febe apre come «pagina di accesso» del sito di prova (Collegamento): semplice testo, nessun modulo; la visita apre la sessione, come ogni pagina |
La mappa dei bersagli di queste pagine è `src/Febe.Core/Config/bersagli.prova.json` (copiata accanto al programma
in `config/`), i segnali di arresto sono in `segnali.prova.json`.
+7
View File
@@ -76,6 +76,13 @@ internal static class Pages
public static string NotFound() => Layout("Pagina non trovata", "nessuna", string.Empty, "<h1>Pagina non trovata</h1>");
/// <summary>What Febe opens as the login page of the test site: there is nothing to type, the visit opens the session.</summary>
public static string Welcome() => Layout("Benvenuto", "nessuna", string.Empty, """
<h1>Benvenuto nel sito di prova</h1>
<p>Qui non c'è nessuna password: il sito di prova ti considera entrato appena apri una sua pagina. Torna a Febe e
premi «Ho finito».</p>
""");
private static string Layout(string title, string page, string attributes, string main) => $"""
<!doctype html>
<html lang="it">
+4
View File
@@ -215,6 +215,10 @@ public sealed class TestSite : IAsyncDisposable
case []:
html = Pages.Home();
break;
case ["benvenuto"]:
// The «pagina di accesso» Febe opens on the test site (LoginUrl): the cookie above already opened the session.
html = Pages.Welcome();
break;
case ["profilo", var user, ..] when World.FindByUsername(user) is null:
html = Pages.ProfileNotFound(user);
status = 404;