From 248e9f74ce14d92ae9e4a934b4fc79cd96f9bfc3 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 21 Oct 2026 10:42:17 +0200 Subject: [PATCH] Prove dell'interfaccia: la risposta in ritardo si trattiene (issue #8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit APageLeftWhileLoadingLeavesNothingBehind apriva Attività e tornava alla Libreria con un setTimeout di 200 ms, poi aspettava la risposta in ritardo di /api/alerts. Su una macchina lenta, a 200 ms Attività non aveva ancora caricato activity.js e day-strip.js: la pagina veniva lasciata prima di montarsi, /api/alerts non partiva mai e l'attesa scadeva dopo 30 s, come nell'esecuzione 22 della CI. Con Chrome rallentato 20 volte (Emulation.setCPUThrottlingRate, solo in locale) fallisce 3 volte su 3 con lo stesso messaggio e la stessa riga, e in 4 giri su 5 i due moduli arrivano dopo il ritorno alla Libreria (fra 212 e 549 ms). ABrowserPageLeftWhileLoadingNeverTakesTheBrowser aveva la stessa finestra, di 150 ms, e a 20x falliva anche lei. Il prodotto non c'entra. UiBrowser.Requests prende il posto di FetchDelays: trattiene le richieste scelte finché la prova non le rilascia, conta quelle partite e quelle finite (dopo la continuazione della pagina e, se lo legge, dopo il corpo della risposta) e registra ogni richiesta della pagina. Le due prove aspettano che la pagina abbia chiesto la risposta, la lasciano, la rilasciano e controllano quando la pagina ne ha finito: nessun timer rimasto, niente di Attività sulla Libreria, nessun browser preso né vista aperta. Allo stesso modo la risposta vecchia della Libreria e le tessere in ritardo di «In evidenza» arrivano sempre dopo il disegno nuovo, invece che dopo 600 o 700 ms. Co-Authored-By: Claude Opus 5.5 --- docs/decisioni.md | 1 + tests/Febe.Tests/Web/InterfaceTests.cs | 68 ++++++++------- tests/Febe.Tests/Web/Support/UiBrowser.cs | 101 +++++++++++++++++++--- 3 files changed, 124 insertions(+), 46 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index fc591f2..689bd51 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -279,3 +279,4 @@ 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`), 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 | diff --git a/tests/Febe.Tests/Web/InterfaceTests.cs b/tests/Febe.Tests/Web/InterfaceTests.cs index 2e015da..1c1c262 100644 --- a/tests/Febe.Tests/Web/InterfaceTests.cs +++ b/tests/Febe.Tests/Web/InterfaceTests.cs @@ -94,22 +94,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); } @@ -302,7 +303,7 @@ public sealed class InterfaceTests } await using var ui = await UiBrowser.StartAsync(); - await ui.AddInitScriptAsync(UiBrowser.FetchDelays); + await ui.AddInitScriptAsync(UiBrowser.Requests); await ui.OpenAsync(new Uri(server.Address, $"/account/{account.Id}?tipo=evidenza")); await ui.WaitAsync("document.querySelector('main .raccolta-titolo') !== null", "raccolte in evidenza"); @@ -314,19 +315,20 @@ public sealed class InterfaceTests await Task.Delay(600); await AssertPostsShownAsync(ui); - // «In evidenza» and at once «Post», while the tiles of the collections are still loading. + // «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.__delays.push({ match: '/api/library/tiles', ms: 600 }); + 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 +338,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"); @@ -480,7 +482,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(); @@ -492,18 +494,18 @@ public sealed class InterfaceTests })(); """); 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"); + Assert.IsTrue((await ui.EvalAsync("document.querySelector('main .attivita') === null && document.querySelector('main .benvenuto') !== null")).GetBoolean(), "nothing of Attività drawn over the Libreria " + ui.Report()); // The page that stays open still works as usual. await ui.NavigateAsync("/attivita"); diff --git a/tests/Febe.Tests/Web/Support/UiBrowser.cs b/tests/Febe.Tests/Web/Support/UiBrowser.cs index 18372db..3feb952 100644 --- a/tests/Febe.Tests/Web/Support/UiBrowser.cs +++ b/tests/Febe.Tests/Web/Support/UiBrowser.cs @@ -16,25 +16,89 @@ 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 until + /// window.__release(match), also one the page aborts meanwhile; window.__started[match] counts the + /// held-back requests that started, window.__done[match] those that are over. + /// + /// 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) => { + let release; + holds.push({ match, gate: new Promise((resolve) => { release = resolve; }), release: () => release() }); + return true; + }; + window.__release = (match) => { + const hold = holds.find((h) => h.match === match); + if (!hold) throw new Error(`nessuna richiesta trattenuta per ${match}`); + hold.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 +311,17 @@ 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 command it sent has reached the + /// server and been answered, and whatever the page did with the answers, a new request included, has been done. The + /// moment to check that something did not happen, instead of a pause a slow machine may not wait out. + /// + 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) {