From 7aaa93fe3b7505485aeb5ec713730ecb02d5b0a5 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 20 Oct 2026 11:27:22 +0200 Subject: [PATCH] Browser di Febe per Windows: all'uscita l'avvio non resta appeso a WebView2 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/decisioni.md | 1 + src/Febe.Desktop/Browser/WebView2Browser.cs | 17 ++++-- src/Febe.Desktop/Browser/WebView2Host.cs | 40 ++++++++++++-- .../WebView2LifecycleTests.cs | 54 +++++++++++++++++++ 4 files changed, 106 insertions(+), 6 deletions(-) diff --git a/docs/decisioni.md b/docs/decisioni.md index e1b0270..d2301f8 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -235,3 +235,4 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | diff --git a/src/Febe.Desktop/Browser/WebView2Browser.cs b/src/Febe.Desktop/Browser/WebView2Browser.cs index 14e1631..36c8405 100644 --- a/src/Febe.Desktop/Browser/WebView2Browser.cs +++ b/src/Febe.Desktop/Browser/WebView2Browser.cs @@ -25,6 +25,9 @@ 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)]; + /// How long stopping waits for the restart loop to end before closing WebView2 anyway. + private static readonly TimeSpan StopWait = TimeSpan.FromSeconds(30); + private readonly WebView2BrowserSettings _settings; private readonly FebePlatformContext _context; private readonly IClock _wallClock; @@ -133,8 +136,9 @@ internal sealed class WebView2Browser : IFebeBrowser } /// - /// Stops the retries, waits for a restart in progress, then closes WebView2 and its window. _lifetime stays - /// undisposed on purpose: a late caller may still read its (cancelled) token. + /// Stops the retries, waits for the restart loop to notice (it stops waiting for WebView2 as soon as + /// _lifetime is cancelled; at most in any case), then closes WebView2 and its window. + /// _lifetime stays undisposed on purpose: a late caller may still read its (cancelled) token. /// public async ValueTask DisposeAsync() { @@ -147,7 +151,14 @@ internal sealed class WebView2Browser : IFebeBrowser if (restarting is not null) { - await restarting.ConfigureAwait(false); + 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); diff --git a/src/Febe.Desktop/Browser/WebView2Host.cs b/src/Febe.Desktop/Browser/WebView2Host.cs index 3cdffad..51db2fc 100644 --- a/src/Febe.Desktop/Browser/WebView2Host.cs +++ b/src/Febe.Desktop/Browser/WebView2Host.cs @@ -123,13 +123,20 @@ internal sealed class WebView2Host : IBrowserHost /// /// 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. + /// and the start counts as done. A failed start leaves nothing open. When 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. /// public Task StartAsync(BrowserOptions options, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); _options = options; - return OnUiAsync(() => ExclusiveAsync(StartCoreAsync)); + var start = OnUiAsync(() => ExclusiveAsync(() => + { + ct.ThrowIfCancellationRequested(); + return StartCoreAsync(); + })); + return UntilCancelledAsync(start, ct); } public Task ShowToUserAsync() => OnUiAsync(() => @@ -170,7 +177,9 @@ internal sealed class WebView2Host : IBrowserHost /// — «Scollega» deletes the profile there — and starts it again. /// stays the same object. The browser starts again even when fails with an /// or ; that error is thrown afterwards. A failed - /// start throws its own error and, like a failed , leaves nothing open. + /// start throws its own error and, like a failed , leaves nothing open. Once begun it goes + /// to the end whatever says (the profile with the Instagram session must go, and the engine + /// starts again after it); stopping waits for it at most . /// public Task RestartAsync(Func? whileStopped, CancellationToken ct) => OnUiAsync(() => ExclusiveAsync(async () => { @@ -253,6 +262,10 @@ internal sealed class WebView2Host : IBrowserHost { 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) { @@ -566,6 +579,27 @@ internal sealed class WebView2Host : IBrowserHost } } + /// + /// Waits for until 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. + /// + 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; + } + } + /// /// Runs 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. diff --git a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs index 5b09e71..155254e 100644 --- a/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs +++ b/tests/Febe.Tests.Windows/WebView2LifecycleTests.cs @@ -186,6 +186,60 @@ public sealed class WebView2LifecycleTests Assert.HasCount(2, bed.Lines.Lines.Where(l => l.Contains("ERRORE", StringComparison.Ordinal)), "only the two failed starts: " + bed.Lines.Text); } + /// + /// «Esci» while the start does not complete (review of 20 October 2026): the composition awaits + /// 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. + /// + [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()