diff --git a/CHANGELOG.md b/CHANGELOG.md index 356393f..e5f6a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Sviluppo e qualità: +- Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le + rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche + con Chrome rallentato 20 volte. - **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 diff --git a/docs/decisioni.md b/docs/decisioni.md index 8412530..000ae3d 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -279,6 +279,11 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | Nelle prove dell'interfaccia una risposta è in ritardo perché la prova la trattiene, mai per un tempo fisso. `UiBrowser.Requests` (al posto di `FetchDelays`) trattiene le richieste scelte finché la prova non le rilascia (`__hold`, `__release`: il rilascio chiude la regola, così lo stesso indirizzo si può trattenere di nuovo, e trattenerlo due volte insieme è un errore), conta quelle partite (`__started`) e quelle finite (`__done`: dopo la continuazione della pagina e, se lo legge, dopo il corpo della risposta) e registra ogni richiesta della pagina (`__asked`). La prova aspetta che la pagina abbia chiesto, fa ciò che deve venire prima (lasciare la pagina, cambiare filtro), rilascia e controlla quando la pagina ne ha finito | Issue #8: `APageLeftWhileLoadingLeavesNothingBehind` tornava alla Libreria 200 ms dopo `navigate('/attivita')`. Su una macchina lenta Attività non aveva ancora caricato `activity.js` e `day-strip.js`: la pagina era lasciata prima di montarsi, `/api/alerts` non partiva mai e l'attesa scadeva dopo 30 s. Con Chrome rallentato 20 volte (`Emulation.setCPUThrottlingRate`, solo in locale) falliva 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4 giri su 5 i due moduli arrivavano dopo il ritorno alla Libreria (fra 212 e 549 ms). `ABrowserPageLeftWhileLoadingNeverTakesTheBrowser` aveva una finestra di 150 ms, e la sua regola di 600 ms tratteneva anche un `begin` mandato per errore, che arrivava al server dopo il controllo: con la pagina Browser rotta apposta la prova passava. Una regola rilasciata restava e valeva per prima: un secondo `__hold` dello stesso indirizzo lasciava passare subito la richiesta, e la prova avrebbe lasciato la pagina a risposta già arrivata (rilievo della revisione) | +| 2026-10-21 | Che dopo «Ho finito», dopo «Riprendi» o lasciando una pagina il browser non sia preso né restituito un'altra volta, le prove lo controllano quando la pagina è quieta (`WaitForQuietAsync`: nessuna richiesta in volo, quindi ogni comando è arrivato al server e la pagina ha finito il seguito di ogni risposta, comprese le richieste che fa partire lì; non aspetta ciò che la pagina rimanda, come le richieste di un osservatore, di un fotogramma, di un timer, del flusso degli eventi o di un modulo che si carica dopo, e qui basta perché il comando sbagliato partirebbe lasciando la pagina o nel seguito di una risposta) sull'elenco delle richieste della pagina (`__asked`) e su quelle viste dal server; non dopo una pausa di 300 o 500 ms. La vista chiusa sul server si aspetta | Con la pausa una macchina lenta poteva controllare prima che il comando sbagliato arrivasse, e la prova passava lo stesso; dopo «Riprendi» la vista chiusa si controllava dopo 300 ms, e lì una macchina lenta faceva fallire la prova. Con copie dell'interfaccia rotte apposta (un «cancel» dopo «Ho finito» nelle pagine Browser e Collegamento, un «begin» dopo «Riprendi», un «begin» che parte solo dopo una risposta del motore) le quattro prove falliscono in ogni giro provato, anche con Chrome rallentato 20 volte. La quiete non copre ciò che parte più tardi (rilievo della revisione): sulla Libreria con 40 elementi, al primo momento senza richieste in volo le 11 righe del mosaico, chieste da un IntersectionObserver dopo il disegno dei giorni, non erano ancora partite in 3 giri su 6 | +| 2026-10-21 | La prova dei tasti della vista remota li manda quando il WebSocket della pagina è aperto (`__sockets` di `UiBrowser.Requests`), non 300 ms dopo che il server ha aperto la vista; la prova del mouse scrive meta e fotogramma senza pausa | Il server apre la vista prima di rispondere al socket (`RemoteViewSocket.HandleAsync`) e la pagina scarta i messaggi finché il socket non è aperto: su una macchina più lenta di 300 ms i tasti andavano persi e la prova falliva dopo 30 s. Ciò che il server scrive resta nella vista finché il socket non è aperto e la pagina ascolta da subito, quindi la pausa del mouse non serviva: il primo fotogramma sullo schermo dice già che il socket è aperto | +| 2026-10-21 | I ridisegni rimandati di una pagina (`later`: 150 ms in «In evidenza») le prove li aspettano come timer: `PageTimers` dice quali timeout erano in sospeso in un dato momento e quando sono finiti; dopo un cambio di dimensione si aspetta un ResizeObserver della prova, chiamato dopo quelli della pagina, e i timer che quelli hanno lasciato. Il trascinamento della maniglia della fascia aspetta ogni passo nel campo dell'ora prima del successivo; l'intestazione dell'account non ha più una pausa fra un'azione e l'altra | Con pause di 500 e 600 ms il ridisegno sbagliato poteva arrivare dopo il controllo. Con 60 ms fra un passo e l'altro una macchina lenta può consegnare più passi come un solo movimento: la prova vedeva solo l'ultimo e non provava più che la maniglia segua tutto il trascinamento. La pausa dell'intestazione non proteggeva nulla: ogni giro aspetta già il menu ridisegnato. Con copie rotte apposta (ridisegno non annullato, osservatore non staccato, tessere tardive disegnate, trascinamento che finisce al primo passo) le prove falliscono in ogni giro provato, anche a 20x; il ridisegno non annullato si vede quando è ancora in sospeso al cambio di filtro, come prima (in tutti i giri provati lo era) | +| 2026-10-21 | `APageLeftWhileLoadingLeavesNothingBehind` controlla che Attività, lasciata mentre carica, non lasci né il timer di un minuto, né l'ascolto della libreria, né avvisi sulla Libreria; e che, aperta, a una modifica della libreria si ricarichi. La modifica la prova la manda alla pagina come la manda il flusso degli eventi (un evento «libreria» sul suo `EventSource`, che chiama subito chi ascolta) e ne ha conferma quando la Libreria richiede i suoi giorni; gli avvisi li registra un MutationObserver, anche quelli già spariti | Rilievo della revisione: il controllo «niente di Attività sulla Libreria» guardava solo `main`, dove Attività non disegna (la sua cornice ne esce prima ancora che il modulo si carichi), e poteva fallire solo per un nodo messo lì direttamente. Con copie rotte apposta la prova di prima passava con l'ascolto della libreria rimasto e con l'errore delle richieste annullate mostrato sulla Libreria; ora le trova entrambe, a velocità normale e con Chrome rallentato 20 volte. Una modifica pubblicata sul server non darebbe lo stesso ordine: il flusso si iscrive alle modifiche in un `Task.Run`, senza dire quando, e le raccoglie per 300 ms | | 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-` 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-` (`internal/app/run/runner.go`); act chiama il contenitore `_WORKFLOW-_JOB-` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-`), i volumi `` e `-env`, la rete `--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-` 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 | diff --git a/docs/stato.md b/docs/stato.md index 74686f3..ce40c09 100644 --- a/docs/stato.md +++ b/docs/stato.md @@ -1,10 +1,22 @@ # Stato Filo fra le sessioni (specifica §15): che cosa è fatto, che cosa è in corso, che cosa è rimandato e perché. -Aggiornato il 20 ottobre 2026, versione 0.1.1 (anteprima). +Aggiornato il 21 ottobre 2026, versione 0.1.1 (anteprima). ## In breve +**21 ottobre 2026.** + +- **0.1.1 rilasciata**: tag `v0.1.1`, release con installatore, zip portabile, modello Unraid e archivio per Compose. + L'immagine Docker non è pubblicata, perché `REGISTRY_TOKEN` manca ancora. +- **La pulizia della CI toglie tutto ciò che non serve più** (decisione di Alberto). Dopo ogni lavoro «immagine» se ne + vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore: la prima volta 26,31 GB. Ogni + lunedì se ne vanno le immagini che nessun contenitore usa, la cache vecchia, i resti di act_runner e le `:sha-` oltre + le 10 più recenti. Mai contenitori, volumi o reti che non siano della CI. A mano c'è «Solo prova» (`docs/processo.md`, + «Pulizia»). +- Le tre prove d'interfaccia trovate instabili dalla CI con Chromium vero sono stabili (#3 e #5 il 20/10, #8 il 21/10). + Le prove d'interfaccia non usano più pause a tempo fisso. + **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: @@ -16,8 +28,8 @@ Windows vero: collegamento, account e sessioni contro il sito di prova, dall'int - 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. +Il lavoro è su sei rami, ciascuno con la sua revisione avversaria, unito in `main` con la PR #2 (CI), la PR +d'integrazione #4, la #6 e la #7 (rilascio 0.1.1). Il 21/10 sono seguite la #9 (pulizia) e la #10 (prove d'interfaccia). 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. @@ -63,11 +75,22 @@ protezione di `main` sono in `docs/processo.md`. 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: 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. + l'immagine, ma non la pubblicano (lo dicono con un avviso), e la pulizia non tocca il registro. Il 21/10 mancava + ancora. Aggiunto il segreto, si rilancia il flusso del tag `v0.1.1`: l'immagine esce e le note della release si + correggono. 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. +7. **Pulizia**: leggere l'elenco della prova del 21/10 (Actions ▸ pulizia, esecuzione #28, «Solo prova») prima della + prima pulizia vera, lunedì 26/10 alle 4:17. Attenzione soprattutto allo store delle immagini scritto all'inizio e + alle righe «toglierei il nome …» delle immagini in uso con più nomi (app di Unraid). +8. Da decidere: + - dopo ogni esecuzione la cache di costruzione si toglie solo se nessuno la usa da 24 ore (`--filter until=24h`). + Senza filtro, a ogni push se ne andrebbe anche quella appena usata dagli altri progetti; per cambiare basta togliere + il filtro in `pulizia-docker.sh penzolanti`; + - gli script di shell di `.gitea/` e `installer/` hanno i commenti in italiano, contro «codice e commenti in + inglese»: o un'eccezione in `docs/decisioni.md`, o una traduzione in un ramo a parte. ## Rilievi aperti (20 ottobre) @@ -82,6 +105,15 @@ protezione di `main` sono in `docs/processo.md`. (vuota) e quella vera arriva dopo la pausa minima, circa 20 minuti. È il comportamento della specifica, ma chi ha appena collegato Febe aspetta. +## Rilievi aperti (21 ottobre) + +- Le note della release scritte da `rilascio.yml` senza immagine dicono «`:latest` resta sulla versione precedente», ma + sul registro un'immagine precedente non c'è mai stata. Da riformulare per il caso della prima pubblicazione. +- Un solo timeout di `OpenAsync` all'apertura di `/browser` (`AfterHoFinitoLeavingTheBrowserPageChangesNothingMore`) in + migliaia di esecuzioni delle prove d'interfaccia, senza causa trovata. Se ricompare nella CI, va fatto dire a + `OpenAsync` quale condizione mancava. +- Su questo PC Febe ha avvisato «Disco quasi pieno»: libreria e dati stanno su C:, dove restano circa 12 GB. + ## Rimandato, e perché - Via `HttpClient` verso il CDN (§6.5 punto 3): dipende da H7. diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs index 2e015da..ec0db2d 100644 --- a/tests/Febe.Tests/Web/InterfaceTests.cs +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -50,6 +50,33 @@ public sealed class InterfaceTests })(); """; + /// + /// Installed before the page scripts: window.__timers() lists the timeouts of the page still pending and + /// window.__timersOver(ids) says whether those have all run or been cleared. A test waits for the timers that + /// were pending at a given moment (a debounced redraw, say) to be over, instead of a pause that may be too short. + /// + private const string PageTimers = """ + (() => { + const set = window.setTimeout.bind(window); + const clear = window.clearTimeout.bind(window); + const pending = new Set(); + window.setTimeout = (fn, ms, ...rest) => { + const id = set((...args) => { + pending.delete(id); + fn(...args); + }, ms, ...rest); + pending.add(id); + return id; + }; + window.clearTimeout = (id) => { + pending.delete(id); + clear(id); + }; + window.__timers = () => [...pending]; + window.__timersOver = (ids) => ids.every((id) => !pending.has(id)); + })(); + """; + // ------------------------------------------------------------------------------------------ the driving lease [TestMethod] @@ -94,22 +121,23 @@ public sealed class InterfaceTests var view = new FakeRemoteViewHost(); await using var server = await DockerAsync(connection, view); await using var ui = await UiBrowser.StartAsync(); - await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/libreria")); - // The status of the connection answers late; Alberto is already elsewhere. - await ui.EvalAsync(""" - import('/js/core/shell.js').then((m) => { - window.__delays.push({ match: '/api/connection', ms: 600 }); - m.navigate('/browser'); - setTimeout(() => m.navigate('/libreria'), 150); - return true; - }) - """); + // The status of the connection answers late: the Browser page asks for it, Alberto goes elsewhere, then it + // comes. In this order on any machine (issue #8: a page left after a fixed delay may not have asked yet). + await ui.EvalAsync("window.__hold('/api/connection')"); + await ui.NavigateAsync("/browser"); + await ui.WaitAsync("window.__started['/api/connection'] >= 1", "pagina Browser in attesa dello stato del collegamento"); + await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + await ui.EvalAsync("window.__release('/api/connection')"); await ui.WaitAsync("window.__done['/api/connection'] >= 1", "risposta in ritardo arrivata"); - await Task.Delay(300); - Assert.IsEmpty(connection.Snapshot(), "nothing taken by a page that is gone"); + + // What the page did with the late answer is done: whatever it asked then is in the list. + CollectionAssert.AreEqual(new[] { "GET /api/connection" }, await ui.AskedAsync("/api/connection"), "nothing taken by a page that is gone"); + Assert.IsEmpty(await ui.AskedAsync("/api/vista"), "no remote view for a page that is gone"); + Assert.IsEmpty(connection.Snapshot()); Assert.IsEmpty(view.Opened); } @@ -120,6 +148,7 @@ public sealed class InterfaceTests var view = new FakeRemoteViewHost(); await using var server = await DockerAsync(connection, view); await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/browser")); await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False"), "il browser in uso"); @@ -128,8 +157,12 @@ public sealed class InterfaceTests await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); - await Task.Delay(500); - CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "«Ho finito» already gave the browser back"); + + // A page gives the browser back as it is left (PageFrame.onLeave): a «cancel» would be asked by now, and once + // the page is quiet every command it asked has reached the server. + await ui.WaitForQuietAsync("richieste della pagina finite"); + CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back"); + CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot()); } [TestMethod] @@ -154,6 +187,7 @@ public sealed class InterfaceTests var view = new FakeRemoteViewHost(); await using var server = await DockerAsync(connection, view); await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:True") && view.Opened.Count == 1, "pagina di accesso nella vista remota"); @@ -164,7 +198,9 @@ public sealed class InterfaceTests await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); - await Task.Delay(500); + await ui.WaitForQuietAsync("richieste della pagina finite"); + CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "«Ho finito» already gave the browser back"); + CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no view opened again"); CollectionAssert.AreEqual(new[] { "begin:True", "finish" }, connection.Snapshot()); Assert.HasCount(1, view.Opened); } @@ -176,23 +212,28 @@ public sealed class InterfaceTests var view = new FakeRemoteViewHost(); await using var server = await DockerAsync(connection, view, new FixedMonitor(EngineMode.StoppedForVerification)); await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); await ui.WaitForAsync(() => connection.Snapshot().Contains("begin:False") && view.Opened.Count == 1, "verifica nella vista remota"); await ui.EvalAsync("document.querySelector('.bottoni-collegamento .btn.primo').click()"); await ui.WaitAsync("document.querySelector('.riapri-browser') !== null", "«Ho finito» fatto, in attesa di «Riprendi»"); await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa dopo «Ho finito»"); - await Task.Delay(500); - CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot(), "no new lease after «Ho finito»"); - Assert.HasCount(1, view.Opened, "no new view after «Ho finito»"); + + // «Ho finito» also asks for the engine: what its answer brings has been drawn once the page is quiet. + await ui.WaitForQuietAsync("richieste di «Ho finito» finite"); + CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "no new lease after «Ho finito»"); + CollectionAssert.AreEqual(new[] { "WS /api/vista" }, await ui.AskedAsync("WS "), "no new view after «Ho finito»"); + CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot()); + Assert.HasCount(1, view.Opened); // «Riapri il browser» takes it again; leaving the page then gives it back. await ui.EvalAsync("document.querySelector('.riapri-browser').click()"); await ui.WaitForAsync(() => connection.Snapshot().Length == 3 && view.Opened.Count == 2, "browser riaperto"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); - await ui.WaitForAsync(() => connection.Snapshot().Length == 4, "il browser restituito lasciando la pagina"); - CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot()); + await ui.WaitForQuietAsync("richieste della pagina finite"); + CollectionAssert.AreEqual(new[] { "begin:False", "finish", "begin:False", "cancel" }, connection.Snapshot(), "leaving the page gives the browser back"); await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); } @@ -204,6 +245,7 @@ public sealed class InterfaceTests var engine = new FixedMonitor(EngineMode.StoppedForVerification); await using var server = await DockerAsync(connection, view, engine); await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/impostazioni/collegamento")); await ui.WaitAsync("document.querySelector('.arresto') !== null", "striscia rossa della verifica"); @@ -216,9 +258,11 @@ public sealed class InterfaceTests connection.Status = Connected; await ui.EvalAsync("import('/js/core/engine.js').then((m) => m.refreshEngine()).then(() => true)"); await ui.WaitAsync("document.querySelector('.pannello.collegato') !== null", "collegato dopo «Riprendi»"); - await Task.Delay(300); + await ui.WaitForQuietAsync("richieste dopo «Riprendi» finite"); + CollectionAssert.AreEqual(new[] { "POST /api/connection/begin", "POST /api/connection/finish" }, await ui.AskedAsync("POST /api/connection/"), "the browser is not taken again"); CollectionAssert.AreEqual(new[] { "begin:False", "finish" }, connection.Snapshot()); - Assert.IsTrue(view.Opened.All(v => v.Disposed)); + await ui.WaitForAsync(() => view.Opened.All(v => v.Disposed), "vista remota chiusa"); + Assert.HasCount(1, view.Opened); } // ------------------------------------------------------------------------------------------ remote view input @@ -230,10 +274,13 @@ public sealed class InterfaceTests var view = new FakeRemoteViewHost(); await using var server = await DockerAsync(connection, view); await using var ui = await UiBrowser.StartAsync(); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/browser")); await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta"); await ui.WaitAsync("document.querySelector('canvas.vista-schermo') !== null", "schermo della vista"); - await Task.Delay(300); + + // The view sends keys only once its socket is open (the server opens the view before it answers the socket). + await ui.WaitAsync("window.__sockets.some((s) => s.url.endsWith('/api/vista') && s.readyState === WebSocket.OPEN)", "vista collegata"); // Italian layout on Windows: AltGr+ò is «@», reported as Ctrl+Alt with the AltGraph modifier. Assert.IsTrue((await ui.EvalAsync("new KeyboardEvent('keydown', { key: '@', modifierAltGraph: true }).getModifierState('AltGraph')")).GetBoolean()); @@ -270,7 +317,9 @@ public sealed class InterfaceTests await ui.OpenAsync(new Uri(server.Address, "/browser")); await ui.WaitForAsync(() => view.Opened.Count == 1, "vista aperta"); var remote = view.Opened.Single(); - await Task.Delay(300); + + // What the view writes waits in it until the socket is open, and the page listens from the start; the first + // frame on the screen says that the socket is open, so the buttons can go. remote.Write(new RemoteViewMeta(320, 225, "https://www.instagram.com/")); remote.Write(new RemoteViewFrame(TestFile.PhotoBytes(3, 320, 225))); await ui.WaitAsync("!document.querySelector('canvas.vista-schermo').hidden", "primo fotogramma"); @@ -302,31 +351,64 @@ public sealed class InterfaceTests } await using var ui = await UiBrowser.StartAsync(); - await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(UiBrowser.Requests); + await ui.AddInitScriptAsync(PageTimers); await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza")); await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza"); - // «Post» after «In evidenza»: the posts stay, also when the area changes size. - await ui.EvalAsync("document.querySelectorAll('.strumenti .filtri button')[0].click()"); - await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); - await Task.Delay(500); - await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false }); - await Task.Delay(600); - await AssertPostsShownAsync(ui); - - // «In evidenza» and at once «Post», while the tiles of the collections are still loading. + // «Post» after «In evidenza»: the posts stay, also once what «In evidenza» left pending has run (it redraws + // itself 150 ms after a change of size, and it has just been drawn). await ui.EvalAsync(""" (() => { - window.__delays.push({ match: '/api/library/tiles', ms: 600 }); + window.__pendingAtSwitch = window.__timers(); + document.querySelectorAll('.strumenti .filtri button')[0].click(); + return true; + })() + """); + await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); + await ui.WaitAsync("window.__timersOver(window.__pendingAtSwitch)", "attese di «In evidenza» finite"); + await AssertPostsShownAsync(ui); + + // The area changes size. The page's own observers see it before this one, which came last: what they left + // pending then (a redraw, a frame) runs, and the posts are still there. + await ui.EvalAsync(""" + (() => { + let before = null; + window.__afterResize = null; + new ResizeObserver((entries, observer) => { + const width = entries[0].contentRect.width; + if (before === null) { + before = width; + return; + } + if (Math.abs(width - before) < 1) return; + observer.disconnect(); + const pending = window.__timers(); + requestAnimationFrame(() => { window.__afterResize = pending; }); + }).observe(document.querySelector('main .corpo > div')); + window.__resizeWatched = () => before !== null; + return true; + })() + """); + await ui.WaitAsync("window.__resizeWatched()", "dimensione dei contenuti osservata"); + await ui.SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject { ["width"] = 1100, ["height"] = 900, ["deviceScaleFactor"] = 1, ["mobile"] = false }); + await ui.WaitAsync("window.__afterResize !== null && window.__timersOver(window.__afterResize)", "contenuti ridisegnati alla nuova larghezza"); + await AssertPostsShownAsync(ui); + + // «In evidenza» and at once «Post», while the tiles of the collections are still loading: they come after the + // posts are drawn. + await ui.EvalAsync(""" + (() => { + window.__hold('/api/library/tiles'); const chips = document.querySelectorAll('.strumenti .filtri button'); chips[2].click(); chips[0].click(); return true; })() """); + await ui.WaitAsync("window.__started['/api/library/tiles'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); + await ui.EvalAsync("window.__release('/api/library/tiles')"); await ui.WaitAsync("window.__done['/api/library/tiles'] >= 1", "tessere delle raccolte arrivate in ritardo"); - await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno') !== null", "mosaico dei post"); - await Task.Delay(400); await AssertPostsShownAsync(ui); } @@ -336,23 +418,23 @@ public sealed class InterfaceTests await using var server = await WebTestServer.StartAsync(); await server.AddAccountWithEntriesAsync("anna.prova", 5, Make.T0, TimeSpan.FromHours(30)); await using var ui = await UiBrowser.StartAsync(); - await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, "/libreria")); await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "mosaico"); - // «Storie» (nothing: an empty answer, late) and at once «Foto». + // «Storie» (nothing: an empty answer, late) and at once «Foto»: the stories answer after the photos are drawn. await ui.EvalAsync(""" (() => { - window.__delays.push({ match: 'kind=stories', ms: 700 }); + window.__hold('kind=stories'); const chips = document.querySelectorAll('.strumenti .filtri button'); chips[3].click(); chips[1].click(); return true; })() """); - await ui.WaitAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto"); + await ui.WaitAsync("window.__started['kind=stories'] >= 1 && document.querySelector('main .mosaico .gruppo-giorno .tess') !== null", "foto"); + await ui.EvalAsync("window.__release('kind=stories')"); await ui.WaitAsync("window.__done['kind=stories'] >= 1", "risposta delle storie arrivata in ritardo"); - await Task.Delay(300); Assert.IsTrue((await ui.EvalAsync("location.search.includes('tipo=foto')")).GetBoolean()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .mosaico .gruppo-giorno .tess') !== null")).GetBoolean(), "the photos are shown " + ui.Report()); Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .vuoto-pagina') === null")).GetBoolean(), "no empty state over the results"); @@ -441,7 +523,6 @@ public sealed class InterfaceTests })() """, $"intestazione aggiornata dopo «{choice}»"); - await Task.Delay(200); } } @@ -480,7 +561,7 @@ public sealed class InterfaceTests { await using var server = await WebTestServer.StartAsync(); await using var ui = await UiBrowser.StartAsync(); - await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.AddInitScriptAsync(""" (() => { const live = new Map(); @@ -489,25 +570,62 @@ public sealed class InterfaceTests window.setInterval = (fn, ms, ...rest) => { const id = set(fn, ms, ...rest); live.set(id, ms); return id; }; window.clearInterval = (id) => { live.delete(id); clear(id); }; window.__intervals = (ms) => [...live.values()].filter((v) => v === ms).length; + // Every short notice shown, also one already gone again. + window.__notices = []; + new MutationObserver((records) => { + for (const record of records) { + for (const node of record.addedNodes) { + if (node.nodeType === 1 && node.matches('.brevi > *')) window.__notices.push(node.textContent); + } + } + }).observe(document, { childList: true, subtree: true }); + // A change of the library as the event stream brings it: every page that listens is called before this + // returns (the number of streams). + const NativeSource = window.EventSource; + const streams = []; + window.EventSource = class extends NativeSource { + constructor(...args) { + super(...args); + streams.push(this); + } + }; + window.__libraryChanged = () => { + for (const stream of streams) stream.dispatchEvent(new MessageEvent('libreria', { data: '{}' })); + return streams.length; + }; })(); """); await ui.OpenAsync(new Uri(server.Address, "/libreria")); - await ui.EvalAsync(""" - import('/js/core/shell.js').then((m) => { - window.__delays.push({ match: '/api/alerts', ms: 600 }); - m.navigate('/attivita'); - setTimeout(() => m.navigate('/libreria'), 200); - return true; - }) - """); - await ui.WaitAsync("location.pathname === '/libreria'", "Libreria"); + + // Attività waits for its alerts and Alberto goes back to the Libreria before they come. Issue #8: going back + // after a fixed 200 ms, a slow machine had not even loaded the page yet, and the alerts were never asked. + await ui.EvalAsync("window.__hold('/api/alerts')"); + await ui.NavigateAsync("/attivita"); + await ui.WaitAsync("window.__started['/api/alerts'] >= 1", "Attività in attesa dei suoi avvisi"); + await ui.NavigateAsync("/libreria"); + await ui.WaitAsync("location.pathname === '/libreria' && document.querySelector('main .benvenuto') !== null", "Libreria (primo avvio)"); + await ui.EvalAsync("window.__release('/api/alerts')"); await ui.WaitAsync("window.__done['/api/alerts'] >= 1", "risposta in ritardo arrivata"); - await Task.Delay(300); Assert.AreEqual(0, (await ui.EvalAsync("window.__intervals(60000)")).GetInt32(), "the minute timer of Attività is gone with its page"); - // The page that stays open still works as usual. + // Nothing of it is shown over the Libreria: what it draws went with its frame, so only a short notice, or a + // node put straight into the page area, could show. + var notices = await ui.EvalAsync("window.__notices"); + Assert.IsEmpty(notices, "no notice of Attività over the Libreria: " + string.Join(" | ", notices)); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .attivita') === null && document.querySelector('main .benvenuto') !== null")).GetBoolean(), "nothing of Attività in the page area " + ui.Report()); + + // Nor does it still listen to the library: a change reaches the Libreria, which asks for its days again, and + // Attività asks for nothing more than when it was opened. + var days = (await ui.AskedAsync("GET /api/library/days")).Length; + Assert.AreEqual(1, (await ui.EvalAsync("window.__libraryChanged()")).GetInt32(), "the event stream of the interface"); + await ui.WaitAsync($"window.__asked.filter((r) => r.includes('GET /api/library/days')).length > {days}", "Libreria aggiornata dopo la modifica"); + CollectionAssert.AreEqual(new[] { "GET /api/alerts" }, await ui.AskedAsync("/api/alerts"), "Attività, left, no longer listens to the library"); + + // The page that stays open still works as usual: its minute timer runs, and a change of the library reloads it. await ui.NavigateAsync("/attivita"); await ui.WaitAsync("window.__intervals(60000) === 1", "Attività aperta"); + await ui.EvalAsync("window.__libraryChanged()"); + await ui.WaitAsync("window.__asked.filter((r) => r.includes('/api/alerts')).length >= 3", "Attività aggiornata dopo la modifica"); await ui.NavigateAsync("/libreria"); await ui.WaitAsync("window.__intervals(60000) === 0", "Attività lasciata"); } @@ -524,19 +642,27 @@ public sealed class InterfaceTests var handle = await ui.EvalAsync("(() => { const r = document.querySelector('.fascia-barra .maniglia').getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })()"); var (handleX, handleY) = (handle[0].GetDouble(), handle[1].GetDouble()); var left = barX - (barWidth / 2); + string TimeAt(double at) + { + var minutes = (int)(Math.Round((at - left) / barWidth * 1440 / 15) * 15); + return $"{minutes / 60:00}:{minutes % 60:00}"; + } + await ui.MouseAsync("mouseMoved", handleX, handleY); await ui.MouseAsync("mousePressed", handleX, handleY, buttons: 1); var x = handleX; foreach (var ratio in new[] { 0.30, 0.34, 0.38, 0.42, 0.46 }) { + // Each step is followed before the next one moves: a handle drawn again would lose the drag after the + // first step, and steps sent together may reach the page as one move. x = left + (barWidth * ratio); await ui.MouseAsync("mouseMoved", x, barY, buttons: 1); - await Task.Delay(60); + var step = TimeAt(x); + await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{step}'", $"inizio della fascia a {step} durante il trascinamento"); } await ui.MouseAsync("mouseReleased", x, barY); - var minutes = (int)(Math.Round((x - left) / barWidth * 1440 / 15) * 15); - var expected = $"{minutes / 60:00}:{minutes % 60:00}"; + var expected = TimeAt(x); await ui.WaitAsync($"document.querySelector('#fascia-inizio').value === '{expected}'", $"inizio della fascia a {expected}"); } diff --git a/tests/Febe.Tests/Web/Support/UiBrowser.cs b/tests/Febe.Tests/Web/Support/UiBrowser.cs index 18372db..3d647d8 100644 --- a/tests/Febe.Tests/Web/Support/UiBrowser.cs +++ b/tests/Febe.Tests/Web/Support/UiBrowser.cs @@ -16,25 +16,93 @@ namespace Febe.Tests.Web.Support; internal sealed class UiBrowser : IAsyncDisposable { /// - /// Installed before the page scripts: window.__delays holds { match, ms } rules that hold back a matching - /// fetch, so that a test can make one answer arrive late (stale answers, slow pages); window.__done[match] - /// counts the held-back requests that are over (answered, failed or aborted). + /// Installed before the page scripts: what the page asks of the server, and answers that come when the test says. + /// + /// window.__asked: every request the page started, in order («GET /api/connection», «POST + /// /api/connection/begin», «WS /api/vista»); window.__sockets: its WebSockets. + /// window.__busy(): the requests not over yet. A fetch is over once the page's own continuation of + /// its answer has run, and the body it reads there (as api.js does) has arrived; a WebSocket once it is open or + /// closed. See . + /// window.__hold(match) holds back every fetch whose address contains match, from then until + /// window.__release(match), also one the page aborts meanwhile. The release lets them go and ends the hold: + /// later requests pass at once, and the address can be held again (twice at the same time is an error). + /// window.__started[match] counts the held-back requests that started and window.__done[match] + /// those that are over, adding up all the holds of that address. + /// + /// An answer is late because the test holds it, never because of a delay the page might outlast on a slow machine: + /// the test waits until the page has asked (__started), does what has to come first, releases it, and + /// checks once the page is done with it (__done). /// - public const string FetchDelays = """ + public const string Requests = """ (() => { - const original = window.fetch.bind(window); - window.__delays = []; + const fetchNow = window.fetch.bind(window); + const later = window.setTimeout.bind(window); + const NativeSocket = window.WebSocket; + const holds = []; + let busy = 0; + const count = (counts, key) => { counts[key] = (counts[key] || 0) + 1; }; + const pathOf = (url) => { const u = new URL(url, location.href); return u.pathname + u.search; }; + window.__asked = []; + window.__sockets = []; + window.__started = {}; window.__done = {}; + window.__busy = () => busy; + window.__hold = (match) => { + if (holds.some((h) => h.match === match)) throw new Error(`richieste già trattenute per ${match}`); + let release; + holds.push({ match, gate: new Promise((resolve) => { release = resolve; }), release: () => release() }); + return true; + }; + // The requests held so far keep their hold and count as over under its match; the next ones pass. + window.__release = (match) => { + const index = holds.findIndex((h) => h.match === match); + if (index < 0) throw new Error(`nessuna richiesta trattenuta per ${match}`); + holds.splice(index, 1)[0].release(); + return true; + }; window.fetch = async (input, init) => { - const url = typeof input === 'string' ? input : input.url; - const rule = window.__delays.find((d) => url.includes(d.match)); - if (!rule) return original(input, init); + const url = input instanceof Request ? input.url : String(input); + const method = ((init && init.method) || (input instanceof Request ? input.method : 'GET')).toUpperCase(); + const hold = holds.find((h) => url.includes(h.match)); + window.__asked.push(`${method} ${pathOf(url)}`); + if (hold) count(window.__started, hold.match); + busy += 1; + let read = Promise.resolve(); try { - await new Promise((resolve) => setTimeout(resolve, rule.ms)); - return await original(input, init); + if (hold) await hold.gate; + const response = await fetchNow(input, init); + for (const name of ['json', 'text', 'blob', 'arrayBuffer']) { + const body = response[name].bind(response); + response[name] = () => { + const reading = body(); + read = reading.then(() => {}, () => {}); + return reading; + }; + } + return response; } finally { - // After the page's own continuation of this answer has run. - setTimeout(() => { window.__done[rule.match] = (window.__done[rule.match] || 0) + 1; }, 50); + // The page's continuation of this answer runs before the first timer and, if it reads the body, the + // continuation of that read runs before the second. + later(() => read.then(() => later(() => { + busy -= 1; + if (hold) count(window.__done, hold.match); + }))); + } + }; + window.WebSocket = class extends NativeSocket { + constructor(...args) { + super(...args); + window.__asked.push(`WS ${pathOf(this.url)}`); + window.__sockets.push(this); + busy += 1; + let connecting = true; + const over = () => { + if (!connecting) return; + connecting = false; + busy -= 1; + }; + this.addEventListener('open', over); + this.addEventListener('close', over); } }; })(); @@ -247,6 +315,21 @@ internal sealed class UiBrowser : IAsyncDisposable public Task AddInitScriptAsync(string source) => SendAsync("Page.addScriptToEvaluateOnNewDocument", new JsonObject { ["source"] = source }); + /// + /// Waits until no request of the page is in flight (): every request it started has reached + /// the server and been answered, and the page's continuation of each answer has run, a request it started there + /// included (that one starts before the answer it follows is over). What the page leaves for later is not waited + /// for: a request started by an observer, an animation frame, a timer, a message of the event stream or a module + /// still loading may come after (the mosaic asks for its rows from an observer, once it has drawn its days). The + /// moment to check that a command the page would send as it is left, or in the continuation of an answer, was not + /// sent, instead of a pause a slow machine may not wait out; for one started later, wait for that request itself. + /// + public Task WaitForQuietAsync(string what) => WaitAsync("window.__busy() === 0", what); + + /// The requests the page started so far () whose «METHOD path» contains the text. + public Task AskedAsync(string match) => + EvalAsync($"window.__asked.filter((r) => r.includes({JsonSerializer.Serialize(match)}))"); + /// Loads an address of the interface and waits until the frame and the first page are drawn. public async Task OpenAsync(Uri address) {